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.

260926 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,
  638. const bool useLocalTime) throw()
  639. {
  640. jassert (year > 100); // year must be a 4-digit version
  641. if (year < 1971 || year >= 2038 || ! useLocalTime)
  642. {
  643. // use extended maths for dates beyond 1970 to 2037..
  644. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  645. : 0;
  646. const int a = (13 - month) / 12;
  647. const int y = year + 4800 - a;
  648. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  649. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  650. - 32045;
  651. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  652. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  653. + milliseconds;
  654. }
  655. else
  656. {
  657. struct tm t;
  658. t.tm_year = year - 1900;
  659. t.tm_mon = month;
  660. t.tm_mday = day;
  661. t.tm_hour = hours;
  662. t.tm_min = minutes;
  663. t.tm_sec = seconds;
  664. t.tm_isdst = -1;
  665. millisSinceEpoch = 1000 * (int64) mktime (&t);
  666. if (millisSinceEpoch < 0)
  667. millisSinceEpoch = 0;
  668. else
  669. millisSinceEpoch += milliseconds;
  670. }
  671. }
  672. Time::~Time() throw()
  673. {
  674. }
  675. const Time& Time::operator= (const Time& other) throw()
  676. {
  677. millisSinceEpoch = other.millisSinceEpoch;
  678. return *this;
  679. }
  680. int64 Time::currentTimeMillis() throw()
  681. {
  682. static uint32 lastCounterResult = 0xffffffff;
  683. static int64 correction = 0;
  684. const uint32 now = getMillisecondCounter();
  685. // check the counter hasn't wrapped (also triggered the first time this function is called)
  686. if (now < lastCounterResult)
  687. {
  688. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  689. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  690. {
  691. // get the time once using normal library calls, and store the difference needed to
  692. // turn the millisecond counter into a real time.
  693. #if JUCE_WIN32
  694. struct _timeb t;
  695. #ifdef USE_NEW_SECURE_TIME_FNS
  696. _ftime_s (&t);
  697. #else
  698. _ftime (&t);
  699. #endif
  700. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  701. #else
  702. struct timeval tv;
  703. struct timezone tz;
  704. gettimeofday (&tv, &tz);
  705. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  706. #endif
  707. }
  708. }
  709. lastCounterResult = now;
  710. return correction + now;
  711. }
  712. uint32 juce_millisecondsSinceStartup() throw();
  713. static uint32 lastMSCounterValue = 0;
  714. uint32 Time::getMillisecondCounter() throw()
  715. {
  716. const uint32 now = juce_millisecondsSinceStartup();
  717. if (now < lastMSCounterValue)
  718. {
  719. // in multi-threaded apps this might be called concurrently, so
  720. // make sure that our last counter value only increases and doesn't
  721. // go backwards..
  722. if (now < lastMSCounterValue - 1000)
  723. lastMSCounterValue = now;
  724. }
  725. else
  726. {
  727. lastMSCounterValue = now;
  728. }
  729. return now;
  730. }
  731. uint32 Time::getApproximateMillisecondCounter() throw()
  732. {
  733. jassert (lastMSCounterValue != 0);
  734. return lastMSCounterValue;
  735. }
  736. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  737. {
  738. for (;;)
  739. {
  740. const uint32 now = getMillisecondCounter();
  741. if (now >= targetTime)
  742. break;
  743. const int toWait = targetTime - now;
  744. if (toWait > 2)
  745. {
  746. Thread::sleep (jmin (20, toWait >> 1));
  747. }
  748. else
  749. {
  750. // xxx should consider using mutex_pause on the mac as it apparently
  751. // makes it seem less like a spinlock and avoids lowering the thread pri.
  752. for (int i = 10; --i >= 0;)
  753. Thread::yield();
  754. }
  755. }
  756. }
  757. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  758. {
  759. return ticks / (double) getHighResolutionTicksPerSecond();
  760. }
  761. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  762. {
  763. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  764. }
  765. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  766. {
  767. return Time (currentTimeMillis());
  768. }
  769. const String Time::toString (const bool includeDate,
  770. const bool includeTime,
  771. const bool includeSeconds,
  772. const bool use24HourClock) const throw()
  773. {
  774. String result;
  775. if (includeDate)
  776. {
  777. result << getDayOfMonth() << ' '
  778. << getMonthName (true) << ' '
  779. << getYear();
  780. if (includeTime)
  781. result << ' ';
  782. }
  783. if (includeTime)
  784. {
  785. if (includeSeconds)
  786. {
  787. result += String::formatted (T("%d:%02d:%02d "),
  788. (use24HourClock) ? getHours()
  789. : getHoursInAmPmFormat(),
  790. getMinutes(),
  791. getSeconds());
  792. }
  793. else
  794. {
  795. result += String::formatted (T("%d.%02d"),
  796. (use24HourClock) ? getHours()
  797. : getHoursInAmPmFormat(),
  798. getMinutes());
  799. }
  800. if (! use24HourClock)
  801. result << (isAfternoon() ? "pm" : "am");
  802. }
  803. return result.trimEnd();
  804. }
  805. const String Time::formatted (const tchar* const format) const throw()
  806. {
  807. tchar buffer[80];
  808. struct tm t;
  809. millisToLocal (millisSinceEpoch, t);
  810. if (CharacterFunctions::ftime (buffer, 79, format, &t) <= 0)
  811. {
  812. int bufferSize = 128;
  813. for (;;)
  814. {
  815. MemoryBlock mb (bufferSize * sizeof (tchar));
  816. tchar* const b = (tchar*) mb.getData();
  817. if (CharacterFunctions::ftime (b, bufferSize, format, &t) > 0)
  818. return String (b);
  819. bufferSize += 128;
  820. }
  821. }
  822. return String (buffer);
  823. }
  824. int Time::getYear() const throw()
  825. {
  826. struct tm t;
  827. millisToLocal (millisSinceEpoch, t);
  828. return t.tm_year + 1900;
  829. }
  830. int Time::getMonth() const throw()
  831. {
  832. struct tm t;
  833. millisToLocal (millisSinceEpoch, t);
  834. return t.tm_mon;
  835. }
  836. int Time::getDayOfMonth() const throw()
  837. {
  838. struct tm t;
  839. millisToLocal (millisSinceEpoch, t);
  840. return t.tm_mday;
  841. }
  842. int Time::getDayOfWeek() const throw()
  843. {
  844. struct tm t;
  845. millisToLocal (millisSinceEpoch, t);
  846. return t.tm_wday;
  847. }
  848. int Time::getHours() const throw()
  849. {
  850. struct tm t;
  851. millisToLocal (millisSinceEpoch, t);
  852. return t.tm_hour;
  853. }
  854. int Time::getHoursInAmPmFormat() const throw()
  855. {
  856. const int hours = getHours();
  857. if (hours == 0)
  858. return 12;
  859. else if (hours <= 12)
  860. return hours;
  861. else
  862. return hours - 12;
  863. }
  864. bool Time::isAfternoon() const throw()
  865. {
  866. return getHours() >= 12;
  867. }
  868. static int extendedModulo (const int64 value, const int modulo) throw()
  869. {
  870. return (int) (value >= 0 ? (value % modulo)
  871. : (value - ((value / modulo) + 1) * modulo));
  872. }
  873. int Time::getMinutes() const throw()
  874. {
  875. return extendedModulo (millisSinceEpoch / 60000, 60);
  876. }
  877. int Time::getSeconds() const throw()
  878. {
  879. return extendedModulo (millisSinceEpoch / 1000, 60);
  880. }
  881. int Time::getMilliseconds() const throw()
  882. {
  883. return extendedModulo (millisSinceEpoch, 1000);
  884. }
  885. bool Time::isDaylightSavingTime() const throw()
  886. {
  887. struct tm t;
  888. millisToLocal (millisSinceEpoch, t);
  889. return t.tm_isdst != 0;
  890. }
  891. const String Time::getTimeZone() const throw()
  892. {
  893. String zone[2];
  894. #if JUCE_WIN32
  895. _tzset();
  896. #ifdef USE_NEW_SECURE_TIME_FNS
  897. {
  898. char name [128];
  899. size_t length;
  900. for (int i = 0; i < 2; ++i)
  901. {
  902. zeromem (name, sizeof (name));
  903. _get_tzname (&length, name, 127, i);
  904. zone[i] = name;
  905. }
  906. }
  907. #else
  908. const char** const zonePtr = (const char**) _tzname;
  909. zone[0] = zonePtr[0];
  910. zone[1] = zonePtr[1];
  911. #endif
  912. #else
  913. tzset();
  914. const char** const zonePtr = (const char**) tzname;
  915. zone[0] = zonePtr[0];
  916. zone[1] = zonePtr[1];
  917. #endif
  918. if (isDaylightSavingTime())
  919. {
  920. zone[0] = zone[1];
  921. if (zone[0].length() > 3
  922. && zone[0].containsIgnoreCase (T("daylight"))
  923. && zone[0].contains (T("GMT")))
  924. zone[0] = "BST";
  925. }
  926. return zone[0].substring (0, 3);
  927. }
  928. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  929. {
  930. return getMonthName (getMonth(), threeLetterVersion);
  931. }
  932. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  933. {
  934. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  935. }
  936. const String Time::getMonthName (int monthNumber,
  937. const bool threeLetterVersion) throw()
  938. {
  939. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  940. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  941. monthNumber %= 12;
  942. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  943. : longMonthNames [monthNumber]);
  944. }
  945. const String Time::getWeekdayName (int day,
  946. const bool threeLetterVersion) throw()
  947. {
  948. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  949. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  950. day %= 7;
  951. return TRANS (threeLetterVersion ? shortDayNames [day]
  952. : longDayNames [day]);
  953. }
  954. END_JUCE_NAMESPACE
  955. /********* End of inlined file: juce_Time.cpp *********/
  956. /********* Start of inlined file: juce_BitArray.cpp *********/
  957. BEGIN_JUCE_NAMESPACE
  958. BitArray::BitArray() throw()
  959. : numValues (4),
  960. highestBit (-1),
  961. negative (false)
  962. {
  963. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  964. }
  965. BitArray::BitArray (const int value) throw()
  966. : numValues (4),
  967. highestBit (31),
  968. negative (value < 0)
  969. {
  970. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  971. values[0] = abs (value);
  972. highestBit = getHighestBit();
  973. }
  974. BitArray::BitArray (int64 value) throw()
  975. : numValues (4),
  976. highestBit (63),
  977. negative (value < 0)
  978. {
  979. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  980. if (value < 0)
  981. value = -value;
  982. values[0] = (unsigned int) value;
  983. values[1] = (unsigned int) (value >> 32);
  984. highestBit = getHighestBit();
  985. }
  986. BitArray::BitArray (const unsigned int value) throw()
  987. : numValues (4),
  988. highestBit (31),
  989. negative (false)
  990. {
  991. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  992. values[0] = value;
  993. highestBit = getHighestBit();
  994. }
  995. BitArray::BitArray (const BitArray& other) throw()
  996. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  997. highestBit (other.getHighestBit()),
  998. negative (other.negative)
  999. {
  1000. const int bytes = sizeof (unsigned int) * (numValues + 1);
  1001. values = (unsigned int*) juce_malloc (bytes);
  1002. memcpy (values, other.values, bytes);
  1003. }
  1004. BitArray::~BitArray() throw()
  1005. {
  1006. juce_free (values);
  1007. }
  1008. const BitArray& BitArray::operator= (const BitArray& other) throw()
  1009. {
  1010. if (this != &other)
  1011. {
  1012. juce_free (values);
  1013. highestBit = other.getHighestBit();
  1014. numValues = jmax (4, (highestBit >> 5) + 1);
  1015. negative = other.negative;
  1016. const int memSize = sizeof (unsigned int) * (numValues + 1);
  1017. values = (unsigned int*)juce_malloc (memSize);
  1018. memcpy (values, other.values, memSize);
  1019. }
  1020. return *this;
  1021. }
  1022. // result == 0 = the same
  1023. // result < 0 = this number is smaller
  1024. // result > 0 = this number is bigger
  1025. int BitArray::compare (const BitArray& other) const throw()
  1026. {
  1027. if (isNegative() == other.isNegative())
  1028. {
  1029. const int absComp = compareAbsolute (other);
  1030. return isNegative() ? -absComp : absComp;
  1031. }
  1032. else
  1033. {
  1034. return isNegative() ? -1 : 1;
  1035. }
  1036. }
  1037. int BitArray::compareAbsolute (const BitArray& other) const throw()
  1038. {
  1039. const int h1 = getHighestBit();
  1040. const int h2 = other.getHighestBit();
  1041. if (h1 > h2)
  1042. return 1;
  1043. else if (h1 < h2)
  1044. return -1;
  1045. for (int i = (h1 >> 5) + 1; --i >= 0;)
  1046. if (values[i] != other.values[i])
  1047. return (values[i] > other.values[i]) ? 1 : -1;
  1048. return 0;
  1049. }
  1050. bool BitArray::operator== (const BitArray& other) const throw()
  1051. {
  1052. return compare (other) == 0;
  1053. }
  1054. bool BitArray::operator!= (const BitArray& other) const throw()
  1055. {
  1056. return compare (other) != 0;
  1057. }
  1058. bool BitArray::operator[] (const int bit) const throw()
  1059. {
  1060. return bit >= 0 && bit <= highestBit
  1061. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  1062. }
  1063. bool BitArray::isEmpty() const throw()
  1064. {
  1065. return getHighestBit() < 0;
  1066. }
  1067. void BitArray::clear() throw()
  1068. {
  1069. if (numValues > 16)
  1070. {
  1071. juce_free (values);
  1072. numValues = 4;
  1073. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1074. }
  1075. else
  1076. {
  1077. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  1078. }
  1079. highestBit = -1;
  1080. negative = false;
  1081. }
  1082. void BitArray::setBit (const int bit) throw()
  1083. {
  1084. if (bit >= 0)
  1085. {
  1086. if (bit > highestBit)
  1087. {
  1088. ensureSize (bit >> 5);
  1089. highestBit = bit;
  1090. }
  1091. values [bit >> 5] |= (1 << (bit & 31));
  1092. }
  1093. }
  1094. void BitArray::setBit (const int bit,
  1095. const bool shouldBeSet) throw()
  1096. {
  1097. if (shouldBeSet)
  1098. setBit (bit);
  1099. else
  1100. clearBit (bit);
  1101. }
  1102. void BitArray::clearBit (const int bit) throw()
  1103. {
  1104. if (bit >= 0 && bit <= highestBit)
  1105. values [bit >> 5] &= ~(1 << (bit & 31));
  1106. }
  1107. void BitArray::setRange (int startBit,
  1108. int numBits,
  1109. const bool shouldBeSet) throw()
  1110. {
  1111. while (--numBits >= 0)
  1112. setBit (startBit++, shouldBeSet);
  1113. }
  1114. void BitArray::insertBit (const int bit,
  1115. const bool shouldBeSet) throw()
  1116. {
  1117. if (bit >= 0)
  1118. shiftBits (1, bit);
  1119. setBit (bit, shouldBeSet);
  1120. }
  1121. void BitArray::andWith (const BitArray& other) throw()
  1122. {
  1123. // this operation will only work with the absolute values
  1124. jassert (isNegative() == other.isNegative());
  1125. int n = numValues;
  1126. while (n > other.numValues)
  1127. values[--n] = 0;
  1128. while (--n >= 0)
  1129. values[n] &= other.values[n];
  1130. if (other.highestBit < highestBit)
  1131. highestBit = other.highestBit;
  1132. highestBit = getHighestBit();
  1133. }
  1134. void BitArray::orWith (const BitArray& other) throw()
  1135. {
  1136. if (other.highestBit < 0)
  1137. return;
  1138. // this operation will only work with the absolute values
  1139. jassert (isNegative() == other.isNegative());
  1140. ensureSize (other.highestBit >> 5);
  1141. int n = (other.highestBit >> 5) + 1;
  1142. while (--n >= 0)
  1143. values[n] |= other.values[n];
  1144. if (other.highestBit > highestBit)
  1145. highestBit = other.highestBit;
  1146. highestBit = getHighestBit();
  1147. }
  1148. void BitArray::xorWith (const BitArray& other) throw()
  1149. {
  1150. if (other.highestBit < 0)
  1151. return;
  1152. // this operation will only work with the absolute values
  1153. jassert (isNegative() == other.isNegative());
  1154. ensureSize (other.highestBit >> 5);
  1155. int n = (other.highestBit >> 5) + 1;
  1156. while (--n >= 0)
  1157. values[n] ^= other.values[n];
  1158. if (other.highestBit > highestBit)
  1159. highestBit = other.highestBit;
  1160. highestBit = getHighestBit();
  1161. }
  1162. void BitArray::add (const BitArray& other) throw()
  1163. {
  1164. if (other.isNegative())
  1165. {
  1166. BitArray o (other);
  1167. o.negate();
  1168. subtract (o);
  1169. return;
  1170. }
  1171. if (isNegative())
  1172. {
  1173. if (compareAbsolute (other) < 0)
  1174. {
  1175. BitArray temp (*this);
  1176. temp.negate();
  1177. *this = other;
  1178. subtract (temp);
  1179. }
  1180. else
  1181. {
  1182. negate();
  1183. subtract (other);
  1184. negate();
  1185. }
  1186. return;
  1187. }
  1188. if (other.highestBit > highestBit)
  1189. highestBit = other.highestBit;
  1190. ++highestBit;
  1191. const int numInts = (highestBit >> 5) + 1;
  1192. ensureSize (numInts);
  1193. int64 remainder = 0;
  1194. for (int i = 0; i <= numInts; ++i)
  1195. {
  1196. if (i < numValues)
  1197. remainder += values[i];
  1198. if (i < other.numValues)
  1199. remainder += other.values[i];
  1200. values[i] = (unsigned int) remainder;
  1201. remainder >>= 32;
  1202. }
  1203. jassert (remainder == 0);
  1204. highestBit = getHighestBit();
  1205. }
  1206. void BitArray::subtract (const BitArray& other) throw()
  1207. {
  1208. if (other.isNegative())
  1209. {
  1210. BitArray o (other);
  1211. o.negate();
  1212. add (o);
  1213. return;
  1214. }
  1215. if (! isNegative())
  1216. {
  1217. if (compareAbsolute (other) < 0)
  1218. {
  1219. BitArray temp (*this);
  1220. *this = other;
  1221. subtract (temp);
  1222. negate();
  1223. return;
  1224. }
  1225. }
  1226. else
  1227. {
  1228. negate();
  1229. add (other);
  1230. negate();
  1231. return;
  1232. }
  1233. const int numInts = (highestBit >> 5) + 1;
  1234. const int maxOtherInts = (other.highestBit >> 5) + 1;
  1235. int64 amountToSubtract = 0;
  1236. for (int i = 0; i <= numInts; ++i)
  1237. {
  1238. if (i <= maxOtherInts)
  1239. amountToSubtract += (int64)other.values[i];
  1240. if (values[i] >= amountToSubtract)
  1241. {
  1242. values[i] = (unsigned int) (values[i] - amountToSubtract);
  1243. amountToSubtract = 0;
  1244. }
  1245. else
  1246. {
  1247. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  1248. values[i] = (unsigned int) n;
  1249. amountToSubtract = 1;
  1250. }
  1251. }
  1252. }
  1253. void BitArray::multiplyBy (const BitArray& other) throw()
  1254. {
  1255. BitArray total;
  1256. highestBit = getHighestBit();
  1257. const bool wasNegative = isNegative();
  1258. setNegative (false);
  1259. for (int i = 0; i <= highestBit; ++i)
  1260. {
  1261. if (operator[](i))
  1262. {
  1263. BitArray n (other);
  1264. n.setNegative (false);
  1265. n.shiftBits (i);
  1266. total.add (n);
  1267. }
  1268. }
  1269. *this = total;
  1270. negative = wasNegative ^ other.isNegative();
  1271. }
  1272. void BitArray::divideBy (const BitArray& divisor, BitArray& remainder) throw()
  1273. {
  1274. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  1275. const int divHB = divisor.getHighestBit();
  1276. const int ourHB = getHighestBit();
  1277. if (divHB < 0 || ourHB < 0)
  1278. {
  1279. // division by zero
  1280. remainder.clear();
  1281. clear();
  1282. }
  1283. else
  1284. {
  1285. remainder = *this;
  1286. remainder.setNegative (false);
  1287. const bool wasNegative = isNegative();
  1288. clear();
  1289. BitArray temp (divisor);
  1290. temp.setNegative (false);
  1291. int leftShift = ourHB - divHB;
  1292. temp.shiftBits (leftShift);
  1293. while (leftShift >= 0)
  1294. {
  1295. if (remainder.compareAbsolute (temp) >= 0)
  1296. {
  1297. remainder.subtract (temp);
  1298. setBit (leftShift);
  1299. }
  1300. if (--leftShift >= 0)
  1301. temp.shiftBits (-1);
  1302. }
  1303. negative = wasNegative ^ divisor.isNegative();
  1304. remainder.setNegative (wasNegative);
  1305. }
  1306. }
  1307. void BitArray::modulo (const BitArray& divisor) throw()
  1308. {
  1309. BitArray remainder;
  1310. divideBy (divisor, remainder);
  1311. *this = remainder;
  1312. }
  1313. static const BitArray simpleGCD (BitArray* m, BitArray* n) throw()
  1314. {
  1315. while (! m->isEmpty())
  1316. {
  1317. if (n->compareAbsolute (*m) > 0)
  1318. swapVariables (m, n);
  1319. m->subtract (*n);
  1320. }
  1321. return *n;
  1322. }
  1323. const BitArray BitArray::findGreatestCommonDivisor (BitArray n) const throw()
  1324. {
  1325. BitArray m (*this);
  1326. while (! n.isEmpty())
  1327. {
  1328. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  1329. return simpleGCD (&m, &n);
  1330. BitArray temp1 (m), temp2;
  1331. temp1.divideBy (n, temp2);
  1332. m = n;
  1333. n = temp2;
  1334. }
  1335. return m;
  1336. }
  1337. void BitArray::exponentModulo (const BitArray& exponent,
  1338. const BitArray& modulus) throw()
  1339. {
  1340. BitArray exp (exponent);
  1341. exp.modulo (modulus);
  1342. BitArray value (*this);
  1343. value.modulo (modulus);
  1344. clear();
  1345. setBit (0);
  1346. while (! exp.isEmpty())
  1347. {
  1348. if (exp [0])
  1349. {
  1350. multiplyBy (value);
  1351. this->modulo (modulus);
  1352. }
  1353. value.multiplyBy (value);
  1354. value.modulo (modulus);
  1355. exp.shiftBits (-1);
  1356. }
  1357. }
  1358. void BitArray::inverseModulo (const BitArray& modulus) throw()
  1359. {
  1360. const BitArray one (1);
  1361. if (modulus == one || modulus.isNegative())
  1362. {
  1363. clear();
  1364. return;
  1365. }
  1366. if (isNegative() || compareAbsolute (modulus) >= 0)
  1367. this->modulo (modulus);
  1368. if (*this == one)
  1369. return;
  1370. if (! (*this)[0])
  1371. {
  1372. // not invertible
  1373. clear();
  1374. return;
  1375. }
  1376. BitArray a1 (modulus);
  1377. BitArray a2 (*this);
  1378. BitArray b1 (modulus);
  1379. BitArray b2 (1);
  1380. while (a2 != one)
  1381. {
  1382. BitArray temp1, temp2, multiplier (a1);
  1383. multiplier.divideBy (a2, temp1);
  1384. temp1 = a2;
  1385. temp1.multiplyBy (multiplier);
  1386. temp2 = a1;
  1387. temp2.subtract (temp1);
  1388. a1 = a2;
  1389. a2 = temp2;
  1390. temp1 = b2;
  1391. temp1.multiplyBy (multiplier);
  1392. temp2 = b1;
  1393. temp2.subtract (temp1);
  1394. b1 = b2;
  1395. b2 = temp2;
  1396. }
  1397. while (b2.isNegative())
  1398. b2.add (modulus);
  1399. b2.modulo (modulus);
  1400. *this = b2;
  1401. }
  1402. void BitArray::shiftBits (int bits, const int startBit) throw()
  1403. {
  1404. if (highestBit < 0)
  1405. return;
  1406. if (startBit > 0)
  1407. {
  1408. if (bits < 0)
  1409. {
  1410. // right shift
  1411. for (int i = startBit; i <= highestBit; ++i)
  1412. setBit (i, operator[] (i - bits));
  1413. highestBit = getHighestBit();
  1414. }
  1415. else if (bits > 0)
  1416. {
  1417. // left shift
  1418. for (int i = highestBit + 1; --i >= startBit;)
  1419. setBit (i + bits, operator[] (i));
  1420. while (--bits >= 0)
  1421. clearBit (bits + startBit);
  1422. }
  1423. }
  1424. else
  1425. {
  1426. if (bits < 0)
  1427. {
  1428. // right shift
  1429. bits = -bits;
  1430. if (bits > highestBit)
  1431. {
  1432. clear();
  1433. }
  1434. else
  1435. {
  1436. const int wordsToMove = bits >> 5;
  1437. int top = 1 + (highestBit >> 5) - wordsToMove;
  1438. highestBit -= bits;
  1439. if (wordsToMove > 0)
  1440. {
  1441. int i;
  1442. for (i = 0; i < top; ++i)
  1443. values [i] = values [i + wordsToMove];
  1444. for (i = 0; i < wordsToMove; ++i)
  1445. values [top + i] = 0;
  1446. bits &= 31;
  1447. }
  1448. if (bits != 0)
  1449. {
  1450. const int invBits = 32 - bits;
  1451. --top;
  1452. for (int i = 0; i < top; ++i)
  1453. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  1454. values[top] = (values[top] >> bits);
  1455. }
  1456. highestBit = getHighestBit();
  1457. }
  1458. }
  1459. else if (bits > 0)
  1460. {
  1461. // left shift
  1462. ensureSize (((highestBit + bits) >> 5) + 1);
  1463. const int wordsToMove = bits >> 5;
  1464. int top = 1 + (highestBit >> 5);
  1465. highestBit += bits;
  1466. if (wordsToMove > 0)
  1467. {
  1468. int i;
  1469. for (i = top; --i >= 0;)
  1470. values [i + wordsToMove] = values [i];
  1471. for (i = 0; i < wordsToMove; ++i)
  1472. values [i] = 0;
  1473. bits &= 31;
  1474. }
  1475. if (bits != 0)
  1476. {
  1477. const int invBits = 32 - bits;
  1478. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  1479. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  1480. values [wordsToMove] = values [wordsToMove] << bits;
  1481. }
  1482. highestBit = getHighestBit();
  1483. }
  1484. }
  1485. }
  1486. int BitArray::getBitRangeAsInt (const int startBit, int numBits) const throw()
  1487. {
  1488. if (numBits > 32)
  1489. {
  1490. jassertfalse
  1491. numBits = 32;
  1492. }
  1493. if (startBit == 0)
  1494. {
  1495. if (numBits < 32)
  1496. return values[0] & ((1 << numBits) - 1);
  1497. return values[0];
  1498. }
  1499. int n = 0;
  1500. for (int i = numBits; --i >= 0;)
  1501. {
  1502. n <<= 1;
  1503. if (operator[] (startBit + i))
  1504. n |= 1;
  1505. }
  1506. return n;
  1507. }
  1508. void BitArray::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet) throw()
  1509. {
  1510. if (numBits > 32)
  1511. {
  1512. jassertfalse
  1513. numBits = 32;
  1514. }
  1515. for (int i = 0; i < numBits; ++i)
  1516. {
  1517. setBit (startBit + i, (valueToSet & 1) != 0);
  1518. valueToSet >>= 1;
  1519. }
  1520. }
  1521. void BitArray::fillBitsRandomly (int startBit, int numBits) throw()
  1522. {
  1523. highestBit = jmax (highestBit, startBit + numBits);
  1524. ensureSize (((startBit + numBits) >> 5) + 1);
  1525. while ((startBit & 31) != 0 && numBits > 0)
  1526. {
  1527. setBit (startBit++, Random::getSystemRandom().nextBool());
  1528. --numBits;
  1529. }
  1530. while (numBits >= 32)
  1531. {
  1532. values [startBit >> 5] = (unsigned int) Random::getSystemRandom().nextInt();
  1533. startBit += 32;
  1534. numBits -= 32;
  1535. }
  1536. while (--numBits >= 0)
  1537. {
  1538. setBit (startBit + numBits, Random::getSystemRandom().nextBool());
  1539. }
  1540. highestBit = getHighestBit();
  1541. }
  1542. void BitArray::createRandomNumber (const BitArray& maximumValue) throw()
  1543. {
  1544. clear();
  1545. do
  1546. {
  1547. fillBitsRandomly (0, maximumValue.getHighestBit() + 1);
  1548. }
  1549. while (compare (maximumValue) >= 0);
  1550. }
  1551. bool BitArray::isNegative() const throw()
  1552. {
  1553. return negative && ! isEmpty();
  1554. }
  1555. void BitArray::setNegative (const bool neg) throw()
  1556. {
  1557. negative = neg;
  1558. }
  1559. void BitArray::negate() throw()
  1560. {
  1561. negative = (! negative) && ! isEmpty();
  1562. }
  1563. int BitArray::countNumberOfSetBits() const throw()
  1564. {
  1565. int total = 0;
  1566. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  1567. {
  1568. unsigned int n = values[i];
  1569. if (n == 0xffffffff)
  1570. {
  1571. total += 32;
  1572. }
  1573. else
  1574. {
  1575. while (n != 0)
  1576. {
  1577. total += (n & 1);
  1578. n >>= 1;
  1579. }
  1580. }
  1581. }
  1582. return total;
  1583. }
  1584. int BitArray::getHighestBit() const throw()
  1585. {
  1586. for (int i = highestBit + 1; --i >= 0;)
  1587. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  1588. return i;
  1589. return -1;
  1590. }
  1591. int BitArray::findNextSetBit (int i) const throw()
  1592. {
  1593. for (; i <= highestBit; ++i)
  1594. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  1595. return i;
  1596. return -1;
  1597. }
  1598. int BitArray::findNextClearBit (int i) const throw()
  1599. {
  1600. for (; i <= highestBit; ++i)
  1601. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  1602. break;
  1603. return i;
  1604. }
  1605. void BitArray::ensureSize (const int numVals) throw()
  1606. {
  1607. if (numVals + 2 >= numValues)
  1608. {
  1609. int oldSize = numValues;
  1610. numValues = ((numVals + 2) * 3) / 2;
  1611. values = (unsigned int*) juce_realloc (values, sizeof (unsigned int) * numValues + 4);
  1612. while (oldSize < numValues)
  1613. values [oldSize++] = 0;
  1614. }
  1615. }
  1616. const String BitArray::toString (const int base) const throw()
  1617. {
  1618. String s;
  1619. BitArray v (*this);
  1620. if (base == 2 || base == 8 || base == 16)
  1621. {
  1622. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  1623. static const tchar* const hexDigits = T("0123456789abcdef");
  1624. for (;;)
  1625. {
  1626. const int remainder = v.getBitRangeAsInt (0, bits);
  1627. v.shiftBits (-bits);
  1628. if (remainder == 0 && v.isEmpty())
  1629. break;
  1630. s = String::charToString (hexDigits [remainder]) + s;
  1631. }
  1632. }
  1633. else if (base == 10)
  1634. {
  1635. const BitArray ten (10);
  1636. BitArray remainder;
  1637. for (;;)
  1638. {
  1639. v.divideBy (ten, remainder);
  1640. if (remainder.isEmpty() && v.isEmpty())
  1641. break;
  1642. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  1643. }
  1644. }
  1645. else
  1646. {
  1647. jassertfalse // can't do the specified base
  1648. return String::empty;
  1649. }
  1650. if (s.isEmpty())
  1651. return T("0");
  1652. return isNegative() ? T("-") + s : s;
  1653. }
  1654. void BitArray::parseString (const String& text,
  1655. const int base) throw()
  1656. {
  1657. clear();
  1658. const tchar* t = (const tchar*) text;
  1659. if (base == 2 || base == 8 || base == 16)
  1660. {
  1661. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  1662. for (;;)
  1663. {
  1664. const tchar c = *t++;
  1665. const int digit = CharacterFunctions::getHexDigitValue (c);
  1666. if (((unsigned int) digit) < (unsigned int) base)
  1667. {
  1668. shiftBits (bits);
  1669. add (digit);
  1670. }
  1671. else if (c == 0)
  1672. {
  1673. break;
  1674. }
  1675. }
  1676. }
  1677. else if (base == 10)
  1678. {
  1679. const BitArray ten ((unsigned int) 10);
  1680. for (;;)
  1681. {
  1682. const tchar c = *t++;
  1683. if (c >= T('0') && c <= T('9'))
  1684. {
  1685. multiplyBy (ten);
  1686. add ((int) (c - T('0')));
  1687. }
  1688. else if (c == 0)
  1689. {
  1690. break;
  1691. }
  1692. }
  1693. }
  1694. setNegative (text.trimStart().startsWithChar (T('-')));
  1695. }
  1696. const MemoryBlock BitArray::toMemoryBlock() const throw()
  1697. {
  1698. const int numBytes = (getHighestBit() + 7) >> 3;
  1699. MemoryBlock mb (numBytes);
  1700. for (int i = 0; i < numBytes; ++i)
  1701. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  1702. return mb;
  1703. }
  1704. void BitArray::loadFromMemoryBlock (const MemoryBlock& data) throw()
  1705. {
  1706. clear();
  1707. for (int i = data.getSize(); --i >= 0;)
  1708. this->setBitRangeAsInt (i << 3, 8, data [i]);
  1709. }
  1710. END_JUCE_NAMESPACE
  1711. /********* End of inlined file: juce_BitArray.cpp *********/
  1712. /********* Start of inlined file: juce_MemoryBlock.cpp *********/
  1713. BEGIN_JUCE_NAMESPACE
  1714. MemoryBlock::MemoryBlock() throw()
  1715. : data (0),
  1716. size (0)
  1717. {
  1718. }
  1719. MemoryBlock::MemoryBlock (const int initialSize,
  1720. const bool initialiseToZero) throw()
  1721. {
  1722. if (initialSize > 0)
  1723. {
  1724. size = initialSize;
  1725. if (initialiseToZero)
  1726. data = (char*) juce_calloc (initialSize);
  1727. else
  1728. data = (char*) juce_malloc (initialSize);
  1729. }
  1730. else
  1731. {
  1732. data = 0;
  1733. size = 0;
  1734. }
  1735. }
  1736. MemoryBlock::MemoryBlock (const MemoryBlock& other) throw()
  1737. : data (0),
  1738. size (other.size)
  1739. {
  1740. if (size > 0)
  1741. {
  1742. jassert (other.data != 0);
  1743. data = (char*) juce_malloc (size);
  1744. memcpy (data, other.data, size);
  1745. }
  1746. }
  1747. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom,
  1748. const int sizeInBytes) throw()
  1749. : data (0),
  1750. size (jmax (0, sizeInBytes))
  1751. {
  1752. jassert (sizeInBytes >= 0);
  1753. if (size > 0)
  1754. {
  1755. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  1756. data = (char*) juce_malloc (size);
  1757. if (dataToInitialiseFrom != 0)
  1758. memcpy (data, dataToInitialiseFrom, size);
  1759. }
  1760. }
  1761. MemoryBlock::~MemoryBlock() throw()
  1762. {
  1763. jassert (size >= 0); // should never happen
  1764. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  1765. juce_free (data);
  1766. }
  1767. const MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other) throw()
  1768. {
  1769. if (this != &other)
  1770. {
  1771. setSize (other.size, false);
  1772. memcpy (data, other.data, size);
  1773. }
  1774. return *this;
  1775. }
  1776. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  1777. {
  1778. return (size == other.size)
  1779. && (memcmp (data, other.data, size) == 0);
  1780. }
  1781. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  1782. {
  1783. return ! operator== (other);
  1784. }
  1785. // this will resize the block to this size
  1786. void MemoryBlock::setSize (const int newSize,
  1787. const bool initialiseToZero) throw()
  1788. {
  1789. if (size != newSize)
  1790. {
  1791. if (newSize <= 0)
  1792. {
  1793. juce_free (data);
  1794. data = 0;
  1795. size = 0;
  1796. }
  1797. else
  1798. {
  1799. if (data != 0)
  1800. {
  1801. data = (char*) juce_realloc (data, newSize);
  1802. if (initialiseToZero && (newSize > size))
  1803. zeromem (data + size, newSize - size);
  1804. }
  1805. else
  1806. {
  1807. if (initialiseToZero)
  1808. data = (char*) juce_calloc (newSize);
  1809. else
  1810. data = (char*) juce_malloc (newSize);
  1811. }
  1812. size = newSize;
  1813. }
  1814. }
  1815. }
  1816. void MemoryBlock::ensureSize (const int minimumSize,
  1817. const bool initialiseToZero) throw()
  1818. {
  1819. if (size < minimumSize)
  1820. setSize (minimumSize, initialiseToZero);
  1821. }
  1822. void MemoryBlock::fillWith (const uint8 value) throw()
  1823. {
  1824. memset (data, (int) value, size);
  1825. }
  1826. void MemoryBlock::append (const void* const srcData,
  1827. const int numBytes) throw()
  1828. {
  1829. if (numBytes > 0)
  1830. {
  1831. const int oldSize = size;
  1832. setSize (size + numBytes);
  1833. memcpy (data + oldSize, srcData, numBytes);
  1834. }
  1835. }
  1836. void MemoryBlock::copyFrom (const void* const src, int offset, int num) throw()
  1837. {
  1838. const char* d = (const char*) src;
  1839. if (offset < 0)
  1840. {
  1841. d -= offset;
  1842. num -= offset;
  1843. offset = 0;
  1844. }
  1845. if (offset + num > size)
  1846. num = size - offset;
  1847. if (num > 0)
  1848. memcpy (data + offset, d, num);
  1849. }
  1850. void MemoryBlock::copyTo (void* const dst, int offset, int num) const throw()
  1851. {
  1852. char* d = (char*) dst;
  1853. if (offset < 0)
  1854. {
  1855. zeromem (d, -offset);
  1856. d -= offset;
  1857. num += offset;
  1858. offset = 0;
  1859. }
  1860. if (offset + num > size)
  1861. {
  1862. const int newNum = size - offset;
  1863. zeromem (d + newNum, num - newNum);
  1864. num = newNum;
  1865. }
  1866. if (num > 0)
  1867. memcpy (d, data + offset, num);
  1868. }
  1869. void MemoryBlock::removeSection (int startByte, int numBytesToRemove) throw()
  1870. {
  1871. if (startByte < 0)
  1872. {
  1873. numBytesToRemove += startByte;
  1874. startByte = 0;
  1875. }
  1876. if (startByte + numBytesToRemove >= size)
  1877. {
  1878. setSize (startByte);
  1879. }
  1880. else if (numBytesToRemove > 0)
  1881. {
  1882. memmove (data + startByte,
  1883. data + startByte + numBytesToRemove,
  1884. size - (startByte + numBytesToRemove));
  1885. setSize (size - numBytesToRemove);
  1886. }
  1887. }
  1888. const String MemoryBlock::toString() const throw()
  1889. {
  1890. return String (data, size);
  1891. }
  1892. int MemoryBlock::getBitRange (const int bitRangeStart, int numBits) const throw()
  1893. {
  1894. int res = 0;
  1895. int byte = bitRangeStart >> 3;
  1896. int offsetInByte = bitRangeStart & 7;
  1897. int bitsSoFar = 0;
  1898. while (numBits > 0 && byte < size)
  1899. {
  1900. const int bitsThisTime = jmin (numBits, 8 - offsetInByte);
  1901. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  1902. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  1903. bitsSoFar += bitsThisTime;
  1904. numBits -= bitsThisTime;
  1905. ++byte;
  1906. offsetInByte = 0;
  1907. }
  1908. return res;
  1909. }
  1910. void MemoryBlock::setBitRange (const int bitRangeStart, int numBits, int bitsToSet) throw()
  1911. {
  1912. int byte = bitRangeStart >> 3;
  1913. int offsetInByte = bitRangeStart & 7;
  1914. unsigned int mask = ~((((unsigned int)0xffffffff) << (32 - numBits)) >> (32 - numBits));
  1915. while (numBits > 0 && byte < size)
  1916. {
  1917. const int bitsThisTime = jmin (numBits, 8 - offsetInByte);
  1918. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int)0xffffffff) >> offsetInByte) << offsetInByte);
  1919. const unsigned int tempBits = bitsToSet << offsetInByte;
  1920. data[byte] = (char)((data[byte] & tempMask) | tempBits);
  1921. ++byte;
  1922. numBits -= bitsThisTime;
  1923. bitsToSet >>= bitsThisTime;
  1924. mask >>= bitsThisTime;
  1925. offsetInByte = 0;
  1926. }
  1927. }
  1928. void MemoryBlock::loadFromHexString (const String& hex) throw()
  1929. {
  1930. ensureSize (hex.length() >> 1);
  1931. char* dest = data;
  1932. int i = 0;
  1933. for (;;)
  1934. {
  1935. int byte = 0;
  1936. for (int loop = 2; --loop >= 0;)
  1937. {
  1938. byte <<= 4;
  1939. for (;;)
  1940. {
  1941. const tchar c = hex [i++];
  1942. if (c >= T('0') && c <= T('9'))
  1943. {
  1944. byte |= c - T('0');
  1945. break;
  1946. }
  1947. else if (c >= T('a') && c <= T('z'))
  1948. {
  1949. byte |= c - (T('a') - 10);
  1950. break;
  1951. }
  1952. else if (c >= T('A') && c <= T('Z'))
  1953. {
  1954. byte |= c - (T('A') - 10);
  1955. break;
  1956. }
  1957. else if (c == 0)
  1958. {
  1959. setSize ((int) (dest - data));
  1960. return;
  1961. }
  1962. }
  1963. }
  1964. *dest++ = (char) byte;
  1965. }
  1966. }
  1967. static const char* const encodingTable
  1968. = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  1969. const String MemoryBlock::toBase64Encoding() const throw()
  1970. {
  1971. const int numChars = ((size << 3) + 5) / 6;
  1972. String destString (size); // store the length, followed by a '.', and then the data.
  1973. const int initialLen = destString.length();
  1974. destString.preallocateStorage (initialLen + 2 + numChars);
  1975. tchar* d = const_cast <tchar*> (((const tchar*) destString) + initialLen);
  1976. *d++ = T('.');
  1977. for (int i = 0; i < numChars; ++i)
  1978. *d++ = encodingTable [getBitRange (i * 6, 6)];
  1979. *d++ = 0;
  1980. return destString;
  1981. }
  1982. bool MemoryBlock::fromBase64Encoding (const String& s) throw()
  1983. {
  1984. const int startPos = s.indexOfChar (T('.')) + 1;
  1985. if (startPos <= 0)
  1986. return false;
  1987. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  1988. setSize (numBytesNeeded, true);
  1989. const int numChars = s.length() - startPos;
  1990. const tchar* const srcChars = ((const tchar*) s) + startPos;
  1991. for (int i = 0; i < numChars; ++i)
  1992. {
  1993. const char c = (char) srcChars[i];
  1994. for (int j = 0; j < 64; ++j)
  1995. {
  1996. if (encodingTable[j] == c)
  1997. {
  1998. setBitRange (i * 6, 6, j);
  1999. break;
  2000. }
  2001. }
  2002. }
  2003. return true;
  2004. }
  2005. END_JUCE_NAMESPACE
  2006. /********* End of inlined file: juce_MemoryBlock.cpp *********/
  2007. /********* Start of inlined file: juce_PropertySet.cpp *********/
  2008. BEGIN_JUCE_NAMESPACE
  2009. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  2010. : properties (ignoreCaseOfKeyNames),
  2011. fallbackProperties (0),
  2012. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  2013. {
  2014. }
  2015. PropertySet::PropertySet (const PropertySet& other) throw()
  2016. : properties (other.properties),
  2017. fallbackProperties (other.fallbackProperties),
  2018. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  2019. {
  2020. }
  2021. const PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  2022. {
  2023. properties = other.properties;
  2024. fallbackProperties = other.fallbackProperties;
  2025. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  2026. propertyChanged();
  2027. return *this;
  2028. }
  2029. PropertySet::~PropertySet()
  2030. {
  2031. }
  2032. void PropertySet::clear()
  2033. {
  2034. const ScopedLock sl (lock);
  2035. if (properties.size() > 0)
  2036. {
  2037. properties.clear();
  2038. propertyChanged();
  2039. }
  2040. }
  2041. const String PropertySet::getValue (const String& keyName,
  2042. const String& defaultValue) const throw()
  2043. {
  2044. const ScopedLock sl (lock);
  2045. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2046. if (index >= 0)
  2047. return properties.getAllValues() [index];
  2048. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  2049. : defaultValue;
  2050. }
  2051. int PropertySet::getIntValue (const String& keyName,
  2052. const int defaultValue) const throw()
  2053. {
  2054. const ScopedLock sl (lock);
  2055. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2056. if (index >= 0)
  2057. return properties.getAllValues() [index].getIntValue();
  2058. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  2059. : defaultValue;
  2060. }
  2061. double PropertySet::getDoubleValue (const String& keyName,
  2062. const double defaultValue) const throw()
  2063. {
  2064. const ScopedLock sl (lock);
  2065. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2066. if (index >= 0)
  2067. return properties.getAllValues()[index].getDoubleValue();
  2068. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  2069. : defaultValue;
  2070. }
  2071. bool PropertySet::getBoolValue (const String& keyName,
  2072. const bool defaultValue) const throw()
  2073. {
  2074. const ScopedLock sl (lock);
  2075. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2076. if (index >= 0)
  2077. return properties.getAllValues() [index].getIntValue() != 0;
  2078. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  2079. : defaultValue;
  2080. }
  2081. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  2082. {
  2083. XmlDocument doc (getValue (keyName));
  2084. return doc.getDocumentElement();
  2085. }
  2086. void PropertySet::setValue (const String& keyName,
  2087. const String& value) throw()
  2088. {
  2089. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  2090. if (keyName.isNotEmpty())
  2091. {
  2092. const ScopedLock sl (lock);
  2093. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2094. if (index < 0 || properties.getAllValues() [index] != value)
  2095. {
  2096. properties.set (keyName, value);
  2097. propertyChanged();
  2098. }
  2099. }
  2100. }
  2101. void PropertySet::removeValue (const String& keyName) throw()
  2102. {
  2103. if (keyName.isNotEmpty())
  2104. {
  2105. const ScopedLock sl (lock);
  2106. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2107. if (index >= 0)
  2108. {
  2109. properties.remove (keyName);
  2110. propertyChanged();
  2111. }
  2112. }
  2113. }
  2114. void PropertySet::setValue (const String& keyName, const tchar* const value) throw()
  2115. {
  2116. setValue (keyName, String (value));
  2117. }
  2118. void PropertySet::setValue (const String& keyName, const int value) throw()
  2119. {
  2120. setValue (keyName, String (value));
  2121. }
  2122. void PropertySet::setValue (const String& keyName, const double value) throw()
  2123. {
  2124. setValue (keyName, String (value));
  2125. }
  2126. void PropertySet::setValue (const String& keyName, const bool value) throw()
  2127. {
  2128. setValue (keyName, String ((value) ? T("1") : T("0")));
  2129. }
  2130. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  2131. {
  2132. setValue (keyName, (xml == 0) ? String::empty
  2133. : xml->createDocument (String::empty, true));
  2134. }
  2135. bool PropertySet::containsKey (const String& keyName) const throw()
  2136. {
  2137. const ScopedLock sl (lock);
  2138. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  2139. }
  2140. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  2141. {
  2142. const ScopedLock sl (lock);
  2143. fallbackProperties = fallbackProperties_;
  2144. }
  2145. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  2146. {
  2147. const ScopedLock sl (lock);
  2148. XmlElement* const xml = new XmlElement (nodeName);
  2149. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  2150. {
  2151. XmlElement* const e = new XmlElement (T("VALUE"));
  2152. e->setAttribute (T("name"), properties.getAllKeys()[i]);
  2153. e->setAttribute (T("val"), properties.getAllValues()[i]);
  2154. xml->addChildElement (e);
  2155. }
  2156. return xml;
  2157. }
  2158. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  2159. {
  2160. const ScopedLock sl (lock);
  2161. clear();
  2162. forEachXmlChildElementWithTagName (xml, e, T("VALUE"))
  2163. {
  2164. if (e->hasAttribute (T("name"))
  2165. && e->hasAttribute (T("val")))
  2166. {
  2167. properties.set (e->getStringAttribute (T("name")),
  2168. e->getStringAttribute (T("val")));
  2169. }
  2170. }
  2171. if (properties.size() > 0)
  2172. propertyChanged();
  2173. }
  2174. void PropertySet::propertyChanged()
  2175. {
  2176. }
  2177. END_JUCE_NAMESPACE
  2178. /********* End of inlined file: juce_PropertySet.cpp *********/
  2179. /********* Start of inlined file: juce_BlowFish.cpp *********/
  2180. BEGIN_JUCE_NAMESPACE
  2181. static const uint32 initialPValues [18] =
  2182. {
  2183. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
  2184. 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  2185. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
  2186. 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  2187. 0x9216d5d9, 0x8979fb1b
  2188. };
  2189. static const uint32 initialSValues [4 * 256] =
  2190. {
  2191. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
  2192. 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  2193. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
  2194. 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  2195. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
  2196. 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  2197. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
  2198. 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  2199. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
  2200. 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  2201. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
  2202. 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  2203. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
  2204. 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  2205. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
  2206. 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  2207. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
  2208. 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  2209. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
  2210. 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  2211. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
  2212. 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  2213. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
  2214. 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  2215. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
  2216. 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  2217. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
  2218. 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  2219. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
  2220. 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  2221. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
  2222. 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  2223. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
  2224. 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  2225. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
  2226. 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  2227. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
  2228. 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  2229. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
  2230. 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  2231. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
  2232. 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  2233. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
  2234. 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  2235. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
  2236. 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  2237. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
  2238. 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  2239. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
  2240. 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  2241. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
  2242. 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  2243. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
  2244. 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  2245. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
  2246. 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  2247. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
  2248. 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  2249. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
  2250. 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  2251. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
  2252. 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  2253. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
  2254. 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  2255. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
  2256. 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  2257. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
  2258. 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  2259. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
  2260. 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  2261. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
  2262. 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  2263. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
  2264. 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  2265. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
  2266. 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  2267. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
  2268. 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  2269. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
  2270. 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  2271. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
  2272. 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  2273. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
  2274. 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  2275. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
  2276. 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  2277. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
  2278. 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  2279. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
  2280. 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  2281. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
  2282. 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  2283. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
  2284. 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  2285. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
  2286. 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  2287. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
  2288. 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  2289. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
  2290. 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  2291. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
  2292. 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  2293. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
  2294. 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  2295. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
  2296. 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  2297. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
  2298. 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  2299. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
  2300. 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  2301. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
  2302. 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  2303. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
  2304. 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  2305. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
  2306. 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  2307. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
  2308. 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  2309. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
  2310. 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  2311. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
  2312. 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  2313. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
  2314. 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  2315. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
  2316. 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  2317. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
  2318. 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  2319. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
  2320. 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  2321. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
  2322. 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  2323. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
  2324. 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  2325. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
  2326. 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  2327. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
  2328. 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  2329. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
  2330. 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  2331. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
  2332. 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  2333. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
  2334. 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  2335. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
  2336. 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  2337. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
  2338. 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  2339. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
  2340. 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  2341. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
  2342. 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  2343. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
  2344. 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  2345. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
  2346. 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  2347. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
  2348. 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  2349. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
  2350. 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  2351. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
  2352. 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  2353. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
  2354. 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  2355. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
  2356. 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  2357. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
  2358. 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  2359. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
  2360. 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  2361. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
  2362. 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  2363. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
  2364. 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  2365. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
  2366. 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  2367. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
  2368. 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  2369. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
  2370. 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  2371. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
  2372. 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  2373. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
  2374. 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  2375. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
  2376. 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  2377. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
  2378. 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  2379. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
  2380. 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  2381. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
  2382. 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  2383. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
  2384. 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  2385. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
  2386. 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  2387. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
  2388. 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  2389. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
  2390. 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  2391. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
  2392. 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  2393. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
  2394. 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  2395. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
  2396. 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  2397. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
  2398. 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  2399. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
  2400. 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  2401. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
  2402. 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  2403. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
  2404. 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  2405. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
  2406. 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  2407. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
  2408. 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  2409. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
  2410. 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  2411. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
  2412. 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  2413. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
  2414. 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  2415. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
  2416. 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  2417. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
  2418. 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  2419. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
  2420. 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  2421. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
  2422. 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  2423. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
  2424. 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  2425. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
  2426. 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  2427. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
  2428. 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  2429. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
  2430. 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  2431. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
  2432. 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  2433. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
  2434. 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  2435. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
  2436. 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  2437. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
  2438. 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  2439. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
  2440. 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  2441. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
  2442. 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  2443. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
  2444. 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  2445. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
  2446. 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  2447. };
  2448. BlowFish::BlowFish (const uint8* keyData, int keyBytes)
  2449. {
  2450. memcpy (p, initialPValues, sizeof (p));
  2451. int i, j;
  2452. for (i = 4; --i >= 0;)
  2453. {
  2454. s[i] = (uint32*) juce_malloc (256 * sizeof (uint32));
  2455. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  2456. }
  2457. j = 0;
  2458. for (i = 0; i < 18; ++i)
  2459. {
  2460. uint32 d = 0;
  2461. for (int k = 0; k < 4; ++k)
  2462. {
  2463. d = (d << 8) | keyData[j];
  2464. if (++j >= keyBytes)
  2465. j = 0;
  2466. }
  2467. p[i] = initialPValues[i] ^ d;
  2468. }
  2469. uint32 l = 0, r = 0;
  2470. for (i = 0; i < 18; i += 2)
  2471. {
  2472. encrypt (l, r);
  2473. p[i] = l;
  2474. p[i + 1] = r;
  2475. }
  2476. for (i = 0; i < 4; ++i)
  2477. {
  2478. for (j = 0; j < 256; j += 2)
  2479. {
  2480. encrypt (l, r);
  2481. s[i][j] = l;
  2482. s[i][j + 1] = r;
  2483. }
  2484. }
  2485. }
  2486. BlowFish::BlowFish (const BlowFish& other)
  2487. {
  2488. for (int i = 4; --i >= 0;)
  2489. s[i] = (uint32*) juce_malloc (256 * sizeof (uint32));
  2490. operator= (other);
  2491. }
  2492. const BlowFish& BlowFish::operator= (const BlowFish& other)
  2493. {
  2494. memcpy (p, other.p, sizeof (p));
  2495. for (int i = 4; --i >= 0;)
  2496. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  2497. return *this;
  2498. }
  2499. BlowFish::~BlowFish()
  2500. {
  2501. for (int i = 4; --i >= 0;)
  2502. juce_free (s[i]);
  2503. }
  2504. uint32 BlowFish::F (uint32 x) const
  2505. {
  2506. uint16 a, b, c, d;
  2507. uint32 y;
  2508. d = (uint16) (x & 0xff);
  2509. x >>= 8;
  2510. c = (uint16) (x & 0xff);
  2511. x >>= 8;
  2512. b = (uint16) (x & 0xff);
  2513. x >>= 8;
  2514. a = (uint16) (x & 0xff);
  2515. y = s[0][a] + s[1][b];
  2516. y = y ^ s[2][c];
  2517. y = y + s[3][d];
  2518. return y;
  2519. }
  2520. void BlowFish::encrypt (uint32& data1,
  2521. uint32& data2) const
  2522. {
  2523. uint32 l = data1;
  2524. uint32 r = data2;
  2525. for (int i = 0; i < 16; ++i)
  2526. {
  2527. l = l ^ p[i];
  2528. r = F (l) ^ r;
  2529. const uint32 temp = l;
  2530. l = r;
  2531. r = temp;
  2532. }
  2533. const uint32 temp = l;
  2534. l = r;
  2535. r = temp;
  2536. r = r ^ p[16];
  2537. l = l ^ p[17];
  2538. data1 = l;
  2539. data2 = r;
  2540. }
  2541. void BlowFish::decrypt (uint32& data1,
  2542. uint32& data2) const
  2543. {
  2544. uint32 l = data1;
  2545. uint32 r = data2;
  2546. for (int i = 17; i > 1; --i)
  2547. {
  2548. l =l ^ p[i];
  2549. r = F (l) ^ r;
  2550. const uint32 temp = l;
  2551. l = r;
  2552. r = temp;
  2553. }
  2554. const uint32 temp = l;
  2555. l = r;
  2556. r = temp;
  2557. r = r ^ p[1];
  2558. l = l ^ p[0];
  2559. data1 = l;
  2560. data2 = r;
  2561. }
  2562. END_JUCE_NAMESPACE
  2563. /********* End of inlined file: juce_BlowFish.cpp *********/
  2564. /********* Start of inlined file: juce_MD5.cpp *********/
  2565. BEGIN_JUCE_NAMESPACE
  2566. MD5::MD5()
  2567. {
  2568. zeromem (result, sizeof (result));
  2569. }
  2570. MD5::MD5 (const MD5& other)
  2571. {
  2572. memcpy (result, other.result, sizeof (result));
  2573. }
  2574. const MD5& MD5::operator= (const MD5& other)
  2575. {
  2576. memcpy (result, other.result, sizeof (result));
  2577. return *this;
  2578. }
  2579. MD5::MD5 (const MemoryBlock& data)
  2580. {
  2581. ProcessContext context;
  2582. context.processBlock ((const uint8*) data.getData(), data.getSize());
  2583. context.finish (result);
  2584. }
  2585. MD5::MD5 (const char* data, const int numBytes)
  2586. {
  2587. ProcessContext context;
  2588. context.processBlock ((const uint8*) data, numBytes);
  2589. context.finish (result);
  2590. }
  2591. MD5::MD5 (const String& text)
  2592. {
  2593. ProcessContext context;
  2594. const int len = text.length();
  2595. const juce_wchar* const t = text;
  2596. for (int i = 0; i < len; ++i)
  2597. {
  2598. // force the string into integer-sized unicode characters, to try to make it
  2599. // get the same results on all platforms + compilers.
  2600. uint32 unicodeChar = (uint32) t[i];
  2601. swapIfBigEndian (unicodeChar);
  2602. context.processBlock ((const uint8*) &unicodeChar,
  2603. sizeof (unicodeChar));
  2604. }
  2605. context.finish (result);
  2606. }
  2607. void MD5::processStream (InputStream& input, int numBytesToRead)
  2608. {
  2609. ProcessContext context;
  2610. if (numBytesToRead < 0)
  2611. numBytesToRead = INT_MAX;
  2612. while (numBytesToRead > 0)
  2613. {
  2614. char tempBuffer [512];
  2615. const int bytesRead = input.read (tempBuffer, jmin (numBytesToRead, sizeof (tempBuffer)));
  2616. if (bytesRead <= 0)
  2617. break;
  2618. numBytesToRead -= bytesRead;
  2619. context.processBlock ((const uint8*) tempBuffer, bytesRead);
  2620. }
  2621. context.finish (result);
  2622. }
  2623. MD5::MD5 (InputStream& input, int numBytesToRead)
  2624. {
  2625. processStream (input, numBytesToRead);
  2626. }
  2627. MD5::MD5 (const File& file)
  2628. {
  2629. FileInputStream* const fin = file.createInputStream();
  2630. if (fin != 0)
  2631. {
  2632. processStream (*fin, -1);
  2633. delete fin;
  2634. }
  2635. else
  2636. {
  2637. zeromem (result, sizeof (result));
  2638. }
  2639. }
  2640. MD5::~MD5()
  2641. {
  2642. }
  2643. MD5::ProcessContext::ProcessContext()
  2644. {
  2645. state[0] = 0x67452301;
  2646. state[1] = 0xefcdab89;
  2647. state[2] = 0x98badcfe;
  2648. state[3] = 0x10325476;
  2649. count[0] = 0;
  2650. count[1] = 0;
  2651. }
  2652. void MD5::ProcessContext::processBlock (const uint8* const data, int dataSize)
  2653. {
  2654. int bufferPos = ((count[0] >> 3) & 0x3F);
  2655. count[0] += (dataSize << 3);
  2656. if (count[0] < ((uint32) dataSize << 3))
  2657. count[1]++;
  2658. count[1] += (dataSize >> 29);
  2659. const int spaceLeft = 64 - bufferPos;
  2660. int i = 0;
  2661. if (dataSize >= spaceLeft)
  2662. {
  2663. memcpy (buffer + bufferPos, data, spaceLeft);
  2664. transform (buffer);
  2665. i = spaceLeft;
  2666. while (i < dataSize - 63)
  2667. {
  2668. transform (data + i);
  2669. i += 64;
  2670. }
  2671. bufferPos = 0;
  2672. }
  2673. memcpy (buffer + bufferPos, data + i, dataSize - i);
  2674. }
  2675. static void encode (uint8* const output,
  2676. const uint32* const input,
  2677. const int numBytes)
  2678. {
  2679. uint32* const o = (uint32*) output;
  2680. for (int i = 0; i < (numBytes >> 2); ++i)
  2681. o[i] = swapIfBigEndian (input [i]);
  2682. }
  2683. static void decode (uint32* const output,
  2684. const uint8* const input,
  2685. const int numBytes)
  2686. {
  2687. for (int i = 0; i < (numBytes >> 2); ++i)
  2688. output[i] = littleEndianInt ((const char*) input + (i << 2));
  2689. }
  2690. void MD5::ProcessContext::finish (uint8* const result)
  2691. {
  2692. unsigned char encodedLength[8];
  2693. encode (encodedLength, count, 8);
  2694. // Pad out to 56 mod 64.
  2695. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  2696. const int paddingLength = (index < 56) ? (56 - index)
  2697. : (120 - index);
  2698. uint8 paddingBuffer [64];
  2699. zeromem (paddingBuffer, paddingLength);
  2700. paddingBuffer [0] = 0x80;
  2701. processBlock (paddingBuffer, paddingLength);
  2702. processBlock (encodedLength, 8);
  2703. encode (result, state, 16);
  2704. zeromem (buffer, sizeof (buffer));
  2705. }
  2706. #define S11 7
  2707. #define S12 12
  2708. #define S13 17
  2709. #define S14 22
  2710. #define S21 5
  2711. #define S22 9
  2712. #define S23 14
  2713. #define S24 20
  2714. #define S31 4
  2715. #define S32 11
  2716. #define S33 16
  2717. #define S34 23
  2718. #define S41 6
  2719. #define S42 10
  2720. #define S43 15
  2721. #define S44 21
  2722. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) { return (x & y) | (~x & z); }
  2723. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) { return (x & z) | (y & ~z); }
  2724. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) { return x ^ y ^ z; }
  2725. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) { return y ^ (x | ~z); }
  2726. static inline uint32 rotateLeft (const uint32 x, const uint32 n) { return (x << n) | (x >> (32 - n)); }
  2727. static inline void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  2728. {
  2729. a += F (b, c, d) + x + ac;
  2730. a = rotateLeft (a, s) + b;
  2731. }
  2732. static inline void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  2733. {
  2734. a += G (b, c, d) + x + ac;
  2735. a = rotateLeft (a, s) + b;
  2736. }
  2737. static inline void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  2738. {
  2739. a += H (b, c, d) + x + ac;
  2740. a = rotateLeft (a, s) + b;
  2741. }
  2742. static inline void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  2743. {
  2744. a += I (b, c, d) + x + ac;
  2745. a = rotateLeft (a, s) + b;
  2746. }
  2747. void MD5::ProcessContext::transform (const uint8* const buffer)
  2748. {
  2749. uint32 a = state[0];
  2750. uint32 b = state[1];
  2751. uint32 c = state[2];
  2752. uint32 d = state[3];
  2753. uint32 x[16];
  2754. decode (x, buffer, 64);
  2755. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
  2756. FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
  2757. FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
  2758. FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
  2759. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
  2760. FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
  2761. FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
  2762. FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
  2763. FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
  2764. FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
  2765. FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
  2766. FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
  2767. FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
  2768. FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
  2769. FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
  2770. FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
  2771. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
  2772. GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
  2773. GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
  2774. GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
  2775. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
  2776. GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
  2777. GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
  2778. GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
  2779. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
  2780. GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
  2781. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
  2782. GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
  2783. GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
  2784. GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
  2785. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
  2786. GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
  2787. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
  2788. HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
  2789. HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
  2790. HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
  2791. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
  2792. HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
  2793. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
  2794. HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
  2795. HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
  2796. HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
  2797. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
  2798. HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
  2799. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
  2800. HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
  2801. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
  2802. HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
  2803. II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
  2804. II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
  2805. II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
  2806. II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
  2807. II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
  2808. II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
  2809. II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
  2810. II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
  2811. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
  2812. II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
  2813. II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
  2814. II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
  2815. II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
  2816. II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
  2817. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
  2818. II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
  2819. state[0] += a;
  2820. state[1] += b;
  2821. state[2] += c;
  2822. state[3] += d;
  2823. zeromem (x, sizeof (x));
  2824. }
  2825. const MemoryBlock MD5::getRawChecksumData() const
  2826. {
  2827. return MemoryBlock (result, 16);
  2828. }
  2829. const String MD5::toHexString() const
  2830. {
  2831. return String::toHexString (result, 16, 0);
  2832. }
  2833. bool MD5::operator== (const MD5& other) const
  2834. {
  2835. return memcmp (result, other.result, 16) == 0;
  2836. }
  2837. bool MD5::operator!= (const MD5& other) const
  2838. {
  2839. return ! operator== (other);
  2840. }
  2841. END_JUCE_NAMESPACE
  2842. /********* End of inlined file: juce_MD5.cpp *********/
  2843. /********* Start of inlined file: juce_Primes.cpp *********/
  2844. BEGIN_JUCE_NAMESPACE
  2845. static void createSmallSieve (const int numBits, BitArray& result) throw()
  2846. {
  2847. result.setBit (numBits);
  2848. result.clearBit (numBits); // to enlarge the array
  2849. result.setBit (0);
  2850. int n = 2;
  2851. do
  2852. {
  2853. for (int i = n + n; i < numBits; i += n)
  2854. result.setBit (i);
  2855. n = result.findNextClearBit (n + 1);
  2856. }
  2857. while (n <= (numBits >> 1));
  2858. }
  2859. static void bigSieve (const BitArray& base,
  2860. const int numBits,
  2861. BitArray& result,
  2862. const BitArray& smallSieve,
  2863. const int smallSieveSize) throw()
  2864. {
  2865. jassert (! base[0]); // must be even!
  2866. result.setBit (numBits);
  2867. result.clearBit (numBits); // to enlarge the array
  2868. int index = smallSieve.findNextClearBit (0);
  2869. do
  2870. {
  2871. const int prime = (index << 1) + 1;
  2872. BitArray r (base);
  2873. BitArray remainder;
  2874. r.divideBy (prime, remainder);
  2875. int i = prime - remainder.getBitRangeAsInt (0, 32);
  2876. if (r.isEmpty())
  2877. i += prime;
  2878. if ((i & 1) == 0)
  2879. i += prime;
  2880. i = (i - 1) >> 1;
  2881. while (i < numBits)
  2882. {
  2883. result.setBit (i);
  2884. i += prime;
  2885. }
  2886. index = smallSieve.findNextClearBit (index + 1);
  2887. }
  2888. while (index < smallSieveSize);
  2889. }
  2890. static bool findCandidate (const BitArray& base,
  2891. const BitArray& sieve,
  2892. const int numBits,
  2893. BitArray& result,
  2894. const int certainty) throw()
  2895. {
  2896. for (int i = 0; i < numBits; ++i)
  2897. {
  2898. if (! sieve[i])
  2899. {
  2900. result = base;
  2901. result.add (BitArray ((unsigned int) ((i << 1) + 1)));
  2902. if (Primes::isProbablyPrime (result, certainty))
  2903. return true;
  2904. }
  2905. }
  2906. return false;
  2907. }
  2908. const BitArray Primes::createProbablePrime (const int bitLength,
  2909. const int certainty) throw()
  2910. {
  2911. BitArray smallSieve;
  2912. const int smallSieveSize = 15000;
  2913. createSmallSieve (smallSieveSize, smallSieve);
  2914. BitArray p;
  2915. p.fillBitsRandomly (0, bitLength);
  2916. p.setBit (bitLength - 1);
  2917. p.clearBit (0);
  2918. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  2919. while (p.getHighestBit() < bitLength)
  2920. {
  2921. p.add (2 * searchLen);
  2922. BitArray sieve;
  2923. bigSieve (p, searchLen, sieve,
  2924. smallSieve, smallSieveSize);
  2925. BitArray candidate;
  2926. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  2927. return candidate;
  2928. }
  2929. jassertfalse
  2930. return BitArray();
  2931. }
  2932. static bool passesMillerRabin (const BitArray& n, int iterations) throw()
  2933. {
  2934. const BitArray one (1);
  2935. const BitArray two (2);
  2936. BitArray nMinusOne (n);
  2937. nMinusOne.subtract (one);
  2938. BitArray d (nMinusOne);
  2939. const int s = d.findNextSetBit (0);
  2940. d.shiftBits (-s);
  2941. BitArray smallPrimes;
  2942. int numBitsInSmallPrimes = 0;
  2943. for (;;)
  2944. {
  2945. numBitsInSmallPrimes += 256;
  2946. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  2947. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  2948. if (numPrimesFound > iterations + 1)
  2949. break;
  2950. }
  2951. int smallPrime = 2;
  2952. while (--iterations >= 0)
  2953. {
  2954. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  2955. BitArray r (smallPrime);
  2956. //r.createRandomNumber (nMinusOne);
  2957. r.exponentModulo (d, n);
  2958. if (! (r == one || r == nMinusOne))
  2959. {
  2960. for (int j = 0; j < s; ++j)
  2961. {
  2962. r.exponentModulo (two, n);
  2963. if (r == nMinusOne)
  2964. break;
  2965. }
  2966. if (r != nMinusOne)
  2967. return false;
  2968. }
  2969. }
  2970. return true;
  2971. }
  2972. bool Primes::isProbablyPrime (const BitArray& number,
  2973. const int certainty) throw()
  2974. {
  2975. if (! number[0])
  2976. return false;
  2977. if (number.getHighestBit() <= 10)
  2978. {
  2979. const int num = number.getBitRangeAsInt (0, 10);
  2980. for (int i = num / 2; --i > 1;)
  2981. if (num % i == 0)
  2982. return false;
  2983. return true;
  2984. }
  2985. else
  2986. {
  2987. const BitArray screen (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23);
  2988. if (number.findGreatestCommonDivisor (screen) != BitArray (1))
  2989. return false;
  2990. return passesMillerRabin (number, certainty);
  2991. }
  2992. }
  2993. END_JUCE_NAMESPACE
  2994. /********* End of inlined file: juce_Primes.cpp *********/
  2995. /********* Start of inlined file: juce_RSAKey.cpp *********/
  2996. BEGIN_JUCE_NAMESPACE
  2997. RSAKey::RSAKey() throw()
  2998. {
  2999. }
  3000. RSAKey::RSAKey (const String& s) throw()
  3001. {
  3002. if (s.containsChar (T(',')))
  3003. {
  3004. part1.parseString (s.upToFirstOccurrenceOf (T(","), false, false), 16);
  3005. part2.parseString (s.fromFirstOccurrenceOf (T(","), false, false), 16);
  3006. }
  3007. else
  3008. {
  3009. // the string needs to be two hex numbers, comma-separated..
  3010. jassertfalse;
  3011. }
  3012. }
  3013. RSAKey::~RSAKey() throw()
  3014. {
  3015. }
  3016. const String RSAKey::toString() const throw()
  3017. {
  3018. return part1.toString (16) + T(",") + part2.toString (16);
  3019. }
  3020. bool RSAKey::applyToValue (BitArray& value) const throw()
  3021. {
  3022. if (part1.isEmpty() || part2.isEmpty()
  3023. || value.compare (0) <= 0)
  3024. {
  3025. jassertfalse // using an uninitialised key
  3026. value.clear();
  3027. return false;
  3028. }
  3029. BitArray result;
  3030. while (! value.isEmpty())
  3031. {
  3032. result.multiplyBy (part2);
  3033. BitArray remainder;
  3034. value.divideBy (part2, remainder);
  3035. remainder.exponentModulo (part1, part2);
  3036. result.add (remainder);
  3037. }
  3038. value = result;
  3039. return true;
  3040. }
  3041. static const BitArray findBestCommonDivisor (const BitArray& p,
  3042. const BitArray& q) throw()
  3043. {
  3044. const BitArray one (1);
  3045. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  3046. // are fast to divide + multiply
  3047. for (int i = 2; i <= 65536; i *= 2)
  3048. {
  3049. const BitArray e (1 + i);
  3050. if (e.findGreatestCommonDivisor (p) == one
  3051. && e.findGreatestCommonDivisor (q) == one)
  3052. {
  3053. return e;
  3054. }
  3055. }
  3056. BitArray e (4);
  3057. while (! (e.findGreatestCommonDivisor (p) == one
  3058. && e.findGreatestCommonDivisor (q) == one))
  3059. {
  3060. e.add (one);
  3061. }
  3062. return e;
  3063. }
  3064. void RSAKey::createKeyPair (RSAKey& publicKey,
  3065. RSAKey& privateKey,
  3066. const int numBits) throw()
  3067. {
  3068. jassert (numBits > 16); // not much point using less than this..
  3069. BitArray p (Primes::createProbablePrime (numBits / 2, 30));
  3070. BitArray q (Primes::createProbablePrime (numBits - numBits / 2, 30));
  3071. BitArray n (p);
  3072. n.multiplyBy (q); // n = pq
  3073. const BitArray one (1);
  3074. p.subtract (one);
  3075. q.subtract (one);
  3076. BitArray m (p);
  3077. m.multiplyBy (q); // m = (p - 1)(q - 1)
  3078. const BitArray e (findBestCommonDivisor (p, q));
  3079. BitArray d (e);
  3080. d.inverseModulo (m);
  3081. publicKey.part1 = e;
  3082. publicKey.part2 = n;
  3083. privateKey.part1 = d;
  3084. privateKey.part2 = n;
  3085. }
  3086. END_JUCE_NAMESPACE
  3087. /********* End of inlined file: juce_RSAKey.cpp *********/
  3088. /********* Start of inlined file: juce_InputStream.cpp *********/
  3089. BEGIN_JUCE_NAMESPACE
  3090. char InputStream::readByte()
  3091. {
  3092. char temp = 0;
  3093. read (&temp, 1);
  3094. return temp;
  3095. }
  3096. bool InputStream::readBool()
  3097. {
  3098. return readByte() != 0;
  3099. }
  3100. short InputStream::readShort()
  3101. {
  3102. char temp [2];
  3103. if (read (temp, 2) == 2)
  3104. return (short) littleEndianShort (temp);
  3105. else
  3106. return 0;
  3107. }
  3108. short InputStream::readShortBigEndian()
  3109. {
  3110. char temp [2];
  3111. if (read (temp, 2) == 2)
  3112. return (short) bigEndianShort (temp);
  3113. else
  3114. return 0;
  3115. }
  3116. int InputStream::readInt()
  3117. {
  3118. char temp [4];
  3119. if (read (temp, 4) == 4)
  3120. return (int) littleEndianInt (temp);
  3121. else
  3122. return 0;
  3123. }
  3124. int InputStream::readIntBigEndian()
  3125. {
  3126. char temp [4];
  3127. if (read (temp, 4) == 4)
  3128. return (int) bigEndianInt (temp);
  3129. else
  3130. return 0;
  3131. }
  3132. int InputStream::readCompressedInt()
  3133. {
  3134. int num = 0;
  3135. if (! isExhausted())
  3136. {
  3137. unsigned char numBytes = readByte();
  3138. const bool negative = (numBytes & 0x80) != 0;
  3139. numBytes &= 0x7f;
  3140. if (numBytes <= 4)
  3141. {
  3142. if (read (&num, numBytes) != numBytes)
  3143. return 0;
  3144. if (negative)
  3145. num = -num;
  3146. }
  3147. }
  3148. return num;
  3149. }
  3150. int64 InputStream::readInt64()
  3151. {
  3152. char temp [8];
  3153. if (read (temp, 8) == 8)
  3154. return (int64) swapIfBigEndian (*(uint64*)temp);
  3155. else
  3156. return 0;
  3157. }
  3158. int64 InputStream::readInt64BigEndian()
  3159. {
  3160. char temp [8];
  3161. if (read (temp, 8) == 8)
  3162. return (int64) swapIfLittleEndian (*(uint64*)temp);
  3163. else
  3164. return 0;
  3165. }
  3166. float InputStream::readFloat()
  3167. {
  3168. union { int asInt; float asFloat; } n;
  3169. n.asInt = readInt();
  3170. return n.asFloat;
  3171. }
  3172. float InputStream::readFloatBigEndian()
  3173. {
  3174. union { int asInt; float asFloat; } n;
  3175. n.asInt = readIntBigEndian();
  3176. return n.asFloat;
  3177. }
  3178. double InputStream::readDouble()
  3179. {
  3180. union { int64 asInt; double asDouble; } n;
  3181. n.asInt = readInt64();
  3182. return n.asDouble;
  3183. }
  3184. double InputStream::readDoubleBigEndian()
  3185. {
  3186. union { int64 asInt; double asDouble; } n;
  3187. n.asInt = readInt64BigEndian();
  3188. return n.asDouble;
  3189. }
  3190. const String InputStream::readString()
  3191. {
  3192. const int tempBufferSize = 256;
  3193. uint8 temp [tempBufferSize];
  3194. int i = 0;
  3195. while ((temp [i++] = readByte()) != 0)
  3196. {
  3197. if (i == tempBufferSize)
  3198. {
  3199. // too big for our quick buffer, so read it in blocks..
  3200. String result (String::fromUTF8 (temp, i));
  3201. i = 0;
  3202. for (;;)
  3203. {
  3204. if ((temp [i++] = readByte()) == 0)
  3205. {
  3206. result += String::fromUTF8 (temp, i - 1);
  3207. break;
  3208. }
  3209. else if (i == tempBufferSize)
  3210. {
  3211. result += String::fromUTF8 (temp, i);
  3212. i = 0;
  3213. }
  3214. }
  3215. return result;
  3216. }
  3217. }
  3218. return String::fromUTF8 (temp, i - 1);
  3219. }
  3220. const String InputStream::readNextLine()
  3221. {
  3222. String s;
  3223. const int maxChars = 256;
  3224. tchar buffer [maxChars];
  3225. int charsInBuffer = 0;
  3226. while (! isExhausted())
  3227. {
  3228. const uint8 c = readByte();
  3229. const int64 lastPos = getPosition();
  3230. if (c == '\n')
  3231. {
  3232. break;
  3233. }
  3234. else if (c == '\r')
  3235. {
  3236. if (readByte() != '\n')
  3237. setPosition (lastPos);
  3238. break;
  3239. }
  3240. buffer [charsInBuffer++] = c;
  3241. if (charsInBuffer == maxChars)
  3242. {
  3243. s.append (buffer, maxChars);
  3244. charsInBuffer = 0;
  3245. }
  3246. }
  3247. if (charsInBuffer > 0)
  3248. s.append (buffer, charsInBuffer);
  3249. return s;
  3250. }
  3251. int InputStream::readIntoMemoryBlock (MemoryBlock& block,
  3252. int numBytes)
  3253. {
  3254. const int64 totalLength = getTotalLength();
  3255. if (totalLength >= 0)
  3256. {
  3257. const int totalBytesRemaining = (int) jmin ((int64) 0x7fffffff,
  3258. totalLength - getPosition());
  3259. if (numBytes < 0)
  3260. numBytes = totalBytesRemaining;
  3261. else if (numBytes > 0)
  3262. numBytes = jmin (numBytes, totalBytesRemaining);
  3263. else
  3264. return 0;
  3265. }
  3266. const int originalBlockSize = block.getSize();
  3267. int totalBytesRead = 0;
  3268. if (numBytes > 0)
  3269. {
  3270. // know how many bytes we want, so we can resize the block first..
  3271. block.setSize (originalBlockSize + numBytes, false);
  3272. totalBytesRead = read (((char*) block.getData()) + originalBlockSize, numBytes);
  3273. }
  3274. else
  3275. {
  3276. // read until end of stram..
  3277. const int chunkSize = 32768;
  3278. for (;;)
  3279. {
  3280. block.ensureSize (originalBlockSize + totalBytesRead + chunkSize, false);
  3281. const int bytesJustIn = read (((char*) block.getData())
  3282. + originalBlockSize
  3283. + totalBytesRead,
  3284. chunkSize);
  3285. if (bytesJustIn == 0)
  3286. break;
  3287. totalBytesRead += bytesJustIn;
  3288. }
  3289. }
  3290. // trim off any excess left at the end
  3291. block.setSize (originalBlockSize + totalBytesRead, false);
  3292. return totalBytesRead;
  3293. }
  3294. const String InputStream::readEntireStreamAsString()
  3295. {
  3296. MemoryBlock mb;
  3297. const int size = readIntoMemoryBlock (mb);
  3298. return String::createStringFromData ((const char*) mb.getData(), size);
  3299. }
  3300. void InputStream::skipNextBytes (int64 numBytesToSkip)
  3301. {
  3302. if (numBytesToSkip > 0)
  3303. {
  3304. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  3305. MemoryBlock temp (skipBufferSize);
  3306. while ((numBytesToSkip > 0) && ! isExhausted())
  3307. {
  3308. numBytesToSkip -= read (temp.getData(), (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  3309. }
  3310. }
  3311. }
  3312. END_JUCE_NAMESPACE
  3313. /********* End of inlined file: juce_InputStream.cpp *********/
  3314. /********* Start of inlined file: juce_OutputStream.cpp *********/
  3315. BEGIN_JUCE_NAMESPACE
  3316. #if JUCE_DEBUG
  3317. static CriticalSection activeStreamLock;
  3318. static VoidArray activeStreams;
  3319. void juce_CheckForDanglingStreams()
  3320. {
  3321. /*
  3322. It's always a bad idea to leak any object, but if you're leaking output
  3323. streams, then there's a good chance that you're failing to flush a file
  3324. to disk properly, which could result in corrupted data and other similar
  3325. nastiness..
  3326. */
  3327. jassert (activeStreams.size() == 0);
  3328. };
  3329. #endif
  3330. OutputStream::OutputStream() throw()
  3331. {
  3332. #if JUCE_DEBUG
  3333. activeStreamLock.enter();
  3334. activeStreams.add (this);
  3335. activeStreamLock.exit();
  3336. #endif
  3337. }
  3338. OutputStream::~OutputStream()
  3339. {
  3340. #if JUCE_DEBUG
  3341. activeStreamLock.enter();
  3342. activeStreams.removeValue (this);
  3343. activeStreamLock.exit();
  3344. #endif
  3345. }
  3346. void OutputStream::writeBool (bool b)
  3347. {
  3348. writeByte ((b) ? (char) 1
  3349. : (char) 0);
  3350. }
  3351. void OutputStream::writeByte (char byte)
  3352. {
  3353. write (&byte, 1);
  3354. }
  3355. void OutputStream::writeShort (short value)
  3356. {
  3357. const unsigned short v = swapIfBigEndian ((unsigned short) value);
  3358. write (&v, 2);
  3359. }
  3360. void OutputStream::writeShortBigEndian (short value)
  3361. {
  3362. const unsigned short v = swapIfLittleEndian ((unsigned short) value);
  3363. write (&v, 2);
  3364. }
  3365. void OutputStream::writeInt (int value)
  3366. {
  3367. const unsigned int v = swapIfBigEndian ((unsigned int) value);
  3368. write (&v, 4);
  3369. }
  3370. void OutputStream::writeIntBigEndian (int value)
  3371. {
  3372. const unsigned int v = swapIfLittleEndian ((unsigned int) value);
  3373. write (&v, 4);
  3374. }
  3375. void OutputStream::writeCompressedInt (int value)
  3376. {
  3377. unsigned int un = (value < 0) ? (unsigned int) -value
  3378. : (unsigned int) value;
  3379. unsigned int tn = un;
  3380. int numSigBytes = 0;
  3381. do
  3382. {
  3383. tn >>= 8;
  3384. numSigBytes++;
  3385. } while (tn & 0xff);
  3386. if (value < 0)
  3387. numSigBytes |= 0x80;
  3388. writeByte ((char) numSigBytes);
  3389. write (&un, numSigBytes);
  3390. }
  3391. void OutputStream::writeInt64 (int64 value)
  3392. {
  3393. const uint64 v = swapIfBigEndian ((uint64) value);
  3394. write (&v, 8);
  3395. }
  3396. void OutputStream::writeInt64BigEndian (int64 value)
  3397. {
  3398. const uint64 v = swapIfLittleEndian ((uint64) value);
  3399. write (&v, 8);
  3400. }
  3401. void OutputStream::writeFloat (float value)
  3402. {
  3403. union { int asInt; float asFloat; } n;
  3404. n.asFloat = value;
  3405. writeInt (n.asInt);
  3406. }
  3407. void OutputStream::writeFloatBigEndian (float value)
  3408. {
  3409. union { int asInt; float asFloat; } n;
  3410. n.asFloat = value;
  3411. writeIntBigEndian (n.asInt);
  3412. }
  3413. void OutputStream::writeDouble (double value)
  3414. {
  3415. union { int64 asInt; double asDouble; } n;
  3416. n.asDouble = value;
  3417. writeInt64 (n.asInt);
  3418. }
  3419. void OutputStream::writeDoubleBigEndian (double value)
  3420. {
  3421. union { int64 asInt; double asDouble; } n;
  3422. n.asDouble = value;
  3423. writeInt64BigEndian (n.asInt);
  3424. }
  3425. void OutputStream::writeString (const String& text)
  3426. {
  3427. const int numBytes = text.copyToUTF8 (0);
  3428. uint8* const temp = (uint8*) juce_malloc (numBytes);
  3429. text.copyToUTF8 (temp);
  3430. write (temp, numBytes); // (numBytes includes the terminating null).
  3431. juce_free (temp);
  3432. }
  3433. void OutputStream::printf (const char* pf, ...)
  3434. {
  3435. unsigned int bufSize = 256;
  3436. char* buf = (char*) juce_malloc (bufSize);
  3437. for (;;)
  3438. {
  3439. va_list list;
  3440. va_start (list, pf);
  3441. const int num = CharacterFunctions::vprintf (buf, bufSize, pf, list);
  3442. va_end (list);
  3443. if (num > 0)
  3444. {
  3445. write (buf, num);
  3446. break;
  3447. }
  3448. else if (num == 0)
  3449. {
  3450. break;
  3451. }
  3452. juce_free (buf);
  3453. bufSize += 256;
  3454. buf = (char*) juce_malloc (bufSize);
  3455. }
  3456. juce_free (buf);
  3457. }
  3458. OutputStream& OutputStream::operator<< (const int number)
  3459. {
  3460. const String s (number);
  3461. write ((const char*) s, s.length());
  3462. return *this;
  3463. }
  3464. OutputStream& OutputStream::operator<< (const double number)
  3465. {
  3466. const String s (number);
  3467. write ((const char*) s, s.length());
  3468. return *this;
  3469. }
  3470. OutputStream& OutputStream::operator<< (const char character)
  3471. {
  3472. writeByte (character);
  3473. return *this;
  3474. }
  3475. OutputStream& OutputStream::operator<< (const char* const text)
  3476. {
  3477. write (text, (int) strlen (text));
  3478. return *this;
  3479. }
  3480. OutputStream& OutputStream::operator<< (const juce_wchar* const text)
  3481. {
  3482. const String s (text);
  3483. write ((const char*) s, s.length());
  3484. return *this;
  3485. }
  3486. OutputStream& OutputStream::operator<< (const String& text)
  3487. {
  3488. write ((const char*) text,
  3489. text.length());
  3490. return *this;
  3491. }
  3492. void OutputStream::writeText (const String& text,
  3493. const bool asUnicode,
  3494. const bool writeUnicodeHeaderBytes)
  3495. {
  3496. if (asUnicode)
  3497. {
  3498. if (writeUnicodeHeaderBytes)
  3499. write ("\x0ff\x0fe", 2);
  3500. const juce_wchar* src = (const juce_wchar*) text;
  3501. bool lastCharWasReturn = false;
  3502. while (*src != 0)
  3503. {
  3504. if (*src == L'\n' && ! lastCharWasReturn)
  3505. writeShort ((short) L'\r');
  3506. lastCharWasReturn = (*src == L'\r');
  3507. writeShort ((short) *src++);
  3508. }
  3509. }
  3510. else
  3511. {
  3512. const char* src = (const char*) text;
  3513. const char* t = src;
  3514. for (;;)
  3515. {
  3516. if (*t == '\n')
  3517. {
  3518. if (t > src)
  3519. write (src, (int) (t - src));
  3520. write ("\r\n", 2);
  3521. src = t + 1;
  3522. }
  3523. else if (*t == '\r')
  3524. {
  3525. if (t[1] == '\n')
  3526. ++t;
  3527. }
  3528. else if (*t == 0)
  3529. {
  3530. if (t > src)
  3531. write (src, (int) (t - src));
  3532. break;
  3533. }
  3534. ++t;
  3535. }
  3536. }
  3537. }
  3538. int OutputStream::writeFromInputStream (InputStream& source,
  3539. int numBytesToWrite)
  3540. {
  3541. if (numBytesToWrite < 0)
  3542. numBytesToWrite = 0x7fffffff;
  3543. int numWritten = 0;
  3544. while (numBytesToWrite > 0 && ! source.isExhausted())
  3545. {
  3546. char buffer [8192];
  3547. const int num = source.read (buffer, jmin (numBytesToWrite, sizeof (buffer)));
  3548. if (num == 0)
  3549. break;
  3550. write (buffer, num);
  3551. numBytesToWrite -= num;
  3552. numWritten += num;
  3553. }
  3554. return numWritten;
  3555. }
  3556. END_JUCE_NAMESPACE
  3557. /********* End of inlined file: juce_OutputStream.cpp *********/
  3558. /********* Start of inlined file: juce_DirectoryIterator.cpp *********/
  3559. BEGIN_JUCE_NAMESPACE
  3560. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  3561. bool* isDirectory, bool* isHidden, int64* fileSize,
  3562. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  3563. bool juce_findFileNext (void* handle, String& resultFile,
  3564. bool* isDirectory, bool* isHidden, int64* fileSize,
  3565. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  3566. void juce_findFileClose (void* handle) throw();
  3567. DirectoryIterator::DirectoryIterator (const File& directory,
  3568. bool isRecursive,
  3569. const String& wc,
  3570. const int whatToLookFor_) throw()
  3571. : wildCard (wc),
  3572. index (-1),
  3573. whatToLookFor (whatToLookFor_),
  3574. subIterator (0)
  3575. {
  3576. // you have to specify the type of files you're looking for!
  3577. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  3578. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  3579. String path (directory.getFullPathName());
  3580. if (! path.endsWithChar (File::separator))
  3581. path += File::separator;
  3582. String filename;
  3583. bool isDirectory, isHidden;
  3584. void* const handle = juce_findFileStart (path,
  3585. isRecursive ? T("*") : wc,
  3586. filename, &isDirectory, &isHidden, 0, 0, 0, 0);
  3587. if (handle != 0)
  3588. {
  3589. do
  3590. {
  3591. if (! filename.containsOnly (T(".")))
  3592. {
  3593. bool addToList = false;
  3594. if (isDirectory)
  3595. {
  3596. if (isRecursive
  3597. && ((whatToLookFor_ & File::ignoreHiddenFiles) == 0
  3598. || ! isHidden))
  3599. {
  3600. dirsFound.add (new File (path + filename, 0));
  3601. }
  3602. addToList = (whatToLookFor_ & File::findDirectories) != 0;
  3603. }
  3604. else
  3605. {
  3606. addToList = (whatToLookFor_ & File::findFiles) != 0;
  3607. }
  3608. // if it's recursive, we're not relying on the OS iterator
  3609. // to do the wildcard match, so do it now..
  3610. if (isRecursive && addToList)
  3611. addToList = filename.matchesWildcard (wc, true);
  3612. if (addToList && (whatToLookFor_ & File::ignoreHiddenFiles) != 0)
  3613. addToList = ! isHidden;
  3614. if (addToList)
  3615. filesFound.add (new File (path + filename, 0));
  3616. }
  3617. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  3618. juce_findFileClose (handle);
  3619. }
  3620. }
  3621. DirectoryIterator::~DirectoryIterator() throw()
  3622. {
  3623. if (subIterator != 0)
  3624. delete subIterator;
  3625. }
  3626. bool DirectoryIterator::next() throw()
  3627. {
  3628. if (subIterator != 0)
  3629. {
  3630. if (subIterator->next())
  3631. return true;
  3632. deleteAndZero (subIterator);
  3633. }
  3634. if (index >= filesFound.size() + dirsFound.size() - 1)
  3635. return false;
  3636. ++index;
  3637. if (index >= filesFound.size())
  3638. {
  3639. subIterator = new DirectoryIterator (*(dirsFound [index - filesFound.size()]),
  3640. true, wildCard, whatToLookFor);
  3641. return next();
  3642. }
  3643. return true;
  3644. }
  3645. const File DirectoryIterator::getFile() const throw()
  3646. {
  3647. if (subIterator != 0)
  3648. return subIterator->getFile();
  3649. const File* const f = filesFound [index];
  3650. return (f != 0) ? *f
  3651. : File::nonexistent;
  3652. }
  3653. float DirectoryIterator::getEstimatedProgress() const throw()
  3654. {
  3655. if (filesFound.size() + dirsFound.size() == 0)
  3656. {
  3657. return 0.0f;
  3658. }
  3659. else
  3660. {
  3661. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  3662. : (float) index;
  3663. return detailedIndex / (filesFound.size() + dirsFound.size());
  3664. }
  3665. }
  3666. END_JUCE_NAMESPACE
  3667. /********* End of inlined file: juce_DirectoryIterator.cpp *********/
  3668. /********* Start of inlined file: juce_File.cpp *********/
  3669. #ifdef _MSC_VER
  3670. #pragma warning (disable: 4514)
  3671. #pragma warning (push)
  3672. #endif
  3673. #ifndef JUCE_WIN32
  3674. #include <pwd.h>
  3675. #endif
  3676. BEGIN_JUCE_NAMESPACE
  3677. #ifdef _MSC_VER
  3678. #pragma warning (pop)
  3679. #endif
  3680. void* juce_fileOpen (const String& path, bool forWriting) throw();
  3681. void juce_fileClose (void* handle) throw();
  3682. int juce_fileWrite (void* handle, const void* buffer, int size) throw();
  3683. int64 juce_fileGetPosition (void* handle) throw();
  3684. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  3685. void juce_fileFlush (void* handle) throw();
  3686. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw();
  3687. bool juce_isDirectory (const String& fileName) throw();
  3688. int64 juce_getFileSize (const String& fileName) throw();
  3689. bool juce_canWriteToFile (const String& fileName) throw();
  3690. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw();
  3691. void juce_getFileTimes (const String& fileName, int64& modificationTime, int64& accessTime, int64& creationTime) throw();
  3692. bool juce_setFileTimes (const String& fileName, int64 modificationTime, int64 accessTime, int64 creationTime) throw();
  3693. bool juce_deleteFile (const String& fileName) throw();
  3694. bool juce_copyFile (const String& source, const String& dest) throw();
  3695. bool juce_moveFile (const String& source, const String& dest) throw();
  3696. // this must also create all paths involved in the directory.
  3697. void juce_createDirectory (const String& fileName) throw();
  3698. bool juce_launchFile (const String& fileName, const String& parameters) throw();
  3699. const StringArray juce_getFileSystemRoots() throw();
  3700. const String juce_getVolumeLabel (const String& filenameOnVolume, int& volumeSerialNumber) throw();
  3701. // starts a directory search operation with a wildcard, returning a handle for
  3702. // use in calls to juce_findFileNext.
  3703. // juce_firstResultFile gets the name of the file (not the whole pathname) and
  3704. // the other pointers, if non-null, are set based on the properties of the file.
  3705. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  3706. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  3707. Time* creationTime, bool* isReadOnly) throw();
  3708. // returns false when no more files are found
  3709. bool juce_findFileNext (void* handle, String& resultFile,
  3710. bool* isDirectory, bool* isHidden, int64* fileSize,
  3711. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  3712. void juce_findFileClose (void* handle) throw();
  3713. static const String parseAbsolutePath (String path) throw()
  3714. {
  3715. if (path.isEmpty())
  3716. return String::empty;
  3717. #if JUCE_WIN32
  3718. // Windows..
  3719. path = path.replaceCharacter (T('/'), T('\\')).unquoted();
  3720. if (path.startsWithChar (File::separator))
  3721. {
  3722. if (path[1] != File::separator)
  3723. {
  3724. jassertfalse // using a filename that starts with a slash is a bit dodgy on
  3725. // Windows, because it needs a drive letter, which in this case
  3726. // we'll take from the CWD.. but this is a bit of an assumption that
  3727. // could be wrong..
  3728. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  3729. }
  3730. }
  3731. else if (path.indexOfChar (T(':')) < 0)
  3732. {
  3733. if (path.isEmpty())
  3734. return String::empty;
  3735. jassertfalse // using a partial filename is a bad way to initialise a file, because
  3736. // we don't know what directory to put it in.
  3737. // Here we'll assume it's in the CWD, but this might not be what was
  3738. // intended..
  3739. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  3740. }
  3741. #else
  3742. // Mac or Linux..
  3743. path = path.replaceCharacter (T('\\'), T('/')).unquoted();
  3744. if (path.startsWithChar (T('~')))
  3745. {
  3746. const char* homeDir = 0;
  3747. if (path[1] == File::separator || path[1] == 0)
  3748. {
  3749. // expand a name of the form "~/abc"
  3750. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  3751. + path.substring (1);
  3752. }
  3753. else
  3754. {
  3755. // expand a name of type "~dave/abc"
  3756. const String userName (path.substring (1)
  3757. .upToFirstOccurrenceOf (T("/"), false, false));
  3758. struct passwd* const pw = getpwnam (userName);
  3759. if (pw != 0)
  3760. {
  3761. String home (homeDir);
  3762. if (home.endsWithChar (File::separator))
  3763. home [home.length() - 1] = 0;
  3764. path = String (pw->pw_dir)
  3765. + path.substring (userName.length());
  3766. }
  3767. }
  3768. }
  3769. else if (! path.startsWithChar (File::separator))
  3770. {
  3771. while (path.startsWith (T("./")))
  3772. path = path.substring (2);
  3773. if (path.isEmpty())
  3774. return String::empty;
  3775. jassertfalse // using a partial filename is a bad way to initialise a file, because
  3776. // we don't know what directory to put it in.
  3777. // Here we'll assume it's in the CWD, but this might not be what was
  3778. // intended..
  3779. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  3780. }
  3781. #endif
  3782. int len = path.length();
  3783. while (--len > 0 && path [len] == File::separator)
  3784. path [len] = 0;
  3785. return path;
  3786. }
  3787. const File File::nonexistent;
  3788. File::File (const String& fullPathName) throw()
  3789. : fullPath (parseAbsolutePath (fullPathName))
  3790. {
  3791. }
  3792. File::File (const String& path, int) throw()
  3793. : fullPath (path)
  3794. {
  3795. }
  3796. File::File (const File& other) throw()
  3797. : fullPath (other.fullPath)
  3798. {
  3799. }
  3800. const File& File::operator= (const String& newPath) throw()
  3801. {
  3802. fullPath = parseAbsolutePath (newPath);
  3803. return *this;
  3804. }
  3805. const File& File::operator= (const File& other) throw()
  3806. {
  3807. fullPath = other.fullPath;
  3808. return *this;
  3809. }
  3810. #if JUCE_LINUX
  3811. #define NAMES_ARE_CASE_SENSITIVE 1
  3812. #endif
  3813. bool File::areFileNamesCaseSensitive()
  3814. {
  3815. #if NAMES_ARE_CASE_SENSITIVE
  3816. return true;
  3817. #else
  3818. return false;
  3819. #endif
  3820. }
  3821. bool File::operator== (const File& other) const throw()
  3822. {
  3823. // case-insensitive on Windows, but not on linux.
  3824. #if NAMES_ARE_CASE_SENSITIVE
  3825. return fullPath == other.fullPath;
  3826. #else
  3827. return fullPath.equalsIgnoreCase (other.fullPath);
  3828. #endif
  3829. }
  3830. bool File::operator!= (const File& other) const throw()
  3831. {
  3832. return ! operator== (other);
  3833. }
  3834. bool File::exists() const throw()
  3835. {
  3836. return juce_fileExists (fullPath, false);
  3837. }
  3838. bool File::existsAsFile() const throw()
  3839. {
  3840. return juce_fileExists (fullPath, true);
  3841. }
  3842. bool File::isDirectory() const throw()
  3843. {
  3844. return juce_isDirectory (fullPath);
  3845. }
  3846. bool File::hasWriteAccess() const throw()
  3847. {
  3848. if (exists())
  3849. return juce_canWriteToFile (fullPath);
  3850. #ifndef JUCE_WIN32
  3851. else if ((! isDirectory()) && fullPath.containsChar (separator))
  3852. return getParentDirectory().hasWriteAccess();
  3853. else
  3854. return false;
  3855. #else
  3856. // on windows, it seems that even read-only directories can still be written into,
  3857. // so checking the parent directory's permissions would return the wrong result..
  3858. else
  3859. return true;
  3860. #endif
  3861. }
  3862. bool File::setReadOnly (const bool shouldBeReadOnly,
  3863. const bool applyRecursively) const throw()
  3864. {
  3865. bool worked = true;
  3866. if (applyRecursively && isDirectory())
  3867. {
  3868. OwnedArray <File> subFiles;
  3869. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  3870. for (int i = subFiles.size(); --i >= 0;)
  3871. worked = subFiles[i]->setReadOnly (shouldBeReadOnly, true) && worked;
  3872. }
  3873. return juce_setFileReadOnly (fullPath, shouldBeReadOnly) && worked;
  3874. }
  3875. bool File::deleteFile() const throw()
  3876. {
  3877. return (! exists())
  3878. || juce_deleteFile (fullPath);
  3879. }
  3880. bool File::deleteRecursively() const throw()
  3881. {
  3882. bool worked = true;
  3883. if (isDirectory())
  3884. {
  3885. OwnedArray<File> subFiles;
  3886. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  3887. for (int i = subFiles.size(); --i >= 0;)
  3888. worked = subFiles[i]->deleteRecursively() && worked;
  3889. }
  3890. return deleteFile() && worked;
  3891. }
  3892. bool File::moveFileTo (const File& newFile) const throw()
  3893. {
  3894. if (newFile.fullPath == fullPath)
  3895. return true;
  3896. #if ! NAMES_ARE_CASE_SENSITIVE
  3897. if (*this != newFile)
  3898. #endif
  3899. if (! newFile.deleteFile())
  3900. return false;
  3901. return juce_moveFile (fullPath, newFile.fullPath);
  3902. }
  3903. bool File::copyFileTo (const File& newFile) const throw()
  3904. {
  3905. if (*this == newFile)
  3906. return true;
  3907. if (! newFile.deleteFile())
  3908. return false;
  3909. return juce_copyFile (fullPath, newFile.fullPath);
  3910. }
  3911. bool File::copyDirectoryTo (const File& newDirectory) const throw()
  3912. {
  3913. if (isDirectory() && newDirectory.createDirectory())
  3914. {
  3915. OwnedArray<File> subFiles;
  3916. findChildFiles (subFiles, File::findFiles, false);
  3917. int i;
  3918. for (i = 0; i < subFiles.size(); ++i)
  3919. if (! subFiles[i]->copyFileTo (newDirectory.getChildFile (subFiles[i]->getFileName())))
  3920. return false;
  3921. subFiles.clear();
  3922. findChildFiles (subFiles, File::findDirectories, false);
  3923. for (i = 0; i < subFiles.size(); ++i)
  3924. if (! subFiles[i]->copyDirectoryTo (newDirectory.getChildFile (subFiles[i]->getFileName())))
  3925. return false;
  3926. return true;
  3927. }
  3928. return false;
  3929. }
  3930. const String File::getPathUpToLastSlash() const throw()
  3931. {
  3932. const int lastSlash = fullPath.lastIndexOfChar (separator);
  3933. if (lastSlash > 0)
  3934. return fullPath.substring (0, lastSlash);
  3935. else if (lastSlash == 0)
  3936. return separatorString;
  3937. else
  3938. return fullPath;
  3939. }
  3940. const File File::getParentDirectory() const throw()
  3941. {
  3942. return File (getPathUpToLastSlash());
  3943. }
  3944. const String File::getFileName() const throw()
  3945. {
  3946. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  3947. }
  3948. int File::hashCode() const throw()
  3949. {
  3950. return fullPath.hashCode();
  3951. }
  3952. int64 File::hashCode64() const throw()
  3953. {
  3954. return fullPath.hashCode64();
  3955. }
  3956. const String File::getFileNameWithoutExtension() const throw()
  3957. {
  3958. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  3959. const int lastDot = fullPath.lastIndexOfChar (T('.'));
  3960. if (lastDot > lastSlash)
  3961. return fullPath.substring (lastSlash, lastDot);
  3962. else
  3963. return fullPath.substring (lastSlash);
  3964. }
  3965. bool File::isAChildOf (const File& potentialParent) const throw()
  3966. {
  3967. const String ourPath (getPathUpToLastSlash());
  3968. #if NAMES_ARE_CASE_SENSITIVE
  3969. if (potentialParent.fullPath == ourPath)
  3970. #else
  3971. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  3972. #endif
  3973. {
  3974. return true;
  3975. }
  3976. else if (potentialParent.fullPath.length() >= ourPath.length())
  3977. {
  3978. return false;
  3979. }
  3980. else
  3981. {
  3982. return getParentDirectory().isAChildOf (potentialParent);
  3983. }
  3984. }
  3985. bool File::isAbsolutePath (const String& path) throw()
  3986. {
  3987. return path.startsWithChar (T('/')) || path.startsWithChar (T('\\'))
  3988. #if JUCE_WIN32
  3989. || (path.isNotEmpty() && ((const String&) path)[1] == T(':'));
  3990. #else
  3991. || path.startsWithChar (T('~'));
  3992. #endif
  3993. }
  3994. const File File::getChildFile (String relativePath) const throw()
  3995. {
  3996. if (isAbsolutePath (relativePath))
  3997. {
  3998. // the path is really absolute..
  3999. return File (relativePath);
  4000. }
  4001. else
  4002. {
  4003. // it's relative, so remove any ../ or ./ bits at the start.
  4004. String path (fullPath);
  4005. if (relativePath[0] == T('.'))
  4006. {
  4007. #if JUCE_WIN32
  4008. relativePath = relativePath.replaceCharacter (T('/'), T('\\')).trimStart();
  4009. #else
  4010. relativePath = relativePath.replaceCharacter (T('\\'), T('/')).trimStart();
  4011. #endif
  4012. while (relativePath[0] == T('.'))
  4013. {
  4014. if (relativePath[1] == T('.'))
  4015. {
  4016. if (relativePath [2] == 0 || relativePath[2] == separator)
  4017. {
  4018. const int lastSlash = path.lastIndexOfChar (separator);
  4019. if (lastSlash > 0)
  4020. path = path.substring (0, lastSlash);
  4021. relativePath = relativePath.substring (3);
  4022. }
  4023. else
  4024. {
  4025. break;
  4026. }
  4027. }
  4028. else if (relativePath[1] == separator)
  4029. {
  4030. relativePath = relativePath.substring (2);
  4031. }
  4032. else
  4033. {
  4034. break;
  4035. }
  4036. }
  4037. }
  4038. if (! path.endsWithChar (separator))
  4039. path += separator;
  4040. return File (path + relativePath);
  4041. }
  4042. }
  4043. const File File::getSiblingFile (const String& fileName) const throw()
  4044. {
  4045. return getParentDirectory().getChildFile (fileName);
  4046. }
  4047. int64 File::getSize() const throw()
  4048. {
  4049. return juce_getFileSize (fullPath);
  4050. }
  4051. const String File::descriptionOfSizeInBytes (const int64 bytes)
  4052. {
  4053. if (bytes == 1)
  4054. {
  4055. return "1 byte";
  4056. }
  4057. else if (bytes < 1024)
  4058. {
  4059. return String ((int) bytes) + " bytes";
  4060. }
  4061. else if (bytes < 1024 * 1024)
  4062. {
  4063. return String (bytes / 1024.0, 1) + " KB";
  4064. }
  4065. else if (bytes < 1024 * 1024 * 1024)
  4066. {
  4067. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  4068. }
  4069. else
  4070. {
  4071. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  4072. }
  4073. }
  4074. bool File::create() const throw()
  4075. {
  4076. if (! exists())
  4077. {
  4078. const File parentDir (getParentDirectory());
  4079. if (parentDir == *this || ! parentDir.createDirectory())
  4080. return false;
  4081. void* const fh = juce_fileOpen (fullPath, true);
  4082. if (fh == 0)
  4083. return false;
  4084. juce_fileClose (fh);
  4085. }
  4086. return true;
  4087. }
  4088. bool File::createDirectory() const throw()
  4089. {
  4090. if (! isDirectory())
  4091. {
  4092. const File parentDir (getParentDirectory());
  4093. if (parentDir == *this || ! parentDir.createDirectory())
  4094. return false;
  4095. String dir (fullPath);
  4096. while (dir.endsWithChar (separator))
  4097. dir [dir.length() - 1] = 0;
  4098. juce_createDirectory (dir);
  4099. return isDirectory();
  4100. }
  4101. return true;
  4102. }
  4103. const Time File::getCreationTime() const throw()
  4104. {
  4105. int64 m, a, c;
  4106. juce_getFileTimes (fullPath, m, a, c);
  4107. return Time (c);
  4108. }
  4109. bool File::setCreationTime (const Time& t) const throw()
  4110. {
  4111. return juce_setFileTimes (fullPath, 0, 0, t.toMilliseconds());
  4112. }
  4113. const Time File::getLastModificationTime() const throw()
  4114. {
  4115. int64 m, a, c;
  4116. juce_getFileTimes (fullPath, m, a, c);
  4117. return Time (m);
  4118. }
  4119. bool File::setLastModificationTime (const Time& t) const throw()
  4120. {
  4121. return juce_setFileTimes (fullPath, t.toMilliseconds(), 0, 0);
  4122. }
  4123. const Time File::getLastAccessTime() const throw()
  4124. {
  4125. int64 m, a, c;
  4126. juce_getFileTimes (fullPath, m, a, c);
  4127. return Time (a);
  4128. }
  4129. bool File::setLastAccessTime (const Time& t) const throw()
  4130. {
  4131. return juce_setFileTimes (fullPath, 0, t.toMilliseconds(), 0);
  4132. }
  4133. bool File::loadFileAsData (MemoryBlock& destBlock) const throw()
  4134. {
  4135. if (! existsAsFile())
  4136. return false;
  4137. FileInputStream in (*this);
  4138. return getSize() == in.readIntoMemoryBlock (destBlock);
  4139. }
  4140. const String File::loadFileAsString() const throw()
  4141. {
  4142. if (! existsAsFile())
  4143. return String::empty;
  4144. FileInputStream in (*this);
  4145. return in.readEntireStreamAsString();
  4146. }
  4147. static inline bool fileTypeMatches (const int whatToLookFor,
  4148. const bool isDir,
  4149. const bool isHidden)
  4150. {
  4151. return (whatToLookFor & (isDir ? File::findDirectories
  4152. : File::findFiles)) != 0
  4153. && ((! isHidden)
  4154. || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  4155. }
  4156. int File::findChildFiles (OwnedArray<File>& results,
  4157. const int whatToLookFor,
  4158. const bool searchRecursively,
  4159. const String& wildCardPattern) const throw()
  4160. {
  4161. // you have to specify the type of files you're looking for!
  4162. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  4163. int total = 0;
  4164. // find child files or directories in this directory first..
  4165. if (isDirectory())
  4166. {
  4167. String path (fullPath);
  4168. if (! path.endsWithChar (separator))
  4169. path += separator;
  4170. String filename;
  4171. bool isDirectory, isHidden;
  4172. void* const handle = juce_findFileStart (path,
  4173. wildCardPattern,
  4174. filename,
  4175. &isDirectory, &isHidden,
  4176. 0, 0, 0, 0);
  4177. if (handle != 0)
  4178. {
  4179. do
  4180. {
  4181. if (fileTypeMatches (whatToLookFor, isDirectory, isHidden)
  4182. && ! filename.containsOnly (T(".")))
  4183. {
  4184. results.add (new File (path + filename, 0));
  4185. ++total;
  4186. }
  4187. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  4188. juce_findFileClose (handle);
  4189. }
  4190. }
  4191. else
  4192. {
  4193. // trying to search for files inside a non-directory?
  4194. //jassertfalse
  4195. }
  4196. // and recurse down if required.
  4197. if (searchRecursively)
  4198. {
  4199. OwnedArray <File> subDirectories;
  4200. findChildFiles (subDirectories, File::findDirectories, false);
  4201. for (int i = 0; i < subDirectories.size(); ++i)
  4202. {
  4203. total += subDirectories.getUnchecked(i)
  4204. ->findChildFiles (results,
  4205. whatToLookFor,
  4206. true,
  4207. wildCardPattern);
  4208. }
  4209. }
  4210. return total;
  4211. }
  4212. int File::getNumberOfChildFiles (const int whatToLookFor,
  4213. const String& wildCardPattern) const throw()
  4214. {
  4215. // you have to specify the type of files you're looking for!
  4216. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  4217. int count = 0;
  4218. if (isDirectory())
  4219. {
  4220. String filename;
  4221. bool isDirectory, isHidden;
  4222. void* const handle = juce_findFileStart (fullPath,
  4223. wildCardPattern,
  4224. filename,
  4225. &isDirectory, &isHidden,
  4226. 0, 0, 0, 0);
  4227. if (handle != 0)
  4228. {
  4229. do
  4230. {
  4231. if (fileTypeMatches (whatToLookFor, isDirectory, isHidden)
  4232. && ! filename.containsOnly (T(".")))
  4233. {
  4234. ++count;
  4235. }
  4236. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  4237. juce_findFileClose (handle);
  4238. }
  4239. }
  4240. else
  4241. {
  4242. // trying to search for files inside a non-directory?
  4243. jassertfalse
  4244. }
  4245. return count;
  4246. }
  4247. const File File::getNonexistentChildFile (const String& prefix_,
  4248. const String& suffix,
  4249. bool putNumbersInBrackets) const throw()
  4250. {
  4251. File f (getChildFile (prefix_ + suffix));
  4252. if (f.exists())
  4253. {
  4254. int num = 2;
  4255. String prefix (prefix_);
  4256. // remove any bracketed numbers that may already be on the end..
  4257. if (prefix.trim().endsWithChar (T(')')))
  4258. {
  4259. putNumbersInBrackets = true;
  4260. const int openBracks = prefix.lastIndexOfChar (T('('));
  4261. const int closeBracks = prefix.lastIndexOfChar (T(')'));
  4262. if (openBracks > 0
  4263. && closeBracks > openBracks
  4264. && prefix.substring (openBracks + 1, closeBracks).containsOnly (T("0123456789")))
  4265. {
  4266. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  4267. prefix = prefix.substring (0, openBracks);
  4268. }
  4269. }
  4270. // also use brackets if it ends in a digit.
  4271. putNumbersInBrackets = putNumbersInBrackets
  4272. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  4273. do
  4274. {
  4275. if (putNumbersInBrackets)
  4276. f = getChildFile (prefix + T('(') + String (num++) + T(')') + suffix);
  4277. else
  4278. f = getChildFile (prefix + String (num++) + suffix);
  4279. } while (f.exists());
  4280. }
  4281. return f;
  4282. }
  4283. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const throw()
  4284. {
  4285. if (exists())
  4286. {
  4287. return getParentDirectory()
  4288. .getNonexistentChildFile (getFileNameWithoutExtension(),
  4289. getFileExtension(),
  4290. putNumbersInBrackets);
  4291. }
  4292. else
  4293. {
  4294. return *this;
  4295. }
  4296. }
  4297. const String File::getFileExtension() const throw()
  4298. {
  4299. String ext;
  4300. if (! isDirectory())
  4301. {
  4302. const int indexOfDot = fullPath.lastIndexOfChar (T('.'));
  4303. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  4304. ext = fullPath.substring (indexOfDot);
  4305. }
  4306. return ext;
  4307. }
  4308. bool File::hasFileExtension (const String& possibleSuffix) const throw()
  4309. {
  4310. if (possibleSuffix.isEmpty())
  4311. return fullPath.lastIndexOfChar (T('.')) <= fullPath.lastIndexOfChar (separator);
  4312. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  4313. {
  4314. if (possibleSuffix.startsWithChar (T('.')))
  4315. return true;
  4316. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  4317. if (dotPos >= 0)
  4318. return fullPath [dotPos] == T('.');
  4319. }
  4320. return false;
  4321. }
  4322. const File File::withFileExtension (const String& newExtension) const throw()
  4323. {
  4324. if (fullPath.isEmpty())
  4325. return File::nonexistent;
  4326. String filePart (getFileName());
  4327. int i = filePart.lastIndexOfChar (T('.'));
  4328. if (i < 0)
  4329. i = filePart.length();
  4330. String newExt (newExtension);
  4331. if (newExt.isNotEmpty() && ! newExt.startsWithChar (T('.')))
  4332. newExt = T(".") + newExt;
  4333. return getSiblingFile (filePart.substring (0, i) + newExt);
  4334. }
  4335. bool File::startAsProcess (const String& parameters) const throw()
  4336. {
  4337. return exists()
  4338. && juce_launchFile (fullPath, parameters);
  4339. }
  4340. FileInputStream* File::createInputStream() const throw()
  4341. {
  4342. if (existsAsFile())
  4343. return new FileInputStream (*this);
  4344. else
  4345. return 0;
  4346. }
  4347. FileOutputStream* File::createOutputStream (const int bufferSize) const throw()
  4348. {
  4349. FileOutputStream* const out = new FileOutputStream (*this, bufferSize);
  4350. if (out->failedToOpen())
  4351. {
  4352. delete out;
  4353. return 0;
  4354. }
  4355. else
  4356. {
  4357. return out;
  4358. }
  4359. }
  4360. bool File::appendData (const void* const dataToAppend,
  4361. const int numberOfBytes) const throw()
  4362. {
  4363. if (numberOfBytes > 0)
  4364. {
  4365. FileOutputStream* const out = createOutputStream();
  4366. if (out == 0)
  4367. return false;
  4368. out->write (dataToAppend, numberOfBytes);
  4369. delete out;
  4370. }
  4371. return true;
  4372. }
  4373. bool File::replaceWithData (const void* const dataToWrite,
  4374. const int numberOfBytes) const throw()
  4375. {
  4376. jassert (numberOfBytes >= 0); // a negative number of bytes??
  4377. if (numberOfBytes <= 0)
  4378. return deleteFile();
  4379. const File tempFile (getSiblingFile (T(".") + getFileName()).getNonexistentSibling (false));
  4380. if (tempFile.appendData (dataToWrite, numberOfBytes)
  4381. && tempFile.moveFileTo (*this))
  4382. {
  4383. return true;
  4384. }
  4385. tempFile.deleteFile();
  4386. return false;
  4387. }
  4388. bool File::appendText (const String& text,
  4389. const bool asUnicode,
  4390. const bool writeUnicodeHeaderBytes) const throw()
  4391. {
  4392. FileOutputStream* const out = createOutputStream();
  4393. if (out != 0)
  4394. {
  4395. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  4396. delete out;
  4397. return true;
  4398. }
  4399. return false;
  4400. }
  4401. bool File::printf (const tchar* pf, ...) const throw()
  4402. {
  4403. va_list list;
  4404. va_start (list, pf);
  4405. String text;
  4406. text.vprintf (pf, list);
  4407. return appendData ((const char*) text, text.length());
  4408. }
  4409. bool File::replaceWithText (const String& textToWrite,
  4410. const bool asUnicode,
  4411. const bool writeUnicodeHeaderBytes) const throw()
  4412. {
  4413. const File tempFile (getSiblingFile (T(".") + getFileName()).getNonexistentSibling (false));
  4414. if (tempFile.appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes)
  4415. && tempFile.moveFileTo (*this))
  4416. {
  4417. return true;
  4418. }
  4419. tempFile.deleteFile();
  4420. return false;
  4421. }
  4422. const String File::createLegalPathName (const String& original) throw()
  4423. {
  4424. String s (original);
  4425. String start;
  4426. if (s[1] == T(':'))
  4427. {
  4428. start = s.substring (0, 2);
  4429. s = s.substring (2);
  4430. }
  4431. return start + s.removeCharacters (T("\"#@,;:<>*^|?"))
  4432. .substring (0, 1024);
  4433. }
  4434. const String File::createLegalFileName (const String& original) throw()
  4435. {
  4436. String s (original.removeCharacters (T("\"#@,;:<>*^|?\\/")));
  4437. const int maxLength = 128; // only the length of the filename, not the whole path
  4438. const int len = s.length();
  4439. if (len > maxLength)
  4440. {
  4441. const int lastDot = s.lastIndexOfChar (T('.'));
  4442. if (lastDot > jmax (0, len - 12))
  4443. {
  4444. s = s.substring (0, maxLength - (len - lastDot))
  4445. + s.substring (lastDot);
  4446. }
  4447. else
  4448. {
  4449. s = s.substring (0, maxLength);
  4450. }
  4451. }
  4452. return s;
  4453. }
  4454. const String File::getRelativePathFrom (const File& dir) const throw()
  4455. {
  4456. String thisPath (fullPath);
  4457. {
  4458. int len = thisPath.length();
  4459. while (--len >= 0 && thisPath [len] == File::separator)
  4460. thisPath [len] = 0;
  4461. }
  4462. String dirPath ((dir.existsAsFile()) ? dir.getParentDirectory().getFullPathName()
  4463. : dir.fullPath);
  4464. if (! dirPath.endsWithChar (separator))
  4465. dirPath += separator;
  4466. const int len = jmin (thisPath.length(), dirPath.length());
  4467. int commonBitLength = 0;
  4468. for (int i = 0; i < len; ++i)
  4469. {
  4470. #if NAMES_ARE_CASE_SENSITIVE
  4471. if (thisPath[i] != dirPath[i])
  4472. #else
  4473. if (CharacterFunctions::toLowerCase (thisPath[i])
  4474. != CharacterFunctions::toLowerCase (dirPath[i]))
  4475. #endif
  4476. {
  4477. break;
  4478. }
  4479. ++commonBitLength;
  4480. }
  4481. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  4482. --commonBitLength;
  4483. // if the only common bit is the root, then just return the full path..
  4484. #if JUCE_WIN32
  4485. if (commonBitLength <= 0
  4486. || (commonBitLength == 1 && thisPath [1] == File::separator)
  4487. || (commonBitLength <= 3 && thisPath [1] == T(':')))
  4488. #else
  4489. if (commonBitLength <= 0
  4490. || (commonBitLength == 1 && thisPath [1] == File::separator))
  4491. #endif
  4492. return fullPath;
  4493. thisPath = thisPath.substring (commonBitLength);
  4494. dirPath = dirPath.substring (commonBitLength);
  4495. while (dirPath.isNotEmpty())
  4496. {
  4497. #if JUCE_WIN32
  4498. thisPath = T("..\\") + thisPath;
  4499. #else
  4500. thisPath = T("../") + thisPath;
  4501. #endif
  4502. const int sep = dirPath.indexOfChar (separator);
  4503. if (sep >= 0)
  4504. dirPath = dirPath.substring (sep + 1);
  4505. else
  4506. dirPath = String::empty;
  4507. }
  4508. return thisPath;
  4509. }
  4510. void File::findFileSystemRoots (OwnedArray<File>& destArray) throw()
  4511. {
  4512. const StringArray roots (juce_getFileSystemRoots());
  4513. for (int i = 0; i < roots.size(); ++i)
  4514. destArray.add (new File (roots[i]));
  4515. }
  4516. const String File::getVolumeLabel() const throw()
  4517. {
  4518. int serialNum;
  4519. return juce_getVolumeLabel (fullPath, serialNum);
  4520. }
  4521. int File::getVolumeSerialNumber() const throw()
  4522. {
  4523. int serialNum;
  4524. juce_getVolumeLabel (fullPath, serialNum);
  4525. return serialNum;
  4526. }
  4527. const File File::createTempFile (const String& fileNameEnding) throw()
  4528. {
  4529. String tempName (T("temp"));
  4530. static int tempNum = 0;
  4531. tempName << tempNum++ << fileNameEnding;
  4532. const File tempFile (getSpecialLocation (tempDirectory)
  4533. .getChildFile (tempName));
  4534. if (tempFile.exists())
  4535. return createTempFile (fileNameEnding);
  4536. else
  4537. return tempFile;
  4538. }
  4539. END_JUCE_NAMESPACE
  4540. /********* End of inlined file: juce_File.cpp *********/
  4541. /********* Start of inlined file: juce_FileInputStream.cpp *********/
  4542. BEGIN_JUCE_NAMESPACE
  4543. void* juce_fileOpen (const String& path, bool forWriting) throw();
  4544. void juce_fileClose (void* handle) throw();
  4545. int juce_fileRead (void* handle, void* buffer, int size) throw();
  4546. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  4547. FileInputStream::FileInputStream (const File& f)
  4548. : file (f),
  4549. currentPosition (0),
  4550. needToSeek (true)
  4551. {
  4552. totalSize = f.getSize();
  4553. fileHandle = juce_fileOpen (f.getFullPathName(), false);
  4554. }
  4555. FileInputStream::~FileInputStream()
  4556. {
  4557. juce_fileClose (fileHandle);
  4558. }
  4559. int64 FileInputStream::getTotalLength()
  4560. {
  4561. return totalSize;
  4562. }
  4563. int FileInputStream::read (void* buffer, int bytesToRead)
  4564. {
  4565. int num = 0;
  4566. if (needToSeek)
  4567. {
  4568. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  4569. return 0;
  4570. needToSeek = false;
  4571. }
  4572. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  4573. currentPosition += num;
  4574. return num;
  4575. }
  4576. bool FileInputStream::isExhausted()
  4577. {
  4578. return currentPosition >= totalSize;
  4579. }
  4580. int64 FileInputStream::getPosition()
  4581. {
  4582. return currentPosition;
  4583. }
  4584. bool FileInputStream::setPosition (int64 pos)
  4585. {
  4586. pos = jlimit ((int64) 0, totalSize, pos);
  4587. needToSeek |= (currentPosition != pos);
  4588. currentPosition = pos;
  4589. return true;
  4590. }
  4591. END_JUCE_NAMESPACE
  4592. /********* End of inlined file: juce_FileInputStream.cpp *********/
  4593. /********* Start of inlined file: juce_FileOutputStream.cpp *********/
  4594. BEGIN_JUCE_NAMESPACE
  4595. void* juce_fileOpen (const String& path, bool forWriting) throw();
  4596. void juce_fileClose (void* handle) throw();
  4597. int juce_fileWrite (void* handle, const void* buffer, int size) throw();
  4598. void juce_fileFlush (void* handle) throw();
  4599. int64 juce_fileGetPosition (void* handle) throw();
  4600. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  4601. FileOutputStream::FileOutputStream (const File& f,
  4602. const int bufferSize_)
  4603. : file (f),
  4604. bufferSize (bufferSize_),
  4605. bytesInBuffer (0)
  4606. {
  4607. fileHandle = juce_fileOpen (f.getFullPathName(), true);
  4608. if (fileHandle != 0)
  4609. {
  4610. currentPosition = juce_fileGetPosition (fileHandle);
  4611. if (currentPosition < 0)
  4612. {
  4613. jassertfalse
  4614. juce_fileClose (fileHandle);
  4615. fileHandle = 0;
  4616. }
  4617. }
  4618. buffer = (char*) juce_malloc (jmax (bufferSize_, 16));
  4619. }
  4620. FileOutputStream::~FileOutputStream()
  4621. {
  4622. flush();
  4623. juce_fileClose (fileHandle);
  4624. juce_free (buffer);
  4625. }
  4626. int64 FileOutputStream::getPosition()
  4627. {
  4628. return currentPosition;
  4629. }
  4630. bool FileOutputStream::setPosition (int64 newPosition)
  4631. {
  4632. if (newPosition != currentPosition)
  4633. {
  4634. flush();
  4635. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  4636. }
  4637. return newPosition == currentPosition;
  4638. }
  4639. void FileOutputStream::flush()
  4640. {
  4641. if (bytesInBuffer > 0)
  4642. {
  4643. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  4644. bytesInBuffer = 0;
  4645. }
  4646. juce_fileFlush (fileHandle);
  4647. }
  4648. bool FileOutputStream::write (const void* const src, const int numBytes)
  4649. {
  4650. if (bytesInBuffer + numBytes < bufferSize)
  4651. {
  4652. memcpy (buffer + bytesInBuffer, src, numBytes);
  4653. bytesInBuffer += numBytes;
  4654. currentPosition += numBytes;
  4655. }
  4656. else
  4657. {
  4658. if (bytesInBuffer > 0)
  4659. {
  4660. // flush the reservoir
  4661. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  4662. bytesInBuffer = 0;
  4663. if (! wroteOk)
  4664. return false;
  4665. }
  4666. if (numBytes < bufferSize)
  4667. {
  4668. memcpy (buffer + bytesInBuffer, src, numBytes);
  4669. bytesInBuffer += numBytes;
  4670. currentPosition += numBytes;
  4671. }
  4672. else
  4673. {
  4674. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  4675. currentPosition += bytesWritten;
  4676. return bytesWritten == numBytes;
  4677. }
  4678. }
  4679. return true;
  4680. }
  4681. END_JUCE_NAMESPACE
  4682. /********* End of inlined file: juce_FileOutputStream.cpp *********/
  4683. /********* Start of inlined file: juce_FileSearchPath.cpp *********/
  4684. BEGIN_JUCE_NAMESPACE
  4685. FileSearchPath::FileSearchPath()
  4686. {
  4687. }
  4688. FileSearchPath::FileSearchPath (const String& path)
  4689. {
  4690. init (path);
  4691. }
  4692. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  4693. : directories (other.directories)
  4694. {
  4695. }
  4696. FileSearchPath::~FileSearchPath()
  4697. {
  4698. }
  4699. const FileSearchPath& FileSearchPath::operator= (const String& path)
  4700. {
  4701. init (path);
  4702. return *this;
  4703. }
  4704. void FileSearchPath::init (const String& path)
  4705. {
  4706. directories.clear();
  4707. directories.addTokens (path, T(";"), T("\""));
  4708. directories.trim();
  4709. directories.removeEmptyStrings();
  4710. for (int i = directories.size(); --i >= 0;)
  4711. directories.set (i, directories[i].unquoted());
  4712. }
  4713. int FileSearchPath::getNumPaths() const
  4714. {
  4715. return directories.size();
  4716. }
  4717. const File FileSearchPath::operator[] (const int index) const
  4718. {
  4719. return File (directories [index]);
  4720. }
  4721. const String FileSearchPath::toString() const
  4722. {
  4723. StringArray directories2 (directories);
  4724. for (int i = directories2.size(); --i >= 0;)
  4725. if (directories2[i].containsChar (T(';')))
  4726. directories2.set (i, directories2[i].quoted());
  4727. return directories2.joinIntoString (T(";"));
  4728. }
  4729. void FileSearchPath::add (const File& dir, const int insertIndex)
  4730. {
  4731. directories.insert (insertIndex, dir.getFullPathName());
  4732. }
  4733. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  4734. {
  4735. for (int i = 0; i < directories.size(); ++i)
  4736. if (File (directories[i]) == dir)
  4737. return;
  4738. add (dir);
  4739. }
  4740. void FileSearchPath::remove (const int index)
  4741. {
  4742. directories.remove (index);
  4743. }
  4744. void FileSearchPath::addPath (const FileSearchPath& other)
  4745. {
  4746. for (int i = 0; i < other.getNumPaths(); ++i)
  4747. addIfNotAlreadyThere (other[i]);
  4748. }
  4749. void FileSearchPath::removeRedundantPaths()
  4750. {
  4751. for (int i = directories.size(); --i >= 0;)
  4752. {
  4753. const File d1 (directories[i]);
  4754. for (int j = directories.size(); --j >= 0;)
  4755. {
  4756. const File d2 (directories[j]);
  4757. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  4758. {
  4759. directories.remove (i);
  4760. break;
  4761. }
  4762. }
  4763. }
  4764. }
  4765. void FileSearchPath::removeNonExistentPaths()
  4766. {
  4767. for (int i = directories.size(); --i >= 0;)
  4768. if (! File (directories[i]).isDirectory())
  4769. directories.remove (i);
  4770. }
  4771. int FileSearchPath::findChildFiles (OwnedArray<File>& results,
  4772. const int whatToLookFor,
  4773. const bool searchRecursively,
  4774. const String& wildCardPattern) const
  4775. {
  4776. int total = 0;
  4777. for (int i = 0; i < directories.size(); ++i)
  4778. total += operator[] (i).findChildFiles (results,
  4779. whatToLookFor,
  4780. searchRecursively,
  4781. wildCardPattern);
  4782. return total;
  4783. }
  4784. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  4785. const bool checkRecursively) const
  4786. {
  4787. for (int i = directories.size(); --i >= 0;)
  4788. {
  4789. const File d (directories[i]);
  4790. if (checkRecursively)
  4791. {
  4792. if (fileToCheck.isAChildOf (d))
  4793. return true;
  4794. }
  4795. else
  4796. {
  4797. if (fileToCheck.getParentDirectory() == d)
  4798. return true;
  4799. }
  4800. }
  4801. return false;
  4802. }
  4803. END_JUCE_NAMESPACE
  4804. /********* End of inlined file: juce_FileSearchPath.cpp *********/
  4805. /********* Start of inlined file: juce_NamedPipe.cpp *********/
  4806. BEGIN_JUCE_NAMESPACE
  4807. NamedPipe::NamedPipe()
  4808. : internal (0)
  4809. {
  4810. }
  4811. NamedPipe::~NamedPipe()
  4812. {
  4813. close();
  4814. }
  4815. bool NamedPipe::openExisting (const String& pipeName)
  4816. {
  4817. currentPipeName = pipeName;
  4818. return openInternal (pipeName, false);
  4819. }
  4820. bool NamedPipe::createNewPipe (const String& pipeName)
  4821. {
  4822. currentPipeName = pipeName;
  4823. return openInternal (pipeName, true);
  4824. }
  4825. bool NamedPipe::isOpen() const throw()
  4826. {
  4827. return internal != 0;
  4828. }
  4829. const String NamedPipe::getName() const throw()
  4830. {
  4831. return currentPipeName;
  4832. }
  4833. // other methods for this class are implemented in the platform-specific files
  4834. END_JUCE_NAMESPACE
  4835. /********* End of inlined file: juce_NamedPipe.cpp *********/
  4836. /********* Start of inlined file: juce_Socket.cpp *********/
  4837. #ifdef _WIN32
  4838. #include <winsock2.h>
  4839. #ifdef _MSC_VER
  4840. #pragma warning (disable : 4127 4389 4018)
  4841. #endif
  4842. #else
  4843. #ifndef LINUX
  4844. #include <Carbon/Carbon.h>
  4845. #endif
  4846. #include <sys/types.h>
  4847. #include <netdb.h>
  4848. #include <sys/socket.h>
  4849. #include <arpa/inet.h>
  4850. #include <sys/errno.h>
  4851. #include <netinet/tcp.h>
  4852. #include <netinet/in.h>
  4853. #include <fcntl.h>
  4854. #include <unistd.h>
  4855. #endif
  4856. BEGIN_JUCE_NAMESPACE
  4857. #if JUCE_WIN32
  4858. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  4859. juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  4860. static void initWin32Sockets()
  4861. {
  4862. static CriticalSection lock;
  4863. const ScopedLock sl (lock);
  4864. if (juce_CloseWin32SocketLib == 0)
  4865. {
  4866. WSADATA wsaData;
  4867. const WORD wVersionRequested = MAKEWORD (1, 1);
  4868. WSAStartup (wVersionRequested, &wsaData);
  4869. juce_CloseWin32SocketLib = &WSACleanup;
  4870. }
  4871. }
  4872. #endif
  4873. static bool resetSocketOptions (const int handle, const bool isDatagram) throw()
  4874. {
  4875. if (handle <= 0)
  4876. return false;
  4877. const int sndBufSize = 65536;
  4878. const int rcvBufSize = 65536;
  4879. const int one = 1;
  4880. return setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (int)) == 0
  4881. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (int)) == 0
  4882. && (isDatagram || (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (int)) == 0));
  4883. }
  4884. static bool bindSocketToPort (const int handle, const int port) throw()
  4885. {
  4886. if (handle == 0 || port <= 0)
  4887. return false;
  4888. struct sockaddr_in servTmpAddr;
  4889. zerostruct (servTmpAddr);
  4890. servTmpAddr.sin_family = PF_INET;
  4891. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  4892. servTmpAddr.sin_port = htons ((uint16) port);
  4893. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  4894. }
  4895. static int readSocket (const int handle,
  4896. void* const destBuffer, const int maxBytesToRead,
  4897. bool volatile& connected) throw()
  4898. {
  4899. int bytesRead = 0;
  4900. while (bytesRead < maxBytesToRead)
  4901. {
  4902. int bytesThisTime;
  4903. #if JUCE_WIN32
  4904. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  4905. #else
  4906. while ((bytesThisTime = ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  4907. && errno == EINTR
  4908. && connected)
  4909. {
  4910. }
  4911. #endif
  4912. if (bytesThisTime <= 0 || ! connected)
  4913. {
  4914. if (bytesRead == 0)
  4915. bytesRead = -1;
  4916. break;
  4917. }
  4918. bytesRead += bytesThisTime;
  4919. }
  4920. return bytesRead;
  4921. }
  4922. static int waitForReadiness (const int handle, const bool forReading,
  4923. const int timeoutMsecs) throw()
  4924. {
  4925. struct timeval timeout;
  4926. struct timeval* timeoutp;
  4927. if (timeoutMsecs >= 0)
  4928. {
  4929. timeout.tv_sec = timeoutMsecs / 1000;
  4930. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  4931. timeoutp = &timeout;
  4932. }
  4933. else
  4934. {
  4935. timeoutp = 0;
  4936. }
  4937. fd_set rset, wset;
  4938. FD_ZERO (&rset);
  4939. FD_SET (handle, &rset);
  4940. FD_ZERO (&wset);
  4941. FD_SET (handle, &wset);
  4942. fd_set* const prset = forReading ? &rset : 0;
  4943. fd_set* const pwset = forReading ? 0 : &wset;
  4944. #if JUCE_WIN32
  4945. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  4946. return -1;
  4947. #else
  4948. {
  4949. int result;
  4950. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  4951. && errno == EINTR)
  4952. {
  4953. }
  4954. if (result < 0)
  4955. return -1;
  4956. }
  4957. #endif
  4958. {
  4959. int opt;
  4960. #if defined (JUCE_LINUX) || (defined (JUCE_MAC) && ! MACOS_10_2_OR_EARLIER)
  4961. socklen_t len = sizeof (opt);
  4962. #else
  4963. int len = sizeof (opt);
  4964. #endif
  4965. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  4966. || opt != 0)
  4967. return -1;
  4968. }
  4969. if ((forReading && FD_ISSET (handle, &rset))
  4970. || ((! forReading) && FD_ISSET (handle, &wset)))
  4971. return 1;
  4972. return 0;
  4973. }
  4974. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  4975. {
  4976. #if JUCE_WIN32
  4977. u_long nonBlocking = shouldBlock ? 0 : 1;
  4978. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  4979. return false;
  4980. #else
  4981. int socketFlags = fcntl (handle, F_GETFL, 0);
  4982. if (socketFlags == -1)
  4983. return false;
  4984. if (shouldBlock)
  4985. socketFlags &= ~O_NONBLOCK;
  4986. else
  4987. socketFlags |= O_NONBLOCK;
  4988. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  4989. return false;
  4990. #endif
  4991. return true;
  4992. }
  4993. static bool connectSocket (int volatile& handle,
  4994. const bool isDatagram,
  4995. void** serverAddress,
  4996. const String& hostName,
  4997. const int portNumber,
  4998. const int timeOutMillisecs) throw()
  4999. {
  5000. struct hostent* const hostEnt = gethostbyname (hostName);
  5001. if (hostEnt == 0)
  5002. return false;
  5003. struct in_addr targetAddress;
  5004. memcpy (&targetAddress.s_addr,
  5005. *(hostEnt->h_addr_list),
  5006. sizeof (targetAddress.s_addr));
  5007. struct sockaddr_in servTmpAddr;
  5008. zerostruct (servTmpAddr);
  5009. servTmpAddr.sin_family = PF_INET;
  5010. servTmpAddr.sin_addr = targetAddress;
  5011. servTmpAddr.sin_port = htons ((uint16) portNumber);
  5012. if (handle < 0)
  5013. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  5014. if (handle < 0)
  5015. return false;
  5016. if (isDatagram)
  5017. {
  5018. *serverAddress = new struct sockaddr_in();
  5019. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  5020. return true;
  5021. }
  5022. setSocketBlockingState (handle, false);
  5023. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  5024. if (result < 0)
  5025. {
  5026. #if JUCE_WIN32
  5027. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  5028. #else
  5029. if (errno == EINPROGRESS)
  5030. #endif
  5031. {
  5032. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  5033. {
  5034. setSocketBlockingState (handle, true);
  5035. return false;
  5036. }
  5037. }
  5038. }
  5039. setSocketBlockingState (handle, true);
  5040. resetSocketOptions (handle, false);
  5041. return true;
  5042. }
  5043. StreamingSocket::StreamingSocket()
  5044. : portNumber (0),
  5045. handle (-1),
  5046. connected (false),
  5047. isListener (false)
  5048. {
  5049. #if JUCE_WIN32
  5050. initWin32Sockets();
  5051. #endif
  5052. }
  5053. StreamingSocket::StreamingSocket (const String& hostName_,
  5054. const int portNumber_,
  5055. const int handle_)
  5056. : hostName (hostName_),
  5057. portNumber (portNumber_),
  5058. handle (handle_),
  5059. connected (true),
  5060. isListener (false)
  5061. {
  5062. #if JUCE_WIN32
  5063. initWin32Sockets();
  5064. #endif
  5065. resetSocketOptions (handle_, false);
  5066. }
  5067. StreamingSocket::~StreamingSocket()
  5068. {
  5069. close();
  5070. }
  5071. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead)
  5072. {
  5073. return (connected && ! isListener) ? readSocket (handle, destBuffer, maxBytesToRead, connected)
  5074. : -1;
  5075. }
  5076. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  5077. {
  5078. if (isListener || ! connected)
  5079. return -1;
  5080. #if JUCE_WIN32
  5081. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  5082. #else
  5083. int result;
  5084. while ((result = ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  5085. && errno == EINTR)
  5086. {
  5087. }
  5088. return result;
  5089. #endif
  5090. }
  5091. int StreamingSocket::waitUntilReady (const bool readyForReading,
  5092. const int timeoutMsecs) const
  5093. {
  5094. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  5095. : -1;
  5096. }
  5097. bool StreamingSocket::bindToPort (const int port)
  5098. {
  5099. return bindSocketToPort (handle, port);
  5100. }
  5101. bool StreamingSocket::connect (const String& remoteHostName,
  5102. const int remotePortNumber,
  5103. const int timeOutMillisecs)
  5104. {
  5105. if (isListener)
  5106. {
  5107. jassertfalse // a listener socket can't connect to another one!
  5108. return false;
  5109. }
  5110. if (connected)
  5111. close();
  5112. hostName = remoteHostName;
  5113. portNumber = remotePortNumber;
  5114. isListener = false;
  5115. connected = connectSocket (handle, false, 0, remoteHostName,
  5116. remotePortNumber, timeOutMillisecs);
  5117. if (! (connected && resetSocketOptions (handle, false)))
  5118. {
  5119. close();
  5120. return false;
  5121. }
  5122. return true;
  5123. }
  5124. void StreamingSocket::close()
  5125. {
  5126. #if JUCE_WIN32
  5127. closesocket (handle);
  5128. connected = false;
  5129. #else
  5130. if (connected)
  5131. {
  5132. connected = false;
  5133. if (isListener)
  5134. {
  5135. // need to do this to interrupt the accept() function..
  5136. StreamingSocket temp;
  5137. temp.connect ("localhost", portNumber, 1000);
  5138. }
  5139. }
  5140. ::close (handle);
  5141. #endif
  5142. hostName = String::empty;
  5143. portNumber = 0;
  5144. handle = -1;
  5145. isListener = false;
  5146. }
  5147. bool StreamingSocket::createListener (const int newPortNumber)
  5148. {
  5149. if (connected)
  5150. close();
  5151. hostName = "listener";
  5152. portNumber = newPortNumber;
  5153. isListener = true;
  5154. struct sockaddr_in servTmpAddr;
  5155. zerostruct (servTmpAddr);
  5156. servTmpAddr.sin_family = PF_INET;
  5157. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  5158. servTmpAddr.sin_port = htons ((uint16) portNumber);
  5159. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  5160. if (handle < 0)
  5161. return false;
  5162. const int reuse = 1;
  5163. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  5164. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  5165. || listen (handle, SOMAXCONN) < 0)
  5166. {
  5167. close();
  5168. return false;
  5169. }
  5170. connected = true;
  5171. return true;
  5172. }
  5173. StreamingSocket* StreamingSocket::waitForNextConnection() const
  5174. {
  5175. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  5176. // prepare this socket as a listener.
  5177. if (connected && isListener)
  5178. {
  5179. struct sockaddr address;
  5180. #if defined (JUCE_LINUX) || (defined (JUCE_MAC) && ! MACOS_10_2_OR_EARLIER)
  5181. socklen_t len = sizeof (sockaddr);
  5182. #else
  5183. int len = sizeof (sockaddr);
  5184. #endif
  5185. const int newSocket = (int) accept (handle, &address, &len);
  5186. if (newSocket >= 0 && connected)
  5187. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  5188. portNumber, newSocket);
  5189. }
  5190. return 0;
  5191. }
  5192. bool StreamingSocket::isLocal() const throw()
  5193. {
  5194. return hostName == T("127.0.0.1");
  5195. }
  5196. DatagramSocket::DatagramSocket (const int localPortNumber)
  5197. : portNumber (0),
  5198. handle (-1),
  5199. connected (false),
  5200. serverAddress (0)
  5201. {
  5202. #if JUCE_WIN32
  5203. initWin32Sockets();
  5204. #endif
  5205. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  5206. bindToPort (localPortNumber);
  5207. }
  5208. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  5209. const int handle_, const int localPortNumber)
  5210. : hostName (hostName_),
  5211. portNumber (portNumber_),
  5212. handle (handle_),
  5213. connected (true),
  5214. serverAddress (0)
  5215. {
  5216. #if JUCE_WIN32
  5217. initWin32Sockets();
  5218. #endif
  5219. resetSocketOptions (handle_, true);
  5220. bindToPort (localPortNumber);
  5221. }
  5222. DatagramSocket::~DatagramSocket()
  5223. {
  5224. close();
  5225. delete ((struct sockaddr_in*) serverAddress);
  5226. serverAddress = 0;
  5227. }
  5228. void DatagramSocket::close()
  5229. {
  5230. #if JUCE_WIN32
  5231. closesocket (handle);
  5232. connected = false;
  5233. #else
  5234. connected = false;
  5235. ::close (handle);
  5236. #endif
  5237. hostName = String::empty;
  5238. portNumber = 0;
  5239. handle = -1;
  5240. }
  5241. bool DatagramSocket::bindToPort (const int port)
  5242. {
  5243. return bindSocketToPort (handle, port);
  5244. }
  5245. bool DatagramSocket::connect (const String& remoteHostName,
  5246. const int remotePortNumber,
  5247. const int timeOutMillisecs)
  5248. {
  5249. if (connected)
  5250. close();
  5251. hostName = remoteHostName;
  5252. portNumber = remotePortNumber;
  5253. connected = connectSocket (handle, true, &serverAddress,
  5254. remoteHostName, remotePortNumber,
  5255. timeOutMillisecs);
  5256. if (! (connected && resetSocketOptions (handle, true)))
  5257. {
  5258. close();
  5259. return false;
  5260. }
  5261. return true;
  5262. }
  5263. DatagramSocket* DatagramSocket::waitForNextConnection() const
  5264. {
  5265. struct sockaddr address;
  5266. #if defined (JUCE_LINUX) || (defined (JUCE_MAC) && ! MACOS_10_2_OR_EARLIER)
  5267. socklen_t len = sizeof (sockaddr);
  5268. #else
  5269. int len = sizeof (sockaddr);
  5270. #endif
  5271. while (waitUntilReady (true, -1) == 1)
  5272. {
  5273. char buf[1];
  5274. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  5275. {
  5276. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  5277. ntohs (((struct sockaddr_in*) &address)->sin_port),
  5278. -1, -1);
  5279. }
  5280. }
  5281. return 0;
  5282. }
  5283. int DatagramSocket::waitUntilReady (const bool readyForReading,
  5284. const int timeoutMsecs) const
  5285. {
  5286. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  5287. : -1;
  5288. }
  5289. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead)
  5290. {
  5291. return connected ? readSocket (handle, destBuffer, maxBytesToRead, connected)
  5292. : -1;
  5293. }
  5294. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  5295. {
  5296. // You need to call connect() first to set the server address..
  5297. jassert (serverAddress != 0 && connected);
  5298. return connected ? sendto (handle, (const char*) sourceBuffer,
  5299. numBytesToWrite, 0,
  5300. (const struct sockaddr*) serverAddress,
  5301. sizeof (struct sockaddr_in))
  5302. : -1;
  5303. }
  5304. bool DatagramSocket::isLocal() const throw()
  5305. {
  5306. return hostName == T("127.0.0.1");
  5307. }
  5308. END_JUCE_NAMESPACE
  5309. /********* End of inlined file: juce_Socket.cpp *********/
  5310. /********* Start of inlined file: juce_URL.cpp *********/
  5311. BEGIN_JUCE_NAMESPACE
  5312. URL::URL() throw()
  5313. {
  5314. }
  5315. URL::URL (const String& url_)
  5316. : url (url_)
  5317. {
  5318. int i = url.indexOfChar (T('?'));
  5319. if (i >= 0)
  5320. {
  5321. do
  5322. {
  5323. const int nextAmp = url.indexOfChar (i + 1, T('&'));
  5324. const int equalsPos = url.indexOfChar (i + 1, T('='));
  5325. if (equalsPos > i + 1)
  5326. {
  5327. if (nextAmp < 0)
  5328. {
  5329. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  5330. removeEscapeChars (url.substring (equalsPos + 1)));
  5331. }
  5332. else if (nextAmp > 0 && equalsPos < nextAmp)
  5333. {
  5334. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  5335. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  5336. }
  5337. }
  5338. i = nextAmp;
  5339. }
  5340. while (i >= 0);
  5341. url = url.upToFirstOccurrenceOf (T("?"), false, false);
  5342. }
  5343. }
  5344. URL::URL (const URL& other)
  5345. : url (other.url),
  5346. parameters (other.parameters),
  5347. filesToUpload (other.filesToUpload),
  5348. mimeTypes (other.mimeTypes)
  5349. {
  5350. }
  5351. const URL& URL::operator= (const URL& other)
  5352. {
  5353. url = other.url;
  5354. parameters = other.parameters;
  5355. filesToUpload = other.filesToUpload;
  5356. mimeTypes = other.mimeTypes;
  5357. return *this;
  5358. }
  5359. URL::~URL() throw()
  5360. {
  5361. }
  5362. static const String getMangledParameters (const StringPairArray& parameters)
  5363. {
  5364. String p;
  5365. for (int i = 0; i < parameters.size(); ++i)
  5366. {
  5367. if (i > 0)
  5368. p += T("&");
  5369. p << URL::addEscapeChars (parameters.getAllKeys() [i])
  5370. << T("=")
  5371. << URL::addEscapeChars (parameters.getAllValues() [i]);
  5372. }
  5373. return p;
  5374. }
  5375. const String URL::toString (const bool includeGetParameters) const
  5376. {
  5377. if (includeGetParameters && parameters.size() > 0)
  5378. return url + T("?") + getMangledParameters (parameters);
  5379. else
  5380. return url;
  5381. }
  5382. bool URL::isWellFormed() const
  5383. {
  5384. //xxx TODO
  5385. return url.isNotEmpty();
  5386. }
  5387. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  5388. {
  5389. return (possibleURL.containsChar (T('.'))
  5390. && (! possibleURL.containsChar (T('@')))
  5391. && (! possibleURL.endsWithChar (T('.')))
  5392. && (possibleURL.startsWithIgnoreCase (T("www."))
  5393. || possibleURL.startsWithIgnoreCase (T("http:"))
  5394. || possibleURL.startsWithIgnoreCase (T("ftp:"))
  5395. || possibleURL.endsWithIgnoreCase (T(".com"))
  5396. || possibleURL.endsWithIgnoreCase (T(".net"))
  5397. || possibleURL.endsWithIgnoreCase (T(".org"))
  5398. || possibleURL.endsWithIgnoreCase (T(".co.uk")))
  5399. || possibleURL.startsWithIgnoreCase (T("file:")));
  5400. }
  5401. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  5402. {
  5403. const int atSign = possibleEmailAddress.indexOfChar (T('@'));
  5404. return atSign > 0
  5405. && possibleEmailAddress.lastIndexOfChar (T('.')) > (atSign + 1)
  5406. && (! possibleEmailAddress.endsWithChar (T('.')));
  5407. }
  5408. void* juce_openInternetFile (const String& url,
  5409. const String& headers,
  5410. const MemoryBlock& optionalPostData,
  5411. const bool isPost,
  5412. URL::OpenStreamProgressCallback* callback,
  5413. void* callbackContext,
  5414. int timeOutMs);
  5415. void juce_closeInternetFile (void* handle);
  5416. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  5417. int juce_seekInInternetFile (void* handle, int newPosition);
  5418. class WebInputStream : public InputStream
  5419. {
  5420. public:
  5421. WebInputStream (const URL& url,
  5422. const bool isPost_,
  5423. URL::OpenStreamProgressCallback* const progressCallback_,
  5424. void* const progressCallbackContext_,
  5425. const String& extraHeaders,
  5426. int timeOutMs_)
  5427. : position (0),
  5428. finished (false),
  5429. isPost (isPost_),
  5430. progressCallback (progressCallback_),
  5431. progressCallbackContext (progressCallbackContext_),
  5432. timeOutMs (timeOutMs_)
  5433. {
  5434. server = url.toString (! isPost);
  5435. if (isPost_)
  5436. createHeadersAndPostData (url);
  5437. headers += extraHeaders;
  5438. if (! headers.endsWithChar (T('\n')))
  5439. headers << "\r\n";
  5440. handle = juce_openInternetFile (server, headers, postData, isPost,
  5441. progressCallback_, progressCallbackContext_,
  5442. timeOutMs);
  5443. }
  5444. ~WebInputStream()
  5445. {
  5446. juce_closeInternetFile (handle);
  5447. }
  5448. bool isError() const throw()
  5449. {
  5450. return handle == 0;
  5451. }
  5452. int64 getTotalLength()
  5453. {
  5454. return -1;
  5455. }
  5456. bool isExhausted()
  5457. {
  5458. return finished;
  5459. }
  5460. int read (void* dest, int bytes)
  5461. {
  5462. if (finished || isError())
  5463. {
  5464. return 0;
  5465. }
  5466. else
  5467. {
  5468. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  5469. position += bytesRead;
  5470. if (bytesRead == 0)
  5471. finished = true;
  5472. return bytesRead;
  5473. }
  5474. }
  5475. int64 getPosition()
  5476. {
  5477. return position;
  5478. }
  5479. bool setPosition (int64 wantedPos)
  5480. {
  5481. if (wantedPos != position)
  5482. {
  5483. finished = false;
  5484. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  5485. if (actualPos == wantedPos)
  5486. {
  5487. position = wantedPos;
  5488. }
  5489. else
  5490. {
  5491. if (wantedPos < position)
  5492. {
  5493. juce_closeInternetFile (handle);
  5494. position = 0;
  5495. finished = false;
  5496. handle = juce_openInternetFile (server, headers, postData, isPost,
  5497. progressCallback, progressCallbackContext,
  5498. timeOutMs);
  5499. }
  5500. skipNextBytes (wantedPos - position);
  5501. }
  5502. }
  5503. return true;
  5504. }
  5505. juce_UseDebuggingNewOperator
  5506. private:
  5507. String server, headers;
  5508. MemoryBlock postData;
  5509. int64 position;
  5510. bool finished;
  5511. const bool isPost;
  5512. void* handle;
  5513. URL::OpenStreamProgressCallback* const progressCallback;
  5514. void* const progressCallbackContext;
  5515. const int timeOutMs;
  5516. void createHeadersAndPostData (const URL& url)
  5517. {
  5518. if (url.getFilesToUpload().size() > 0)
  5519. {
  5520. // need to upload some files, so do it as multi-part...
  5521. String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  5522. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  5523. appendUTF8ToPostData ("--" + boundary);
  5524. int i;
  5525. for (i = 0; i < url.getParameters().size(); ++i)
  5526. {
  5527. String s;
  5528. s << "\r\nContent-Disposition: form-data; name=\""
  5529. << url.getParameters().getAllKeys() [i]
  5530. << "\"\r\n\r\n"
  5531. << url.getParameters().getAllValues() [i]
  5532. << "\r\n--"
  5533. << boundary;
  5534. appendUTF8ToPostData (s);
  5535. }
  5536. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  5537. {
  5538. const File f (url.getFilesToUpload().getAllValues() [i]);
  5539. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  5540. String s;
  5541. s << "\r\nContent-Disposition: form-data; name=\""
  5542. << paramName
  5543. << "\"; filename=\""
  5544. << f.getFileName()
  5545. << "\"\r\n";
  5546. const String mimeType (url.getMimeTypesOfUploadFiles()
  5547. .getValue (paramName, String::empty));
  5548. if (mimeType.isNotEmpty())
  5549. s << "Content-Type: " << mimeType << "\r\n";
  5550. s << "Content-Transfer-Encoding: binary\r\n\r\n";
  5551. appendUTF8ToPostData (s);
  5552. f.loadFileAsData (postData);
  5553. s = "\r\n--" + boundary;
  5554. appendUTF8ToPostData (s);
  5555. }
  5556. appendUTF8ToPostData ("--\r\n");
  5557. }
  5558. else
  5559. {
  5560. // just a short text attachment, so use simple url encoding..
  5561. const String params (getMangledParameters (url.getParameters()));
  5562. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  5563. + String ((int) strlen (params.toUTF8()))
  5564. + "\r\n";
  5565. appendUTF8ToPostData (params);
  5566. }
  5567. }
  5568. void appendUTF8ToPostData (const String& text) throw()
  5569. {
  5570. postData.append (text.toUTF8(),
  5571. (int) strlen (text.toUTF8()));
  5572. }
  5573. WebInputStream (const WebInputStream&);
  5574. const WebInputStream& operator= (const WebInputStream&);
  5575. };
  5576. InputStream* URL::createInputStream (const bool usePostCommand,
  5577. OpenStreamProgressCallback* const progressCallback,
  5578. void* const progressCallbackContext,
  5579. const String& extraHeaders,
  5580. const int timeOutMs) const
  5581. {
  5582. WebInputStream* wi = new WebInputStream (*this, usePostCommand,
  5583. progressCallback, progressCallbackContext,
  5584. extraHeaders,
  5585. timeOutMs);
  5586. if (wi->isError())
  5587. {
  5588. delete wi;
  5589. wi = 0;
  5590. }
  5591. return wi;
  5592. }
  5593. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  5594. const bool usePostCommand) const
  5595. {
  5596. InputStream* const in = createInputStream (usePostCommand);
  5597. if (in != 0)
  5598. {
  5599. in->readIntoMemoryBlock (destData, -1);
  5600. delete in;
  5601. return true;
  5602. }
  5603. return false;
  5604. }
  5605. const String URL::readEntireTextStream (const bool usePostCommand) const
  5606. {
  5607. String result;
  5608. InputStream* const in = createInputStream (usePostCommand);
  5609. if (in != 0)
  5610. {
  5611. result = in->readEntireStreamAsString();
  5612. delete in;
  5613. }
  5614. return result;
  5615. }
  5616. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  5617. {
  5618. XmlDocument doc (readEntireTextStream (usePostCommand));
  5619. return doc.getDocumentElement();
  5620. }
  5621. const URL URL::withParameter (const String& parameterName,
  5622. const String& parameterValue) const
  5623. {
  5624. URL u (*this);
  5625. u.parameters.set (parameterName, parameterValue);
  5626. return u;
  5627. }
  5628. const URL URL::withFileToUpload (const String& parameterName,
  5629. const File& fileToUpload,
  5630. const String& mimeType) const
  5631. {
  5632. URL u (*this);
  5633. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  5634. u.mimeTypes.set (parameterName, mimeType);
  5635. return u;
  5636. }
  5637. const StringPairArray& URL::getParameters() const throw()
  5638. {
  5639. return parameters;
  5640. }
  5641. const StringPairArray& URL::getFilesToUpload() const throw()
  5642. {
  5643. return filesToUpload;
  5644. }
  5645. const StringPairArray& URL::getMimeTypesOfUploadFiles() const throw()
  5646. {
  5647. return mimeTypes;
  5648. }
  5649. const String URL::removeEscapeChars (const String& s)
  5650. {
  5651. const int len = s.length();
  5652. uint8* const resultUTF8 = (uint8*) juce_calloc (len * 4);
  5653. uint8* r = resultUTF8;
  5654. for (int i = 0; i < len; ++i)
  5655. {
  5656. char c = (char) s[i];
  5657. if (c == 0)
  5658. break;
  5659. if (c == '+')
  5660. {
  5661. c = ' ';
  5662. }
  5663. else if (c == '%')
  5664. {
  5665. c = (char) s.substring (i + 1, i + 3).getHexValue32();
  5666. i += 2;
  5667. }
  5668. *r++ = c;
  5669. }
  5670. const String stringResult (String::fromUTF8 (resultUTF8));
  5671. juce_free (resultUTF8);
  5672. return stringResult;
  5673. }
  5674. const String URL::addEscapeChars (const String& s)
  5675. {
  5676. String result;
  5677. result.preallocateStorage (s.length() + 8);
  5678. const char* utf8 = s.toUTF8();
  5679. while (*utf8 != 0)
  5680. {
  5681. const char c = *utf8++;
  5682. if (c == ' ')
  5683. {
  5684. result += T('+');
  5685. }
  5686. else if (CharacterFunctions::isLetterOrDigit (c)
  5687. || CharacterFunctions::indexOfChar ("_-$.*!'(),", c, false) >= 0)
  5688. {
  5689. result << c;
  5690. }
  5691. else
  5692. {
  5693. const int v = (int) (uint8) c;
  5694. if (v < 0x10)
  5695. result << T("%0");
  5696. else
  5697. result << T('%');
  5698. result << String::toHexString (v);
  5699. }
  5700. }
  5701. return result;
  5702. }
  5703. extern bool juce_launchFile (const String& fileName,
  5704. const String& parameters) throw();
  5705. bool URL::launchInDefaultBrowser() const
  5706. {
  5707. String u (toString (true));
  5708. if (u.contains (T("@")) && ! u.contains (T(":")))
  5709. u = "mailto:" + u;
  5710. return juce_launchFile (u, String::empty);
  5711. }
  5712. END_JUCE_NAMESPACE
  5713. /********* End of inlined file: juce_URL.cpp *********/
  5714. /********* Start of inlined file: juce_BufferedInputStream.cpp *********/
  5715. BEGIN_JUCE_NAMESPACE
  5716. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  5717. const int bufferSize_,
  5718. const bool deleteSourceWhenDestroyed_) throw()
  5719. : source (source_),
  5720. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  5721. bufferSize (jmax (256, bufferSize_)),
  5722. position (source_->getPosition()),
  5723. lastReadPos (0),
  5724. bufferOverlap (128)
  5725. {
  5726. const int sourceSize = (int) source_->getTotalLength();
  5727. if (sourceSize >= 0)
  5728. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  5729. bufferStart = position;
  5730. buffer = (char*) juce_malloc (bufferSize);
  5731. }
  5732. BufferedInputStream::~BufferedInputStream() throw()
  5733. {
  5734. if (deleteSourceWhenDestroyed)
  5735. delete source;
  5736. juce_free (buffer);
  5737. }
  5738. int64 BufferedInputStream::getTotalLength()
  5739. {
  5740. return source->getTotalLength();
  5741. }
  5742. int64 BufferedInputStream::getPosition()
  5743. {
  5744. return position;
  5745. }
  5746. bool BufferedInputStream::setPosition (int64 newPosition)
  5747. {
  5748. position = jmax ((int64) 0, newPosition);
  5749. return true;
  5750. }
  5751. bool BufferedInputStream::isExhausted()
  5752. {
  5753. return (position >= lastReadPos)
  5754. && source->isExhausted();
  5755. }
  5756. void BufferedInputStream::ensureBuffered()
  5757. {
  5758. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  5759. if (position < bufferStart || position >= bufferEndOverlap)
  5760. {
  5761. int bytesRead;
  5762. if (position < lastReadPos
  5763. && position >= bufferEndOverlap
  5764. && position >= bufferStart)
  5765. {
  5766. const int bytesToKeep = (int) (lastReadPos - position);
  5767. memmove (buffer, buffer + position - bufferStart, bytesToKeep);
  5768. bufferStart = position;
  5769. bytesRead = source->read (buffer + bytesToKeep,
  5770. bufferSize - bytesToKeep);
  5771. lastReadPos += bytesRead;
  5772. bytesRead += bytesToKeep;
  5773. }
  5774. else
  5775. {
  5776. bufferStart = position;
  5777. source->setPosition (bufferStart);
  5778. bytesRead = source->read (buffer, bufferSize);
  5779. lastReadPos = bufferStart + bytesRead;
  5780. }
  5781. while (bytesRead < bufferSize)
  5782. buffer [bytesRead++] = 0;
  5783. }
  5784. }
  5785. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  5786. {
  5787. if (position >= bufferStart
  5788. && position + maxBytesToRead <= lastReadPos)
  5789. {
  5790. memcpy (destBuffer, buffer + (position - bufferStart), maxBytesToRead);
  5791. position += maxBytesToRead;
  5792. return maxBytesToRead;
  5793. }
  5794. else
  5795. {
  5796. if (position < bufferStart || position >= lastReadPos)
  5797. ensureBuffered();
  5798. int bytesRead = 0;
  5799. while (maxBytesToRead > 0)
  5800. {
  5801. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  5802. if (bytesAvailable > 0)
  5803. {
  5804. memcpy (destBuffer, buffer + (position - bufferStart), bytesAvailable);
  5805. maxBytesToRead -= bytesAvailable;
  5806. bytesRead += bytesAvailable;
  5807. position += bytesAvailable;
  5808. destBuffer = (void*) (((char*) destBuffer) + bytesAvailable);
  5809. }
  5810. ensureBuffered();
  5811. if (isExhausted())
  5812. break;
  5813. }
  5814. return bytesRead;
  5815. }
  5816. }
  5817. const String BufferedInputStream::readString()
  5818. {
  5819. if (position >= bufferStart
  5820. && position < lastReadPos)
  5821. {
  5822. const int maxChars = (int) (lastReadPos - position);
  5823. const char* const src = buffer + (position - bufferStart);
  5824. for (int i = 0; i < maxChars; ++i)
  5825. {
  5826. if (src[i] == 0)
  5827. {
  5828. position += i + 1;
  5829. return String::fromUTF8 ((const uint8*) src, i);
  5830. }
  5831. }
  5832. }
  5833. return InputStream::readString();
  5834. }
  5835. END_JUCE_NAMESPACE
  5836. /********* End of inlined file: juce_BufferedInputStream.cpp *********/
  5837. /********* Start of inlined file: juce_FileInputSource.cpp *********/
  5838. BEGIN_JUCE_NAMESPACE
  5839. FileInputSource::FileInputSource (const File& file_) throw()
  5840. : file (file_)
  5841. {
  5842. }
  5843. FileInputSource::~FileInputSource()
  5844. {
  5845. }
  5846. InputStream* FileInputSource::createInputStream()
  5847. {
  5848. return file.createInputStream();
  5849. }
  5850. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  5851. {
  5852. return file.getSiblingFile (relatedItemPath).createInputStream();
  5853. }
  5854. int64 FileInputSource::hashCode() const
  5855. {
  5856. return file.hashCode();
  5857. }
  5858. END_JUCE_NAMESPACE
  5859. /********* End of inlined file: juce_FileInputSource.cpp *********/
  5860. /********* Start of inlined file: juce_MemoryInputStream.cpp *********/
  5861. BEGIN_JUCE_NAMESPACE
  5862. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  5863. const int sourceDataSize,
  5864. const bool keepInternalCopy) throw()
  5865. : data ((const char*) sourceData),
  5866. dataSize (sourceDataSize),
  5867. position (0)
  5868. {
  5869. if (keepInternalCopy)
  5870. {
  5871. internalCopy.append (data, sourceDataSize);
  5872. data = (const char*) internalCopy.getData();
  5873. }
  5874. }
  5875. MemoryInputStream::~MemoryInputStream() throw()
  5876. {
  5877. }
  5878. int64 MemoryInputStream::getTotalLength()
  5879. {
  5880. return dataSize;
  5881. }
  5882. int MemoryInputStream::read (void* buffer, int howMany)
  5883. {
  5884. const int num = jmin (howMany, dataSize - position);
  5885. memcpy (buffer, data + position, num);
  5886. position += num;
  5887. return num;
  5888. }
  5889. bool MemoryInputStream::isExhausted()
  5890. {
  5891. return (position >= dataSize);
  5892. }
  5893. bool MemoryInputStream::setPosition (int64 pos)
  5894. {
  5895. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  5896. return true;
  5897. }
  5898. int64 MemoryInputStream::getPosition()
  5899. {
  5900. return position;
  5901. }
  5902. END_JUCE_NAMESPACE
  5903. /********* End of inlined file: juce_MemoryInputStream.cpp *********/
  5904. /********* Start of inlined file: juce_MemoryOutputStream.cpp *********/
  5905. BEGIN_JUCE_NAMESPACE
  5906. MemoryOutputStream::MemoryOutputStream (const int initialSize,
  5907. const int blockSizeToIncreaseBy,
  5908. MemoryBlock* const memoryBlockToWriteTo) throw()
  5909. : data (memoryBlockToWriteTo),
  5910. position (0),
  5911. size (0),
  5912. blockSize (jmax (16, blockSizeToIncreaseBy)),
  5913. ownsMemoryBlock (memoryBlockToWriteTo == 0)
  5914. {
  5915. if (memoryBlockToWriteTo == 0)
  5916. data = new MemoryBlock (initialSize);
  5917. else
  5918. memoryBlockToWriteTo->setSize (initialSize, false);
  5919. }
  5920. MemoryOutputStream::~MemoryOutputStream() throw()
  5921. {
  5922. if (ownsMemoryBlock)
  5923. delete data;
  5924. else
  5925. flush();
  5926. }
  5927. void MemoryOutputStream::flush()
  5928. {
  5929. if (! ownsMemoryBlock)
  5930. data->setSize (size, false);
  5931. }
  5932. void MemoryOutputStream::reset() throw()
  5933. {
  5934. position = 0;
  5935. size = 0;
  5936. }
  5937. bool MemoryOutputStream::write (const void* buffer, int howMany)
  5938. {
  5939. int storageNeeded = position + howMany + 1;
  5940. storageNeeded = storageNeeded - (storageNeeded % blockSize) + blockSize;
  5941. data->ensureSize (storageNeeded);
  5942. data->copyFrom (buffer, position, howMany);
  5943. position += howMany;
  5944. size = jmax (size, position);
  5945. return true;
  5946. }
  5947. const char* MemoryOutputStream::getData() throw()
  5948. {
  5949. if (data->getSize() > size)
  5950. ((char*) data->getData()) [size] = 0;
  5951. return (const char*) data->getData();
  5952. }
  5953. int MemoryOutputStream::getDataSize() const throw()
  5954. {
  5955. return size;
  5956. }
  5957. int64 MemoryOutputStream::getPosition()
  5958. {
  5959. return position;
  5960. }
  5961. bool MemoryOutputStream::setPosition (int64 newPosition)
  5962. {
  5963. if (newPosition <= size)
  5964. {
  5965. // ok to seek backwards
  5966. position = jlimit (0, size, (int) newPosition);
  5967. return true;
  5968. }
  5969. else
  5970. {
  5971. // trying to make it bigger isn't a good thing to do..
  5972. return false;
  5973. }
  5974. }
  5975. END_JUCE_NAMESPACE
  5976. /********* End of inlined file: juce_MemoryOutputStream.cpp *********/
  5977. /********* Start of inlined file: juce_SubregionStream.cpp *********/
  5978. BEGIN_JUCE_NAMESPACE
  5979. SubregionStream::SubregionStream (InputStream* const sourceStream,
  5980. const int64 startPositionInSourceStream_,
  5981. const int64 lengthOfSourceStream_,
  5982. const bool deleteSourceWhenDestroyed_) throw()
  5983. : source (sourceStream),
  5984. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  5985. startPositionInSourceStream (startPositionInSourceStream_),
  5986. lengthOfSourceStream (lengthOfSourceStream_)
  5987. {
  5988. setPosition (0);
  5989. }
  5990. SubregionStream::~SubregionStream() throw()
  5991. {
  5992. if (deleteSourceWhenDestroyed)
  5993. delete source;
  5994. }
  5995. int64 SubregionStream::getTotalLength()
  5996. {
  5997. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  5998. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  5999. : srcLen;
  6000. }
  6001. int64 SubregionStream::getPosition()
  6002. {
  6003. return source->getPosition() - startPositionInSourceStream;
  6004. }
  6005. bool SubregionStream::setPosition (int64 newPosition)
  6006. {
  6007. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  6008. }
  6009. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  6010. {
  6011. if (lengthOfSourceStream < 0)
  6012. {
  6013. return source->read (destBuffer, maxBytesToRead);
  6014. }
  6015. else
  6016. {
  6017. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  6018. if (maxBytesToRead <= 0)
  6019. return 0;
  6020. return source->read (destBuffer, maxBytesToRead);
  6021. }
  6022. }
  6023. bool SubregionStream::isExhausted()
  6024. {
  6025. if (lengthOfSourceStream >= 0)
  6026. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  6027. else
  6028. return source->isExhausted();
  6029. }
  6030. END_JUCE_NAMESPACE
  6031. /********* End of inlined file: juce_SubregionStream.cpp *********/
  6032. /********* Start of inlined file: juce_PerformanceCounter.cpp *********/
  6033. BEGIN_JUCE_NAMESPACE
  6034. PerformanceCounter::PerformanceCounter (const String& name_,
  6035. int runsPerPrintout,
  6036. const File& loggingFile)
  6037. : name (name_),
  6038. numRuns (0),
  6039. runsPerPrint (runsPerPrintout),
  6040. totalTime (0),
  6041. outputFile (loggingFile)
  6042. {
  6043. if (outputFile != File::nonexistent)
  6044. {
  6045. String s ("**** Counter for \"");
  6046. s << name_ << "\" started at: "
  6047. << Time::getCurrentTime().toString (true, true)
  6048. << "\r\n";
  6049. outputFile.appendText (s, false, false);
  6050. }
  6051. }
  6052. PerformanceCounter::~PerformanceCounter()
  6053. {
  6054. printStatistics();
  6055. }
  6056. void PerformanceCounter::start()
  6057. {
  6058. started = Time::getHighResolutionTicks();
  6059. }
  6060. void PerformanceCounter::stop()
  6061. {
  6062. const int64 now = Time::getHighResolutionTicks();
  6063. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  6064. if (++numRuns == runsPerPrint)
  6065. printStatistics();
  6066. }
  6067. void PerformanceCounter::printStatistics()
  6068. {
  6069. if (numRuns > 0)
  6070. {
  6071. String s ("Performance count for \"");
  6072. s << name << "\" - average over " << numRuns << " run(s) = ";
  6073. const int micros = (int) (totalTime * (1000.0 / numRuns));
  6074. if (micros > 10000)
  6075. s << (micros/1000) << " millisecs";
  6076. else
  6077. s << micros << " microsecs";
  6078. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  6079. Logger::outputDebugString (s);
  6080. s << "\r\n";
  6081. if (outputFile != File::nonexistent)
  6082. outputFile.appendText (s, false, false);
  6083. numRuns = 0;
  6084. totalTime = 0;
  6085. }
  6086. }
  6087. END_JUCE_NAMESPACE
  6088. /********* End of inlined file: juce_PerformanceCounter.cpp *********/
  6089. /********* Start of inlined file: juce_Uuid.cpp *********/
  6090. BEGIN_JUCE_NAMESPACE
  6091. Uuid::Uuid()
  6092. {
  6093. // do some serious mixing up of our MAC addresses and different types of time info,
  6094. // plus a couple of passes of pseudo-random numbers over the whole thing.
  6095. SystemStats::getMACAddresses (value.asInt64, 2);
  6096. int i;
  6097. for (i = 16; --i >= 0;)
  6098. {
  6099. Random r (Time::getHighResolutionTicks()
  6100. + Random::getSystemRandom().nextInt()
  6101. + value.asInt [i & 3]);
  6102. value.asBytes[i] ^= (uint8) r.nextInt();
  6103. }
  6104. value.asInt64 [0] ^= Time::getHighResolutionTicks();
  6105. value.asInt64 [1] ^= Time::currentTimeMillis();
  6106. for (i = 4; --i >= 0;)
  6107. {
  6108. Random r (Time::getHighResolutionTicks() ^ value.asInt[i]);
  6109. value.asInt[i] ^= r.nextInt();
  6110. }
  6111. }
  6112. Uuid::~Uuid() throw()
  6113. {
  6114. }
  6115. Uuid::Uuid (const Uuid& other)
  6116. : value (other.value)
  6117. {
  6118. }
  6119. Uuid& Uuid::operator= (const Uuid& other)
  6120. {
  6121. if (this != &other)
  6122. value = other.value;
  6123. return *this;
  6124. }
  6125. bool Uuid::operator== (const Uuid& other) const
  6126. {
  6127. return memcmp (value.asBytes, other.value.asBytes, 16) == 0;
  6128. }
  6129. bool Uuid::operator!= (const Uuid& other) const
  6130. {
  6131. return ! operator== (other);
  6132. }
  6133. bool Uuid::isNull() const throw()
  6134. {
  6135. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  6136. }
  6137. const String Uuid::toString() const
  6138. {
  6139. return String::toHexString (value.asBytes, 16, 0);
  6140. }
  6141. Uuid::Uuid (const String& uuidString)
  6142. {
  6143. operator= (uuidString);
  6144. }
  6145. Uuid& Uuid::operator= (const String& uuidString)
  6146. {
  6147. int destIndex = 0;
  6148. int i = 0;
  6149. for (;;)
  6150. {
  6151. int byte = 0;
  6152. for (int loop = 2; --loop >= 0;)
  6153. {
  6154. byte <<= 4;
  6155. for (;;)
  6156. {
  6157. const tchar c = uuidString [i++];
  6158. if (c >= T('0') && c <= T('9'))
  6159. {
  6160. byte |= c - T('0');
  6161. break;
  6162. }
  6163. else if (c >= T('a') && c <= T('z'))
  6164. {
  6165. byte |= c - (T('a') - 10);
  6166. break;
  6167. }
  6168. else if (c >= T('A') && c <= T('Z'))
  6169. {
  6170. byte |= c - (T('A') - 10);
  6171. break;
  6172. }
  6173. else if (c == 0)
  6174. {
  6175. while (destIndex < 16)
  6176. value.asBytes [destIndex++] = 0;
  6177. return *this;
  6178. }
  6179. }
  6180. }
  6181. value.asBytes [destIndex++] = (uint8) byte;
  6182. }
  6183. }
  6184. Uuid::Uuid (const uint8* const rawData)
  6185. {
  6186. operator= (rawData);
  6187. }
  6188. Uuid& Uuid::operator= (const uint8* const rawData)
  6189. {
  6190. if (rawData != 0)
  6191. memcpy (value.asBytes, rawData, 16);
  6192. else
  6193. zeromem (value.asBytes, 16);
  6194. return *this;
  6195. }
  6196. END_JUCE_NAMESPACE
  6197. /********* End of inlined file: juce_Uuid.cpp *********/
  6198. /********* Start of inlined file: juce_ZipFile.cpp *********/
  6199. BEGIN_JUCE_NAMESPACE
  6200. struct ZipEntryInfo
  6201. {
  6202. ZipFile::ZipEntry entry;
  6203. int streamOffset;
  6204. int compressedSize;
  6205. bool compressed;
  6206. };
  6207. class ZipInputStream : public InputStream
  6208. {
  6209. public:
  6210. ZipInputStream (ZipFile& file_,
  6211. ZipEntryInfo& zei) throw()
  6212. : file (file_),
  6213. zipEntryInfo (zei),
  6214. pos (0),
  6215. headerSize (0),
  6216. inputStream (0)
  6217. {
  6218. inputStream = file_.inputStream;
  6219. if (file_.inputSource != 0)
  6220. {
  6221. inputStream = file.inputSource->createInputStream();
  6222. }
  6223. else
  6224. {
  6225. #ifdef JUCE_DEBUG
  6226. file_.numOpenStreams++;
  6227. #endif
  6228. }
  6229. char buffer [30];
  6230. if (inputStream != 0
  6231. && inputStream->setPosition (zei.streamOffset)
  6232. && inputStream->read (buffer, 30) == 30
  6233. && littleEndianInt (buffer) == 0x04034b50)
  6234. {
  6235. headerSize = 30 + littleEndianShort (buffer + 26)
  6236. + littleEndianShort (buffer + 28);
  6237. }
  6238. }
  6239. ~ZipInputStream() throw()
  6240. {
  6241. #ifdef JUCE_DEBUG
  6242. if (inputStream != 0 && inputStream == file.inputStream)
  6243. file.numOpenStreams--;
  6244. #endif
  6245. if (inputStream != file.inputStream)
  6246. delete inputStream;
  6247. }
  6248. int64 getTotalLength() throw()
  6249. {
  6250. return zipEntryInfo.compressedSize;
  6251. }
  6252. int read (void* buffer, int howMany) throw()
  6253. {
  6254. if (headerSize <= 0)
  6255. return 0;
  6256. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  6257. if (inputStream == 0)
  6258. return 0;
  6259. int num;
  6260. if (inputStream == file.inputStream)
  6261. {
  6262. const ScopedLock sl (file.lock);
  6263. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  6264. num = inputStream->read (buffer, howMany);
  6265. }
  6266. else
  6267. {
  6268. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  6269. num = inputStream->read (buffer, howMany);
  6270. }
  6271. pos += num;
  6272. return num;
  6273. }
  6274. bool isExhausted() throw()
  6275. {
  6276. return pos >= zipEntryInfo.compressedSize;
  6277. }
  6278. int64 getPosition() throw()
  6279. {
  6280. return pos;
  6281. }
  6282. bool setPosition (int64 newPos) throw()
  6283. {
  6284. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  6285. return true;
  6286. }
  6287. private:
  6288. ZipFile& file;
  6289. ZipEntryInfo zipEntryInfo;
  6290. int64 pos;
  6291. int headerSize;
  6292. InputStream* inputStream;
  6293. ZipInputStream (const ZipInputStream&);
  6294. const ZipInputStream& operator= (const ZipInputStream&);
  6295. };
  6296. ZipFile::ZipFile (InputStream* const source_,
  6297. const bool deleteStreamWhenDestroyed_) throw()
  6298. : inputStream (source_),
  6299. inputSource (0),
  6300. deleteStreamWhenDestroyed (deleteStreamWhenDestroyed_)
  6301. #ifdef JUCE_DEBUG
  6302. , numOpenStreams (0)
  6303. #endif
  6304. {
  6305. init();
  6306. }
  6307. ZipFile::ZipFile (const File& file)
  6308. : inputStream (0),
  6309. deleteStreamWhenDestroyed (false)
  6310. #ifdef JUCE_DEBUG
  6311. , numOpenStreams (0)
  6312. #endif
  6313. {
  6314. inputSource = new FileInputSource (file);
  6315. init();
  6316. }
  6317. ZipFile::ZipFile (InputSource* const inputSource_)
  6318. : inputStream (0),
  6319. inputSource (inputSource_),
  6320. deleteStreamWhenDestroyed (false)
  6321. #ifdef JUCE_DEBUG
  6322. , numOpenStreams (0)
  6323. #endif
  6324. {
  6325. init();
  6326. }
  6327. ZipFile::~ZipFile() throw()
  6328. {
  6329. for (int i = entries.size(); --i >= 0;)
  6330. {
  6331. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [i];
  6332. delete zei;
  6333. }
  6334. if (deleteStreamWhenDestroyed)
  6335. delete inputStream;
  6336. delete inputSource;
  6337. #ifdef JUCE_DEBUG
  6338. // If you hit this assertion, it means you've created a stream to read
  6339. // one of the items in the zipfile, but you've forgotten to delete that
  6340. // stream object before deleting the file.. Streams can't be kept open
  6341. // after the file is deleted because they need to share the input
  6342. // stream that the file uses to read itself.
  6343. jassert (numOpenStreams == 0);
  6344. #endif
  6345. }
  6346. int ZipFile::getNumEntries() const throw()
  6347. {
  6348. return entries.size();
  6349. }
  6350. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  6351. {
  6352. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [index];
  6353. return (zei != 0) ? &(zei->entry)
  6354. : 0;
  6355. }
  6356. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  6357. {
  6358. for (int i = 0; i < entries.size(); ++i)
  6359. if (((ZipEntryInfo*) entries.getUnchecked (i))->entry.filename == fileName)
  6360. return i;
  6361. return -1;
  6362. }
  6363. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  6364. {
  6365. return getEntry (getIndexOfFileName (fileName));
  6366. }
  6367. InputStream* ZipFile::createStreamForEntry (const int index)
  6368. {
  6369. ZipEntryInfo* const zei = (ZipEntryInfo*) entries[index];
  6370. InputStream* stream = 0;
  6371. if (zei != 0)
  6372. {
  6373. stream = new ZipInputStream (*this, *zei);
  6374. if (zei->compressed)
  6375. {
  6376. stream = new GZIPDecompressorInputStream (stream, true, true,
  6377. zei->entry.uncompressedSize);
  6378. // (much faster to unzip in big blocks using a buffer..)
  6379. stream = new BufferedInputStream (stream, 32768, true);
  6380. }
  6381. }
  6382. return stream;
  6383. }
  6384. class ZipFilenameComparator
  6385. {
  6386. public:
  6387. static int compareElements (const void* const first, const void* const second) throw()
  6388. {
  6389. return ((const ZipEntryInfo*) first)->entry.filename
  6390. .compare (((const ZipEntryInfo*) second)->entry.filename);
  6391. }
  6392. };
  6393. void ZipFile::sortEntriesByFilename()
  6394. {
  6395. ZipFilenameComparator sorter;
  6396. entries.sort (sorter);
  6397. }
  6398. void ZipFile::init()
  6399. {
  6400. InputStream* in = inputStream;
  6401. bool deleteInput = false;
  6402. if (inputSource != 0)
  6403. {
  6404. deleteInput = true;
  6405. in = inputSource->createInputStream();
  6406. }
  6407. if (in != 0)
  6408. {
  6409. numEntries = 0;
  6410. int pos = findEndOfZipEntryTable (in);
  6411. if (pos >= 0 && pos < in->getTotalLength())
  6412. {
  6413. const int size = (int) (in->getTotalLength() - pos);
  6414. in->setPosition (pos);
  6415. MemoryBlock headerData;
  6416. if (in->readIntoMemoryBlock (headerData, size) == size)
  6417. {
  6418. pos = 0;
  6419. for (int i = 0; i < numEntries; ++i)
  6420. {
  6421. if (pos + 46 > size)
  6422. break;
  6423. const char* const buffer = ((const char*) headerData.getData()) + pos;
  6424. const int fileNameLen = littleEndianShort (buffer + 28);
  6425. if (pos + 46 + fileNameLen > size)
  6426. break;
  6427. ZipEntryInfo* const zei = new ZipEntryInfo();
  6428. zei->entry.filename = String (buffer + 46, fileNameLen);
  6429. const int time = littleEndianShort (buffer + 12);
  6430. const int date = littleEndianShort (buffer + 14);
  6431. const int year = 1980 + (date >> 9);
  6432. const int month = ((date >> 5) & 15) - 1;
  6433. const int day = date & 31;
  6434. const int hours = time >> 11;
  6435. const int minutes = (time >> 5) & 63;
  6436. const int seconds = (time & 31) << 1;
  6437. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  6438. zei->compressed = littleEndianShort (buffer + 10) != 0;
  6439. zei->compressedSize = littleEndianInt (buffer + 20);
  6440. zei->entry.uncompressedSize = littleEndianInt (buffer + 24);
  6441. zei->streamOffset = littleEndianInt (buffer + 42);
  6442. entries.add (zei);
  6443. pos += 46 + fileNameLen
  6444. + littleEndianShort (buffer + 30)
  6445. + littleEndianShort (buffer + 32);
  6446. }
  6447. }
  6448. }
  6449. if (deleteInput)
  6450. delete in;
  6451. }
  6452. }
  6453. int ZipFile::findEndOfZipEntryTable (InputStream* input)
  6454. {
  6455. BufferedInputStream in (input, 8192, false);
  6456. in.setPosition (in.getTotalLength());
  6457. int64 pos = in.getPosition();
  6458. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  6459. char buffer [32];
  6460. zeromem (buffer, sizeof (buffer));
  6461. while (pos > lowestPos)
  6462. {
  6463. in.setPosition (pos - 22);
  6464. pos = in.getPosition();
  6465. memcpy (buffer + 22, buffer, 4);
  6466. if (in.read (buffer, 22) != 22)
  6467. return 0;
  6468. for (int i = 0; i < 22; ++i)
  6469. {
  6470. if (littleEndianInt (buffer + i) == 0x06054b50)
  6471. {
  6472. in.setPosition (pos + i);
  6473. in.read (buffer, 22);
  6474. numEntries = littleEndianShort (buffer + 10);
  6475. return littleEndianInt (buffer + 16);
  6476. }
  6477. }
  6478. }
  6479. return 0;
  6480. }
  6481. void ZipFile::uncompressTo (const File& targetDirectory,
  6482. const bool shouldOverwriteFiles)
  6483. {
  6484. for (int i = 0; i < entries.size(); ++i)
  6485. {
  6486. const ZipEntryInfo& zei = *(ZipEntryInfo*) entries[i];
  6487. const File targetFile (targetDirectory.getChildFile (zei.entry.filename));
  6488. if (zei.entry.filename.endsWithChar (T('/')))
  6489. {
  6490. targetFile.createDirectory(); // (entry is a directory, not a file)
  6491. }
  6492. else
  6493. {
  6494. InputStream* const in = createStreamForEntry (i);
  6495. if (in != 0)
  6496. {
  6497. if (shouldOverwriteFiles)
  6498. targetFile.deleteFile();
  6499. if ((! targetFile.exists())
  6500. && targetFile.getParentDirectory().createDirectory())
  6501. {
  6502. FileOutputStream* const out = targetFile.createOutputStream();
  6503. if (out != 0)
  6504. {
  6505. out->writeFromInputStream (*in, -1);
  6506. delete out;
  6507. targetFile.setCreationTime (zei.entry.fileTime);
  6508. targetFile.setLastModificationTime (zei.entry.fileTime);
  6509. targetFile.setLastAccessTime (zei.entry.fileTime);
  6510. }
  6511. }
  6512. delete in;
  6513. }
  6514. }
  6515. }
  6516. }
  6517. END_JUCE_NAMESPACE
  6518. /********* End of inlined file: juce_ZipFile.cpp *********/
  6519. /********* Start of inlined file: juce_CharacterFunctions.cpp *********/
  6520. #ifdef _MSC_VER
  6521. #pragma warning (disable: 4514 4996)
  6522. #pragma warning (push)
  6523. #endif
  6524. #include <cwctype>
  6525. #include <cctype>
  6526. #include <ctime>
  6527. #ifdef _MSC_VER
  6528. #pragma warning (pop)
  6529. #endif
  6530. BEGIN_JUCE_NAMESPACE
  6531. int CharacterFunctions::length (const char* const s) throw()
  6532. {
  6533. return (int) strlen (s);
  6534. }
  6535. int CharacterFunctions::length (const juce_wchar* const s) throw()
  6536. {
  6537. #if MACOS_10_2_OR_EARLIER
  6538. int n = 0;
  6539. while (s[n] != 0)
  6540. ++n;
  6541. return n;
  6542. #else
  6543. return (int) wcslen (s);
  6544. #endif
  6545. }
  6546. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  6547. {
  6548. strncpy (dest, src, maxChars);
  6549. }
  6550. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  6551. {
  6552. #if MACOS_10_2_OR_EARLIER
  6553. while (--maxChars >= 0 && *src != 0)
  6554. *dest++ = *src++;
  6555. *dest = 0;
  6556. #else
  6557. wcsncpy (dest, src, maxChars);
  6558. #endif
  6559. }
  6560. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  6561. {
  6562. mbstowcs (dest, src, maxChars);
  6563. }
  6564. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  6565. {
  6566. wcstombs (dest, src, maxChars);
  6567. }
  6568. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  6569. {
  6570. return (int) wcstombs (0, src, 0);
  6571. }
  6572. void CharacterFunctions::append (char* dest, const char* src) throw()
  6573. {
  6574. strcat (dest, src);
  6575. }
  6576. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  6577. {
  6578. #if MACOS_10_2_OR_EARLIER
  6579. while (*dest != 0)
  6580. ++dest;
  6581. while (*src != 0)
  6582. *dest++ = *src++;
  6583. *dest = 0;
  6584. #else
  6585. wcscat (dest, src);
  6586. #endif
  6587. }
  6588. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  6589. {
  6590. return strcmp (s1, s2);
  6591. }
  6592. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  6593. {
  6594. jassert (s1 != 0 && s2 != 0);
  6595. #if MACOS_10_2_OR_EARLIER
  6596. for (;;)
  6597. {
  6598. if (*s1 != *s2)
  6599. {
  6600. const int diff = *s1 - *s2;
  6601. if (diff != 0)
  6602. return diff < 0 ? -1 : 1;
  6603. }
  6604. else if (*s1 == 0)
  6605. break;
  6606. ++s1;
  6607. ++s2;
  6608. }
  6609. return 0;
  6610. #else
  6611. return wcscmp (s1, s2);
  6612. #endif
  6613. }
  6614. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  6615. {
  6616. jassert (s1 != 0 && s2 != 0);
  6617. return strncmp (s1, s2, maxChars);
  6618. }
  6619. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  6620. {
  6621. jassert (s1 != 0 && s2 != 0);
  6622. #if MACOS_10_2_OR_EARLIER
  6623. while (--maxChars >= 0)
  6624. {
  6625. if (*s1 != *s2)
  6626. return (*s1 < *s2) ? -1 : 1;
  6627. else if (*s1 == 0)
  6628. break;
  6629. ++s1;
  6630. ++s2;
  6631. }
  6632. return 0;
  6633. #else
  6634. return wcsncmp (s1, s2, maxChars);
  6635. #endif
  6636. }
  6637. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  6638. {
  6639. jassert (s1 != 0 && s2 != 0);
  6640. #if JUCE_WIN32
  6641. return stricmp (s1, s2);
  6642. #else
  6643. return strcasecmp (s1, s2);
  6644. #endif
  6645. }
  6646. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  6647. {
  6648. jassert (s1 != 0 && s2 != 0);
  6649. #if JUCE_WIN32
  6650. return _wcsicmp (s1, s2);
  6651. #else
  6652. for (;;)
  6653. {
  6654. if (*s1 != *s2)
  6655. {
  6656. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  6657. if (diff != 0)
  6658. return diff < 0 ? -1 : 1;
  6659. }
  6660. else if (*s1 == 0)
  6661. break;
  6662. ++s1;
  6663. ++s2;
  6664. }
  6665. return 0;
  6666. #endif
  6667. }
  6668. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  6669. {
  6670. jassert (s1 != 0 && s2 != 0);
  6671. #if JUCE_WIN32
  6672. return strnicmp (s1, s2, maxChars);
  6673. #else
  6674. return strncasecmp (s1, s2, maxChars);
  6675. #endif
  6676. }
  6677. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  6678. {
  6679. jassert (s1 != 0 && s2 != 0);
  6680. #if JUCE_WIN32
  6681. return _wcsnicmp (s1, s2, maxChars);
  6682. #else
  6683. while (--maxChars >= 0)
  6684. {
  6685. if (*s1 != *s2)
  6686. {
  6687. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  6688. if (diff != 0)
  6689. return diff < 0 ? -1 : 1;
  6690. }
  6691. else if (*s1 == 0)
  6692. break;
  6693. ++s1;
  6694. ++s2;
  6695. }
  6696. return 0;
  6697. #endif
  6698. }
  6699. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  6700. {
  6701. return strstr (haystack, needle);
  6702. }
  6703. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  6704. {
  6705. #if MACOS_10_2_OR_EARLIER
  6706. while (*haystack != 0)
  6707. {
  6708. const juce_wchar* s1 = haystack;
  6709. const juce_wchar* s2 = needle;
  6710. for (;;)
  6711. {
  6712. if (*s2 == 0)
  6713. return haystack;
  6714. if (*s1 != *s2 || *s2 == 0)
  6715. break;
  6716. ++s1;
  6717. ++s2;
  6718. }
  6719. ++haystack;
  6720. }
  6721. return 0;
  6722. #else
  6723. return wcsstr (haystack, needle);
  6724. #endif
  6725. }
  6726. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  6727. {
  6728. if (haystack != 0)
  6729. {
  6730. int i = 0;
  6731. if (ignoreCase)
  6732. {
  6733. const char n1 = toLowerCase (needle);
  6734. const char n2 = toUpperCase (needle);
  6735. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  6736. {
  6737. while (haystack[i] != 0)
  6738. {
  6739. if (haystack[i] == n1 || haystack[i] == n2)
  6740. return i;
  6741. ++i;
  6742. }
  6743. return -1;
  6744. }
  6745. jassert (n1 == needle);
  6746. }
  6747. while (haystack[i] != 0)
  6748. {
  6749. if (haystack[i] == needle)
  6750. return i;
  6751. ++i;
  6752. }
  6753. }
  6754. return -1;
  6755. }
  6756. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  6757. {
  6758. if (haystack != 0)
  6759. {
  6760. int i = 0;
  6761. if (ignoreCase)
  6762. {
  6763. const juce_wchar n1 = toLowerCase (needle);
  6764. const juce_wchar n2 = toUpperCase (needle);
  6765. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  6766. {
  6767. while (haystack[i] != 0)
  6768. {
  6769. if (haystack[i] == n1 || haystack[i] == n2)
  6770. return i;
  6771. ++i;
  6772. }
  6773. return -1;
  6774. }
  6775. jassert (n1 == needle);
  6776. }
  6777. while (haystack[i] != 0)
  6778. {
  6779. if (haystack[i] == needle)
  6780. return i;
  6781. ++i;
  6782. }
  6783. }
  6784. return -1;
  6785. }
  6786. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  6787. {
  6788. jassert (haystack != 0);
  6789. int i = 0;
  6790. while (haystack[i] != 0)
  6791. {
  6792. if (haystack[i] == needle)
  6793. return i;
  6794. ++i;
  6795. }
  6796. return -1;
  6797. }
  6798. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  6799. {
  6800. jassert (haystack != 0);
  6801. int i = 0;
  6802. while (haystack[i] != 0)
  6803. {
  6804. if (haystack[i] == needle)
  6805. return i;
  6806. ++i;
  6807. }
  6808. return -1;
  6809. }
  6810. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  6811. {
  6812. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  6813. }
  6814. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  6815. {
  6816. if (allowedChars == 0)
  6817. return 0;
  6818. int i = 0;
  6819. for (;;)
  6820. {
  6821. if (indexOfCharFast (allowedChars, text[i]) < 0)
  6822. break;
  6823. ++i;
  6824. }
  6825. return i;
  6826. }
  6827. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  6828. {
  6829. return (int) strftime (dest, maxChars, format, tm);
  6830. }
  6831. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  6832. {
  6833. #if MACOS_10_2_OR_EARLIER
  6834. const String formatTemp (format);
  6835. size_t num = strftime ((char*) dest, maxChars, (const char*) formatTemp, tm);
  6836. String temp ((char*) dest);
  6837. temp.copyToBuffer (dest, num);
  6838. dest [num] = 0;
  6839. return (int) num;
  6840. #else
  6841. return (int) wcsftime (dest, maxChars, format, tm);
  6842. #endif
  6843. }
  6844. int CharacterFunctions::getIntValue (const char* const s) throw()
  6845. {
  6846. return atoi (s);
  6847. }
  6848. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  6849. {
  6850. #if JUCE_WIN32
  6851. return _wtoi (s);
  6852. #else
  6853. int v = 0;
  6854. while (isWhitespace (*s))
  6855. ++s;
  6856. const bool isNeg = *s == T('-');
  6857. if (isNeg)
  6858. ++s;
  6859. for (;;)
  6860. {
  6861. const wchar_t c = *s++;
  6862. if (c >= T('0') && c <= T('9'))
  6863. v = v * 10 + (int) (c - T('0'));
  6864. else
  6865. break;
  6866. }
  6867. return isNeg ? -v : v;
  6868. #endif
  6869. }
  6870. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  6871. {
  6872. #if JUCE_LINUX
  6873. return atoll (s);
  6874. #elif defined (JUCE_WIN32)
  6875. return _atoi64 (s);
  6876. #else
  6877. int64 v = 0;
  6878. while (isWhitespace (*s))
  6879. ++s;
  6880. const bool isNeg = *s == T('-');
  6881. if (isNeg)
  6882. ++s;
  6883. for (;;)
  6884. {
  6885. const char c = *s++;
  6886. if (c >= '0' && c <= '9')
  6887. v = v * 10 + (int64) (c - '0');
  6888. else
  6889. break;
  6890. }
  6891. return isNeg ? -v : v;
  6892. #endif
  6893. }
  6894. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  6895. {
  6896. #if JUCE_WIN32
  6897. return _wtoi64 (s);
  6898. #else
  6899. int64 v = 0;
  6900. while (isWhitespace (*s))
  6901. ++s;
  6902. const bool isNeg = *s == T('-');
  6903. if (isNeg)
  6904. ++s;
  6905. for (;;)
  6906. {
  6907. const juce_wchar c = *s++;
  6908. if (c >= T('0') && c <= T('9'))
  6909. v = v * 10 + (int64) (c - T('0'));
  6910. else
  6911. break;
  6912. }
  6913. return isNeg ? -v : v;
  6914. #endif
  6915. }
  6916. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  6917. {
  6918. return atof (s);
  6919. }
  6920. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  6921. {
  6922. #if MACOS_10_2_OR_EARLIER
  6923. String temp (s);
  6924. return atof ((const char*) temp);
  6925. #else
  6926. wchar_t* endChar;
  6927. return wcstod (s, &endChar);
  6928. #endif
  6929. }
  6930. char CharacterFunctions::toUpperCase (const char character) throw()
  6931. {
  6932. return (char) toupper (character);
  6933. }
  6934. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  6935. {
  6936. #if MACOS_10_2_OR_EARLIER
  6937. return toupper ((char) character);
  6938. #else
  6939. return towupper (character);
  6940. #endif
  6941. }
  6942. void CharacterFunctions::toUpperCase (char* s) throw()
  6943. {
  6944. #if JUCE_WIN32
  6945. strupr (s);
  6946. #else
  6947. while (*s != 0)
  6948. {
  6949. *s = toUpperCase (*s);
  6950. ++s;
  6951. }
  6952. #endif
  6953. }
  6954. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  6955. {
  6956. #if JUCE_WIN32
  6957. _wcsupr (s);
  6958. #else
  6959. while (*s != 0)
  6960. {
  6961. *s = toUpperCase (*s);
  6962. ++s;
  6963. }
  6964. #endif
  6965. }
  6966. bool CharacterFunctions::isUpperCase (const char character) throw()
  6967. {
  6968. return isupper (character) != 0;
  6969. }
  6970. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  6971. {
  6972. #if JUCE_WIN32
  6973. return iswupper (character) != 0;
  6974. #else
  6975. return toLowerCase (character) != character;
  6976. #endif
  6977. }
  6978. char CharacterFunctions::toLowerCase (const char character) throw()
  6979. {
  6980. return (char) tolower (character);
  6981. }
  6982. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  6983. {
  6984. #if MACOS_10_2_OR_EARLIER
  6985. return tolower ((char) character);
  6986. #else
  6987. return towlower (character);
  6988. #endif
  6989. }
  6990. void CharacterFunctions::toLowerCase (char* s) throw()
  6991. {
  6992. #if JUCE_WIN32
  6993. strlwr (s);
  6994. #else
  6995. while (*s != 0)
  6996. {
  6997. *s = toLowerCase (*s);
  6998. ++s;
  6999. }
  7000. #endif
  7001. }
  7002. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  7003. {
  7004. #if JUCE_WIN32
  7005. _wcslwr (s);
  7006. #else
  7007. while (*s != 0)
  7008. {
  7009. *s = toLowerCase (*s);
  7010. ++s;
  7011. }
  7012. #endif
  7013. }
  7014. bool CharacterFunctions::isLowerCase (const char character) throw()
  7015. {
  7016. return islower (character) != 0;
  7017. }
  7018. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  7019. {
  7020. #if JUCE_WIN32
  7021. return iswlower (character) != 0;
  7022. #else
  7023. return toUpperCase (character) != character;
  7024. #endif
  7025. }
  7026. bool CharacterFunctions::isWhitespace (const char character) throw()
  7027. {
  7028. return character == T(' ') || (character <= 13 && character >= 9);
  7029. }
  7030. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  7031. {
  7032. #if MACOS_10_2_OR_EARLIER
  7033. return isWhitespace ((char) character);
  7034. #else
  7035. return iswspace (character) != 0;
  7036. #endif
  7037. }
  7038. bool CharacterFunctions::isDigit (const char character) throw()
  7039. {
  7040. return (character >= '0' && character <= '9');
  7041. }
  7042. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  7043. {
  7044. #if MACOS_10_2_OR_EARLIER
  7045. return isdigit ((char) character) != 0;
  7046. #else
  7047. return iswdigit (character) != 0;
  7048. #endif
  7049. }
  7050. bool CharacterFunctions::isLetter (const char character) throw()
  7051. {
  7052. return (character >= 'a' && character <= 'z')
  7053. || (character >= 'A' && character <= 'Z');
  7054. }
  7055. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  7056. {
  7057. #if MACOS_10_2_OR_EARLIER
  7058. return isLetter ((char) character);
  7059. #else
  7060. return iswalpha (character) != 0;
  7061. #endif
  7062. }
  7063. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  7064. {
  7065. return (character >= 'a' && character <= 'z')
  7066. || (character >= 'A' && character <= 'Z')
  7067. || (character >= '0' && character <= '9');
  7068. }
  7069. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  7070. {
  7071. #if MACOS_10_2_OR_EARLIER
  7072. return isLetterOrDigit ((char) character);
  7073. #else
  7074. return iswalnum (character) != 0;
  7075. #endif
  7076. }
  7077. int CharacterFunctions::getHexDigitValue (const tchar digit) throw()
  7078. {
  7079. if (digit >= T('0') && digit <= T('9'))
  7080. return digit - T('0');
  7081. else if (digit >= T('a') && digit <= T('f'))
  7082. return digit - (T('a') - 10);
  7083. else if (digit >= T('A') && digit <= T('F'))
  7084. return digit - (T('A') - 10);
  7085. return -1;
  7086. }
  7087. int CharacterFunctions::printf (char* const dest, const int maxLength, const char* const format, ...) throw()
  7088. {
  7089. va_list list;
  7090. va_start (list, format);
  7091. return vprintf (dest, maxLength, format, list);
  7092. }
  7093. int CharacterFunctions::printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw()
  7094. {
  7095. va_list list;
  7096. va_start (list, format);
  7097. return vprintf (dest, maxLength, format, list);
  7098. }
  7099. int CharacterFunctions::vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw()
  7100. {
  7101. #if JUCE_WIN32
  7102. return (int) _vsnprintf (dest, maxLength, format, args);
  7103. #else
  7104. return (int) vsnprintf (dest, maxLength, format, args);
  7105. #endif
  7106. }
  7107. int CharacterFunctions::vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw()
  7108. {
  7109. #if MACOS_10_3_OR_EARLIER
  7110. const String formatTemp (format);
  7111. size_t num = vprintf ((char*) dest, maxLength, formatTemp, args);
  7112. String temp ((char*) dest);
  7113. temp.copyToBuffer (dest, num);
  7114. dest [num] = 0;
  7115. return (int) num;
  7116. #elif defined (JUCE_WIN32)
  7117. return (int) _vsnwprintf (dest, maxLength, format, args);
  7118. #else
  7119. return (int) vswprintf (dest, maxLength, format, args);
  7120. #endif
  7121. }
  7122. END_JUCE_NAMESPACE
  7123. /********* End of inlined file: juce_CharacterFunctions.cpp *********/
  7124. /********* Start of inlined file: juce_LocalisedStrings.cpp *********/
  7125. BEGIN_JUCE_NAMESPACE
  7126. LocalisedStrings::LocalisedStrings (const String& fileContents) throw()
  7127. {
  7128. loadFromText (fileContents);
  7129. }
  7130. LocalisedStrings::LocalisedStrings (const File& fileToLoad) throw()
  7131. {
  7132. loadFromText (fileToLoad.loadFileAsString());
  7133. }
  7134. LocalisedStrings::~LocalisedStrings() throw()
  7135. {
  7136. }
  7137. const String LocalisedStrings::translate (const String& text) const throw()
  7138. {
  7139. return translations.getValue (text, text);
  7140. }
  7141. static int findCloseQuote (const String& text, int startPos) throw()
  7142. {
  7143. tchar lastChar = 0;
  7144. for (;;)
  7145. {
  7146. const tchar c = text [startPos];
  7147. if (c == 0 || (c == T('"') && lastChar != T('\\')))
  7148. break;
  7149. lastChar = c;
  7150. ++startPos;
  7151. }
  7152. return startPos;
  7153. }
  7154. static const String unescapeString (const String& s) throw()
  7155. {
  7156. return s.replace (T("\\\""), T("\""))
  7157. .replace (T("\\\'"), T("\'"))
  7158. .replace (T("\\t"), T("\t"))
  7159. .replace (T("\\r"), T("\r"))
  7160. .replace (T("\\n"), T("\n"));
  7161. }
  7162. void LocalisedStrings::loadFromText (const String& fileContents) throw()
  7163. {
  7164. StringArray lines;
  7165. lines.addLines (fileContents);
  7166. for (int i = 0; i < lines.size(); ++i)
  7167. {
  7168. String line (lines[i].trim());
  7169. if (line.startsWithChar (T('"')))
  7170. {
  7171. int closeQuote = findCloseQuote (line, 1);
  7172. const String originalText (unescapeString (line.substring (1, closeQuote)));
  7173. if (originalText.isNotEmpty())
  7174. {
  7175. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  7176. closeQuote = findCloseQuote (line, openingQuote + 1);
  7177. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  7178. if (newText.isNotEmpty())
  7179. translations.set (originalText, newText);
  7180. }
  7181. }
  7182. else if (line.startsWithIgnoreCase (T("language:")))
  7183. {
  7184. languageName = line.substring (9).trim();
  7185. }
  7186. else if (line.startsWithIgnoreCase (T("countries:")))
  7187. {
  7188. countryCodes.addTokens (line.substring (10).trim(), true);
  7189. countryCodes.trim();
  7190. countryCodes.removeEmptyStrings();
  7191. }
  7192. }
  7193. }
  7194. static CriticalSection currentMappingsLock;
  7195. static LocalisedStrings* currentMappings = 0;
  7196. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations) throw()
  7197. {
  7198. const ScopedLock sl (currentMappingsLock);
  7199. delete currentMappings;
  7200. currentMappings = newTranslations;
  7201. }
  7202. LocalisedStrings* LocalisedStrings::getCurrentMappings() throw()
  7203. {
  7204. return currentMappings;
  7205. }
  7206. const String LocalisedStrings::translateWithCurrentMappings (const String& text) throw()
  7207. {
  7208. const ScopedLock sl (currentMappingsLock);
  7209. if (currentMappings != 0)
  7210. return currentMappings->translate (text);
  7211. return text;
  7212. }
  7213. const String LocalisedStrings::translateWithCurrentMappings (const char* text) throw()
  7214. {
  7215. return translateWithCurrentMappings (String (text));
  7216. }
  7217. END_JUCE_NAMESPACE
  7218. /********* End of inlined file: juce_LocalisedStrings.cpp *********/
  7219. /********* Start of inlined file: juce_String.cpp *********/
  7220. #ifdef _MSC_VER
  7221. #pragma warning (disable: 4514)
  7222. #pragma warning (push)
  7223. #endif
  7224. #include <locale>
  7225. #if JUCE_MSVC
  7226. #include <float.h>
  7227. #endif
  7228. BEGIN_JUCE_NAMESPACE
  7229. #ifdef _MSC_VER
  7230. #pragma warning (pop)
  7231. #endif
  7232. static const char* const emptyCharString = "\0\0\0\0JUCE";
  7233. static const int safeEmptyStringRefCount = 0x3fffffff;
  7234. String::InternalRefCountedStringHolder String::emptyString = { safeEmptyStringRefCount, 0, { 0 } };
  7235. static tchar decimalPoint = T('.');
  7236. void juce_initialiseStrings()
  7237. {
  7238. decimalPoint = String::fromUTF8 ((const uint8*) localeconv()->decimal_point) [0];
  7239. }
  7240. void String::deleteInternal() throw()
  7241. {
  7242. if (atomicDecrementAndReturn (text->refCount) == 0)
  7243. juce_free (text);
  7244. }
  7245. void String::createInternal (const int numChars) throw()
  7246. {
  7247. jassert (numChars > 0);
  7248. text = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  7249. + numChars * sizeof (tchar));
  7250. text->refCount = 1;
  7251. text->allocatedNumChars = numChars;
  7252. text->text[0] = 0;
  7253. }
  7254. void String::createInternal (const tchar* const t, const tchar* const textEnd) throw()
  7255. {
  7256. jassert (*(textEnd - 1) == 0); // must have a null terminator
  7257. const int numChars = (int) (textEnd - t);
  7258. createInternal (numChars - 1);
  7259. memcpy (text->text, t, numChars * sizeof (tchar));
  7260. }
  7261. void String::appendInternal (const tchar* const newText,
  7262. const int numExtraChars) throw()
  7263. {
  7264. if (numExtraChars > 0)
  7265. {
  7266. const int oldLen = CharacterFunctions::length (text->text);
  7267. const int newTotalLen = oldLen + numExtraChars;
  7268. if (text->refCount > 1)
  7269. {
  7270. // it's in use by other strings as well, so we need to make a private copy before messing with it..
  7271. InternalRefCountedStringHolder* const newTextHolder
  7272. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  7273. + newTotalLen * sizeof (tchar));
  7274. newTextHolder->refCount = 1;
  7275. newTextHolder->allocatedNumChars = newTotalLen;
  7276. memcpy (newTextHolder->text, text->text, oldLen * sizeof (tchar));
  7277. memcpy (newTextHolder->text + oldLen, newText, numExtraChars * sizeof (tchar));
  7278. InternalRefCountedStringHolder* const old = text;
  7279. text = newTextHolder;
  7280. if (atomicDecrementAndReturn (old->refCount) == 0)
  7281. juce_free (old);
  7282. }
  7283. else
  7284. {
  7285. // no other strings using it, so just expand it if needed..
  7286. if (newTotalLen > text->allocatedNumChars)
  7287. {
  7288. text = (InternalRefCountedStringHolder*)
  7289. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7290. + newTotalLen * sizeof (tchar));
  7291. text->allocatedNumChars = newTotalLen;
  7292. }
  7293. memcpy (text->text + oldLen, newText, numExtraChars * sizeof (tchar));
  7294. }
  7295. text->text [newTotalLen] = 0;
  7296. }
  7297. }
  7298. void String::dupeInternalIfMultiplyReferenced() throw()
  7299. {
  7300. if (text->refCount > 1)
  7301. {
  7302. InternalRefCountedStringHolder* const old = text;
  7303. const int len = old->allocatedNumChars;
  7304. InternalRefCountedStringHolder* const newTextHolder
  7305. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  7306. + len * sizeof (tchar));
  7307. newTextHolder->refCount = 1;
  7308. newTextHolder->allocatedNumChars = len;
  7309. memcpy (newTextHolder->text, old->text, (len + 1) * sizeof (tchar));
  7310. text = newTextHolder;
  7311. if (atomicDecrementAndReturn (old->refCount) == 0)
  7312. juce_free (old);
  7313. }
  7314. }
  7315. const String String::empty;
  7316. String::String() throw()
  7317. : text (&emptyString)
  7318. {
  7319. }
  7320. String::String (const String& other) throw()
  7321. : text (other.text)
  7322. {
  7323. atomicIncrement (text->refCount);
  7324. }
  7325. String::String (const int numChars,
  7326. const int /*dummyVariable*/) throw()
  7327. {
  7328. createInternal (numChars);
  7329. }
  7330. String::String (const char* const t) throw()
  7331. {
  7332. if (t != 0 && *t != 0)
  7333. {
  7334. const int len = CharacterFunctions::length (t);
  7335. createInternal (len);
  7336. #if JUCE_STRINGS_ARE_UNICODE
  7337. CharacterFunctions::copy (text->text, t, len + 1);
  7338. #else
  7339. memcpy (text->text, t, len + 1);
  7340. #endif
  7341. }
  7342. else
  7343. {
  7344. text = &emptyString;
  7345. emptyString.refCount = safeEmptyStringRefCount;
  7346. }
  7347. }
  7348. String::String (const juce_wchar* const t) throw()
  7349. {
  7350. if (t != 0 && *t != 0)
  7351. {
  7352. #if JUCE_STRINGS_ARE_UNICODE
  7353. const int len = CharacterFunctions::length (t);
  7354. createInternal (len);
  7355. memcpy (text->text, t, (len + 1) * sizeof (tchar));
  7356. #else
  7357. const int len = CharacterFunctions::bytesRequiredForCopy (t);
  7358. createInternal (len);
  7359. CharacterFunctions::copy (text->text, t, len + 1);
  7360. #endif
  7361. }
  7362. else
  7363. {
  7364. text = &emptyString;
  7365. emptyString.refCount = safeEmptyStringRefCount;
  7366. }
  7367. }
  7368. String::String (const char* const t,
  7369. const int maxChars) throw()
  7370. {
  7371. int i;
  7372. for (i = 0; i < maxChars; ++i)
  7373. if (t[i] == 0)
  7374. break;
  7375. if (i > 0)
  7376. {
  7377. createInternal (i);
  7378. #if JUCE_STRINGS_ARE_UNICODE
  7379. CharacterFunctions::copy (text->text, t, i);
  7380. #else
  7381. memcpy (text->text, t, i);
  7382. #endif
  7383. text->text [i] = 0;
  7384. }
  7385. else
  7386. {
  7387. text = &emptyString;
  7388. emptyString.refCount = safeEmptyStringRefCount;
  7389. }
  7390. }
  7391. String::String (const juce_wchar* const t,
  7392. const int maxChars) throw()
  7393. {
  7394. int i;
  7395. for (i = 0; i < maxChars; ++i)
  7396. if (t[i] == 0)
  7397. break;
  7398. if (i > 0)
  7399. {
  7400. createInternal (i);
  7401. #if JUCE_STRINGS_ARE_UNICODE
  7402. memcpy (text->text, t, i * sizeof (tchar));
  7403. #else
  7404. CharacterFunctions::copy (text->text, t, i);
  7405. #endif
  7406. text->text [i] = 0;
  7407. }
  7408. else
  7409. {
  7410. text = &emptyString;
  7411. emptyString.refCount = safeEmptyStringRefCount;
  7412. }
  7413. }
  7414. const String String::charToString (const tchar character) throw()
  7415. {
  7416. tchar temp[2];
  7417. temp[0] = character;
  7418. temp[1] = 0;
  7419. return String (temp);
  7420. }
  7421. // pass in a pointer to the END of a buffer..
  7422. static tchar* int64ToCharString (tchar* t, const int64 n) throw()
  7423. {
  7424. *--t = 0;
  7425. int64 v = (n >= 0) ? n : -n;
  7426. do
  7427. {
  7428. *--t = (tchar) (T('0') + (int) (v % 10));
  7429. v /= 10;
  7430. } while (v > 0);
  7431. if (n < 0)
  7432. *--t = T('-');
  7433. return t;
  7434. }
  7435. static tchar* intToCharString (tchar* t, const int n) throw()
  7436. {
  7437. if (n == (int) 0x80000000) // (would cause an overflow)
  7438. return int64ToCharString (t, n);
  7439. *--t = 0;
  7440. int v = abs (n);
  7441. do
  7442. {
  7443. *--t = (tchar) (T('0') + (v % 10));
  7444. v /= 10;
  7445. } while (v > 0);
  7446. if (n < 0)
  7447. *--t = T('-');
  7448. return t;
  7449. }
  7450. static tchar* uintToCharString (tchar* t, unsigned int v) throw()
  7451. {
  7452. *--t = 0;
  7453. do
  7454. {
  7455. *--t = (tchar) (T('0') + (v % 10));
  7456. v /= 10;
  7457. } while (v > 0);
  7458. return t;
  7459. }
  7460. String::String (const int number) throw()
  7461. {
  7462. tchar buffer [16];
  7463. tchar* const end = buffer + 16;
  7464. createInternal (intToCharString (end, number), end);
  7465. }
  7466. String::String (const unsigned int number) throw()
  7467. {
  7468. tchar buffer [16];
  7469. tchar* const end = buffer + 16;
  7470. createInternal (uintToCharString (end, number), end);
  7471. }
  7472. String::String (const short number) throw()
  7473. {
  7474. tchar buffer [16];
  7475. tchar* const end = buffer + 16;
  7476. createInternal (intToCharString (end, (int) number), end);
  7477. }
  7478. String::String (const unsigned short number) throw()
  7479. {
  7480. tchar buffer [16];
  7481. tchar* const end = buffer + 16;
  7482. createInternal (uintToCharString (end, (unsigned int) number), end);
  7483. }
  7484. String::String (const int64 number) throw()
  7485. {
  7486. tchar buffer [32];
  7487. tchar* const end = buffer + 32;
  7488. createInternal (int64ToCharString (end, number), end);
  7489. }
  7490. String::String (const uint64 number) throw()
  7491. {
  7492. tchar buffer [32];
  7493. tchar* const end = buffer + 32;
  7494. tchar* t = end;
  7495. *--t = 0;
  7496. int64 v = number;
  7497. do
  7498. {
  7499. *--t = (tchar) (T('0') + (int) (v % 10));
  7500. v /= 10;
  7501. } while (v > 0);
  7502. createInternal (t, end);
  7503. }
  7504. // a double-to-string routine that actually uses the number of dec. places you asked for
  7505. // without resorting to exponent notation if the number's too big or small (which is what printf does).
  7506. void String::doubleToStringWithDecPlaces (double n, int numDecPlaces) throw()
  7507. {
  7508. const int bufSize = 80;
  7509. tchar buffer [bufSize];
  7510. int len;
  7511. tchar* t;
  7512. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  7513. {
  7514. int64 v = (int64) (pow (10.0, numDecPlaces) * fabs (n) + 0.5);
  7515. t = buffer + bufSize;
  7516. *--t = (tchar) 0;
  7517. while (numDecPlaces >= 0 || v > 0)
  7518. {
  7519. if (numDecPlaces == 0)
  7520. *--t = decimalPoint;
  7521. *--t = (tchar) (T('0') + (v % 10));
  7522. v /= 10;
  7523. --numDecPlaces;
  7524. }
  7525. if (n < 0)
  7526. *--t = T('-');
  7527. len = (int) ((buffer + bufSize) - t);
  7528. }
  7529. else
  7530. {
  7531. len = CharacterFunctions::printf (buffer, bufSize, T("%.9g"), n) + 1;
  7532. t = buffer;
  7533. }
  7534. if (len > 1)
  7535. {
  7536. jassert (len < numElementsInArray (buffer));
  7537. createInternal (len - 1);
  7538. memcpy (text->text, t, len * sizeof (tchar));
  7539. }
  7540. else
  7541. {
  7542. jassert (*t == 0);
  7543. text = &emptyString;
  7544. emptyString.refCount = safeEmptyStringRefCount;
  7545. }
  7546. }
  7547. String::String (const float number,
  7548. const int numberOfDecimalPlaces) throw()
  7549. {
  7550. doubleToStringWithDecPlaces ((double) number,
  7551. numberOfDecimalPlaces);
  7552. }
  7553. String::String (const double number,
  7554. const int numberOfDecimalPlaces) throw()
  7555. {
  7556. doubleToStringWithDecPlaces (number,
  7557. numberOfDecimalPlaces);
  7558. }
  7559. String::~String() throw()
  7560. {
  7561. if (atomicDecrementAndReturn (text->refCount) == 0)
  7562. juce_free (text);
  7563. }
  7564. void String::preallocateStorage (const int numChars) throw()
  7565. {
  7566. if (numChars > text->allocatedNumChars)
  7567. {
  7568. dupeInternalIfMultiplyReferenced();
  7569. text = (InternalRefCountedStringHolder*) juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7570. + numChars * sizeof (tchar));
  7571. text->allocatedNumChars = numChars;
  7572. }
  7573. }
  7574. #if JUCE_STRINGS_ARE_UNICODE
  7575. String::operator const char*() const throw()
  7576. {
  7577. if (isEmpty())
  7578. {
  7579. return (const char*) emptyCharString;
  7580. }
  7581. else
  7582. {
  7583. String* const mutableThis = const_cast <String*> (this);
  7584. mutableThis->dupeInternalIfMultiplyReferenced();
  7585. int len = CharacterFunctions::bytesRequiredForCopy (text->text) + 1;
  7586. mutableThis->text = (InternalRefCountedStringHolder*)
  7587. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7588. + (len * sizeof (juce_wchar) + len));
  7589. char* otherCopy = (char*) (text->text + len);
  7590. --len;
  7591. CharacterFunctions::copy (otherCopy, text->text, len);
  7592. otherCopy [len] = 0;
  7593. return otherCopy;
  7594. }
  7595. }
  7596. #else
  7597. String::operator const juce_wchar*() const throw()
  7598. {
  7599. if (isEmpty())
  7600. {
  7601. return (const juce_wchar*) emptyCharString;
  7602. }
  7603. else
  7604. {
  7605. String* const mutableThis = const_cast <String*> (this);
  7606. mutableThis->dupeInternalIfMultiplyReferenced();
  7607. int len = CharacterFunctions::length (text->text) + 1;
  7608. mutableThis->text = (InternalRefCountedStringHolder*)
  7609. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7610. + (len * sizeof (juce_wchar) + len));
  7611. juce_wchar* otherCopy = (juce_wchar*) (text->text + len);
  7612. --len;
  7613. CharacterFunctions::copy (otherCopy, text->text, len);
  7614. otherCopy [len] = 0;
  7615. return otherCopy;
  7616. }
  7617. }
  7618. #endif
  7619. void String::copyToBuffer (char* const destBuffer,
  7620. const int bufferSizeBytes) const throw()
  7621. {
  7622. #if JUCE_STRINGS_ARE_UNICODE
  7623. const int len = jmin (bufferSizeBytes, CharacterFunctions::bytesRequiredForCopy (text->text));
  7624. CharacterFunctions::copy (destBuffer, text->text, len);
  7625. #else
  7626. const int len = jmin (bufferSizeBytes, length());
  7627. memcpy (destBuffer, text->text, len * sizeof (tchar));
  7628. #endif
  7629. destBuffer [len] = 0;
  7630. }
  7631. void String::copyToBuffer (juce_wchar* const destBuffer,
  7632. const int maxCharsToCopy) const throw()
  7633. {
  7634. const int len = jmin (maxCharsToCopy, length());
  7635. #if JUCE_STRINGS_ARE_UNICODE
  7636. memcpy (destBuffer, text->text, len * sizeof (juce_wchar));
  7637. #else
  7638. CharacterFunctions::copy (destBuffer, text->text, len);
  7639. #endif
  7640. destBuffer [len] = 0;
  7641. }
  7642. int String::length() const throw()
  7643. {
  7644. return CharacterFunctions::length (text->text);
  7645. }
  7646. int String::hashCode() const throw()
  7647. {
  7648. const tchar* t = text->text;
  7649. int result = 0;
  7650. while (*t != (tchar) 0)
  7651. result = 31 * result + *t++;
  7652. return result;
  7653. }
  7654. int64 String::hashCode64() const throw()
  7655. {
  7656. const tchar* t = text->text;
  7657. int64 result = 0;
  7658. while (*t != (tchar) 0)
  7659. result = 101 * result + *t++;
  7660. return result;
  7661. }
  7662. const String& String::operator= (const tchar* const otherText) throw()
  7663. {
  7664. if (otherText != 0 && *otherText != 0)
  7665. {
  7666. const int otherLen = CharacterFunctions::length (otherText);
  7667. if (otherLen > 0)
  7668. {
  7669. // avoid resizing the memory block if the string is
  7670. // shrinking..
  7671. if (text->refCount > 1
  7672. || otherLen > text->allocatedNumChars
  7673. || otherLen <= (text->allocatedNumChars >> 1))
  7674. {
  7675. deleteInternal();
  7676. createInternal (otherLen);
  7677. }
  7678. memcpy (text->text, otherText, (otherLen + 1) * sizeof (tchar));
  7679. return *this;
  7680. }
  7681. }
  7682. deleteInternal();
  7683. text = &emptyString;
  7684. emptyString.refCount = safeEmptyStringRefCount;
  7685. return *this;
  7686. }
  7687. const String& String::operator= (const String& other) throw()
  7688. {
  7689. if (this != &other)
  7690. {
  7691. atomicIncrement (other.text->refCount);
  7692. if (atomicDecrementAndReturn (text->refCount) == 0)
  7693. juce_free (text);
  7694. text = other.text;
  7695. }
  7696. return *this;
  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. : isEmpty();
  7707. }
  7708. bool String::equalsIgnoreCase (const tchar* t) const throw()
  7709. {
  7710. return t != 0 ? CharacterFunctions::compareIgnoreCase (text->text, t) == 0
  7711. : isEmpty();
  7712. }
  7713. bool String::equalsIgnoreCase (const String& other) const throw()
  7714. {
  7715. return text == other.text
  7716. || CharacterFunctions::compareIgnoreCase (text->text, other.text->text) == 0;
  7717. }
  7718. bool String::operator!= (const String& other) const throw()
  7719. {
  7720. return text != other.text
  7721. && CharacterFunctions::compare (text->text, other.text->text) != 0;
  7722. }
  7723. bool String::operator!= (const tchar* const t) const throw()
  7724. {
  7725. return t != 0 ? (CharacterFunctions::compare (text->text, t) != 0)
  7726. : isNotEmpty();
  7727. }
  7728. bool String::operator> (const String& other) const throw()
  7729. {
  7730. return compare (other) > 0;
  7731. }
  7732. bool String::operator< (const tchar* const other) const throw()
  7733. {
  7734. return compare (other) < 0;
  7735. }
  7736. bool String::operator>= (const String& other) const throw()
  7737. {
  7738. return compare (other) >= 0;
  7739. }
  7740. bool String::operator<= (const tchar* const other) const throw()
  7741. {
  7742. return compare (other) <= 0;
  7743. }
  7744. int String::compare (const tchar* const other) const throw()
  7745. {
  7746. return other != 0 ? CharacterFunctions::compare (text->text, other)
  7747. : isEmpty();
  7748. }
  7749. int String::compareIgnoreCase (const tchar* const other) const throw()
  7750. {
  7751. return other != 0 ? CharacterFunctions::compareIgnoreCase (text->text, other)
  7752. : isEmpty();
  7753. }
  7754. int String::compareLexicographically (const tchar* other) const throw()
  7755. {
  7756. if (other == 0)
  7757. return isEmpty();
  7758. const tchar* s1 = text->text;
  7759. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  7760. ++s1;
  7761. while (*other != 0 && ! CharacterFunctions::isLetterOrDigit (*other))
  7762. ++other;
  7763. return CharacterFunctions::compareIgnoreCase (s1, other);
  7764. }
  7765. const String String::operator+ (const String& other) const throw()
  7766. {
  7767. if (*(other.text->text) == 0)
  7768. return *this;
  7769. if (isEmpty())
  7770. return other;
  7771. const int len = CharacterFunctions::length (text->text);
  7772. const int otherLen = CharacterFunctions::length (other.text->text);
  7773. String result (len + otherLen, (int) 0);
  7774. memcpy (result.text->text, text->text, len * sizeof (tchar));
  7775. memcpy (result.text->text + len, other.text->text, otherLen * sizeof (tchar));
  7776. result.text->text [len + otherLen] = 0;
  7777. return result;
  7778. }
  7779. const String String::operator+ (const tchar* const textToAppend) const throw()
  7780. {
  7781. if (textToAppend == 0 || *textToAppend == 0)
  7782. return *this;
  7783. const int len = CharacterFunctions::length (text->text);
  7784. const int otherLen = CharacterFunctions::length (textToAppend);
  7785. String result (len + otherLen, (int) 0);
  7786. memcpy (result.text->text, text->text, len * sizeof (tchar));
  7787. memcpy (result.text->text + len, textToAppend, otherLen * sizeof (tchar));
  7788. result.text->text [len + otherLen] = 0;
  7789. return result;
  7790. }
  7791. const String String::operator+ (const tchar characterToAppend) const throw()
  7792. {
  7793. if (characterToAppend == 0)
  7794. return *this;
  7795. const int len = CharacterFunctions::length (text->text);
  7796. String result ((int) (len + 1), (int) 0);
  7797. memcpy (result.text->text, text->text, len * sizeof (tchar));
  7798. result.text->text[len] = characterToAppend;
  7799. result.text->text[len + 1] = 0;
  7800. return result;
  7801. }
  7802. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  7803. const String& string2) throw()
  7804. {
  7805. String s (string1);
  7806. s += string2;
  7807. return s;
  7808. }
  7809. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  7810. const String& string2) throw()
  7811. {
  7812. String s (string1);
  7813. s += string2;
  7814. return s;
  7815. }
  7816. const String& String::operator+= (const tchar* const t) throw()
  7817. {
  7818. if (t != 0)
  7819. appendInternal (t, CharacterFunctions::length (t));
  7820. return *this;
  7821. }
  7822. const String& String::operator+= (const String& other) throw()
  7823. {
  7824. if (isEmpty())
  7825. operator= (other);
  7826. else
  7827. appendInternal (other.text->text,
  7828. CharacterFunctions::length (other.text->text));
  7829. return *this;
  7830. }
  7831. const String& String::operator+= (const char ch) throw()
  7832. {
  7833. char asString[2];
  7834. asString[0] = ch;
  7835. asString[1] = 0;
  7836. #if JUCE_STRINGS_ARE_UNICODE
  7837. operator+= (String (asString));
  7838. #else
  7839. appendInternal (asString, 1);
  7840. #endif
  7841. return *this;
  7842. }
  7843. const String& String::operator+= (const juce_wchar ch) throw()
  7844. {
  7845. juce_wchar asString[2];
  7846. asString[0] = ch;
  7847. asString[1] = 0;
  7848. #if JUCE_STRINGS_ARE_UNICODE
  7849. appendInternal (asString, 1);
  7850. #else
  7851. operator+= (String (asString));
  7852. #endif
  7853. return *this;
  7854. }
  7855. void String::append (const tchar* const other,
  7856. const int howMany) throw()
  7857. {
  7858. if (howMany > 0)
  7859. {
  7860. int i;
  7861. for (i = 0; i < howMany; ++i)
  7862. if (other[i] == 0)
  7863. break;
  7864. appendInternal (other, i);
  7865. }
  7866. }
  7867. String& String::operator<< (const int number) throw()
  7868. {
  7869. tchar buffer [64];
  7870. tchar* const end = buffer + 64;
  7871. const tchar* const t = intToCharString (end, number);
  7872. appendInternal (t, (int) (end - t) - 1);
  7873. return *this;
  7874. }
  7875. String& String::operator<< (const unsigned int number) throw()
  7876. {
  7877. tchar buffer [64];
  7878. tchar* const end = buffer + 64;
  7879. const tchar* const t = uintToCharString (end, number);
  7880. appendInternal (t, (int) (end - t) - 1);
  7881. return *this;
  7882. }
  7883. String& String::operator<< (const short number) throw()
  7884. {
  7885. tchar buffer [64];
  7886. tchar* const end = buffer + 64;
  7887. const tchar* const t = intToCharString (end, (int) number);
  7888. appendInternal (t, (int) (end - t) - 1);
  7889. return *this;
  7890. }
  7891. String& String::operator<< (const double number) throw()
  7892. {
  7893. operator+= (String (number));
  7894. return *this;
  7895. }
  7896. String& String::operator<< (const float number) throw()
  7897. {
  7898. operator+= (String (number));
  7899. return *this;
  7900. }
  7901. String& String::operator<< (const char character) throw()
  7902. {
  7903. operator+= (character);
  7904. return *this;
  7905. }
  7906. String& String::operator<< (const juce_wchar character) throw()
  7907. {
  7908. operator+= (character);
  7909. return *this;
  7910. }
  7911. String& String::operator<< (const char* const t) throw()
  7912. {
  7913. #if JUCE_STRINGS_ARE_UNICODE
  7914. operator+= (String (t));
  7915. #else
  7916. operator+= (t);
  7917. #endif
  7918. return *this;
  7919. }
  7920. String& String::operator<< (const juce_wchar* const t) throw()
  7921. {
  7922. #if JUCE_STRINGS_ARE_UNICODE
  7923. operator+= (t);
  7924. #else
  7925. operator+= (String (t));
  7926. #endif
  7927. return *this;
  7928. }
  7929. String& String::operator<< (const String& t) throw()
  7930. {
  7931. operator+= (t);
  7932. return *this;
  7933. }
  7934. int String::indexOfChar (const tchar character) const throw()
  7935. {
  7936. const tchar* t = text->text;
  7937. for (;;)
  7938. {
  7939. if (*t == character)
  7940. return (int) (t - text->text);
  7941. if (*t++ == 0)
  7942. return -1;
  7943. }
  7944. }
  7945. int String::lastIndexOfChar (const tchar character) const throw()
  7946. {
  7947. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  7948. if (text->text[i] == character)
  7949. return i;
  7950. return -1;
  7951. }
  7952. int String::indexOf (const tchar* const t) const throw()
  7953. {
  7954. const tchar* const r = CharacterFunctions::find (text->text, t);
  7955. return (r == 0) ? -1
  7956. : (int) (r - text->text);
  7957. }
  7958. int String::indexOfChar (const int startIndex,
  7959. const tchar character) const throw()
  7960. {
  7961. if (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text))
  7962. return -1;
  7963. const tchar* t = text->text + jmax (0, startIndex);
  7964. for (;;)
  7965. {
  7966. if (*t == character)
  7967. return (int) (t - text->text);
  7968. if (*t++ == 0)
  7969. return -1;
  7970. }
  7971. }
  7972. int String::indexOfAnyOf (const tchar* const charactersToLookFor,
  7973. const int startIndex,
  7974. const bool ignoreCase) const throw()
  7975. {
  7976. if (charactersToLookFor == 0
  7977. || (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text)))
  7978. return -1;
  7979. const tchar* t = text->text + jmax (0, startIndex);
  7980. while (*t != 0)
  7981. {
  7982. if (CharacterFunctions::indexOfChar (charactersToLookFor, *t, ignoreCase) >= 0)
  7983. return (int) (t - text->text);
  7984. ++t;
  7985. }
  7986. return -1;
  7987. }
  7988. int String::indexOf (const int startIndex,
  7989. const tchar* const other) const throw()
  7990. {
  7991. if (other == 0 || startIndex >= CharacterFunctions::length (text->text))
  7992. return -1;
  7993. const tchar* const found = CharacterFunctions::find (text->text + jmax (0, startIndex),
  7994. other);
  7995. return (found == 0) ? -1
  7996. : (int) (found - text->text);
  7997. }
  7998. int String::indexOfIgnoreCase (const tchar* const other) const throw()
  7999. {
  8000. if (other != 0 && *other != 0)
  8001. {
  8002. const int len = CharacterFunctions::length (other);
  8003. const int end = CharacterFunctions::length (text->text) - len;
  8004. for (int i = 0; i <= end; ++i)
  8005. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  8006. return i;
  8007. }
  8008. return -1;
  8009. }
  8010. int String::indexOfIgnoreCase (const int startIndex,
  8011. const tchar* const other) const throw()
  8012. {
  8013. if (other != 0 && *other != 0)
  8014. {
  8015. const int len = CharacterFunctions::length (other);
  8016. const int end = length() - len;
  8017. for (int i = jmax (0, startIndex); i <= end; ++i)
  8018. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  8019. return i;
  8020. }
  8021. return -1;
  8022. }
  8023. int String::lastIndexOf (const tchar* const other) const throw()
  8024. {
  8025. if (other != 0 && *other != 0)
  8026. {
  8027. const int len = CharacterFunctions::length (other);
  8028. int i = length() - len;
  8029. if (i >= 0)
  8030. {
  8031. const tchar* n = text->text + i;
  8032. while (i >= 0)
  8033. {
  8034. if (CharacterFunctions::compare (n--, other, len) == 0)
  8035. return i;
  8036. --i;
  8037. }
  8038. }
  8039. }
  8040. return -1;
  8041. }
  8042. int String::lastIndexOfIgnoreCase (const tchar* const other) const throw()
  8043. {
  8044. if (other != 0 && *other != 0)
  8045. {
  8046. const int len = CharacterFunctions::length (other);
  8047. int i = length() - len;
  8048. if (i >= 0)
  8049. {
  8050. const tchar* n = text->text + i;
  8051. while (i >= 0)
  8052. {
  8053. if (CharacterFunctions::compareIgnoreCase (n--, other, len) == 0)
  8054. return i;
  8055. --i;
  8056. }
  8057. }
  8058. }
  8059. return -1;
  8060. }
  8061. int String::lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  8062. const bool ignoreCase) const throw()
  8063. {
  8064. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  8065. if (CharacterFunctions::indexOfChar (charactersToLookFor, text->text [i], ignoreCase) >= 0)
  8066. return i;
  8067. return -1;
  8068. }
  8069. bool String::contains (const tchar* const other) const throw()
  8070. {
  8071. return indexOf (other) >= 0;
  8072. }
  8073. bool String::containsChar (const tchar character) const throw()
  8074. {
  8075. return indexOfChar (character) >= 0;
  8076. }
  8077. bool String::containsIgnoreCase (const tchar* const t) const throw()
  8078. {
  8079. return indexOfIgnoreCase (t) >= 0;
  8080. }
  8081. int String::indexOfWholeWord (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::compare (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. int String::indexOfWholeWordIgnoreCase (const tchar* const word) const throw()
  8102. {
  8103. if (word != 0 && *word != 0)
  8104. {
  8105. const int wordLen = CharacterFunctions::length (word);
  8106. const int end = length() - wordLen;
  8107. const tchar* t = text->text;
  8108. for (int i = 0; i <= end; ++i)
  8109. {
  8110. if (CharacterFunctions::compareIgnoreCase (t, word, wordLen) == 0
  8111. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  8112. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  8113. {
  8114. return i;
  8115. }
  8116. ++t;
  8117. }
  8118. }
  8119. return -1;
  8120. }
  8121. bool String::containsWholeWord (const tchar* const wordToLookFor) const throw()
  8122. {
  8123. return indexOfWholeWord (wordToLookFor) >= 0;
  8124. }
  8125. bool String::containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw()
  8126. {
  8127. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  8128. }
  8129. static int indexOfMatch (const tchar* const wildcard,
  8130. const tchar* const test,
  8131. const bool ignoreCase) throw()
  8132. {
  8133. int start = 0;
  8134. while (test [start] != 0)
  8135. {
  8136. int i = 0;
  8137. for (;;)
  8138. {
  8139. const tchar wc = wildcard [i];
  8140. const tchar c = test [i + start];
  8141. if (wc == c
  8142. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  8143. || (wc == T('?') && c != 0))
  8144. {
  8145. if (wc == 0)
  8146. return start;
  8147. ++i;
  8148. }
  8149. else
  8150. {
  8151. if (wc == T('*') && (wildcard [i + 1] == 0
  8152. || indexOfMatch (wildcard + i + 1,
  8153. test + start + i,
  8154. ignoreCase) >= 0))
  8155. {
  8156. return start;
  8157. }
  8158. break;
  8159. }
  8160. }
  8161. ++start;
  8162. }
  8163. return -1;
  8164. }
  8165. bool String::matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw()
  8166. {
  8167. int i = 0;
  8168. for (;;)
  8169. {
  8170. const tchar wc = wildcard [i];
  8171. const tchar c = text->text [i];
  8172. if (wc == c
  8173. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  8174. || (wc == T('?') && c != 0))
  8175. {
  8176. if (wc == 0)
  8177. return true;
  8178. ++i;
  8179. }
  8180. else
  8181. {
  8182. return wc == T('*') && (wildcard [i + 1] == 0
  8183. || indexOfMatch (wildcard + i + 1,
  8184. text->text + i,
  8185. ignoreCase) >= 0);
  8186. }
  8187. }
  8188. }
  8189. void String::printf (const tchar* const pf, ...) throw()
  8190. {
  8191. va_list list;
  8192. va_start (list, pf);
  8193. vprintf (pf, list);
  8194. }
  8195. const String String::formatted (const tchar* const pf, ...) throw()
  8196. {
  8197. va_list list;
  8198. va_start (list, pf);
  8199. String result;
  8200. result.vprintf (pf, list);
  8201. return result;
  8202. }
  8203. void String::vprintf (const tchar* const pf, va_list& args) throw()
  8204. {
  8205. tchar stackBuf [256];
  8206. unsigned int bufSize = 256;
  8207. tchar* buf = stackBuf;
  8208. deleteInternal();
  8209. do
  8210. {
  8211. #if JUCE_LINUX && JUCE_64BIT
  8212. va_list tempArgs;
  8213. va_copy (tempArgs, args);
  8214. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, tempArgs);
  8215. va_end (tempArgs);
  8216. #else
  8217. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, args);
  8218. #endif
  8219. if (num > 0)
  8220. {
  8221. createInternal (num);
  8222. memcpy (text->text, buf, (num + 1) * sizeof (tchar));
  8223. break;
  8224. }
  8225. else if (num == 0)
  8226. {
  8227. text = &emptyString;
  8228. emptyString.refCount = safeEmptyStringRefCount;
  8229. break;
  8230. }
  8231. if (buf != stackBuf)
  8232. juce_free (buf);
  8233. bufSize += 256;
  8234. buf = (tchar*) juce_malloc (bufSize * sizeof (tchar));
  8235. }
  8236. while (bufSize < 65536); // this is a sanity check to avoid situations where vprintf repeatedly
  8237. // returns -1 because of an error rather than because it needs more space.
  8238. if (buf != stackBuf)
  8239. juce_free (buf);
  8240. }
  8241. const String String::repeatedString (const tchar* const stringToRepeat,
  8242. int numberOfTimesToRepeat) throw()
  8243. {
  8244. const int len = CharacterFunctions::length (stringToRepeat);
  8245. String result ((int) (len * numberOfTimesToRepeat + 1), (int) 0);
  8246. tchar* n = result.text->text;
  8247. n[0] = 0;
  8248. while (--numberOfTimesToRepeat >= 0)
  8249. {
  8250. CharacterFunctions::append (n, stringToRepeat);
  8251. n += len;
  8252. }
  8253. return result;
  8254. }
  8255. const String String::replaceSection (int index,
  8256. int numCharsToReplace,
  8257. const tchar* const stringToInsert) const throw()
  8258. {
  8259. if (index < 0)
  8260. {
  8261. // a negative index to replace from?
  8262. jassertfalse
  8263. index = 0;
  8264. }
  8265. if (numCharsToReplace < 0)
  8266. {
  8267. // replacing a negative number of characters?
  8268. numCharsToReplace = 0;
  8269. jassertfalse;
  8270. }
  8271. const int len = length();
  8272. if (index + numCharsToReplace > len)
  8273. {
  8274. if (index > len)
  8275. {
  8276. // replacing beyond the end of the string?
  8277. index = len;
  8278. jassertfalse
  8279. }
  8280. numCharsToReplace = len - index;
  8281. }
  8282. const int newStringLen = (stringToInsert != 0) ? CharacterFunctions::length (stringToInsert) : 0;
  8283. const int newTotalLen = len + newStringLen - numCharsToReplace;
  8284. String result (newTotalLen, (int) 0);
  8285. memcpy (result.text->text,
  8286. text->text,
  8287. index * sizeof (tchar));
  8288. if (newStringLen > 0)
  8289. memcpy (result.text->text + index,
  8290. stringToInsert,
  8291. newStringLen * sizeof (tchar));
  8292. const int endStringLen = newTotalLen - (index + newStringLen);
  8293. if (endStringLen > 0)
  8294. memcpy (result.text->text + (index + newStringLen),
  8295. text->text + (index + numCharsToReplace),
  8296. endStringLen * sizeof (tchar));
  8297. result.text->text [newTotalLen] = 0;
  8298. return result;
  8299. }
  8300. const String String::replace (const tchar* const stringToReplace,
  8301. const tchar* const stringToInsert,
  8302. const bool ignoreCase) const throw()
  8303. {
  8304. const int stringToReplaceLen = CharacterFunctions::length (stringToReplace);
  8305. const int stringToInsertLen = CharacterFunctions::length (stringToInsert);
  8306. int i = 0;
  8307. String result (*this);
  8308. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  8309. : result.indexOf (i, stringToReplace))) >= 0)
  8310. {
  8311. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  8312. i += stringToInsertLen;
  8313. }
  8314. return result;
  8315. }
  8316. const String String::replaceCharacter (const tchar charToReplace,
  8317. const tchar charToInsert) const throw()
  8318. {
  8319. const int index = indexOfChar (charToReplace);
  8320. if (index < 0)
  8321. return *this;
  8322. String result (*this);
  8323. result.dupeInternalIfMultiplyReferenced();
  8324. tchar* t = result.text->text + index;
  8325. while (*t != 0)
  8326. {
  8327. if (*t == charToReplace)
  8328. *t = charToInsert;
  8329. ++t;
  8330. }
  8331. return result;
  8332. }
  8333. const String String::replaceCharacters (const String& charactersToReplace,
  8334. const tchar* const charactersToInsertInstead) const throw()
  8335. {
  8336. String result (*this);
  8337. result.dupeInternalIfMultiplyReferenced();
  8338. tchar* t = result.text->text;
  8339. const int len2 = CharacterFunctions::length (charactersToInsertInstead);
  8340. // the two strings passed in are supposed to be the same length!
  8341. jassert (len2 == charactersToReplace.length());
  8342. while (*t != 0)
  8343. {
  8344. const int index = charactersToReplace.indexOfChar (*t);
  8345. if (((unsigned int) index) < (unsigned int) len2)
  8346. *t = charactersToInsertInstead [index];
  8347. ++t;
  8348. }
  8349. return result;
  8350. }
  8351. bool String::startsWith (const tchar* const other) const throw()
  8352. {
  8353. return other != 0
  8354. && CharacterFunctions::compare (text->text, other, CharacterFunctions::length (other)) == 0;
  8355. }
  8356. bool String::startsWithIgnoreCase (const tchar* const other) const throw()
  8357. {
  8358. return other != 0
  8359. && CharacterFunctions::compareIgnoreCase (text->text, other, CharacterFunctions::length (other)) == 0;
  8360. }
  8361. bool String::startsWithChar (const tchar character) const throw()
  8362. {
  8363. return text->text[0] == character;
  8364. }
  8365. bool String::endsWithChar (const tchar character) const throw()
  8366. {
  8367. return text->text[0] != 0
  8368. && text->text [length() - 1] == character;
  8369. }
  8370. bool String::endsWith (const tchar* const other) const throw()
  8371. {
  8372. if (other == 0)
  8373. return false;
  8374. const int thisLen = length();
  8375. const int otherLen = CharacterFunctions::length (other);
  8376. return thisLen >= otherLen
  8377. && CharacterFunctions::compare (text->text + thisLen - otherLen, other) == 0;
  8378. }
  8379. bool String::endsWithIgnoreCase (const tchar* const other) const throw()
  8380. {
  8381. if (other == 0)
  8382. return false;
  8383. const int thisLen = length();
  8384. const int otherLen = CharacterFunctions::length (other);
  8385. return thisLen >= otherLen
  8386. && CharacterFunctions::compareIgnoreCase (text->text + thisLen - otherLen, other) == 0;
  8387. }
  8388. const String String::toUpperCase() const throw()
  8389. {
  8390. String result (*this);
  8391. result.dupeInternalIfMultiplyReferenced();
  8392. CharacterFunctions::toUpperCase (result.text->text);
  8393. return result;
  8394. }
  8395. const String String::toLowerCase() const throw()
  8396. {
  8397. String result (*this);
  8398. result.dupeInternalIfMultiplyReferenced();
  8399. CharacterFunctions::toLowerCase (result.text->text);
  8400. return result;
  8401. }
  8402. tchar& String::operator[] (const int index) throw()
  8403. {
  8404. jassert (((unsigned int) index) <= (unsigned int) length());
  8405. dupeInternalIfMultiplyReferenced();
  8406. return text->text [index];
  8407. }
  8408. tchar String::getLastCharacter() const throw()
  8409. {
  8410. return (isEmpty()) ? ((tchar) 0)
  8411. : text->text [CharacterFunctions::length (text->text) - 1];
  8412. }
  8413. const String String::substring (int start, int end) const throw()
  8414. {
  8415. if (start < 0)
  8416. start = 0;
  8417. else if (end <= start)
  8418. return empty;
  8419. int len = 0;
  8420. const tchar* const t = text->text;
  8421. while (len <= end && t [len] != 0)
  8422. ++len;
  8423. if (end >= len)
  8424. {
  8425. if (start == 0)
  8426. return *this;
  8427. end = len;
  8428. }
  8429. return String (text->text + start,
  8430. end - start);
  8431. }
  8432. const String String::substring (const int start) const throw()
  8433. {
  8434. if (start <= 0)
  8435. return *this;
  8436. const int len = CharacterFunctions::length (text->text);
  8437. if (start >= len)
  8438. return empty;
  8439. else
  8440. return String (text->text + start,
  8441. len - start);
  8442. }
  8443. const String String::dropLastCharacters (const int numberToDrop) const throw()
  8444. {
  8445. return String (text->text,
  8446. jmax (0, CharacterFunctions::length (text->text) - numberToDrop));
  8447. }
  8448. const String String::fromFirstOccurrenceOf (const tchar* const sub,
  8449. const bool includeSubString,
  8450. const bool ignoreCase) const throw()
  8451. {
  8452. const int i = ignoreCase ? indexOf (sub)
  8453. : indexOfIgnoreCase (sub);
  8454. if (i < 0)
  8455. return empty;
  8456. else
  8457. return substring ((includeSubString) ? i : i + CharacterFunctions::length (sub));
  8458. }
  8459. const String String::fromLastOccurrenceOf (const tchar* const sub,
  8460. const bool includeSubString,
  8461. const bool ignoreCase) const throw()
  8462. {
  8463. const int i = ignoreCase ? lastIndexOf (sub)
  8464. : lastIndexOfIgnoreCase (sub);
  8465. if (i < 0)
  8466. return *this;
  8467. else
  8468. return substring ((includeSubString) ? i : i + CharacterFunctions::length (sub));
  8469. }
  8470. const String String::upToFirstOccurrenceOf (const tchar* const sub,
  8471. const bool includeSubString,
  8472. const bool ignoreCase) const throw()
  8473. {
  8474. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  8475. : indexOf (sub);
  8476. if (i < 0)
  8477. return *this;
  8478. else
  8479. return substring (0, (includeSubString) ? i + CharacterFunctions::length (sub) : i);
  8480. }
  8481. const String String::upToLastOccurrenceOf (const tchar* const sub,
  8482. const bool includeSubString,
  8483. const bool ignoreCase) const throw()
  8484. {
  8485. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  8486. : lastIndexOf (sub);
  8487. if (i < 0)
  8488. return *this;
  8489. return substring (0, (includeSubString) ? i + CharacterFunctions::length (sub) : i);
  8490. }
  8491. bool String::isQuotedString() const throw()
  8492. {
  8493. const String trimmed (trimStart());
  8494. return trimmed[0] == T('"')
  8495. || trimmed[0] == T('\'');
  8496. }
  8497. const String String::unquoted() const throw()
  8498. {
  8499. String s (*this);
  8500. if (s[0] == T('"') || s[0] == T('\''))
  8501. s = s.substring (1);
  8502. const int lastCharIndex = s.length() - 1;
  8503. if (lastCharIndex >= 0
  8504. && (s [lastCharIndex] == T('"') || s[lastCharIndex] == T('\'')))
  8505. s [lastCharIndex] = 0;
  8506. return s;
  8507. }
  8508. const String String::quoted (const tchar quoteCharacter) const throw()
  8509. {
  8510. if (isEmpty())
  8511. return charToString (quoteCharacter) + quoteCharacter;
  8512. String t (*this);
  8513. if (! t.startsWithChar (quoteCharacter))
  8514. t = charToString (quoteCharacter) + t;
  8515. if (! t.endsWithChar (quoteCharacter))
  8516. t += quoteCharacter;
  8517. return t;
  8518. }
  8519. const String String::trim() const throw()
  8520. {
  8521. if (isEmpty())
  8522. return empty;
  8523. int start = 0;
  8524. while (CharacterFunctions::isWhitespace (text->text [start]))
  8525. ++start;
  8526. const int len = CharacterFunctions::length (text->text);
  8527. int end = len - 1;
  8528. while ((end >= start) && CharacterFunctions::isWhitespace (text->text [end]))
  8529. --end;
  8530. ++end;
  8531. if (end <= start)
  8532. return empty;
  8533. else if (start > 0 || end < len)
  8534. return String (text->text + start, end - start);
  8535. else
  8536. return *this;
  8537. }
  8538. const String String::trimStart() const throw()
  8539. {
  8540. if (isEmpty())
  8541. return empty;
  8542. const tchar* t = text->text;
  8543. while (CharacterFunctions::isWhitespace (*t))
  8544. ++t;
  8545. if (t == text->text)
  8546. return *this;
  8547. else
  8548. return String (t);
  8549. }
  8550. const String String::trimEnd() const throw()
  8551. {
  8552. if (isEmpty())
  8553. return empty;
  8554. const tchar* endT = text->text + (CharacterFunctions::length (text->text) - 1);
  8555. while ((endT >= text->text) && CharacterFunctions::isWhitespace (*endT))
  8556. --endT;
  8557. return String (text->text, (int) (++endT - text->text));
  8558. }
  8559. const String String::retainCharacters (const tchar* const charactersToRetain) const throw()
  8560. {
  8561. jassert (charactersToRetain != 0);
  8562. if (isEmpty())
  8563. return empty;
  8564. String result (text->allocatedNumChars, (int) 0);
  8565. tchar* dst = result.text->text;
  8566. const tchar* src = text->text;
  8567. while (*src != 0)
  8568. {
  8569. if (CharacterFunctions::indexOfCharFast (charactersToRetain, *src) >= 0)
  8570. *dst++ = *src;
  8571. ++src;
  8572. }
  8573. *dst = 0;
  8574. return result;
  8575. }
  8576. const String String::removeCharacters (const tchar* const charactersToRemove) const throw()
  8577. {
  8578. jassert (charactersToRemove != 0);
  8579. if (isEmpty())
  8580. return empty;
  8581. String result (text->allocatedNumChars, (int) 0);
  8582. tchar* dst = result.text->text;
  8583. const tchar* src = text->text;
  8584. while (*src != 0)
  8585. {
  8586. if (CharacterFunctions::indexOfCharFast (charactersToRemove, *src) < 0)
  8587. *dst++ = *src;
  8588. ++src;
  8589. }
  8590. *dst = 0;
  8591. return result;
  8592. }
  8593. const String String::initialSectionContainingOnly (const tchar* const permittedCharacters) const throw()
  8594. {
  8595. return substring (0, CharacterFunctions::getIntialSectionContainingOnly (text->text, permittedCharacters));
  8596. }
  8597. const String String::initialSectionNotContaining (const tchar* const charactersToStopAt) const throw()
  8598. {
  8599. jassert (charactersToStopAt != 0);
  8600. const tchar* const t = text->text;
  8601. int i = 0;
  8602. while (t[i] != 0)
  8603. {
  8604. if (CharacterFunctions::indexOfCharFast (charactersToStopAt, t[i]) >= 0)
  8605. return String (text->text, i);
  8606. ++i;
  8607. }
  8608. return empty;
  8609. }
  8610. bool String::containsOnly (const tchar* const chars) const throw()
  8611. {
  8612. jassert (chars != 0);
  8613. const tchar* t = text->text;
  8614. while (*t != 0)
  8615. if (CharacterFunctions::indexOfCharFast (chars, *t++) < 0)
  8616. return false;
  8617. return true;
  8618. }
  8619. bool String::containsAnyOf (const tchar* const chars) const throw()
  8620. {
  8621. jassert (chars != 0);
  8622. const tchar* t = text->text;
  8623. while (*t != 0)
  8624. if (CharacterFunctions::indexOfCharFast (chars, *t++) >= 0)
  8625. return true;
  8626. return false;
  8627. }
  8628. int String::getIntValue() const throw()
  8629. {
  8630. return CharacterFunctions::getIntValue (text->text);
  8631. }
  8632. int String::getTrailingIntValue() const throw()
  8633. {
  8634. int n = 0;
  8635. int mult = 1;
  8636. const tchar* t = text->text + length();
  8637. while (--t >= text->text)
  8638. {
  8639. const tchar c = *t;
  8640. if (! CharacterFunctions::isDigit (c))
  8641. {
  8642. if (c == T('-'))
  8643. n = -n;
  8644. break;
  8645. }
  8646. n += mult * (c - T('0'));
  8647. mult *= 10;
  8648. }
  8649. return n;
  8650. }
  8651. int64 String::getLargeIntValue() const throw()
  8652. {
  8653. return CharacterFunctions::getInt64Value (text->text);
  8654. }
  8655. float String::getFloatValue() const throw()
  8656. {
  8657. return (float) CharacterFunctions::getDoubleValue (text->text);
  8658. }
  8659. double String::getDoubleValue() const throw()
  8660. {
  8661. return CharacterFunctions::getDoubleValue (text->text);
  8662. }
  8663. static const tchar* const hexDigits = T("0123456789abcdef");
  8664. const String String::toHexString (const int number) throw()
  8665. {
  8666. tchar buffer[32];
  8667. tchar* const end = buffer + 32;
  8668. tchar* t = end;
  8669. *--t = 0;
  8670. unsigned int v = (unsigned int) number;
  8671. do
  8672. {
  8673. *--t = hexDigits [v & 15];
  8674. v >>= 4;
  8675. } while (v != 0);
  8676. return String (t, (int) (((char*) end) - (char*) t) - 1);
  8677. }
  8678. const String String::toHexString (const int64 number) throw()
  8679. {
  8680. tchar buffer[32];
  8681. tchar* const end = buffer + 32;
  8682. tchar* t = end;
  8683. *--t = 0;
  8684. uint64 v = (uint64) number;
  8685. do
  8686. {
  8687. *--t = hexDigits [(int) (v & 15)];
  8688. v >>= 4;
  8689. } while (v != 0);
  8690. return String (t, (int) (((char*) end) - (char*) t));
  8691. }
  8692. const String String::toHexString (const short number) throw()
  8693. {
  8694. return toHexString ((int) (unsigned short) number);
  8695. }
  8696. const String String::toHexString (const unsigned char* data,
  8697. const int size,
  8698. const int groupSize) throw()
  8699. {
  8700. if (size <= 0)
  8701. return empty;
  8702. int numChars = (size * 2) + 2;
  8703. if (groupSize > 0)
  8704. numChars += size / groupSize;
  8705. String s (numChars, (int) 0);
  8706. tchar* d = s.text->text;
  8707. for (int i = 0; i < size; ++i)
  8708. {
  8709. *d++ = hexDigits [(*data) >> 4];
  8710. *d++ = hexDigits [(*data) & 0xf];
  8711. ++data;
  8712. if (groupSize > 0 && (i % groupSize) == 0)
  8713. *d++ = T(' ');
  8714. }
  8715. if (groupSize > 0)
  8716. --d;
  8717. *d = 0;
  8718. return s;
  8719. }
  8720. int String::getHexValue32() const throw()
  8721. {
  8722. int result = 0;
  8723. const tchar* c = text->text;
  8724. for (;;)
  8725. {
  8726. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  8727. if (hexValue >= 0)
  8728. result = (result << 4) | hexValue;
  8729. else if (*c == 0)
  8730. break;
  8731. ++c;
  8732. }
  8733. return result;
  8734. }
  8735. int64 String::getHexValue64() const throw()
  8736. {
  8737. int64 result = 0;
  8738. const tchar* c = text->text;
  8739. for (;;)
  8740. {
  8741. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  8742. if (hexValue >= 0)
  8743. result = (result << 4) | hexValue;
  8744. else if (*c == 0)
  8745. break;
  8746. ++c;
  8747. }
  8748. return result;
  8749. }
  8750. const String String::createStringFromData (const void* const data_,
  8751. const int size) throw()
  8752. {
  8753. const char* const data = (const char*) data_;
  8754. if (size <= 0 || data == 0)
  8755. {
  8756. return empty;
  8757. }
  8758. else if (size < 2)
  8759. {
  8760. return charToString (data[0]);
  8761. }
  8762. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  8763. || (data[0] == (char)-1 && data[1] == (char)-2))
  8764. {
  8765. // assume it's 16-bit unicode
  8766. const bool bigEndian = (data[0] == (char)-2);
  8767. const int numChars = size / 2 - 1;
  8768. String result;
  8769. result.preallocateStorage (numChars + 2);
  8770. const uint16* const src = (const uint16*) (data + 2);
  8771. tchar* const dst = const_cast <tchar*> ((const tchar*) result);
  8772. if (bigEndian)
  8773. {
  8774. for (int i = 0; i < numChars; ++i)
  8775. dst[i] = (tchar) swapIfLittleEndian (src[i]);
  8776. }
  8777. else
  8778. {
  8779. for (int i = 0; i < numChars; ++i)
  8780. dst[i] = (tchar) swapIfBigEndian (src[i]);
  8781. }
  8782. dst [numChars] = 0;
  8783. return result;
  8784. }
  8785. else
  8786. {
  8787. #if JUCE_STRINGS_ARE_UNICODE && JUCE_LINUX
  8788. // (workaround for strange behaviour of mbstowcs)
  8789. int i;
  8790. for (i = 0; i < size; ++i)
  8791. if (data[i] == 0)
  8792. break;
  8793. String result;
  8794. result.preallocateStorage (i + 1);
  8795. tchar* const dst = const_cast <tchar*> ((const tchar*) result);
  8796. for (int j = 0; j < i; ++j)
  8797. dst[j] = (juce_wchar) (unsigned char) data[j];
  8798. dst[i] = 0;
  8799. return result;
  8800. #else
  8801. return String (data, size);
  8802. #endif
  8803. }
  8804. }
  8805. const char* String::toUTF8() const throw()
  8806. {
  8807. if (isEmpty())
  8808. {
  8809. return (const char*) emptyCharString;
  8810. }
  8811. else
  8812. {
  8813. String* const mutableThis = const_cast <String*> (this);
  8814. mutableThis->dupeInternalIfMultiplyReferenced();
  8815. const int currentLen = CharacterFunctions::length (text->text) + 1;
  8816. const int utf8BytesNeeded = copyToUTF8 (0);
  8817. mutableThis->text = (InternalRefCountedStringHolder*)
  8818. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8819. + (currentLen * sizeof (juce_wchar) + utf8BytesNeeded));
  8820. char* const otherCopy = (char*) (text->text + currentLen);
  8821. copyToUTF8 ((uint8*) otherCopy);
  8822. return otherCopy;
  8823. }
  8824. }
  8825. int String::copyToUTF8 (uint8* const buffer) const throw()
  8826. {
  8827. #if JUCE_STRINGS_ARE_UNICODE
  8828. int num = 0, index = 0;
  8829. for (;;)
  8830. {
  8831. const uint32 c = (uint32) text->text [index++];
  8832. if (c >= 0x80)
  8833. {
  8834. int numExtraBytes = 1;
  8835. if (c >= 0x800)
  8836. {
  8837. ++numExtraBytes;
  8838. if (c >= 0x10000)
  8839. {
  8840. ++numExtraBytes;
  8841. if (c >= 0x200000)
  8842. {
  8843. ++numExtraBytes;
  8844. if (c >= 0x4000000)
  8845. ++numExtraBytes;
  8846. }
  8847. }
  8848. }
  8849. if (buffer != 0)
  8850. {
  8851. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  8852. while (--numExtraBytes >= 0)
  8853. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  8854. }
  8855. else
  8856. {
  8857. num += numExtraBytes + 1;
  8858. }
  8859. }
  8860. else
  8861. {
  8862. if (buffer != 0)
  8863. buffer [num] = (uint8) c;
  8864. ++num;
  8865. }
  8866. if (c == 0)
  8867. break;
  8868. }
  8869. return num;
  8870. #else
  8871. const int numBytes = length() + 1;
  8872. if (buffer != 0)
  8873. copyToBuffer ((char*) buffer, numBytes);
  8874. return numBytes;
  8875. #endif
  8876. }
  8877. const String String::fromUTF8 (const uint8* const buffer, int bufferSizeBytes) throw()
  8878. {
  8879. if (buffer == 0)
  8880. return empty;
  8881. if (bufferSizeBytes < 0)
  8882. bufferSizeBytes = INT_MAX;
  8883. int numBytes;
  8884. for (numBytes = 0; numBytes < bufferSizeBytes; ++numBytes)
  8885. if (buffer [numBytes] == 0)
  8886. break;
  8887. String result (numBytes + 1, 0);
  8888. tchar* dest = result.text->text;
  8889. int i = 0;
  8890. while (i < numBytes)
  8891. {
  8892. const uint8 c = buffer [i++];
  8893. if ((c & 0x80) != 0)
  8894. {
  8895. int mask = 0x7f;
  8896. int bit = 0x40;
  8897. int numExtraValues = 0;
  8898. while (bit != 0 && (c & bit) != 0)
  8899. {
  8900. bit >>= 1;
  8901. mask >>= 1;
  8902. ++numExtraValues;
  8903. }
  8904. int n = (c & mask);
  8905. while (--numExtraValues >= 0 && i < bufferSizeBytes)
  8906. {
  8907. const uint8 c = buffer[i];
  8908. if ((c & 0xc0) != 0x80)
  8909. break;
  8910. n <<= 6;
  8911. n |= (c & 0x3f);
  8912. ++i;
  8913. }
  8914. *dest++ = (tchar) n;
  8915. }
  8916. else
  8917. {
  8918. *dest++ = (tchar) c;
  8919. }
  8920. }
  8921. *dest = 0;
  8922. return result;
  8923. }
  8924. END_JUCE_NAMESPACE
  8925. /********* End of inlined file: juce_String.cpp *********/
  8926. /********* Start of inlined file: juce_StringArray.cpp *********/
  8927. BEGIN_JUCE_NAMESPACE
  8928. StringArray::StringArray() throw()
  8929. {
  8930. }
  8931. StringArray::StringArray (const StringArray& other) throw()
  8932. {
  8933. addArray (other);
  8934. }
  8935. StringArray::StringArray (const juce_wchar** const strings,
  8936. const int numberOfStrings) throw()
  8937. {
  8938. for (int i = 0; i < numberOfStrings; ++i)
  8939. add (strings [i]);
  8940. }
  8941. StringArray::StringArray (const char** const strings,
  8942. const int numberOfStrings) throw()
  8943. {
  8944. for (int i = 0; i < numberOfStrings; ++i)
  8945. add (strings [i]);
  8946. }
  8947. StringArray::StringArray (const juce_wchar** const strings) throw()
  8948. {
  8949. int i = 0;
  8950. while (strings[i] != 0)
  8951. add (strings [i++]);
  8952. }
  8953. StringArray::StringArray (const char** const strings) throw()
  8954. {
  8955. int i = 0;
  8956. while (strings[i] != 0)
  8957. add (strings [i++]);
  8958. }
  8959. const StringArray& StringArray::operator= (const StringArray& other) throw()
  8960. {
  8961. if (this != &other)
  8962. {
  8963. clear();
  8964. addArray (other);
  8965. }
  8966. return *this;
  8967. }
  8968. StringArray::~StringArray() throw()
  8969. {
  8970. clear();
  8971. }
  8972. bool StringArray::operator== (const StringArray& other) const throw()
  8973. {
  8974. if (other.size() != size())
  8975. return false;
  8976. for (int i = size(); --i >= 0;)
  8977. {
  8978. if (*(String*) other.strings.getUnchecked(i)
  8979. != *(String*) strings.getUnchecked(i))
  8980. {
  8981. return false;
  8982. }
  8983. }
  8984. return true;
  8985. }
  8986. bool StringArray::operator!= (const StringArray& other) const throw()
  8987. {
  8988. return ! operator== (other);
  8989. }
  8990. void StringArray::clear() throw()
  8991. {
  8992. for (int i = size(); --i >= 0;)
  8993. {
  8994. String* const s = (String*) strings.getUnchecked(i);
  8995. delete s;
  8996. }
  8997. strings.clear();
  8998. }
  8999. const String& StringArray::operator[] (const int index) const throw()
  9000. {
  9001. if (((unsigned int) index) < (unsigned int) strings.size())
  9002. return *(const String*) (strings.getUnchecked (index));
  9003. return String::empty;
  9004. }
  9005. void StringArray::add (const String& newString) throw()
  9006. {
  9007. strings.add (new String (newString));
  9008. }
  9009. void StringArray::insert (const int index,
  9010. const String& newString) throw()
  9011. {
  9012. strings.insert (index, new String (newString));
  9013. }
  9014. void StringArray::addIfNotAlreadyThere (const String& newString,
  9015. const bool ignoreCase) throw()
  9016. {
  9017. if (! contains (newString, ignoreCase))
  9018. add (newString);
  9019. }
  9020. void StringArray::addArray (const StringArray& otherArray,
  9021. int startIndex,
  9022. int numElementsToAdd) throw()
  9023. {
  9024. if (startIndex < 0)
  9025. {
  9026. jassertfalse
  9027. startIndex = 0;
  9028. }
  9029. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  9030. numElementsToAdd = otherArray.size() - startIndex;
  9031. while (--numElementsToAdd >= 0)
  9032. strings.add (new String (*(const String*) otherArray.strings.getUnchecked (startIndex++)));
  9033. }
  9034. void StringArray::set (const int index,
  9035. const String& newString) throw()
  9036. {
  9037. String* const s = (String*) strings [index];
  9038. if (s != 0)
  9039. {
  9040. *s = newString;
  9041. }
  9042. else if (index >= 0)
  9043. {
  9044. add (newString);
  9045. }
  9046. }
  9047. bool StringArray::contains (const String& stringToLookFor,
  9048. const bool ignoreCase) const throw()
  9049. {
  9050. if (ignoreCase)
  9051. {
  9052. for (int i = size(); --i >= 0;)
  9053. if (stringToLookFor.equalsIgnoreCase (*(const String*)(strings.getUnchecked(i))))
  9054. return true;
  9055. }
  9056. else
  9057. {
  9058. for (int i = size(); --i >= 0;)
  9059. if (stringToLookFor == *(const String*)(strings.getUnchecked(i)))
  9060. return true;
  9061. }
  9062. return false;
  9063. }
  9064. int StringArray::indexOf (const String& stringToLookFor,
  9065. const bool ignoreCase,
  9066. int i) const throw()
  9067. {
  9068. if (i < 0)
  9069. i = 0;
  9070. const int numElements = size();
  9071. if (ignoreCase)
  9072. {
  9073. while (i < numElements)
  9074. {
  9075. if (stringToLookFor.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  9076. return i;
  9077. ++i;
  9078. }
  9079. }
  9080. else
  9081. {
  9082. while (i < numElements)
  9083. {
  9084. if (stringToLookFor == *(const String*) strings.getUnchecked (i))
  9085. return i;
  9086. ++i;
  9087. }
  9088. }
  9089. return -1;
  9090. }
  9091. void StringArray::remove (const int index) throw()
  9092. {
  9093. String* const s = (String*) strings [index];
  9094. if (s != 0)
  9095. {
  9096. strings.remove (index);
  9097. delete s;
  9098. }
  9099. }
  9100. void StringArray::removeString (const String& stringToRemove,
  9101. const bool ignoreCase) throw()
  9102. {
  9103. if (ignoreCase)
  9104. {
  9105. for (int i = size(); --i >= 0;)
  9106. if (stringToRemove.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  9107. remove (i);
  9108. }
  9109. else
  9110. {
  9111. for (int i = size(); --i >= 0;)
  9112. if (stringToRemove == *(const String*) strings.getUnchecked (i))
  9113. remove (i);
  9114. }
  9115. }
  9116. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings) throw()
  9117. {
  9118. if (removeWhitespaceStrings)
  9119. {
  9120. for (int i = size(); --i >= 0;)
  9121. if (((const String*) strings.getUnchecked(i))->trim().isEmpty())
  9122. remove (i);
  9123. }
  9124. else
  9125. {
  9126. for (int i = size(); --i >= 0;)
  9127. if (((const String*) strings.getUnchecked(i))->isEmpty())
  9128. remove (i);
  9129. }
  9130. }
  9131. void StringArray::trim() throw()
  9132. {
  9133. for (int i = size(); --i >= 0;)
  9134. {
  9135. String& s = *(String*) strings.getUnchecked(i);
  9136. s = s.trim();
  9137. }
  9138. }
  9139. class InternalStringArrayComparator
  9140. {
  9141. public:
  9142. static int compareElements (void* const first, void* const second) throw()
  9143. {
  9144. return ((const String*) first)->compare (*(const String*) second);
  9145. }
  9146. };
  9147. class InsensitiveInternalStringArrayComparator
  9148. {
  9149. public:
  9150. static int compareElements (void* const first, void* const second) throw()
  9151. {
  9152. return ((const String*) first)->compareIgnoreCase (*(const String*) second);
  9153. }
  9154. };
  9155. void StringArray::sort (const bool ignoreCase) throw()
  9156. {
  9157. if (ignoreCase)
  9158. {
  9159. InsensitiveInternalStringArrayComparator comp;
  9160. strings.sort (comp);
  9161. }
  9162. else
  9163. {
  9164. InternalStringArrayComparator comp;
  9165. strings.sort (comp);
  9166. }
  9167. }
  9168. void StringArray::move (const int currentIndex, int newIndex) throw()
  9169. {
  9170. strings.move (currentIndex, newIndex);
  9171. }
  9172. const String StringArray::joinIntoString (const String& separator,
  9173. int start,
  9174. int numberToJoin) const throw()
  9175. {
  9176. const int last = (numberToJoin < 0) ? size()
  9177. : jmin (size(), start + numberToJoin);
  9178. if (start < 0)
  9179. start = 0;
  9180. if (start >= last)
  9181. return String::empty;
  9182. if (start == last - 1)
  9183. return *(const String*) strings.getUnchecked (start);
  9184. const int separatorLen = separator.length();
  9185. int charsNeeded = separatorLen * (last - start - 1);
  9186. for (int i = start; i < last; ++i)
  9187. charsNeeded += ((const String*) strings.getUnchecked(i))->length();
  9188. String result;
  9189. result.preallocateStorage (charsNeeded);
  9190. tchar* dest = (tchar*) (const tchar*) result;
  9191. while (start < last)
  9192. {
  9193. const String& s = *(const String*) strings.getUnchecked (start);
  9194. const int len = s.length();
  9195. if (len > 0)
  9196. {
  9197. s.copyToBuffer (dest, len);
  9198. dest += len;
  9199. }
  9200. if (++start < last && separatorLen > 0)
  9201. {
  9202. separator.copyToBuffer (dest, separatorLen);
  9203. dest += separatorLen;
  9204. }
  9205. }
  9206. *dest = 0;
  9207. return result;
  9208. }
  9209. int StringArray::addTokens (const tchar* const text,
  9210. const bool preserveQuotedStrings) throw()
  9211. {
  9212. return addTokens (text,
  9213. T(" \n\r\t"),
  9214. preserveQuotedStrings ? T("\"") : 0);
  9215. }
  9216. int StringArray::addTokens (const tchar* const text,
  9217. const tchar* breakCharacters,
  9218. const tchar* quoteCharacters) throw()
  9219. {
  9220. int num = 0;
  9221. if (text != 0 && *text != 0)
  9222. {
  9223. if (breakCharacters == 0)
  9224. breakCharacters = T("");
  9225. if (quoteCharacters == 0)
  9226. quoteCharacters = T("");
  9227. bool insideQuotes = false;
  9228. tchar currentQuoteChar = 0;
  9229. int i = 0;
  9230. int tokenStart = 0;
  9231. for (;;)
  9232. {
  9233. const tchar c = text[i];
  9234. bool isBreak = (c == 0);
  9235. if (! (insideQuotes || isBreak))
  9236. {
  9237. const tchar* b = breakCharacters;
  9238. while (*b != 0)
  9239. {
  9240. if (*b++ == c)
  9241. {
  9242. isBreak = true;
  9243. break;
  9244. }
  9245. }
  9246. }
  9247. if (! isBreak)
  9248. {
  9249. bool isQuote = false;
  9250. const tchar* q = quoteCharacters;
  9251. while (*q != 0)
  9252. {
  9253. if (*q++ == c)
  9254. {
  9255. isQuote = true;
  9256. break;
  9257. }
  9258. }
  9259. if (isQuote)
  9260. {
  9261. if (insideQuotes)
  9262. {
  9263. // only break out of quotes-mode if we find a matching quote to the
  9264. // one that we opened with..
  9265. if (currentQuoteChar == c)
  9266. insideQuotes = false;
  9267. }
  9268. else
  9269. {
  9270. insideQuotes = true;
  9271. currentQuoteChar = c;
  9272. }
  9273. }
  9274. }
  9275. else
  9276. {
  9277. add (String (text + tokenStart, i - tokenStart));
  9278. ++num;
  9279. tokenStart = i + 1;
  9280. }
  9281. if (c == 0)
  9282. break;
  9283. ++i;
  9284. }
  9285. }
  9286. return num;
  9287. }
  9288. int StringArray::addLines (const tchar* text) throw()
  9289. {
  9290. int numLines = 0;
  9291. if (text != 0)
  9292. {
  9293. while (*text != 0)
  9294. {
  9295. const tchar* const startOfLine = text;
  9296. while (*text != 0)
  9297. {
  9298. if (*text == T('\r'))
  9299. {
  9300. ++text;
  9301. if (*text == T('\n'))
  9302. ++text;
  9303. break;
  9304. }
  9305. if (*text == T('\n'))
  9306. {
  9307. ++text;
  9308. break;
  9309. }
  9310. ++text;
  9311. }
  9312. const tchar* endOfLine = text;
  9313. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  9314. --endOfLine;
  9315. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  9316. --endOfLine;
  9317. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  9318. ++numLines;
  9319. }
  9320. }
  9321. return numLines;
  9322. }
  9323. void StringArray::removeDuplicates (const bool ignoreCase) throw()
  9324. {
  9325. for (int i = 0; i < size() - 1; ++i)
  9326. {
  9327. const String& s = *(String*) strings.getUnchecked(i);
  9328. int nextIndex = i + 1;
  9329. for (;;)
  9330. {
  9331. nextIndex = indexOf (s, ignoreCase, nextIndex);
  9332. if (nextIndex < 0)
  9333. break;
  9334. remove (nextIndex);
  9335. }
  9336. }
  9337. }
  9338. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  9339. const bool appendNumberToFirstInstance,
  9340. const tchar* const preNumberString,
  9341. const tchar* const postNumberString) throw()
  9342. {
  9343. for (int i = 0; i < size() - 1; ++i)
  9344. {
  9345. String& s = *(String*) strings.getUnchecked(i);
  9346. int nextIndex = indexOf (s, ignoreCase, i + 1);
  9347. if (nextIndex >= 0)
  9348. {
  9349. const String original (s);
  9350. int number = 0;
  9351. if (appendNumberToFirstInstance)
  9352. s = original + preNumberString + String (++number) + postNumberString;
  9353. else
  9354. ++number;
  9355. while (nextIndex >= 0)
  9356. {
  9357. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  9358. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  9359. }
  9360. }
  9361. }
  9362. }
  9363. void StringArray::minimiseStorageOverheads() throw()
  9364. {
  9365. strings.minimiseStorageOverheads();
  9366. }
  9367. END_JUCE_NAMESPACE
  9368. /********* End of inlined file: juce_StringArray.cpp *********/
  9369. /********* Start of inlined file: juce_StringPairArray.cpp *********/
  9370. BEGIN_JUCE_NAMESPACE
  9371. StringPairArray::StringPairArray (const bool ignoreCase_) throw()
  9372. : ignoreCase (ignoreCase_)
  9373. {
  9374. }
  9375. StringPairArray::StringPairArray (const StringPairArray& other) throw()
  9376. : keys (other.keys),
  9377. values (other.values),
  9378. ignoreCase (other.ignoreCase)
  9379. {
  9380. }
  9381. StringPairArray::~StringPairArray() throw()
  9382. {
  9383. }
  9384. const StringPairArray& StringPairArray::operator= (const StringPairArray& other) throw()
  9385. {
  9386. keys = other.keys;
  9387. values = other.values;
  9388. return *this;
  9389. }
  9390. bool StringPairArray::operator== (const StringPairArray& other) const throw()
  9391. {
  9392. for (int i = keys.size(); --i >= 0;)
  9393. if (other [keys[i]] != values[i])
  9394. return false;
  9395. return true;
  9396. }
  9397. bool StringPairArray::operator!= (const StringPairArray& other) const throw()
  9398. {
  9399. return ! operator== (other);
  9400. }
  9401. const String& StringPairArray::operator[] (const String& key) const throw()
  9402. {
  9403. return values [keys.indexOf (key, ignoreCase)];
  9404. }
  9405. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  9406. {
  9407. const int i = keys.indexOf (key, ignoreCase);
  9408. if (i >= 0)
  9409. return values[i];
  9410. return defaultReturnValue;
  9411. }
  9412. void StringPairArray::set (const String& key,
  9413. const String& value) throw()
  9414. {
  9415. const int i = keys.indexOf (key, ignoreCase);
  9416. if (i >= 0)
  9417. {
  9418. values.set (i, value);
  9419. }
  9420. else
  9421. {
  9422. keys.add (key);
  9423. values.add (value);
  9424. }
  9425. }
  9426. void StringPairArray::addArray (const StringPairArray& other)
  9427. {
  9428. for (int i = 0; i < other.size(); ++i)
  9429. set (other.keys[i], other.values[i]);
  9430. }
  9431. void StringPairArray::clear() throw()
  9432. {
  9433. keys.clear();
  9434. values.clear();
  9435. }
  9436. void StringPairArray::remove (const String& key) throw()
  9437. {
  9438. remove (keys.indexOf (key, ignoreCase));
  9439. }
  9440. void StringPairArray::remove (const int index) throw()
  9441. {
  9442. keys.remove (index);
  9443. values.remove (index);
  9444. }
  9445. void StringPairArray::minimiseStorageOverheads() throw()
  9446. {
  9447. keys.minimiseStorageOverheads();
  9448. values.minimiseStorageOverheads();
  9449. }
  9450. END_JUCE_NAMESPACE
  9451. /********* End of inlined file: juce_StringPairArray.cpp *********/
  9452. /********* Start of inlined file: juce_XmlDocument.cpp *********/
  9453. BEGIN_JUCE_NAMESPACE
  9454. static bool isXmlIdentifierChar_Slow (const tchar c) throw()
  9455. {
  9456. return CharacterFunctions::isLetterOrDigit (c)
  9457. || c == T('_')
  9458. || c == T('-')
  9459. || c == T(':')
  9460. || c == T('.');
  9461. }
  9462. #define isXmlIdentifierChar(c) \
  9463. ((c > 0 && c <= 127) ? identifierLookupTable [(int) c] : isXmlIdentifierChar_Slow (c))
  9464. XmlDocument::XmlDocument (const String& documentText) throw()
  9465. : originalText (documentText),
  9466. inputSource (0)
  9467. {
  9468. }
  9469. XmlDocument::XmlDocument (const File& file)
  9470. {
  9471. inputSource = new FileInputSource (file);
  9472. }
  9473. XmlDocument::~XmlDocument() throw()
  9474. {
  9475. delete inputSource;
  9476. }
  9477. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  9478. {
  9479. if (inputSource != newSource)
  9480. {
  9481. delete inputSource;
  9482. inputSource = newSource;
  9483. }
  9484. }
  9485. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  9486. {
  9487. String textToParse (originalText);
  9488. if (textToParse.isEmpty() && inputSource != 0)
  9489. {
  9490. InputStream* const in = inputSource->createInputStream();
  9491. if (in != 0)
  9492. {
  9493. MemoryBlock data;
  9494. in->readIntoMemoryBlock (data, onlyReadOuterDocumentElement ? 8192 : -1);
  9495. delete in;
  9496. if (data.getSize() >= 2
  9497. && ((data[0] == (char)-2 && data[1] == (char)-1)
  9498. || (data[0] == (char)-1 && data[1] == (char)-2)))
  9499. {
  9500. textToParse = String::createStringFromData ((const char*) data.getData(), data.getSize());
  9501. }
  9502. else
  9503. {
  9504. textToParse = String::fromUTF8 ((const uint8*) data.getData(), data.getSize());
  9505. }
  9506. if (! onlyReadOuterDocumentElement)
  9507. originalText = textToParse;
  9508. }
  9509. }
  9510. input = textToParse;
  9511. lastError = String::empty;
  9512. errorOccurred = false;
  9513. outOfData = false;
  9514. needToLoadDTD = true;
  9515. for (int i = 0; i < 128; ++i)
  9516. identifierLookupTable[i] = isXmlIdentifierChar_Slow ((tchar) i);
  9517. if (textToParse.isEmpty())
  9518. {
  9519. lastError = "not enough input";
  9520. }
  9521. else
  9522. {
  9523. skipHeader();
  9524. if (input != 0)
  9525. {
  9526. XmlElement* const result = readNextElement (! onlyReadOuterDocumentElement);
  9527. if (errorOccurred)
  9528. delete result;
  9529. else
  9530. return result;
  9531. }
  9532. else
  9533. {
  9534. lastError = "incorrect xml header";
  9535. }
  9536. }
  9537. return 0;
  9538. }
  9539. const String& XmlDocument::getLastParseError() const throw()
  9540. {
  9541. return lastError;
  9542. }
  9543. void XmlDocument::setLastError (const String& desc, const bool carryOn) throw()
  9544. {
  9545. lastError = desc;
  9546. errorOccurred = ! carryOn;
  9547. }
  9548. const String XmlDocument::getFileContents (const String& filename) const
  9549. {
  9550. String result;
  9551. if (inputSource != 0)
  9552. {
  9553. InputStream* const in = inputSource->createInputStreamFor (filename.trim().unquoted());
  9554. if (in != 0)
  9555. {
  9556. result = in->readEntireStreamAsString();
  9557. delete in;
  9558. }
  9559. }
  9560. return result;
  9561. }
  9562. tchar XmlDocument::readNextChar() throw()
  9563. {
  9564. if (*input != 0)
  9565. {
  9566. return *input++;
  9567. }
  9568. else
  9569. {
  9570. outOfData = true;
  9571. return 0;
  9572. }
  9573. }
  9574. int XmlDocument::findNextTokenLength() throw()
  9575. {
  9576. int len = 0;
  9577. tchar c = *input;
  9578. while (isXmlIdentifierChar (c))
  9579. c = input [++len];
  9580. return len;
  9581. }
  9582. void XmlDocument::skipHeader() throw()
  9583. {
  9584. const tchar* const found = CharacterFunctions::find (input, T("<?xml"));
  9585. if (found != 0)
  9586. {
  9587. input = found;
  9588. input = CharacterFunctions::find (input, T("?>"));
  9589. if (input == 0)
  9590. return;
  9591. input += 2;
  9592. }
  9593. skipNextWhiteSpace();
  9594. const tchar* docType = CharacterFunctions::find (input, T("<!DOCTYPE"));
  9595. if (docType == 0)
  9596. return;
  9597. input = docType + 9;
  9598. int n = 1;
  9599. while (n > 0)
  9600. {
  9601. const tchar c = readNextChar();
  9602. if (outOfData)
  9603. return;
  9604. if (c == T('<'))
  9605. ++n;
  9606. else if (c == T('>'))
  9607. --n;
  9608. }
  9609. docType += 9;
  9610. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  9611. }
  9612. void XmlDocument::skipNextWhiteSpace() throw()
  9613. {
  9614. for (;;)
  9615. {
  9616. tchar c = *input;
  9617. while (CharacterFunctions::isWhitespace (c))
  9618. c = *++input;
  9619. if (c == 0)
  9620. {
  9621. outOfData = true;
  9622. break;
  9623. }
  9624. else if (c == T('<'))
  9625. {
  9626. if (input[1] == T('!')
  9627. && input[2] == T('-')
  9628. && input[3] == T('-'))
  9629. {
  9630. const tchar* const closeComment = CharacterFunctions::find (input, T("-->"));
  9631. if (closeComment == 0)
  9632. {
  9633. outOfData = true;
  9634. break;
  9635. }
  9636. input = closeComment + 3;
  9637. continue;
  9638. }
  9639. else if (input[1] == T('?'))
  9640. {
  9641. const tchar* const closeBracket = CharacterFunctions::find (input, T("?>"));
  9642. if (closeBracket == 0)
  9643. {
  9644. outOfData = true;
  9645. break;
  9646. }
  9647. input = closeBracket + 2;
  9648. continue;
  9649. }
  9650. }
  9651. break;
  9652. }
  9653. }
  9654. void XmlDocument::readQuotedString (String& result) throw()
  9655. {
  9656. const tchar quote = readNextChar();
  9657. while (! outOfData)
  9658. {
  9659. const tchar character = readNextChar();
  9660. if (character == quote)
  9661. break;
  9662. if (character == T('&'))
  9663. {
  9664. --input;
  9665. readEntity (result);
  9666. }
  9667. else
  9668. {
  9669. --input;
  9670. const tchar* const start = input;
  9671. for (;;)
  9672. {
  9673. const tchar character = *input;
  9674. if (character == quote)
  9675. {
  9676. result.append (start, (int) (input - start));
  9677. ++input;
  9678. return;
  9679. }
  9680. else if (character == T('&'))
  9681. {
  9682. result.append (start, (int) (input - start));
  9683. break;
  9684. }
  9685. else if (character == 0)
  9686. {
  9687. outOfData = true;
  9688. setLastError ("unmatched quotes", false);
  9689. break;
  9690. }
  9691. ++input;
  9692. }
  9693. }
  9694. }
  9695. }
  9696. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements) throw()
  9697. {
  9698. XmlElement* node = 0;
  9699. skipNextWhiteSpace();
  9700. if (outOfData)
  9701. return 0;
  9702. input = CharacterFunctions::find (input, T("<"));
  9703. if (input != 0)
  9704. {
  9705. ++input;
  9706. int tagLen = findNextTokenLength();
  9707. if (tagLen == 0)
  9708. {
  9709. // no tag name - but allow for a gap after the '<' before giving an error
  9710. skipNextWhiteSpace();
  9711. tagLen = findNextTokenLength();
  9712. if (tagLen == 0)
  9713. {
  9714. setLastError ("tag name missing", false);
  9715. return node;
  9716. }
  9717. }
  9718. node = new XmlElement (input, tagLen);
  9719. input += tagLen;
  9720. XmlElement::XmlAttributeNode* lastAttribute = 0;
  9721. // look for attributes
  9722. for (;;)
  9723. {
  9724. skipNextWhiteSpace();
  9725. const tchar c = *input;
  9726. // empty tag..
  9727. if (c == T('/') && input[1] == T('>'))
  9728. {
  9729. input += 2;
  9730. break;
  9731. }
  9732. // parse the guts of the element..
  9733. if (c == T('>'))
  9734. {
  9735. ++input;
  9736. skipNextWhiteSpace();
  9737. if (alsoParseSubElements)
  9738. readChildElements (node);
  9739. break;
  9740. }
  9741. // get an attribute..
  9742. if (isXmlIdentifierChar (c))
  9743. {
  9744. const int attNameLen = findNextTokenLength();
  9745. if (attNameLen > 0)
  9746. {
  9747. const tchar* attNameStart = input;
  9748. input += attNameLen;
  9749. skipNextWhiteSpace();
  9750. if (readNextChar() == T('='))
  9751. {
  9752. skipNextWhiteSpace();
  9753. const tchar c = *input;
  9754. if (c == T('"') || c == T('\''))
  9755. {
  9756. XmlElement::XmlAttributeNode* const newAtt
  9757. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  9758. String::empty);
  9759. readQuotedString (newAtt->value);
  9760. if (lastAttribute == 0)
  9761. node->attributes = newAtt;
  9762. else
  9763. lastAttribute->next = newAtt;
  9764. lastAttribute = newAtt;
  9765. continue;
  9766. }
  9767. }
  9768. }
  9769. }
  9770. else
  9771. {
  9772. if (! outOfData)
  9773. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  9774. }
  9775. break;
  9776. }
  9777. }
  9778. return node;
  9779. }
  9780. void XmlDocument::readChildElements (XmlElement* parent) throw()
  9781. {
  9782. XmlElement* lastChildNode = 0;
  9783. for (;;)
  9784. {
  9785. skipNextWhiteSpace();
  9786. if (outOfData)
  9787. {
  9788. setLastError ("unmatched tags", false);
  9789. break;
  9790. }
  9791. if (*input == T('<'))
  9792. {
  9793. if (input[1] == T('/'))
  9794. {
  9795. // our close tag..
  9796. input = CharacterFunctions::find (input, T(">"));
  9797. ++input;
  9798. break;
  9799. }
  9800. else if (input[1] == T('!')
  9801. && input[2] == T('[')
  9802. && input[3] == T('C')
  9803. && input[4] == T('D')
  9804. && input[5] == T('A')
  9805. && input[6] == T('T')
  9806. && input[7] == T('A')
  9807. && input[8] == T('['))
  9808. {
  9809. input += 9;
  9810. const tchar* const inputStart = input;
  9811. int len = 0;
  9812. for (;;)
  9813. {
  9814. if (*input == 0)
  9815. {
  9816. setLastError ("unterminated CDATA section", false);
  9817. outOfData = true;
  9818. break;
  9819. }
  9820. else if (input[0] == T(']')
  9821. && input[1] == T(']')
  9822. && input[2] == T('>'))
  9823. {
  9824. input += 3;
  9825. break;
  9826. }
  9827. ++input;
  9828. ++len;
  9829. }
  9830. XmlElement* const e = new XmlElement ((int) 0);
  9831. e->setText (String (inputStart, len));
  9832. if (lastChildNode != 0)
  9833. lastChildNode->nextElement = e;
  9834. else
  9835. parent->addChildElement (e);
  9836. lastChildNode = e;
  9837. }
  9838. else
  9839. {
  9840. // this is some other element, so parse and add it..
  9841. XmlElement* const n = readNextElement (true);
  9842. if (n != 0)
  9843. {
  9844. if (lastChildNode == 0)
  9845. parent->addChildElement (n);
  9846. else
  9847. lastChildNode->nextElement = n;
  9848. lastChildNode = n;
  9849. }
  9850. else
  9851. {
  9852. return;
  9853. }
  9854. }
  9855. }
  9856. else
  9857. {
  9858. // read character block..
  9859. XmlElement* const e = new XmlElement ((int)0);
  9860. if (lastChildNode != 0)
  9861. lastChildNode->nextElement = e;
  9862. else
  9863. parent->addChildElement (e);
  9864. lastChildNode = e;
  9865. String textElementContent;
  9866. for (;;)
  9867. {
  9868. const tchar c = *input;
  9869. if (c == T('<'))
  9870. break;
  9871. if (c == 0)
  9872. {
  9873. setLastError ("unmatched tags", false);
  9874. outOfData = true;
  9875. return;
  9876. }
  9877. if (c == T('&'))
  9878. {
  9879. String entity;
  9880. readEntity (entity);
  9881. if (entity.startsWithChar (T('<')) && entity [1] != 0)
  9882. {
  9883. const tchar* const oldInput = input;
  9884. const bool oldOutOfData = outOfData;
  9885. input = (const tchar*) entity;
  9886. outOfData = false;
  9887. for (;;)
  9888. {
  9889. XmlElement* const n = readNextElement (true);
  9890. if (n == 0)
  9891. break;
  9892. if (lastChildNode == 0)
  9893. parent->addChildElement (n);
  9894. else
  9895. lastChildNode->nextElement = n;
  9896. lastChildNode = n;
  9897. }
  9898. input = oldInput;
  9899. outOfData = oldOutOfData;
  9900. }
  9901. else
  9902. {
  9903. textElementContent += entity;
  9904. }
  9905. }
  9906. else
  9907. {
  9908. const tchar* start = input;
  9909. int len = 0;
  9910. for (;;)
  9911. {
  9912. const tchar c = *input;
  9913. if (c == T('<') || c == T('&'))
  9914. {
  9915. break;
  9916. }
  9917. else if (c == 0)
  9918. {
  9919. setLastError ("unmatched tags", false);
  9920. outOfData = true;
  9921. return;
  9922. }
  9923. ++input;
  9924. ++len;
  9925. }
  9926. textElementContent.append (start, len);
  9927. }
  9928. }
  9929. textElementContent = textElementContent.trim();
  9930. if (textElementContent.isNotEmpty())
  9931. e->setText (textElementContent);
  9932. }
  9933. }
  9934. }
  9935. void XmlDocument::readEntity (String& result) throw()
  9936. {
  9937. // skip over the ampersand
  9938. ++input;
  9939. if (CharacterFunctions::compareIgnoreCase (input, T("amp;"), 4) == 0)
  9940. {
  9941. input += 4;
  9942. result += T("&");
  9943. }
  9944. else if (CharacterFunctions::compareIgnoreCase (input, T("quot;"), 5) == 0)
  9945. {
  9946. input += 5;
  9947. result += T("\"");
  9948. }
  9949. else if (CharacterFunctions::compareIgnoreCase (input, T("apos;"), 5) == 0)
  9950. {
  9951. input += 5;
  9952. result += T("\'");
  9953. }
  9954. else if (CharacterFunctions::compareIgnoreCase (input, T("lt;"), 3) == 0)
  9955. {
  9956. input += 3;
  9957. result += T("<");
  9958. }
  9959. else if (CharacterFunctions::compareIgnoreCase (input, T("gt;"), 3) == 0)
  9960. {
  9961. input += 3;
  9962. result += T(">");
  9963. }
  9964. else if (*input == T('#'))
  9965. {
  9966. int charCode = 0;
  9967. ++input;
  9968. if (*input == T('x') || *input == T('X'))
  9969. {
  9970. ++input;
  9971. int numChars = 0;
  9972. while (input[0] != T(';'))
  9973. {
  9974. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  9975. if (hexValue < 0 || ++numChars > 8)
  9976. {
  9977. setLastError ("illegal escape sequence", true);
  9978. break;
  9979. }
  9980. charCode = (charCode << 4) | hexValue;
  9981. ++input;
  9982. }
  9983. ++input;
  9984. }
  9985. else if (input[0] >= T('0') && input[0] <= T('9'))
  9986. {
  9987. int numChars = 0;
  9988. while (input[0] != T(';'))
  9989. {
  9990. if (++numChars > 12)
  9991. {
  9992. setLastError ("illegal escape sequence", true);
  9993. break;
  9994. }
  9995. charCode = charCode * 10 + (input[0] - T('0'));
  9996. ++input;
  9997. }
  9998. ++input;
  9999. }
  10000. else
  10001. {
  10002. setLastError ("illegal escape sequence", true);
  10003. result += T("&");
  10004. return;
  10005. }
  10006. result << (tchar) charCode;
  10007. }
  10008. else
  10009. {
  10010. const tchar* const entityNameStart = input;
  10011. const tchar* const closingSemiColon = CharacterFunctions::find (input, T(";"));
  10012. if (closingSemiColon == 0)
  10013. {
  10014. outOfData = true;
  10015. result += T("&");
  10016. }
  10017. else
  10018. {
  10019. input = closingSemiColon + 1;
  10020. result += expandExternalEntity (String (entityNameStart,
  10021. (int) (closingSemiColon - entityNameStart)));
  10022. }
  10023. }
  10024. }
  10025. const String XmlDocument::expandEntity (const String& ent)
  10026. {
  10027. if (ent.equalsIgnoreCase (T("amp")))
  10028. {
  10029. return T("&");
  10030. }
  10031. else if (ent.equalsIgnoreCase (T("quot")))
  10032. {
  10033. return T("\"");
  10034. }
  10035. else if (ent.equalsIgnoreCase (T("apos")))
  10036. {
  10037. return T("\'");
  10038. }
  10039. else if (ent.equalsIgnoreCase (T("lt")))
  10040. {
  10041. return T("<");
  10042. }
  10043. else if (ent.equalsIgnoreCase (T("gt")))
  10044. {
  10045. return T(">");
  10046. }
  10047. else if (ent[0] == T('#'))
  10048. {
  10049. if (ent[1] == T('x') || ent[1] == T('X'))
  10050. {
  10051. return String::charToString ((tchar) ent.substring (2).getHexValue32());
  10052. }
  10053. else if (ent[1] >= T('0') && ent[1] <= T('9'))
  10054. {
  10055. return String::charToString ((tchar) ent.substring (1).getIntValue());
  10056. }
  10057. setLastError ("illegal escape sequence", false);
  10058. return T("&");
  10059. }
  10060. else
  10061. {
  10062. return expandExternalEntity (ent);
  10063. }
  10064. }
  10065. const String XmlDocument::expandExternalEntity (const String& entity)
  10066. {
  10067. if (needToLoadDTD)
  10068. {
  10069. if (dtdText.isNotEmpty())
  10070. {
  10071. while (dtdText.endsWithChar (T('>')))
  10072. dtdText = dtdText.dropLastCharacters (1);
  10073. tokenisedDTD.addTokens (dtdText, true);
  10074. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase (T("system"))
  10075. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  10076. {
  10077. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  10078. tokenisedDTD.clear();
  10079. tokenisedDTD.addTokens (getFileContents (fn), true);
  10080. }
  10081. else
  10082. {
  10083. tokenisedDTD.clear();
  10084. const int openBracket = dtdText.indexOfChar (T('['));
  10085. if (openBracket > 0)
  10086. {
  10087. const int closeBracket = dtdText.lastIndexOfChar (T(']'));
  10088. if (closeBracket > openBracket)
  10089. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  10090. closeBracket), true);
  10091. }
  10092. }
  10093. for (int i = tokenisedDTD.size(); --i >= 0;)
  10094. {
  10095. if (tokenisedDTD[i].startsWithChar (T('%'))
  10096. && tokenisedDTD[i].endsWithChar (T(';')))
  10097. {
  10098. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  10099. StringArray newToks;
  10100. newToks.addTokens (parsed, true);
  10101. tokenisedDTD.remove (i);
  10102. for (int j = newToks.size(); --j >= 0;)
  10103. tokenisedDTD.insert (i, newToks[j]);
  10104. }
  10105. }
  10106. }
  10107. needToLoadDTD = false;
  10108. }
  10109. for (int i = 0; i < tokenisedDTD.size(); ++i)
  10110. {
  10111. if (tokenisedDTD[i] == entity)
  10112. {
  10113. if (tokenisedDTD[i - 1].equalsIgnoreCase (T("<!entity")))
  10114. {
  10115. String ent (tokenisedDTD [i + 1]);
  10116. while (ent.endsWithChar (T('>')))
  10117. ent = ent.dropLastCharacters (1);
  10118. ent = ent.trim().unquoted();
  10119. // check for sub-entities..
  10120. int ampersand = ent.indexOfChar (T('&'));
  10121. while (ampersand >= 0)
  10122. {
  10123. const int semiColon = ent.indexOf (i + 1, T(";"));
  10124. if (semiColon < 0)
  10125. {
  10126. setLastError ("entity without terminating semi-colon", false);
  10127. break;
  10128. }
  10129. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  10130. ent = ent.substring (0, ampersand)
  10131. + resolved
  10132. + ent.substring (semiColon + 1);
  10133. ampersand = ent.indexOfChar (semiColon + 1, T('&'));
  10134. }
  10135. return ent;
  10136. }
  10137. }
  10138. }
  10139. setLastError ("unknown entity", true);
  10140. return entity;
  10141. }
  10142. const String XmlDocument::getParameterEntity (const String& entity)
  10143. {
  10144. for (int i = 0; i < tokenisedDTD.size(); ++i)
  10145. {
  10146. if (tokenisedDTD[i] == entity)
  10147. {
  10148. if (tokenisedDTD [i - 1] == T("%")
  10149. && tokenisedDTD [i - 2].equalsIgnoreCase (T("<!entity")))
  10150. {
  10151. String ent (tokenisedDTD [i + 1]);
  10152. while (ent.endsWithChar (T('>')))
  10153. ent = ent.dropLastCharacters (1);
  10154. if (ent.equalsIgnoreCase (T("system")))
  10155. {
  10156. String filename (tokenisedDTD [i + 2]);
  10157. while (filename.endsWithChar (T('>')))
  10158. filename = filename.dropLastCharacters (1);
  10159. return getFileContents (filename);
  10160. }
  10161. else
  10162. {
  10163. return ent.trim().unquoted();
  10164. }
  10165. }
  10166. }
  10167. }
  10168. return entity;
  10169. }
  10170. END_JUCE_NAMESPACE
  10171. /********* End of inlined file: juce_XmlDocument.cpp *********/
  10172. /********* Start of inlined file: juce_XmlElement.cpp *********/
  10173. BEGIN_JUCE_NAMESPACE
  10174. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  10175. : name (other.name),
  10176. value (other.value),
  10177. next (0)
  10178. {
  10179. }
  10180. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_,
  10181. const String& value_) throw()
  10182. : name (name_),
  10183. value (value_),
  10184. next (0)
  10185. {
  10186. }
  10187. XmlElement::XmlElement (const String& tagName_) throw()
  10188. : tagName (tagName_),
  10189. firstChildElement (0),
  10190. nextElement (0),
  10191. attributes (0)
  10192. {
  10193. // the tag name mustn't be empty, or it'll look like a text element!
  10194. jassert (tagName_.trim().isNotEmpty())
  10195. }
  10196. XmlElement::XmlElement (int /*dummy*/) throw()
  10197. : firstChildElement (0),
  10198. nextElement (0),
  10199. attributes (0)
  10200. {
  10201. }
  10202. XmlElement::XmlElement (const tchar* const tagName_,
  10203. const int nameLen) throw()
  10204. : tagName (tagName_, nameLen),
  10205. firstChildElement (0),
  10206. nextElement (0),
  10207. attributes (0)
  10208. {
  10209. }
  10210. XmlElement::XmlElement (const XmlElement& other) throw()
  10211. : tagName (other.tagName),
  10212. firstChildElement (0),
  10213. nextElement (0),
  10214. attributes (0)
  10215. {
  10216. copyChildrenAndAttributesFrom (other);
  10217. }
  10218. const XmlElement& XmlElement::operator= (const XmlElement& other) throw()
  10219. {
  10220. if (this != &other)
  10221. {
  10222. removeAllAttributes();
  10223. deleteAllChildElements();
  10224. tagName = other.tagName;
  10225. copyChildrenAndAttributesFrom (other);
  10226. }
  10227. return *this;
  10228. }
  10229. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other) throw()
  10230. {
  10231. XmlElement* child = other.firstChildElement;
  10232. XmlElement* lastChild = 0;
  10233. while (child != 0)
  10234. {
  10235. XmlElement* const copiedChild = new XmlElement (*child);
  10236. if (lastChild != 0)
  10237. lastChild->nextElement = copiedChild;
  10238. else
  10239. firstChildElement = copiedChild;
  10240. lastChild = copiedChild;
  10241. child = child->nextElement;
  10242. }
  10243. const XmlAttributeNode* att = other.attributes;
  10244. XmlAttributeNode* lastAtt = 0;
  10245. while (att != 0)
  10246. {
  10247. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  10248. if (lastAtt != 0)
  10249. lastAtt->next = newAtt;
  10250. else
  10251. attributes = newAtt;
  10252. lastAtt = newAtt;
  10253. att = att->next;
  10254. }
  10255. }
  10256. XmlElement::~XmlElement() throw()
  10257. {
  10258. XmlElement* child = firstChildElement;
  10259. while (child != 0)
  10260. {
  10261. XmlElement* const nextChild = child->nextElement;
  10262. delete child;
  10263. child = nextChild;
  10264. }
  10265. XmlAttributeNode* att = attributes;
  10266. while (att != 0)
  10267. {
  10268. XmlAttributeNode* const nextAtt = att->next;
  10269. delete att;
  10270. att = nextAtt;
  10271. }
  10272. }
  10273. static bool isLegalXmlChar (const juce_wchar character)
  10274. {
  10275. if ((character >= 'a' && character <= 'z')
  10276. || (character >= 'A' && character <= 'Z')
  10277. || (character >= '0' && character <= '9'))
  10278. return true;
  10279. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}";
  10280. do
  10281. {
  10282. if (((juce_wchar) (uint8) *t) == character)
  10283. return true;
  10284. }
  10285. while (*++t != 0);
  10286. return false;
  10287. }
  10288. static void escapeIllegalXmlChars (OutputStream& outputStream,
  10289. const String& text,
  10290. const bool changeNewLines) throw()
  10291. {
  10292. const juce_wchar* t = (const juce_wchar*) text;
  10293. for (;;)
  10294. {
  10295. const juce_wchar character = *t++;
  10296. if (character == 0)
  10297. {
  10298. break;
  10299. }
  10300. else if (isLegalXmlChar (character))
  10301. {
  10302. outputStream.writeByte ((char) character);
  10303. }
  10304. else
  10305. {
  10306. switch (character)
  10307. {
  10308. case '&':
  10309. outputStream.write ("&amp;", 5);
  10310. break;
  10311. case '"':
  10312. outputStream.write ("&quot;", 6);
  10313. break;
  10314. case '>':
  10315. outputStream.write ("&gt;", 4);
  10316. break;
  10317. case '<':
  10318. outputStream.write ("&lt;", 4);
  10319. break;
  10320. case '\n':
  10321. if (changeNewLines)
  10322. outputStream.write ("&#10;", 5);
  10323. else
  10324. outputStream.writeByte ((char) character);
  10325. break;
  10326. case '\r':
  10327. if (changeNewLines)
  10328. outputStream.write ("&#13;", 5);
  10329. else
  10330. outputStream.writeByte ((char) character);
  10331. break;
  10332. default:
  10333. {
  10334. String encoded (T("&#"));
  10335. encoded << String ((int) (unsigned int) character).trim()
  10336. << T(';');
  10337. outputStream.write ((const char*) encoded, encoded.length());
  10338. }
  10339. }
  10340. }
  10341. }
  10342. }
  10343. static void writeSpaces (OutputStream& out, int numSpaces) throw()
  10344. {
  10345. if (numSpaces > 0)
  10346. {
  10347. const char* const blanks = " ";
  10348. const int blankSize = (int) sizeof (blanks) - 1;
  10349. while (numSpaces > blankSize)
  10350. {
  10351. out.write (blanks, blankSize);
  10352. numSpaces -= blankSize;
  10353. }
  10354. out.write (blanks, numSpaces);
  10355. }
  10356. }
  10357. void XmlElement::writeElementAsText (OutputStream& outputStream,
  10358. const int indentationLevel) const throw()
  10359. {
  10360. writeSpaces (outputStream, indentationLevel);
  10361. if (! isTextElement())
  10362. {
  10363. outputStream.writeByte ('<');
  10364. const int nameLen = tagName.length();
  10365. outputStream.write ((const char*) tagName, nameLen);
  10366. const int attIndent = indentationLevel + nameLen + 1;
  10367. int lineLen = 0;
  10368. const XmlAttributeNode* att = attributes;
  10369. while (att != 0)
  10370. {
  10371. if (lineLen > 60 && indentationLevel >= 0)
  10372. {
  10373. outputStream.write ("\r\n", 2);
  10374. writeSpaces (outputStream, attIndent);
  10375. lineLen = 0;
  10376. }
  10377. const int attNameLen = att->name.length();
  10378. outputStream.writeByte (' ');
  10379. outputStream.write ((const char*) (att->name), attNameLen);
  10380. outputStream.write ("=\"", 2);
  10381. escapeIllegalXmlChars (outputStream, att->value, true);
  10382. outputStream.writeByte ('"');
  10383. lineLen += 4 + attNameLen + att->value.length();
  10384. att = att->next;
  10385. }
  10386. if (firstChildElement != 0)
  10387. {
  10388. XmlElement* child = firstChildElement;
  10389. if (child->nextElement == 0 && child->isTextElement())
  10390. {
  10391. outputStream.writeByte ('>');
  10392. escapeIllegalXmlChars (outputStream, child->getText(), false);
  10393. }
  10394. else
  10395. {
  10396. if (indentationLevel >= 0)
  10397. outputStream.write (">\r\n", 3);
  10398. else
  10399. outputStream.writeByte ('>');
  10400. bool lastWasTextNode = false;
  10401. while (child != 0)
  10402. {
  10403. if (child->isTextElement())
  10404. {
  10405. if ((! lastWasTextNode) && (indentationLevel >= 0))
  10406. writeSpaces (outputStream, indentationLevel + 2);
  10407. escapeIllegalXmlChars (outputStream, child->getText(), false);
  10408. lastWasTextNode = true;
  10409. }
  10410. else
  10411. {
  10412. if (indentationLevel >= 0)
  10413. {
  10414. if (lastWasTextNode)
  10415. outputStream.write ("\r\n", 2);
  10416. child->writeElementAsText (outputStream, indentationLevel + 2);
  10417. }
  10418. else
  10419. {
  10420. child->writeElementAsText (outputStream, indentationLevel);
  10421. }
  10422. lastWasTextNode = false;
  10423. }
  10424. child = child->nextElement;
  10425. }
  10426. if (indentationLevel >= 0)
  10427. {
  10428. if (lastWasTextNode)
  10429. outputStream.write ("\r\n", 2);
  10430. writeSpaces (outputStream, indentationLevel);
  10431. }
  10432. }
  10433. outputStream.write ("</", 2);
  10434. outputStream.write ((const char*) tagName, nameLen);
  10435. if (indentationLevel >= 0)
  10436. outputStream.write (">\r\n", 3);
  10437. else
  10438. outputStream.writeByte ('>');
  10439. }
  10440. else
  10441. {
  10442. if (indentationLevel >= 0)
  10443. outputStream.write ("/>\r\n", 4);
  10444. else
  10445. outputStream.write ("/>", 2);
  10446. }
  10447. }
  10448. else
  10449. {
  10450. if (indentationLevel >= 0)
  10451. writeSpaces (outputStream, indentationLevel + 2);
  10452. escapeIllegalXmlChars (outputStream, getText(), false);
  10453. }
  10454. }
  10455. const String XmlElement::createDocument (const String& dtd,
  10456. const bool allOnOneLine,
  10457. const bool includeXmlHeader,
  10458. const tchar* const encoding) const throw()
  10459. {
  10460. String doc;
  10461. doc.preallocateStorage (1024);
  10462. if (includeXmlHeader)
  10463. {
  10464. doc << "<?xml version=\"1.0\" encoding=\""
  10465. << encoding;
  10466. if (allOnOneLine)
  10467. doc += "\"?> ";
  10468. else
  10469. doc += "\"?>\n\n";
  10470. }
  10471. if (dtd.isNotEmpty())
  10472. {
  10473. if (allOnOneLine)
  10474. doc << dtd << " ";
  10475. else
  10476. doc << dtd << "\r\n";
  10477. }
  10478. MemoryOutputStream mem (2048, 4096);
  10479. writeElementAsText (mem, allOnOneLine ? -1 : 0);
  10480. return doc + String (mem.getData(),
  10481. mem.getDataSize());
  10482. }
  10483. bool XmlElement::writeToFile (const File& f,
  10484. const String& dtd,
  10485. const tchar* const encoding) const throw()
  10486. {
  10487. if (f.hasWriteAccess())
  10488. {
  10489. const File tempFile (f.getNonexistentSibling());
  10490. FileOutputStream* const out = tempFile.createOutputStream();
  10491. if (out != 0)
  10492. {
  10493. *out << "<?xml version=\"1.0\" encoding=\"" << encoding << "\"?>\r\n\r\n"
  10494. << dtd << "\r\n";
  10495. writeElementAsText (*out, 0);
  10496. delete out;
  10497. if (tempFile.moveFileTo (f))
  10498. return true;
  10499. tempFile.deleteFile();
  10500. }
  10501. }
  10502. return false;
  10503. }
  10504. bool XmlElement::hasTagName (const tchar* const tagNameWanted) const throw()
  10505. {
  10506. #ifdef JUCE_DEBUG
  10507. // if debugging, check that the case is actually the same, because
  10508. // valid xml is case-sensitive, and although this lets it pass, it's
  10509. // better not to..
  10510. if (tagName.equalsIgnoreCase (tagNameWanted))
  10511. {
  10512. jassert (tagName == tagNameWanted);
  10513. return true;
  10514. }
  10515. else
  10516. {
  10517. return false;
  10518. }
  10519. #else
  10520. return tagName.equalsIgnoreCase (tagNameWanted);
  10521. #endif
  10522. }
  10523. XmlElement* XmlElement::getNextElementWithTagName (const tchar* const requiredTagName) const
  10524. {
  10525. XmlElement* e = nextElement;
  10526. while (e != 0 && ! e->hasTagName (requiredTagName))
  10527. e = e->nextElement;
  10528. return e;
  10529. }
  10530. int XmlElement::getNumAttributes() const throw()
  10531. {
  10532. const XmlAttributeNode* att = attributes;
  10533. int count = 0;
  10534. while (att != 0)
  10535. {
  10536. att = att->next;
  10537. ++count;
  10538. }
  10539. return count;
  10540. }
  10541. const String& XmlElement::getAttributeName (const int index) const throw()
  10542. {
  10543. const XmlAttributeNode* att = attributes;
  10544. int count = 0;
  10545. while (att != 0)
  10546. {
  10547. if (count == index)
  10548. return att->name;
  10549. att = att->next;
  10550. ++count;
  10551. }
  10552. return String::empty;
  10553. }
  10554. const String& XmlElement::getAttributeValue (const int index) const throw()
  10555. {
  10556. const XmlAttributeNode* att = attributes;
  10557. int count = 0;
  10558. while (att != 0)
  10559. {
  10560. if (count == index)
  10561. return att->value;
  10562. att = att->next;
  10563. ++count;
  10564. }
  10565. return String::empty;
  10566. }
  10567. bool XmlElement::hasAttribute (const tchar* const attributeName) const throw()
  10568. {
  10569. const XmlAttributeNode* att = attributes;
  10570. while (att != 0)
  10571. {
  10572. if (att->name.equalsIgnoreCase (attributeName))
  10573. return true;
  10574. att = att->next;
  10575. }
  10576. return false;
  10577. }
  10578. const String XmlElement::getStringAttribute (const tchar* const attributeName,
  10579. const tchar* const defaultReturnValue) const throw()
  10580. {
  10581. const XmlAttributeNode* att = attributes;
  10582. while (att != 0)
  10583. {
  10584. if (att->name.equalsIgnoreCase (attributeName))
  10585. return att->value;
  10586. att = att->next;
  10587. }
  10588. return defaultReturnValue;
  10589. }
  10590. int XmlElement::getIntAttribute (const tchar* const attributeName,
  10591. const int defaultReturnValue) const throw()
  10592. {
  10593. const XmlAttributeNode* att = attributes;
  10594. while (att != 0)
  10595. {
  10596. if (att->name.equalsIgnoreCase (attributeName))
  10597. return att->value.getIntValue();
  10598. att = att->next;
  10599. }
  10600. return defaultReturnValue;
  10601. }
  10602. double XmlElement::getDoubleAttribute (const tchar* const attributeName,
  10603. const double defaultReturnValue) const throw()
  10604. {
  10605. const XmlAttributeNode* att = attributes;
  10606. while (att != 0)
  10607. {
  10608. if (att->name.equalsIgnoreCase (attributeName))
  10609. return att->value.getDoubleValue();
  10610. att = att->next;
  10611. }
  10612. return defaultReturnValue;
  10613. }
  10614. bool XmlElement::getBoolAttribute (const tchar* const attributeName,
  10615. const bool defaultReturnValue) const throw()
  10616. {
  10617. const XmlAttributeNode* att = attributes;
  10618. while (att != 0)
  10619. {
  10620. if (att->name.equalsIgnoreCase (attributeName))
  10621. {
  10622. tchar firstChar = att->value[0];
  10623. if (CharacterFunctions::isWhitespace (firstChar))
  10624. firstChar = att->value.trimStart() [0];
  10625. return firstChar == T('1')
  10626. || firstChar == T('t')
  10627. || firstChar == T('y')
  10628. || firstChar == T('T')
  10629. || firstChar == T('Y');
  10630. }
  10631. att = att->next;
  10632. }
  10633. return defaultReturnValue;
  10634. }
  10635. bool XmlElement::compareAttribute (const tchar* const attributeName,
  10636. const tchar* const stringToCompareAgainst,
  10637. const bool ignoreCase) const throw()
  10638. {
  10639. const XmlAttributeNode* att = attributes;
  10640. while (att != 0)
  10641. {
  10642. if (att->name.equalsIgnoreCase (attributeName))
  10643. {
  10644. if (ignoreCase)
  10645. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  10646. else
  10647. return att->value == stringToCompareAgainst;
  10648. }
  10649. att = att->next;
  10650. }
  10651. return false;
  10652. }
  10653. void XmlElement::setAttribute (const tchar* const attributeName,
  10654. const String& value) throw()
  10655. {
  10656. #ifdef JUCE_DEBUG
  10657. // check the identifier being passed in is legal..
  10658. const tchar* t = attributeName;
  10659. while (*t != 0)
  10660. {
  10661. jassert (CharacterFunctions::isLetterOrDigit (*t)
  10662. || *t == T('_')
  10663. || *t == T('-')
  10664. || *t == T(':'));
  10665. ++t;
  10666. }
  10667. #endif
  10668. if (attributes == 0)
  10669. {
  10670. attributes = new XmlAttributeNode (attributeName, value);
  10671. }
  10672. else
  10673. {
  10674. XmlAttributeNode* att = attributes;
  10675. for (;;)
  10676. {
  10677. if (att->name.equalsIgnoreCase (attributeName))
  10678. {
  10679. att->value = value;
  10680. break;
  10681. }
  10682. else if (att->next == 0)
  10683. {
  10684. att->next = new XmlAttributeNode (attributeName, value);
  10685. break;
  10686. }
  10687. att = att->next;
  10688. }
  10689. }
  10690. }
  10691. void XmlElement::setAttribute (const tchar* const attributeName,
  10692. const tchar* const text) throw()
  10693. {
  10694. setAttribute (attributeName, String (text));
  10695. }
  10696. void XmlElement::setAttribute (const tchar* const attributeName,
  10697. const int number) throw()
  10698. {
  10699. setAttribute (attributeName, String (number));
  10700. }
  10701. void XmlElement::setAttribute (const tchar* const attributeName,
  10702. const double number) throw()
  10703. {
  10704. tchar buffer [40];
  10705. CharacterFunctions::printf (buffer, numElementsInArray (buffer), T("%.9g"), number);
  10706. setAttribute (attributeName, buffer);
  10707. }
  10708. void XmlElement::removeAttribute (const tchar* const attributeName) throw()
  10709. {
  10710. XmlAttributeNode* att = attributes;
  10711. XmlAttributeNode* lastAtt = 0;
  10712. while (att != 0)
  10713. {
  10714. if (att->name.equalsIgnoreCase (attributeName))
  10715. {
  10716. if (lastAtt == 0)
  10717. attributes = att->next;
  10718. else
  10719. lastAtt->next = att->next;
  10720. delete att;
  10721. break;
  10722. }
  10723. lastAtt = att;
  10724. att = att->next;
  10725. }
  10726. }
  10727. void XmlElement::removeAllAttributes() throw()
  10728. {
  10729. while (attributes != 0)
  10730. {
  10731. XmlAttributeNode* const nextAtt = attributes->next;
  10732. delete attributes;
  10733. attributes = nextAtt;
  10734. }
  10735. }
  10736. int XmlElement::getNumChildElements() const throw()
  10737. {
  10738. int count = 0;
  10739. const XmlElement* child = firstChildElement;
  10740. while (child != 0)
  10741. {
  10742. ++count;
  10743. child = child->nextElement;
  10744. }
  10745. return count;
  10746. }
  10747. XmlElement* XmlElement::getChildElement (const int index) const throw()
  10748. {
  10749. int count = 0;
  10750. XmlElement* child = firstChildElement;
  10751. while (child != 0 && count < index)
  10752. {
  10753. child = child->nextElement;
  10754. ++count;
  10755. }
  10756. return child;
  10757. }
  10758. XmlElement* XmlElement::getChildByName (const tchar* const childName) const throw()
  10759. {
  10760. XmlElement* child = firstChildElement;
  10761. while (child != 0)
  10762. {
  10763. if (child->hasTagName (childName))
  10764. break;
  10765. child = child->nextElement;
  10766. }
  10767. return child;
  10768. }
  10769. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  10770. {
  10771. if (newNode != 0)
  10772. {
  10773. if (firstChildElement == 0)
  10774. {
  10775. firstChildElement = newNode;
  10776. }
  10777. else
  10778. {
  10779. XmlElement* child = firstChildElement;
  10780. while (child->nextElement != 0)
  10781. child = child->nextElement;
  10782. child->nextElement = newNode;
  10783. // if this is non-zero, then something's probably
  10784. // gone wrong..
  10785. jassert (newNode->nextElement == 0);
  10786. }
  10787. }
  10788. }
  10789. void XmlElement::insertChildElement (XmlElement* const newNode,
  10790. int indexToInsertAt) throw()
  10791. {
  10792. if (newNode != 0)
  10793. {
  10794. removeChildElement (newNode, false);
  10795. if (indexToInsertAt == 0)
  10796. {
  10797. newNode->nextElement = firstChildElement;
  10798. firstChildElement = newNode;
  10799. }
  10800. else
  10801. {
  10802. if (firstChildElement == 0)
  10803. {
  10804. firstChildElement = newNode;
  10805. }
  10806. else
  10807. {
  10808. if (indexToInsertAt < 0)
  10809. indexToInsertAt = INT_MAX;
  10810. XmlElement* child = firstChildElement;
  10811. while (child->nextElement != 0 && --indexToInsertAt > 0)
  10812. child = child->nextElement;
  10813. newNode->nextElement = child->nextElement;
  10814. child->nextElement = newNode;
  10815. }
  10816. }
  10817. }
  10818. }
  10819. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  10820. XmlElement* const newNode) throw()
  10821. {
  10822. if (newNode != 0)
  10823. {
  10824. XmlElement* child = firstChildElement;
  10825. XmlElement* previousNode = 0;
  10826. while (child != 0)
  10827. {
  10828. if (child == currentChildElement)
  10829. {
  10830. if (child != newNode)
  10831. {
  10832. if (previousNode == 0)
  10833. firstChildElement = newNode;
  10834. else
  10835. previousNode->nextElement = newNode;
  10836. newNode->nextElement = child->nextElement;
  10837. delete child;
  10838. }
  10839. return true;
  10840. }
  10841. previousNode = child;
  10842. child = child->nextElement;
  10843. }
  10844. }
  10845. return false;
  10846. }
  10847. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  10848. const bool shouldDeleteTheChild) throw()
  10849. {
  10850. if (childToRemove != 0)
  10851. {
  10852. if (firstChildElement == childToRemove)
  10853. {
  10854. firstChildElement = childToRemove->nextElement;
  10855. childToRemove->nextElement = 0;
  10856. }
  10857. else
  10858. {
  10859. XmlElement* child = firstChildElement;
  10860. XmlElement* last = 0;
  10861. while (child != 0)
  10862. {
  10863. if (child == childToRemove)
  10864. {
  10865. if (last == 0)
  10866. firstChildElement = child->nextElement;
  10867. else
  10868. last->nextElement = child->nextElement;
  10869. childToRemove->nextElement = 0;
  10870. break;
  10871. }
  10872. last = child;
  10873. child = child->nextElement;
  10874. }
  10875. }
  10876. if (shouldDeleteTheChild)
  10877. delete childToRemove;
  10878. }
  10879. }
  10880. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  10881. const bool ignoreOrderOfAttributes) const throw()
  10882. {
  10883. if (this != other)
  10884. {
  10885. if (other == 0 || tagName != other->tagName)
  10886. {
  10887. return false;
  10888. }
  10889. if (ignoreOrderOfAttributes)
  10890. {
  10891. int totalAtts = 0;
  10892. const XmlAttributeNode* att = attributes;
  10893. while (att != 0)
  10894. {
  10895. if (! other->compareAttribute (att->name, att->value))
  10896. return false;
  10897. att = att->next;
  10898. ++totalAtts;
  10899. }
  10900. if (totalAtts != other->getNumAttributes())
  10901. return false;
  10902. }
  10903. else
  10904. {
  10905. const XmlAttributeNode* thisAtt = attributes;
  10906. const XmlAttributeNode* otherAtt = other->attributes;
  10907. for (;;)
  10908. {
  10909. if (thisAtt == 0 || otherAtt == 0)
  10910. {
  10911. if (thisAtt == otherAtt) // both 0, so it's a match
  10912. break;
  10913. return false;
  10914. }
  10915. if (thisAtt->name != otherAtt->name
  10916. || thisAtt->value != otherAtt->value)
  10917. {
  10918. return false;
  10919. }
  10920. thisAtt = thisAtt->next;
  10921. otherAtt = otherAtt->next;
  10922. }
  10923. }
  10924. const XmlElement* thisChild = firstChildElement;
  10925. const XmlElement* otherChild = other->firstChildElement;
  10926. for (;;)
  10927. {
  10928. if (thisChild == 0 || otherChild == 0)
  10929. {
  10930. if (thisChild == otherChild) // both 0, so it's a match
  10931. break;
  10932. return false;
  10933. }
  10934. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  10935. return false;
  10936. thisChild = thisChild->nextElement;
  10937. otherChild = otherChild->nextElement;
  10938. }
  10939. }
  10940. return true;
  10941. }
  10942. void XmlElement::deleteAllChildElements() throw()
  10943. {
  10944. while (firstChildElement != 0)
  10945. {
  10946. XmlElement* const nextChild = firstChildElement->nextElement;
  10947. delete firstChildElement;
  10948. firstChildElement = nextChild;
  10949. }
  10950. }
  10951. void XmlElement::deleteAllChildElementsWithTagName (const tchar* const name) throw()
  10952. {
  10953. XmlElement* child = firstChildElement;
  10954. while (child != 0)
  10955. {
  10956. if (child->hasTagName (name))
  10957. {
  10958. XmlElement* const nextChild = child->nextElement;
  10959. removeChildElement (child, true);
  10960. child = nextChild;
  10961. }
  10962. else
  10963. {
  10964. child = child->nextElement;
  10965. }
  10966. }
  10967. }
  10968. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  10969. {
  10970. const XmlElement* child = firstChildElement;
  10971. while (child != 0)
  10972. {
  10973. if (child == possibleChild)
  10974. return true;
  10975. child = child->nextElement;
  10976. }
  10977. return false;
  10978. }
  10979. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  10980. {
  10981. if (this == elementToLookFor || elementToLookFor == 0)
  10982. return 0;
  10983. XmlElement* child = firstChildElement;
  10984. while (child != 0)
  10985. {
  10986. if (elementToLookFor == child)
  10987. return this;
  10988. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  10989. if (found != 0)
  10990. return found;
  10991. child = child->nextElement;
  10992. }
  10993. return 0;
  10994. }
  10995. XmlElement** XmlElement::getChildElementsAsArray (const int num) const throw()
  10996. {
  10997. XmlElement** const elems = new XmlElement* [num];
  10998. XmlElement* e = firstChildElement;
  10999. int i = 0;
  11000. while (e != 0)
  11001. {
  11002. elems [i++] = e;
  11003. e = e->nextElement;
  11004. }
  11005. return elems;
  11006. }
  11007. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  11008. {
  11009. XmlElement* e = firstChildElement = elems[0];
  11010. for (int i = 1; i < num; ++i)
  11011. {
  11012. e->nextElement = elems[i];
  11013. e = e->nextElement;
  11014. }
  11015. e->nextElement = 0;
  11016. }
  11017. bool XmlElement::isTextElement() const throw()
  11018. {
  11019. return tagName.isEmpty();
  11020. }
  11021. static const tchar* const juce_xmltextContentAttributeName = T("text");
  11022. const String XmlElement::getText() const throw()
  11023. {
  11024. jassert (isTextElement()); // you're trying to get the text from an element that
  11025. // isn't actually a text element.. If this contains text sub-nodes, you
  11026. // can use getAllSubText instead to
  11027. return getStringAttribute (juce_xmltextContentAttributeName);
  11028. }
  11029. void XmlElement::setText (const String& newText) throw()
  11030. {
  11031. if (isTextElement())
  11032. {
  11033. setAttribute (juce_xmltextContentAttributeName, newText);
  11034. }
  11035. else
  11036. {
  11037. jassertfalse // you can only change the text in a text element, not a normal one.
  11038. }
  11039. }
  11040. const String XmlElement::getAllSubText() const throw()
  11041. {
  11042. String result;
  11043. const XmlElement* child = firstChildElement;
  11044. while (child != 0)
  11045. {
  11046. if (child->isTextElement())
  11047. result += child->getText();
  11048. child = child->nextElement;
  11049. }
  11050. return result;
  11051. }
  11052. const String XmlElement::getChildElementAllSubText (const tchar* const childTagName,
  11053. const String& defaultReturnValue) const throw()
  11054. {
  11055. const XmlElement* const child = getChildByName (childTagName);
  11056. if (child != 0)
  11057. return child->getAllSubText();
  11058. return defaultReturnValue;
  11059. }
  11060. XmlElement* XmlElement::createTextElement (const String& text) throw()
  11061. {
  11062. XmlElement* const e = new XmlElement ((int) 0);
  11063. e->setAttribute (juce_xmltextContentAttributeName, text);
  11064. return e;
  11065. }
  11066. void XmlElement::addTextElement (const String& text) throw()
  11067. {
  11068. addChildElement (createTextElement (text));
  11069. }
  11070. void XmlElement::deleteAllTextElements() throw()
  11071. {
  11072. XmlElement* child = firstChildElement;
  11073. while (child != 0)
  11074. {
  11075. XmlElement* const next = child->nextElement;
  11076. if (child->isTextElement())
  11077. removeChildElement (child, true);
  11078. child = next;
  11079. }
  11080. }
  11081. END_JUCE_NAMESPACE
  11082. /********* End of inlined file: juce_XmlElement.cpp *********/
  11083. /********* Start of inlined file: juce_InterProcessLock.cpp *********/
  11084. BEGIN_JUCE_NAMESPACE
  11085. // (implemented in the platform-specific code files)
  11086. END_JUCE_NAMESPACE
  11087. /********* End of inlined file: juce_InterProcessLock.cpp *********/
  11088. /********* Start of inlined file: juce_ReadWriteLock.cpp *********/
  11089. BEGIN_JUCE_NAMESPACE
  11090. ReadWriteLock::ReadWriteLock() throw()
  11091. : numWaitingWriters (0),
  11092. numWriters (0),
  11093. writerThreadId (0)
  11094. {
  11095. }
  11096. ReadWriteLock::~ReadWriteLock() throw()
  11097. {
  11098. jassert (readerThreads.size() == 0);
  11099. jassert (numWriters == 0);
  11100. }
  11101. void ReadWriteLock::enterRead() const throw()
  11102. {
  11103. const int threadId = Thread::getCurrentThreadId();
  11104. const ScopedLock sl (accessLock);
  11105. for (;;)
  11106. {
  11107. jassert (readerThreads.size() % 2 == 0);
  11108. int i;
  11109. for (i = 0; i < readerThreads.size(); i += 2)
  11110. if (readerThreads.getUnchecked(i) == threadId)
  11111. break;
  11112. if (i < readerThreads.size()
  11113. || numWriters + numWaitingWriters == 0
  11114. || (threadId == writerThreadId && numWriters > 0))
  11115. {
  11116. if (i < readerThreads.size())
  11117. {
  11118. readerThreads.set (i + 1, readerThreads.getUnchecked (i + 1) + 1);
  11119. }
  11120. else
  11121. {
  11122. readerThreads.add (threadId);
  11123. readerThreads.add (1);
  11124. }
  11125. return;
  11126. }
  11127. const ScopedUnlock ul (accessLock);
  11128. waitEvent.wait (100);
  11129. }
  11130. }
  11131. void ReadWriteLock::exitRead() const throw()
  11132. {
  11133. const int threadId = Thread::getCurrentThreadId();
  11134. const ScopedLock sl (accessLock);
  11135. for (int i = 0; i < readerThreads.size(); i += 2)
  11136. {
  11137. if (readerThreads.getUnchecked(i) == threadId)
  11138. {
  11139. const int newCount = readerThreads.getUnchecked (i + 1) - 1;
  11140. if (newCount == 0)
  11141. {
  11142. readerThreads.removeRange (i, 2);
  11143. waitEvent.signal();
  11144. }
  11145. else
  11146. {
  11147. readerThreads.set (i + 1, newCount);
  11148. }
  11149. return;
  11150. }
  11151. }
  11152. jassertfalse // unlocking a lock that wasn't locked..
  11153. }
  11154. void ReadWriteLock::enterWrite() const throw()
  11155. {
  11156. const int threadId = Thread::getCurrentThreadId();
  11157. const ScopedLock sl (accessLock);
  11158. for (;;)
  11159. {
  11160. if (readerThreads.size() + numWriters == 0
  11161. || threadId == writerThreadId
  11162. || (readerThreads.size() == 2
  11163. && readerThreads.getUnchecked(0) == threadId))
  11164. {
  11165. writerThreadId = threadId;
  11166. ++numWriters;
  11167. break;
  11168. }
  11169. ++numWaitingWriters;
  11170. accessLock.exit();
  11171. waitEvent.wait (100);
  11172. accessLock.enter();
  11173. --numWaitingWriters;
  11174. }
  11175. }
  11176. bool ReadWriteLock::tryEnterWrite() const throw()
  11177. {
  11178. const int threadId = Thread::getCurrentThreadId();
  11179. const ScopedLock sl (accessLock);
  11180. if (readerThreads.size() + numWriters == 0
  11181. || threadId == writerThreadId
  11182. || (readerThreads.size() == 2
  11183. && readerThreads.getUnchecked(0) == threadId))
  11184. {
  11185. writerThreadId = threadId;
  11186. ++numWriters;
  11187. return true;
  11188. }
  11189. return false;
  11190. }
  11191. void ReadWriteLock::exitWrite() const throw()
  11192. {
  11193. const ScopedLock sl (accessLock);
  11194. // check this thread actually had the lock..
  11195. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  11196. if (--numWriters == 0)
  11197. {
  11198. writerThreadId = 0;
  11199. waitEvent.signal();
  11200. }
  11201. }
  11202. END_JUCE_NAMESPACE
  11203. /********* End of inlined file: juce_ReadWriteLock.cpp *********/
  11204. /********* Start of inlined file: juce_Thread.cpp *********/
  11205. BEGIN_JUCE_NAMESPACE
  11206. // these functions are implemented in the platform-specific code.
  11207. void* juce_createThread (void* userData) throw();
  11208. void juce_killThread (void* handle) throw();
  11209. void juce_setThreadPriority (void* handle, int priority) throw();
  11210. void juce_setCurrentThreadName (const String& name) throw();
  11211. #if JUCE_WIN32
  11212. void juce_CloseThreadHandle (void* handle) throw();
  11213. #endif
  11214. static VoidArray runningThreads (4);
  11215. static CriticalSection runningThreadsLock;
  11216. void Thread::threadEntryPoint (Thread* const thread) throw()
  11217. {
  11218. runningThreadsLock.enter();
  11219. runningThreads.add (thread);
  11220. runningThreadsLock.exit();
  11221. JUCE_TRY
  11222. {
  11223. thread->threadId_ = Thread::getCurrentThreadId();
  11224. if (thread->threadName_.isNotEmpty())
  11225. juce_setCurrentThreadName (thread->threadName_);
  11226. if (thread->startSuspensionEvent_.wait (10000))
  11227. {
  11228. if (thread->affinityMask_ != 0)
  11229. setCurrentThreadAffinityMask (thread->affinityMask_);
  11230. thread->run();
  11231. }
  11232. }
  11233. JUCE_CATCH_ALL_ASSERT
  11234. runningThreadsLock.enter();
  11235. jassert (runningThreads.contains (thread));
  11236. runningThreads.removeValue (thread);
  11237. runningThreadsLock.exit();
  11238. #if JUCE_WIN32
  11239. juce_CloseThreadHandle (thread->threadHandle_);
  11240. #endif
  11241. thread->threadHandle_ = 0;
  11242. thread->threadId_ = 0;
  11243. }
  11244. // used to wrap the incoming call from the platform-specific code
  11245. void JUCE_API juce_threadEntryPoint (void* userData)
  11246. {
  11247. Thread::threadEntryPoint ((Thread*) userData);
  11248. }
  11249. Thread::Thread (const String& threadName)
  11250. : threadName_ (threadName),
  11251. threadHandle_ (0),
  11252. threadPriority_ (5),
  11253. threadId_ (0),
  11254. affinityMask_ (0),
  11255. threadShouldExit_ (false)
  11256. {
  11257. }
  11258. Thread::~Thread()
  11259. {
  11260. stopThread (100);
  11261. }
  11262. void Thread::startThread() throw()
  11263. {
  11264. const ScopedLock sl (startStopLock);
  11265. threadShouldExit_ = false;
  11266. if (threadHandle_ == 0)
  11267. {
  11268. threadHandle_ = juce_createThread ((void*) this);
  11269. juce_setThreadPriority (threadHandle_, threadPriority_);
  11270. startSuspensionEvent_.signal();
  11271. }
  11272. }
  11273. void Thread::startThread (const int priority) throw()
  11274. {
  11275. const ScopedLock sl (startStopLock);
  11276. if (threadHandle_ == 0)
  11277. {
  11278. threadPriority_ = priority;
  11279. startThread();
  11280. }
  11281. else
  11282. {
  11283. setPriority (priority);
  11284. }
  11285. }
  11286. bool Thread::isThreadRunning() const throw()
  11287. {
  11288. return threadHandle_ != 0;
  11289. }
  11290. void Thread::signalThreadShouldExit() throw()
  11291. {
  11292. threadShouldExit_ = true;
  11293. }
  11294. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const throw()
  11295. {
  11296. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  11297. jassert (getThreadId() != getCurrentThreadId());
  11298. const int sleepMsPerIteration = 5;
  11299. int count = timeOutMilliseconds / sleepMsPerIteration;
  11300. while (isThreadRunning())
  11301. {
  11302. if (timeOutMilliseconds > 0 && --count < 0)
  11303. return false;
  11304. sleep (sleepMsPerIteration);
  11305. }
  11306. return true;
  11307. }
  11308. void Thread::stopThread (const int timeOutMilliseconds) throw()
  11309. {
  11310. // agh! You can't stop the thread that's calling this method! How on earth
  11311. // would that work??
  11312. jassert (getCurrentThreadId() != getThreadId());
  11313. const ScopedLock sl (startStopLock);
  11314. if (isThreadRunning())
  11315. {
  11316. signalThreadShouldExit();
  11317. notify();
  11318. if (timeOutMilliseconds != 0)
  11319. waitForThreadToExit (timeOutMilliseconds);
  11320. if (isThreadRunning())
  11321. {
  11322. // very bad karma if this point is reached, as
  11323. // there are bound to be locks and events left in
  11324. // silly states when a thread is killed by force..
  11325. jassertfalse
  11326. Logger::writeToLog ("!! killing thread by force !!");
  11327. juce_killThread (threadHandle_);
  11328. threadHandle_ = 0;
  11329. threadId_ = 0;
  11330. const ScopedLock sl (runningThreadsLock);
  11331. runningThreads.removeValue (this);
  11332. }
  11333. }
  11334. }
  11335. void Thread::setPriority (const int priority) throw()
  11336. {
  11337. const ScopedLock sl (startStopLock);
  11338. threadPriority_ = priority;
  11339. juce_setThreadPriority (threadHandle_, priority);
  11340. }
  11341. void Thread::setCurrentThreadPriority (const int priority) throw()
  11342. {
  11343. juce_setThreadPriority (0, priority);
  11344. }
  11345. void Thread::setAffinityMask (const uint32 affinityMask) throw()
  11346. {
  11347. affinityMask_ = affinityMask;
  11348. }
  11349. int Thread::getThreadId() const throw()
  11350. {
  11351. return threadId_;
  11352. }
  11353. bool Thread::wait (const int timeOutMilliseconds) const throw()
  11354. {
  11355. return defaultEvent_.wait (timeOutMilliseconds);
  11356. }
  11357. void Thread::notify() const throw()
  11358. {
  11359. defaultEvent_.signal();
  11360. }
  11361. int Thread::getNumRunningThreads() throw()
  11362. {
  11363. return runningThreads.size();
  11364. }
  11365. Thread* Thread::getCurrentThread() throw()
  11366. {
  11367. const int thisId = getCurrentThreadId();
  11368. Thread* result = 0;
  11369. runningThreadsLock.enter();
  11370. for (int i = runningThreads.size(); --i >= 0;)
  11371. {
  11372. Thread* const t = (Thread*) (runningThreads.getUnchecked(i));
  11373. if (t->threadId_ == thisId)
  11374. {
  11375. result = t;
  11376. break;
  11377. }
  11378. }
  11379. runningThreadsLock.exit();
  11380. return result;
  11381. }
  11382. void Thread::stopAllThreads (const int timeOutMilliseconds) throw()
  11383. {
  11384. runningThreadsLock.enter();
  11385. for (int i = runningThreads.size(); --i >= 0;)
  11386. ((Thread*) runningThreads.getUnchecked(i))->signalThreadShouldExit();
  11387. runningThreadsLock.exit();
  11388. for (;;)
  11389. {
  11390. runningThreadsLock.enter();
  11391. Thread* const t = (Thread*) runningThreads[0];
  11392. runningThreadsLock.exit();
  11393. if (t == 0)
  11394. break;
  11395. t->stopThread (timeOutMilliseconds);
  11396. }
  11397. }
  11398. END_JUCE_NAMESPACE
  11399. /********* End of inlined file: juce_Thread.cpp *********/
  11400. /********* Start of inlined file: juce_ThreadPool.cpp *********/
  11401. BEGIN_JUCE_NAMESPACE
  11402. ThreadPoolJob::ThreadPoolJob (const String& name)
  11403. : jobName (name),
  11404. pool (0),
  11405. shouldStop (false),
  11406. isActive (false),
  11407. shouldBeDeleted (false)
  11408. {
  11409. }
  11410. ThreadPoolJob::~ThreadPoolJob()
  11411. {
  11412. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  11413. // to remove it first!
  11414. jassert (pool == 0 || ! pool->contains (this));
  11415. }
  11416. const String ThreadPoolJob::getJobName() const
  11417. {
  11418. return jobName;
  11419. }
  11420. void ThreadPoolJob::setJobName (const String& newName)
  11421. {
  11422. jobName = newName;
  11423. }
  11424. void ThreadPoolJob::signalJobShouldExit()
  11425. {
  11426. shouldStop = true;
  11427. }
  11428. class ThreadPoolThread : public Thread
  11429. {
  11430. ThreadPool& pool;
  11431. bool volatile busy;
  11432. ThreadPoolThread (const ThreadPoolThread&);
  11433. const ThreadPoolThread& operator= (const ThreadPoolThread&);
  11434. public:
  11435. ThreadPoolThread (ThreadPool& pool_)
  11436. : Thread (T("Pool")),
  11437. pool (pool_),
  11438. busy (false)
  11439. {
  11440. }
  11441. ~ThreadPoolThread()
  11442. {
  11443. }
  11444. void run()
  11445. {
  11446. while (! threadShouldExit())
  11447. {
  11448. if (! pool.runNextJob())
  11449. wait (500);
  11450. }
  11451. }
  11452. };
  11453. ThreadPool::ThreadPool (const int numThreads_,
  11454. const bool startThreadsOnlyWhenNeeded,
  11455. const int stopThreadsWhenNotUsedTimeoutMs)
  11456. : numThreads (jmax (1, numThreads_)),
  11457. threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  11458. priority (5)
  11459. {
  11460. jassert (numThreads_ > 0); // not much point having one of these with no threads in it.
  11461. threads = (Thread**) juce_calloc (sizeof (Thread*) * numThreads);
  11462. for (int i = numThreads; --i >= 0;)
  11463. {
  11464. threads[i] = new ThreadPoolThread (*this);
  11465. if (! startThreadsOnlyWhenNeeded)
  11466. threads[i]->startThread();
  11467. }
  11468. }
  11469. ThreadPool::~ThreadPool()
  11470. {
  11471. removeAllJobs (true, 4000);
  11472. int i;
  11473. for (i = numThreads; --i >= 0;)
  11474. threads[i]->signalThreadShouldExit();
  11475. for (i = numThreads; --i >= 0;)
  11476. {
  11477. threads[i]->stopThread (500);
  11478. delete threads[i];
  11479. }
  11480. juce_free (threads);
  11481. }
  11482. void ThreadPool::addJob (ThreadPoolJob* const job)
  11483. {
  11484. jassert (job->pool == 0);
  11485. if (job->pool == 0)
  11486. {
  11487. job->pool = this;
  11488. job->shouldStop = false;
  11489. job->isActive = false;
  11490. lock.enter();
  11491. jobs.add (job);
  11492. int numRunning = 0;
  11493. int i;
  11494. for (i = numThreads; --i >= 0;)
  11495. if (threads[i]->isThreadRunning() && ! threads[i]->threadShouldExit())
  11496. ++numRunning;
  11497. if (numRunning < numThreads)
  11498. {
  11499. bool startedOne = false;
  11500. int n = 1000;
  11501. while (--n >= 0 && ! startedOne)
  11502. {
  11503. for (int i = numThreads; --i >= 0;)
  11504. {
  11505. if (! threads[i]->isThreadRunning())
  11506. {
  11507. threads[i]->startThread();
  11508. startedOne = true;
  11509. }
  11510. }
  11511. if (! startedOne)
  11512. Thread::sleep (5);
  11513. }
  11514. }
  11515. lock.exit();
  11516. for (i = numThreads; --i >= 0;)
  11517. threads[i]->notify();
  11518. }
  11519. }
  11520. int ThreadPool::getNumJobs() const throw()
  11521. {
  11522. return jobs.size();
  11523. }
  11524. ThreadPoolJob* ThreadPool::getJob (const int index) const
  11525. {
  11526. const ScopedLock sl (lock);
  11527. return (ThreadPoolJob*) jobs [index];
  11528. }
  11529. bool ThreadPool::contains (const ThreadPoolJob* const job) const throw()
  11530. {
  11531. const ScopedLock sl (lock);
  11532. return jobs.contains ((void*) job);
  11533. }
  11534. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  11535. {
  11536. const ScopedLock sl (lock);
  11537. return jobs.contains ((void*) job) && job->isActive;
  11538. }
  11539. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  11540. const int timeOutMs) const
  11541. {
  11542. if (job != 0)
  11543. {
  11544. const uint32 start = Time::getMillisecondCounter();
  11545. while (contains (job))
  11546. {
  11547. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  11548. return false;
  11549. Thread::sleep (2);
  11550. }
  11551. }
  11552. return true;
  11553. }
  11554. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  11555. const bool interruptIfRunning,
  11556. const int timeOutMs)
  11557. {
  11558. if (job != 0)
  11559. {
  11560. lock.enter();
  11561. if (jobs.contains (job))
  11562. {
  11563. if (job->isActive)
  11564. {
  11565. if (interruptIfRunning)
  11566. job->signalJobShouldExit();
  11567. lock.exit();
  11568. return waitForJobToFinish (job, timeOutMs);
  11569. }
  11570. else
  11571. {
  11572. jobs.removeValue (job);
  11573. }
  11574. }
  11575. lock.exit();
  11576. }
  11577. return true;
  11578. }
  11579. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  11580. const int timeOutMs)
  11581. {
  11582. lock.enter();
  11583. for (int i = jobs.size(); --i >= 0;)
  11584. {
  11585. ThreadPoolJob* const job = (ThreadPoolJob*) jobs.getUnchecked(i);
  11586. if (job->isActive)
  11587. {
  11588. if (interruptRunningJobs)
  11589. job->signalJobShouldExit();
  11590. }
  11591. else
  11592. {
  11593. jobs.remove (i);
  11594. }
  11595. }
  11596. lock.exit();
  11597. const uint32 start = Time::getMillisecondCounter();
  11598. while (jobs.size() > 0)
  11599. {
  11600. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  11601. return false;
  11602. Thread::sleep (2);
  11603. }
  11604. return true;
  11605. }
  11606. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  11607. {
  11608. StringArray s;
  11609. const ScopedLock sl (lock);
  11610. for (int i = 0; i < jobs.size(); ++i)
  11611. {
  11612. const ThreadPoolJob* const job = (const ThreadPoolJob*) jobs.getUnchecked(i);
  11613. if (job->isActive || ! onlyReturnActiveJobs)
  11614. s.add (job->getJobName());
  11615. }
  11616. return s;
  11617. }
  11618. void ThreadPool::setThreadPriorities (const int newPriority)
  11619. {
  11620. if (priority != newPriority)
  11621. {
  11622. priority = newPriority;
  11623. for (int i = numThreads; --i >= 0;)
  11624. threads[i]->setPriority (newPriority);
  11625. }
  11626. }
  11627. bool ThreadPool::runNextJob()
  11628. {
  11629. lock.enter();
  11630. ThreadPoolJob* job = 0;
  11631. for (int i = 0; i < jobs.size(); ++i)
  11632. {
  11633. job = (ThreadPoolJob*) jobs [i];
  11634. if (job != 0 && ! (job->isActive || job->shouldStop))
  11635. break;
  11636. job = 0;
  11637. }
  11638. if (job != 0)
  11639. {
  11640. job->isActive = true;
  11641. lock.exit();
  11642. JUCE_TRY
  11643. {
  11644. ThreadPoolJob::JobStatus result = job->runJob();
  11645. lastJobEndTime = Time::getApproximateMillisecondCounter();
  11646. const ScopedLock sl (lock);
  11647. if (jobs.contains (job))
  11648. {
  11649. job->isActive = false;
  11650. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  11651. {
  11652. job->pool = 0;
  11653. job->shouldStop = true;
  11654. jobs.removeValue (job);
  11655. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  11656. delete job;
  11657. }
  11658. else
  11659. {
  11660. // move the job to the end of the queue if it wants another go
  11661. jobs.move (jobs.indexOf (job), -1);
  11662. }
  11663. }
  11664. }
  11665. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  11666. catch (...)
  11667. {
  11668. lock.enter();
  11669. jobs.removeValue (job);
  11670. lock.exit();
  11671. }
  11672. #endif
  11673. }
  11674. else
  11675. {
  11676. lock.exit();
  11677. if (threadStopTimeout > 0
  11678. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  11679. {
  11680. lock.enter();
  11681. if (jobs.size() == 0)
  11682. {
  11683. for (int i = numThreads; --i >= 0;)
  11684. threads[i]->signalThreadShouldExit();
  11685. }
  11686. lock.exit();
  11687. }
  11688. else
  11689. {
  11690. return false;
  11691. }
  11692. }
  11693. return true;
  11694. }
  11695. END_JUCE_NAMESPACE
  11696. /********* End of inlined file: juce_ThreadPool.cpp *********/
  11697. /********* Start of inlined file: juce_TimeSliceThread.cpp *********/
  11698. BEGIN_JUCE_NAMESPACE
  11699. TimeSliceThread::TimeSliceThread (const String& threadName)
  11700. : Thread (threadName),
  11701. index (0),
  11702. clientBeingCalled (0),
  11703. clientsChanged (false)
  11704. {
  11705. }
  11706. TimeSliceThread::~TimeSliceThread()
  11707. {
  11708. stopThread (2000);
  11709. }
  11710. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  11711. {
  11712. const ScopedLock sl (listLock);
  11713. clients.addIfNotAlreadyThere (client);
  11714. clientsChanged = true;
  11715. notify();
  11716. }
  11717. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  11718. {
  11719. const ScopedLock sl1 (listLock);
  11720. clientsChanged = true;
  11721. // if there's a chance we're in the middle of calling this client, we need to
  11722. // also lock the outer lock..
  11723. if (clientBeingCalled == client)
  11724. {
  11725. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  11726. const ScopedLock sl1 (callbackLock);
  11727. const ScopedLock sl2 (listLock);
  11728. clients.removeValue (client);
  11729. }
  11730. else
  11731. {
  11732. clients.removeValue (client);
  11733. }
  11734. }
  11735. int TimeSliceThread::getNumClients() const throw()
  11736. {
  11737. return clients.size();
  11738. }
  11739. TimeSliceClient* TimeSliceThread::getClient (const int index) const throw()
  11740. {
  11741. const ScopedLock sl (listLock);
  11742. return clients [index];
  11743. }
  11744. void TimeSliceThread::run()
  11745. {
  11746. int numCallsSinceBusy = 0;
  11747. while (! threadShouldExit())
  11748. {
  11749. int timeToWait = 500;
  11750. {
  11751. const ScopedLock sl (callbackLock);
  11752. {
  11753. const ScopedLock sl (listLock);
  11754. if (clients.size() > 0)
  11755. {
  11756. index = (index + 1) % clients.size();
  11757. clientBeingCalled = clients [index];
  11758. }
  11759. else
  11760. {
  11761. index = 0;
  11762. clientBeingCalled = 0;
  11763. }
  11764. if (clientsChanged)
  11765. {
  11766. clientsChanged = false;
  11767. numCallsSinceBusy = 0;
  11768. }
  11769. }
  11770. if (clientBeingCalled != 0)
  11771. {
  11772. if (clientBeingCalled->useTimeSlice())
  11773. numCallsSinceBusy = 0;
  11774. else
  11775. ++numCallsSinceBusy;
  11776. if (numCallsSinceBusy >= clients.size())
  11777. timeToWait = 500;
  11778. else if (index == 0)
  11779. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  11780. else
  11781. timeToWait = 0;
  11782. }
  11783. }
  11784. if (timeToWait > 0)
  11785. wait (timeToWait);
  11786. }
  11787. }
  11788. END_JUCE_NAMESPACE
  11789. /********* End of inlined file: juce_TimeSliceThread.cpp *********/
  11790. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  11791. /********* Start of inlined file: juce_Application.cpp *********/
  11792. #if JUCE_MSVC
  11793. #pragma warning (push)
  11794. #pragma warning (disable: 4245 4514 4100)
  11795. #include <crtdbg.h>
  11796. #pragma warning (pop)
  11797. #endif
  11798. BEGIN_JUCE_NAMESPACE
  11799. void juce_setCurrentExecutableFileName (const String& filename) throw();
  11800. void juce_setCurrentThreadName (const String& name) throw();
  11801. static JUCEApplication* appInstance = 0;
  11802. JUCEApplication::JUCEApplication()
  11803. : appReturnValue (0),
  11804. stillInitialising (true)
  11805. {
  11806. }
  11807. JUCEApplication::~JUCEApplication()
  11808. {
  11809. }
  11810. JUCEApplication* JUCEApplication::getInstance() throw()
  11811. {
  11812. return appInstance;
  11813. }
  11814. bool JUCEApplication::isInitialising() const throw()
  11815. {
  11816. return stillInitialising;
  11817. }
  11818. const String JUCEApplication::getApplicationVersion()
  11819. {
  11820. return String::empty;
  11821. }
  11822. bool JUCEApplication::moreThanOneInstanceAllowed()
  11823. {
  11824. return true;
  11825. }
  11826. void JUCEApplication::anotherInstanceStarted (const String&)
  11827. {
  11828. }
  11829. void JUCEApplication::systemRequestedQuit()
  11830. {
  11831. quit();
  11832. }
  11833. void JUCEApplication::quit (const bool useMaximumForce)
  11834. {
  11835. MessageManager::getInstance()->postQuitMessage (useMaximumForce);
  11836. }
  11837. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  11838. {
  11839. appReturnValue = newReturnValue;
  11840. }
  11841. void JUCEApplication::unhandledException (const std::exception*,
  11842. const String&,
  11843. const int)
  11844. {
  11845. jassertfalse
  11846. }
  11847. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  11848. const char* const sourceFile,
  11849. const int lineNumber)
  11850. {
  11851. if (appInstance != 0)
  11852. appInstance->unhandledException (e, sourceFile, lineNumber);
  11853. }
  11854. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  11855. {
  11856. return 0;
  11857. }
  11858. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  11859. {
  11860. commands.add (StandardApplicationCommandIDs::quit);
  11861. }
  11862. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  11863. {
  11864. if (commandID == StandardApplicationCommandIDs::quit)
  11865. {
  11866. result.setInfo ("Quit",
  11867. "Quits the application",
  11868. "Application",
  11869. 0);
  11870. result.defaultKeypresses.add (KeyPress (T('q'), ModifierKeys::commandModifier, 0));
  11871. }
  11872. }
  11873. bool JUCEApplication::perform (const InvocationInfo& info)
  11874. {
  11875. if (info.commandID == StandardApplicationCommandIDs::quit)
  11876. {
  11877. systemRequestedQuit();
  11878. return true;
  11879. }
  11880. return false;
  11881. }
  11882. int JUCEApplication::main (String& commandLine, JUCEApplication* const app)
  11883. {
  11884. jassert (appInstance == 0);
  11885. appInstance = app;
  11886. bool useForce = true;
  11887. initialiseJuce_GUI();
  11888. InterProcessLock* appLock = 0;
  11889. if (! app->moreThanOneInstanceAllowed())
  11890. {
  11891. appLock = new InterProcessLock ("juceAppLock_" + app->getApplicationName());
  11892. if (! appLock->enter(0))
  11893. {
  11894. MessageManager::broadcastMessage (app->getApplicationName() + "/" + commandLine);
  11895. delete appInstance;
  11896. appInstance = 0;
  11897. commandLine = String::empty;
  11898. DBG ("Another instance is running - quitting...");
  11899. return 0;
  11900. }
  11901. }
  11902. JUCE_TRY
  11903. {
  11904. juce_setCurrentThreadName ("Juce Message Thread");
  11905. // let the app do its setting-up..
  11906. app->initialise (commandLine.trim());
  11907. commandLine = String::empty;
  11908. // register for broadcast new app messages
  11909. MessageManager::getInstance()->registerBroadcastListener (app);
  11910. app->stillInitialising = false;
  11911. // now loop until a quit message is received..
  11912. useForce = MessageManager::getInstance()->runDispatchLoop();
  11913. MessageManager::getInstance()->deregisterBroadcastListener (app);
  11914. if (appLock != 0)
  11915. {
  11916. appLock->exit();
  11917. delete appLock;
  11918. }
  11919. }
  11920. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  11921. catch (const std::exception& e)
  11922. {
  11923. app->unhandledException (&e, __FILE__, __LINE__);
  11924. }
  11925. catch (...)
  11926. {
  11927. app->unhandledException (0, __FILE__, __LINE__);
  11928. }
  11929. #endif
  11930. return shutdownAppAndClearUp (useForce);
  11931. }
  11932. int JUCEApplication::shutdownAppAndClearUp (const bool useMaximumForce)
  11933. {
  11934. jassert (appInstance != 0);
  11935. JUCEApplication* const app = appInstance;
  11936. int returnValue = 0;
  11937. static bool reentrancyCheck = false;
  11938. if (! reentrancyCheck)
  11939. {
  11940. reentrancyCheck = true;
  11941. JUCE_TRY
  11942. {
  11943. // give the app a chance to clean up..
  11944. app->shutdown();
  11945. }
  11946. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  11947. catch (const std::exception& e)
  11948. {
  11949. app->unhandledException (&e, __FILE__, __LINE__);
  11950. }
  11951. catch (...)
  11952. {
  11953. app->unhandledException (0, __FILE__, __LINE__);
  11954. }
  11955. #endif
  11956. JUCE_TRY
  11957. {
  11958. shutdownJuce_GUI();
  11959. returnValue = app->getApplicationReturnValue();
  11960. appInstance = 0;
  11961. delete app;
  11962. }
  11963. JUCE_CATCH_ALL_ASSERT
  11964. if (useMaximumForce)
  11965. {
  11966. Process::terminate();
  11967. }
  11968. reentrancyCheck = false;
  11969. }
  11970. return returnValue;
  11971. }
  11972. int JUCEApplication::main (int argc, char* argv[],
  11973. JUCEApplication* const newApp)
  11974. {
  11975. juce_setCurrentExecutableFileName (String::fromUTF8 ((const uint8*) argv[0]));
  11976. String cmd;
  11977. for (int i = 1; i < argc; ++i)
  11978. cmd << String::fromUTF8 ((const uint8*) argv[i]) << T(' ');
  11979. return JUCEApplication::main (cmd, newApp);
  11980. }
  11981. void JUCEApplication::actionListenerCallback (const String& message)
  11982. {
  11983. if (message.startsWith (getApplicationName() + "/"))
  11984. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  11985. }
  11986. static bool juceInitialisedGUI = false;
  11987. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  11988. {
  11989. if (! juceInitialisedGUI)
  11990. {
  11991. juceInitialisedGUI = true;
  11992. initialiseJuce_NonGUI();
  11993. MessageManager::getInstance();
  11994. Font::initialiseDefaultFontNames();
  11995. LookAndFeel::setDefaultLookAndFeel (0);
  11996. #if JUCE_WIN32 && JUCE_DEBUG
  11997. // This section is just for catching people who mess up their project settings and
  11998. // turn RTTI off..
  11999. try
  12000. {
  12001. TextButton tb (String::empty);
  12002. Component* c = &tb;
  12003. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  12004. c = dynamic_cast <Button*> (c);
  12005. }
  12006. catch (...)
  12007. {
  12008. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  12009. // got as far as this catch statement, then why haven't you got exception catching
  12010. // turned on in the debugger???
  12011. jassertfalse
  12012. }
  12013. #endif
  12014. }
  12015. }
  12016. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  12017. {
  12018. if (juceInitialisedGUI)
  12019. {
  12020. DeletedAtShutdown::deleteAll();
  12021. LookAndFeel::clearDefaultLookAndFeel();
  12022. shutdownJuce_NonGUI();
  12023. juceInitialisedGUI = false;
  12024. }
  12025. }
  12026. END_JUCE_NAMESPACE
  12027. /********* End of inlined file: juce_Application.cpp *********/
  12028. /********* Start of inlined file: juce_ApplicationCommandInfo.cpp *********/
  12029. BEGIN_JUCE_NAMESPACE
  12030. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  12031. : commandID (commandID_),
  12032. flags (0)
  12033. {
  12034. }
  12035. void ApplicationCommandInfo::setInfo (const String& shortName_,
  12036. const String& description_,
  12037. const String& categoryName_,
  12038. const int flags_) throw()
  12039. {
  12040. shortName = shortName_;
  12041. description = description_;
  12042. categoryName = categoryName_;
  12043. flags = flags_;
  12044. }
  12045. void ApplicationCommandInfo::setActive (const bool b) throw()
  12046. {
  12047. if (b)
  12048. flags &= ~isDisabled;
  12049. else
  12050. flags |= isDisabled;
  12051. }
  12052. void ApplicationCommandInfo::setTicked (const bool b) throw()
  12053. {
  12054. if (b)
  12055. flags |= isTicked;
  12056. else
  12057. flags &= ~isTicked;
  12058. }
  12059. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  12060. {
  12061. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  12062. }
  12063. END_JUCE_NAMESPACE
  12064. /********* End of inlined file: juce_ApplicationCommandInfo.cpp *********/
  12065. /********* Start of inlined file: juce_ApplicationCommandManager.cpp *********/
  12066. BEGIN_JUCE_NAMESPACE
  12067. ApplicationCommandManager::ApplicationCommandManager()
  12068. : listeners (8),
  12069. firstTarget (0)
  12070. {
  12071. keyMappings = new KeyPressMappingSet (this);
  12072. Desktop::getInstance().addFocusChangeListener (this);
  12073. }
  12074. ApplicationCommandManager::~ApplicationCommandManager()
  12075. {
  12076. Desktop::getInstance().removeFocusChangeListener (this);
  12077. deleteAndZero (keyMappings);
  12078. }
  12079. void ApplicationCommandManager::clearCommands()
  12080. {
  12081. commands.clear();
  12082. keyMappings->clearAllKeyPresses();
  12083. triggerAsyncUpdate();
  12084. }
  12085. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  12086. {
  12087. // zero isn't a valid command ID!
  12088. jassert (newCommand.commandID != 0);
  12089. // the name isn't optional!
  12090. jassert (newCommand.shortName.isNotEmpty());
  12091. if (getCommandForID (newCommand.commandID) == 0)
  12092. {
  12093. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  12094. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  12095. commands.add (newInfo);
  12096. keyMappings->resetToDefaultMapping (newCommand.commandID);
  12097. triggerAsyncUpdate();
  12098. }
  12099. else
  12100. {
  12101. // trying to re-register the same command with different parameters?
  12102. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  12103. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  12104. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  12105. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  12106. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  12107. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  12108. }
  12109. }
  12110. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  12111. {
  12112. if (target != 0)
  12113. {
  12114. Array <CommandID> commandIDs;
  12115. target->getAllCommands (commandIDs);
  12116. for (int i = 0; i < commandIDs.size(); ++i)
  12117. {
  12118. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  12119. target->getCommandInfo (info.commandID, info);
  12120. registerCommand (info);
  12121. }
  12122. }
  12123. }
  12124. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  12125. {
  12126. for (int i = commands.size(); --i >= 0;)
  12127. {
  12128. if (commands.getUnchecked (i)->commandID == commandID)
  12129. {
  12130. commands.remove (i);
  12131. triggerAsyncUpdate();
  12132. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  12133. for (int j = keys.size(); --j >= 0;)
  12134. keyMappings->removeKeyPress (keys.getReference (j));
  12135. }
  12136. }
  12137. }
  12138. void ApplicationCommandManager::commandStatusChanged()
  12139. {
  12140. triggerAsyncUpdate();
  12141. }
  12142. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  12143. {
  12144. for (int i = commands.size(); --i >= 0;)
  12145. if (commands.getUnchecked(i)->commandID == commandID)
  12146. return commands.getUnchecked(i);
  12147. return 0;
  12148. }
  12149. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  12150. {
  12151. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  12152. return (ci != 0) ? ci->shortName : String::empty;
  12153. }
  12154. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  12155. {
  12156. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  12157. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  12158. : String::empty;
  12159. }
  12160. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  12161. {
  12162. StringArray s;
  12163. for (int i = 0; i < commands.size(); ++i)
  12164. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  12165. return s;
  12166. }
  12167. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  12168. {
  12169. Array <CommandID> results (4);
  12170. for (int i = 0; i < commands.size(); ++i)
  12171. if (commands.getUnchecked(i)->categoryName == categoryName)
  12172. results.add (commands.getUnchecked(i)->commandID);
  12173. return results;
  12174. }
  12175. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  12176. {
  12177. ApplicationCommandTarget::InvocationInfo info (commandID);
  12178. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  12179. return invoke (info, asynchronously);
  12180. }
  12181. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  12182. {
  12183. // This call isn't thread-safe for use from a non-UI thread without locking the message
  12184. // manager first..
  12185. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  12186. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  12187. if (target == 0)
  12188. return false;
  12189. ApplicationCommandInfo commandInfo (0);
  12190. target->getCommandInfo (info_.commandID, commandInfo);
  12191. ApplicationCommandTarget::InvocationInfo info (info_);
  12192. info.commandFlags = commandInfo.flags;
  12193. sendListenerInvokeCallback (info);
  12194. const bool ok = target->invoke (info, asynchronously);
  12195. commandStatusChanged();
  12196. return ok;
  12197. }
  12198. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  12199. {
  12200. return firstTarget != 0 ? firstTarget
  12201. : findDefaultComponentTarget();
  12202. }
  12203. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  12204. {
  12205. firstTarget = newTarget;
  12206. }
  12207. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  12208. ApplicationCommandInfo& upToDateInfo)
  12209. {
  12210. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  12211. if (target == 0)
  12212. target = JUCEApplication::getInstance();
  12213. if (target != 0)
  12214. target = target->getTargetForCommand (commandID);
  12215. if (target != 0)
  12216. target->getCommandInfo (commandID, upToDateInfo);
  12217. return target;
  12218. }
  12219. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  12220. {
  12221. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  12222. if (target == 0 && c != 0)
  12223. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  12224. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  12225. return target;
  12226. }
  12227. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  12228. {
  12229. Component* c = Component::getCurrentlyFocusedComponent();
  12230. if (c == 0)
  12231. {
  12232. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  12233. if (activeWindow != 0)
  12234. {
  12235. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  12236. if (c == 0)
  12237. c = activeWindow;
  12238. }
  12239. }
  12240. if (c == 0)
  12241. {
  12242. // getting a bit desperate now - try all desktop comps..
  12243. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  12244. {
  12245. ApplicationCommandTarget* const target
  12246. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  12247. ->getPeer()->getLastFocusedSubcomponent());
  12248. if (target != 0)
  12249. return target;
  12250. }
  12251. }
  12252. if (c != 0)
  12253. {
  12254. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  12255. // if we're focused on a ResizableWindow, chances are that it's the content
  12256. // component that really should get the event. And if not, the event will
  12257. // still be passed up to the top level window anyway, so let's send it to the
  12258. // content comp.
  12259. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  12260. c = resizableWindow->getContentComponent();
  12261. ApplicationCommandTarget* const target = findTargetForComponent (c);
  12262. if (target != 0)
  12263. return target;
  12264. }
  12265. return JUCEApplication::getInstance();
  12266. }
  12267. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  12268. {
  12269. jassert (listener != 0);
  12270. if (listener != 0)
  12271. listeners.add (listener);
  12272. }
  12273. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  12274. {
  12275. listeners.removeValue (listener);
  12276. }
  12277. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const
  12278. {
  12279. for (int i = listeners.size(); --i >= 0;)
  12280. {
  12281. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandInvoked (info);
  12282. i = jmin (i, listeners.size());
  12283. }
  12284. }
  12285. void ApplicationCommandManager::handleAsyncUpdate()
  12286. {
  12287. for (int i = listeners.size(); --i >= 0;)
  12288. {
  12289. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandListChanged();
  12290. i = jmin (i, listeners.size());
  12291. }
  12292. }
  12293. void ApplicationCommandManager::globalFocusChanged (Component*)
  12294. {
  12295. commandStatusChanged();
  12296. }
  12297. END_JUCE_NAMESPACE
  12298. /********* End of inlined file: juce_ApplicationCommandManager.cpp *********/
  12299. /********* Start of inlined file: juce_ApplicationCommandTarget.cpp *********/
  12300. BEGIN_JUCE_NAMESPACE
  12301. ApplicationCommandTarget::ApplicationCommandTarget()
  12302. : messageInvoker (0)
  12303. {
  12304. }
  12305. ApplicationCommandTarget::~ApplicationCommandTarget()
  12306. {
  12307. deleteAndZero (messageInvoker);
  12308. }
  12309. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  12310. {
  12311. if (isCommandActive (info.commandID))
  12312. {
  12313. if (async)
  12314. {
  12315. if (messageInvoker == 0)
  12316. messageInvoker = new CommandTargetMessageInvoker (this);
  12317. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  12318. return true;
  12319. }
  12320. else
  12321. {
  12322. const bool success = perform (info);
  12323. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  12324. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  12325. // returns the command's info.
  12326. return success;
  12327. }
  12328. }
  12329. return false;
  12330. }
  12331. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  12332. {
  12333. Component* c = dynamic_cast <Component*> (this);
  12334. if (c != 0)
  12335. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  12336. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  12337. return 0;
  12338. }
  12339. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  12340. {
  12341. ApplicationCommandTarget* target = this;
  12342. int depth = 0;
  12343. while (target != 0)
  12344. {
  12345. Array <CommandID> commandIDs;
  12346. target->getAllCommands (commandIDs);
  12347. if (commandIDs.contains (commandID))
  12348. return target;
  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. {
  12361. Array <CommandID> commandIDs;
  12362. target->getAllCommands (commandIDs);
  12363. if (commandIDs.contains (commandID))
  12364. return target;
  12365. }
  12366. }
  12367. return 0;
  12368. }
  12369. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  12370. {
  12371. ApplicationCommandInfo info (commandID);
  12372. info.flags = ApplicationCommandInfo::isDisabled;
  12373. getCommandInfo (commandID, info);
  12374. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  12375. }
  12376. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  12377. {
  12378. ApplicationCommandTarget* target = this;
  12379. int depth = 0;
  12380. while (target != 0)
  12381. {
  12382. if (target->tryToInvoke (info, async))
  12383. return true;
  12384. target = target->getNextCommandTarget();
  12385. ++depth;
  12386. jassert (depth < 100); // could be a recursive command chain??
  12387. jassert (target != this); // definitely a recursive command chain!
  12388. if (depth > 100 || target == this)
  12389. break;
  12390. }
  12391. if (target == 0)
  12392. {
  12393. target = JUCEApplication::getInstance();
  12394. if (target != 0)
  12395. return target->tryToInvoke (info, async);
  12396. }
  12397. return false;
  12398. }
  12399. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  12400. {
  12401. ApplicationCommandTarget::InvocationInfo info (commandID);
  12402. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  12403. return invoke (info, asynchronously);
  12404. }
  12405. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  12406. : commandID (commandID_),
  12407. commandFlags (0),
  12408. invocationMethod (direct),
  12409. originatingComponent (0),
  12410. isKeyDown (false),
  12411. millisecsSinceKeyPressed (0)
  12412. {
  12413. }
  12414. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  12415. : owner (owner_)
  12416. {
  12417. }
  12418. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  12419. {
  12420. }
  12421. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  12422. {
  12423. InvocationInfo* const info = (InvocationInfo*) message.pointerParameter;
  12424. owner->tryToInvoke (*info, false);
  12425. delete info;
  12426. }
  12427. END_JUCE_NAMESPACE
  12428. /********* End of inlined file: juce_ApplicationCommandTarget.cpp *********/
  12429. /********* Start of inlined file: juce_ApplicationProperties.cpp *********/
  12430. BEGIN_JUCE_NAMESPACE
  12431. juce_ImplementSingleton (ApplicationProperties)
  12432. ApplicationProperties::ApplicationProperties() throw()
  12433. : userProps (0),
  12434. commonProps (0),
  12435. msBeforeSaving (3000),
  12436. options (PropertiesFile::storeAsBinary),
  12437. commonSettingsAreReadOnly (0)
  12438. {
  12439. }
  12440. ApplicationProperties::~ApplicationProperties()
  12441. {
  12442. closeFiles();
  12443. clearSingletonInstance();
  12444. }
  12445. void ApplicationProperties::setStorageParameters (const String& applicationName,
  12446. const String& fileNameSuffix,
  12447. const String& folderName_,
  12448. const int millisecondsBeforeSaving,
  12449. const int propertiesFileOptions) throw()
  12450. {
  12451. appName = applicationName;
  12452. fileSuffix = fileNameSuffix;
  12453. folderName = folderName_;
  12454. msBeforeSaving = millisecondsBeforeSaving;
  12455. options = propertiesFileOptions;
  12456. }
  12457. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  12458. const bool testCommonSettings,
  12459. const bool showWarningDialogOnFailure)
  12460. {
  12461. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  12462. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  12463. if (! (userOk && commonOk))
  12464. {
  12465. if (showWarningDialogOnFailure)
  12466. {
  12467. String filenames;
  12468. if (userProps != 0 && ! userOk)
  12469. filenames << '\n' << userProps->getFile().getFullPathName();
  12470. if (commonProps != 0 && ! commonOk)
  12471. filenames << '\n' << commonProps->getFile().getFullPathName();
  12472. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  12473. appName + TRANS(" - Unable to save settings"),
  12474. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  12475. + appName + TRANS(" needs to be able to write to the following files:\n")
  12476. + filenames
  12477. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  12478. }
  12479. return false;
  12480. }
  12481. return true;
  12482. }
  12483. void ApplicationProperties::openFiles() throw()
  12484. {
  12485. // You need to call setStorageParameters() before trying to get hold of the
  12486. // properties!
  12487. jassert (appName.isNotEmpty());
  12488. if (appName.isNotEmpty())
  12489. {
  12490. if (userProps == 0)
  12491. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  12492. false, msBeforeSaving, options);
  12493. if (commonProps == 0)
  12494. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  12495. true, msBeforeSaving, options);
  12496. userProps->setFallbackPropertySet (commonProps);
  12497. }
  12498. }
  12499. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  12500. {
  12501. if (userProps == 0)
  12502. openFiles();
  12503. return userProps;
  12504. }
  12505. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  12506. {
  12507. if (commonProps == 0)
  12508. openFiles();
  12509. if (returnUserPropsIfReadOnly)
  12510. {
  12511. if (commonSettingsAreReadOnly == 0)
  12512. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  12513. if (commonSettingsAreReadOnly > 0)
  12514. return userProps;
  12515. }
  12516. return commonProps;
  12517. }
  12518. bool ApplicationProperties::saveIfNeeded()
  12519. {
  12520. return (userProps == 0 || userProps->saveIfNeeded())
  12521. && (commonProps == 0 || commonProps->saveIfNeeded());
  12522. }
  12523. void ApplicationProperties::closeFiles()
  12524. {
  12525. deleteAndZero (userProps);
  12526. deleteAndZero (commonProps);
  12527. }
  12528. END_JUCE_NAMESPACE
  12529. /********* End of inlined file: juce_ApplicationProperties.cpp *********/
  12530. /********* Start of inlined file: juce_DeletedAtShutdown.cpp *********/
  12531. BEGIN_JUCE_NAMESPACE
  12532. static VoidArray objectsToDelete (16);
  12533. static CriticalSection lock;
  12534. DeletedAtShutdown::DeletedAtShutdown() throw()
  12535. {
  12536. const ScopedLock sl (lock);
  12537. objectsToDelete.add (this);
  12538. }
  12539. DeletedAtShutdown::~DeletedAtShutdown()
  12540. {
  12541. const ScopedLock sl (lock);
  12542. objectsToDelete.removeValue (this);
  12543. }
  12544. void DeletedAtShutdown::deleteAll()
  12545. {
  12546. // make a local copy of the array, so it can't get into a loop if something
  12547. // creates another DeletedAtShutdown object during its destructor.
  12548. lock.enter();
  12549. const VoidArray localCopy (objectsToDelete);
  12550. lock.exit();
  12551. for (int i = localCopy.size(); --i >= 0;)
  12552. {
  12553. JUCE_TRY
  12554. {
  12555. DeletedAtShutdown* const deletee = (DeletedAtShutdown*) localCopy.getUnchecked(i);
  12556. // double-check that it's not already been deleted during another object's destructor.
  12557. lock.enter();
  12558. const bool okToDelete = objectsToDelete.contains (deletee);
  12559. lock.exit();
  12560. if (okToDelete)
  12561. delete deletee;
  12562. }
  12563. JUCE_CATCH_EXCEPTION
  12564. }
  12565. // if no objects got re-created during shutdown, this should have been emptied by their
  12566. // destructors
  12567. jassert (objectsToDelete.size() == 0);
  12568. objectsToDelete.clear(); // just to make sure the array doesn't have any memory still allocated
  12569. }
  12570. END_JUCE_NAMESPACE
  12571. /********* End of inlined file: juce_DeletedAtShutdown.cpp *********/
  12572. /********* Start of inlined file: juce_PropertiesFile.cpp *********/
  12573. BEGIN_JUCE_NAMESPACE
  12574. static const int propFileMagicNumber = ((int) littleEndianInt ("PROP"));
  12575. static const int propFileMagicNumberCompressed = ((int) littleEndianInt ("CPRP"));
  12576. static const tchar* const propertyFileXmlTag = T("PROPERTIES");
  12577. static const tchar* const propertyTagName = T("VALUE");
  12578. PropertiesFile::PropertiesFile (const File& f,
  12579. const int millisecondsBeforeSaving,
  12580. const int options_) throw()
  12581. : PropertySet (ignoreCaseOfKeyNames),
  12582. file (f),
  12583. timerInterval (millisecondsBeforeSaving),
  12584. options (options_),
  12585. needsWriting (false)
  12586. {
  12587. // You need to correctly specify just one storage format for the file
  12588. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  12589. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  12590. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  12591. InputStream* fileStream = f.createInputStream();
  12592. if (fileStream != 0)
  12593. {
  12594. int magicNumber = fileStream->readInt();
  12595. if (magicNumber == propFileMagicNumberCompressed)
  12596. {
  12597. fileStream = new SubregionStream (fileStream, 4, -1, true);
  12598. fileStream = new GZIPDecompressorInputStream (fileStream, true);
  12599. magicNumber = propFileMagicNumber;
  12600. }
  12601. if (magicNumber == propFileMagicNumber)
  12602. {
  12603. BufferedInputStream in (fileStream, 2048, true);
  12604. int numValues = in.readInt();
  12605. while (--numValues >= 0 && ! in.isExhausted())
  12606. {
  12607. const String key (in.readString());
  12608. const String value (in.readString());
  12609. jassert (key.isNotEmpty());
  12610. if (key.isNotEmpty())
  12611. getAllProperties().set (key, value);
  12612. }
  12613. }
  12614. else
  12615. {
  12616. // Not a binary props file - let's see if it's XML..
  12617. delete fileStream;
  12618. XmlDocument parser (f);
  12619. XmlElement* doc = parser.getDocumentElement (true);
  12620. if (doc != 0 && doc->hasTagName (propertyFileXmlTag))
  12621. {
  12622. delete doc;
  12623. doc = parser.getDocumentElement();
  12624. if (doc != 0)
  12625. {
  12626. forEachXmlChildElementWithTagName (*doc, e, propertyTagName)
  12627. {
  12628. const String name (e->getStringAttribute (T("name")));
  12629. if (name.isNotEmpty())
  12630. {
  12631. getAllProperties().set (name,
  12632. e->getFirstChildElement() != 0
  12633. ? e->getFirstChildElement()->createDocument (String::empty, true)
  12634. : e->getStringAttribute (T("val")));
  12635. }
  12636. }
  12637. }
  12638. else
  12639. {
  12640. // must be a pretty broken XML file we're trying to parse here!
  12641. jassertfalse
  12642. }
  12643. delete doc;
  12644. }
  12645. }
  12646. }
  12647. }
  12648. PropertiesFile::~PropertiesFile()
  12649. {
  12650. saveIfNeeded();
  12651. }
  12652. bool PropertiesFile::saveIfNeeded()
  12653. {
  12654. const ScopedLock sl (getLock());
  12655. return (! needsWriting) || save();
  12656. }
  12657. bool PropertiesFile::needsToBeSaved() const throw()
  12658. {
  12659. const ScopedLock sl (getLock());
  12660. return needsWriting;
  12661. }
  12662. bool PropertiesFile::save()
  12663. {
  12664. const ScopedLock sl (getLock());
  12665. stopTimer();
  12666. if (file == File::nonexistent
  12667. || file.isDirectory()
  12668. || ! file.getParentDirectory().createDirectory())
  12669. return false;
  12670. if ((options & storeAsXML) != 0)
  12671. {
  12672. XmlElement* const doc = new XmlElement (propertyFileXmlTag);
  12673. for (int i = 0; i < getAllProperties().size(); ++i)
  12674. {
  12675. XmlElement* const e = new XmlElement (propertyTagName);
  12676. e->setAttribute (T("name"), getAllProperties().getAllKeys() [i]);
  12677. // if the value seems to contain xml, store it as such..
  12678. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  12679. XmlElement* const childElement = xmlContent.getDocumentElement();
  12680. if (childElement != 0)
  12681. e->addChildElement (childElement);
  12682. else
  12683. e->setAttribute (T("val"), getAllProperties().getAllValues() [i]);
  12684. doc->addChildElement (e);
  12685. }
  12686. const bool ok = doc->writeToFile (file, String::empty);
  12687. delete doc;
  12688. return ok;
  12689. }
  12690. else
  12691. {
  12692. const File tempFile (file.getNonexistentSibling (false));
  12693. OutputStream* out = tempFile.createOutputStream();
  12694. if (out != 0)
  12695. {
  12696. if ((options & storeAsCompressedBinary) != 0)
  12697. {
  12698. out->writeInt (propFileMagicNumberCompressed);
  12699. out->flush();
  12700. out = new GZIPCompressorOutputStream (out, 9, true);
  12701. }
  12702. else
  12703. {
  12704. // have you set up the storage option flags correctly?
  12705. jassert ((options & storeAsBinary) != 0);
  12706. out->writeInt (propFileMagicNumber);
  12707. }
  12708. const int numProperties = getAllProperties().size();
  12709. out->writeInt (numProperties);
  12710. for (int i = 0; i < numProperties; ++i)
  12711. {
  12712. out->writeString (getAllProperties().getAllKeys() [i]);
  12713. out->writeString (getAllProperties().getAllValues() [i]);
  12714. }
  12715. out->flush();
  12716. delete out;
  12717. if (tempFile.moveFileTo (file))
  12718. {
  12719. needsWriting = false;
  12720. return true;
  12721. }
  12722. tempFile.deleteFile();
  12723. }
  12724. }
  12725. return false;
  12726. }
  12727. void PropertiesFile::timerCallback()
  12728. {
  12729. saveIfNeeded();
  12730. }
  12731. void PropertiesFile::propertyChanged()
  12732. {
  12733. sendChangeMessage (this);
  12734. needsWriting = true;
  12735. if (timerInterval > 0)
  12736. startTimer (timerInterval);
  12737. else if (timerInterval == 0)
  12738. saveIfNeeded();
  12739. }
  12740. const File PropertiesFile::getFile() const throw()
  12741. {
  12742. return file;
  12743. }
  12744. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  12745. const String& fileNameSuffix,
  12746. const String& folderName,
  12747. const bool commonToAllUsers)
  12748. {
  12749. // mustn't have illegal characters in this name..
  12750. jassert (applicationName == File::createLegalFileName (applicationName));
  12751. #if JUCE_MAC
  12752. File dir (commonToAllUsers ? "/Library/Preferences"
  12753. : "~/Library/Preferences");
  12754. if (folderName.isNotEmpty())
  12755. dir = dir.getChildFile (folderName);
  12756. #endif
  12757. #ifdef JUCE_LINUX
  12758. const File dir ((commonToAllUsers ? T("/var/") : T("~/"))
  12759. + (folderName.isNotEmpty() ? folderName
  12760. : (T(".") + applicationName)));
  12761. #endif
  12762. #if JUCE_WIN32
  12763. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  12764. : File::userApplicationDataDirectory));
  12765. if (dir == File::nonexistent)
  12766. return File::nonexistent;
  12767. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  12768. : applicationName);
  12769. #endif
  12770. return dir.getChildFile (applicationName)
  12771. .withFileExtension (fileNameSuffix);
  12772. }
  12773. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  12774. const String& fileNameSuffix,
  12775. const String& folderName,
  12776. const bool commonToAllUsers,
  12777. const int millisecondsBeforeSaving,
  12778. const int propertiesFileOptions)
  12779. {
  12780. const File file (getDefaultAppSettingsFile (applicationName,
  12781. fileNameSuffix,
  12782. folderName,
  12783. commonToAllUsers));
  12784. jassert (file != File::nonexistent);
  12785. if (file == File::nonexistent)
  12786. return 0;
  12787. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions);
  12788. }
  12789. END_JUCE_NAMESPACE
  12790. /********* End of inlined file: juce_PropertiesFile.cpp *********/
  12791. /********* Start of inlined file: juce_AiffAudioFormat.cpp *********/
  12792. BEGIN_JUCE_NAMESPACE
  12793. #undef chunkName
  12794. #define chunkName(a) (int)littleEndianInt(a)
  12795. #define aiffFormatName TRANS("AIFF file")
  12796. static const tchar* const aiffExtensions[] = { T(".aiff"), T(".aif"), 0 };
  12797. class AiffAudioFormatReader : public AudioFormatReader
  12798. {
  12799. public:
  12800. int bytesPerFrame;
  12801. int64 dataChunkStart;
  12802. bool littleEndian;
  12803. AiffAudioFormatReader (InputStream* in)
  12804. : AudioFormatReader (in, aiffFormatName)
  12805. {
  12806. if (input->readInt() == chunkName ("FORM"))
  12807. {
  12808. const int len = input->readIntBigEndian();
  12809. const int64 end = input->getPosition() + len;
  12810. const int nextType = input->readInt();
  12811. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  12812. {
  12813. bool hasGotVer = false;
  12814. bool hasGotData = false;
  12815. bool hasGotType = false;
  12816. while (input->getPosition() < end)
  12817. {
  12818. const int type = input->readInt();
  12819. const uint32 length = (uint32) input->readIntBigEndian();
  12820. const int64 chunkEnd = input->getPosition() + length;
  12821. if (type == chunkName ("FVER"))
  12822. {
  12823. hasGotVer = true;
  12824. const int ver = input->readIntBigEndian();
  12825. if (ver != 0 && ver != (int)0xa2805140)
  12826. break;
  12827. }
  12828. else if (type == chunkName ("COMM"))
  12829. {
  12830. hasGotType = true;
  12831. numChannels = (unsigned int)input->readShortBigEndian();
  12832. lengthInSamples = input->readIntBigEndian();
  12833. bitsPerSample = input->readShortBigEndian();
  12834. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  12835. unsigned char sampleRateBytes[10];
  12836. input->read (sampleRateBytes, 10);
  12837. const int byte0 = sampleRateBytes[0];
  12838. if ((byte0 & 0x80) != 0
  12839. || byte0 <= 0x3F || byte0 > 0x40
  12840. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  12841. break;
  12842. unsigned int sampRate = bigEndianInt ((char*) sampleRateBytes + 2);
  12843. sampRate >>= (16414 - bigEndianShort ((char*) sampleRateBytes));
  12844. sampleRate = (int)sampRate;
  12845. if (length <= 18)
  12846. {
  12847. // some types don't have a chunk large enough to include a compression
  12848. // type, so assume it's just big-endian pcm
  12849. littleEndian = false;
  12850. }
  12851. else
  12852. {
  12853. const int compType = input->readInt();
  12854. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  12855. {
  12856. littleEndian = false;
  12857. }
  12858. else if (compType == chunkName ("sowt"))
  12859. {
  12860. littleEndian = true;
  12861. }
  12862. else
  12863. {
  12864. sampleRate = 0;
  12865. break;
  12866. }
  12867. }
  12868. }
  12869. else if (type == chunkName ("SSND"))
  12870. {
  12871. hasGotData = true;
  12872. const int offset = input->readIntBigEndian();
  12873. dataChunkStart = input->getPosition() + 4 + offset;
  12874. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  12875. }
  12876. else if ((hasGotVer && hasGotData && hasGotType)
  12877. || chunkEnd < input->getPosition()
  12878. || input->isExhausted())
  12879. {
  12880. break;
  12881. }
  12882. input->setPosition (chunkEnd);
  12883. }
  12884. }
  12885. }
  12886. }
  12887. ~AiffAudioFormatReader()
  12888. {
  12889. }
  12890. bool read (int** destSamples,
  12891. int64 startSampleInFile,
  12892. int numSamples)
  12893. {
  12894. int64 start = startSampleInFile;
  12895. int startOffsetInDestBuffer = 0;
  12896. if (startSampleInFile < 0)
  12897. {
  12898. const int silence = (int) jmin (-startSampleInFile, (int64) numSamples);
  12899. int** destChan = destSamples;
  12900. for (int i = 2; --i >= 0;)
  12901. {
  12902. if (*destChan != 0)
  12903. {
  12904. zeromem (*destChan, sizeof (int) * silence);
  12905. ++destChan;
  12906. }
  12907. }
  12908. startOffsetInDestBuffer += silence;
  12909. numSamples -= silence;
  12910. start = 0;
  12911. }
  12912. int numToDo = jlimit (0, numSamples, (int) (lengthInSamples - start));
  12913. if (numToDo > 0)
  12914. {
  12915. input->setPosition (dataChunkStart + start * bytesPerFrame);
  12916. int num = numToDo;
  12917. int* left = destSamples[0];
  12918. if (left != 0)
  12919. left += startOffsetInDestBuffer;
  12920. int* right = destSamples[1];
  12921. if (right != 0)
  12922. right += startOffsetInDestBuffer;
  12923. // (keep this a multiple of 3)
  12924. const int tempBufSize = 1440 * 4;
  12925. char tempBuffer [tempBufSize];
  12926. while (num > 0)
  12927. {
  12928. const int numThisTime = jmin (tempBufSize / bytesPerFrame, num);
  12929. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  12930. if (bytesRead < numThisTime * bytesPerFrame)
  12931. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  12932. if (bitsPerSample == 16)
  12933. {
  12934. if (littleEndian)
  12935. {
  12936. const short* src = (const short*) tempBuffer;
  12937. if (numChannels > 1)
  12938. {
  12939. if (left == 0)
  12940. {
  12941. for (int i = numThisTime; --i >= 0;)
  12942. {
  12943. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12944. ++src;
  12945. }
  12946. }
  12947. else if (right == 0)
  12948. {
  12949. for (int i = numThisTime; --i >= 0;)
  12950. {
  12951. ++src;
  12952. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12953. }
  12954. }
  12955. else
  12956. {
  12957. for (int i = numThisTime; --i >= 0;)
  12958. {
  12959. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12960. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12961. }
  12962. }
  12963. }
  12964. else
  12965. {
  12966. for (int i = numThisTime; --i >= 0;)
  12967. {
  12968. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12969. }
  12970. }
  12971. }
  12972. else
  12973. {
  12974. const char* src = (const char*) tempBuffer;
  12975. if (numChannels > 1)
  12976. {
  12977. if (left == 0)
  12978. {
  12979. for (int i = numThisTime; --i >= 0;)
  12980. {
  12981. *right++ = bigEndianShort (src) << 16;
  12982. src += 4;
  12983. }
  12984. }
  12985. else if (right == 0)
  12986. {
  12987. for (int i = numThisTime; --i >= 0;)
  12988. {
  12989. src += 2;
  12990. *left++ = bigEndianShort (src) << 16;
  12991. src += 2;
  12992. }
  12993. }
  12994. else
  12995. {
  12996. for (int i = numThisTime; --i >= 0;)
  12997. {
  12998. *left++ = bigEndianShort (src) << 16;
  12999. src += 2;
  13000. *right++ = bigEndianShort (src) << 16;
  13001. src += 2;
  13002. }
  13003. }
  13004. }
  13005. else
  13006. {
  13007. for (int i = numThisTime; --i >= 0;)
  13008. {
  13009. *left++ = bigEndianShort (src) << 16;
  13010. src += 2;
  13011. }
  13012. }
  13013. }
  13014. }
  13015. else if (bitsPerSample == 24)
  13016. {
  13017. const char* src = (const char*)tempBuffer;
  13018. if (littleEndian)
  13019. {
  13020. if (numChannels > 1)
  13021. {
  13022. if (left == 0)
  13023. {
  13024. for (int i = numThisTime; --i >= 0;)
  13025. {
  13026. *right++ = littleEndian24Bit (src) << 8;
  13027. src += 6;
  13028. }
  13029. }
  13030. else if (right == 0)
  13031. {
  13032. for (int i = numThisTime; --i >= 0;)
  13033. {
  13034. src += 3;
  13035. *left++ = littleEndian24Bit (src) << 8;
  13036. src += 3;
  13037. }
  13038. }
  13039. else
  13040. {
  13041. for (int i = numThisTime; --i >= 0;)
  13042. {
  13043. *left++ = littleEndian24Bit (src) << 8;
  13044. src += 3;
  13045. *right++ = littleEndian24Bit (src) << 8;
  13046. src += 3;
  13047. }
  13048. }
  13049. }
  13050. else
  13051. {
  13052. for (int i = numThisTime; --i >= 0;)
  13053. {
  13054. *left++ = littleEndian24Bit (src) << 8;
  13055. src += 3;
  13056. }
  13057. }
  13058. }
  13059. else
  13060. {
  13061. if (numChannels > 1)
  13062. {
  13063. if (left == 0)
  13064. {
  13065. for (int i = numThisTime; --i >= 0;)
  13066. {
  13067. *right++ = bigEndian24Bit (src) << 8;
  13068. src += 6;
  13069. }
  13070. }
  13071. else if (right == 0)
  13072. {
  13073. for (int i = numThisTime; --i >= 0;)
  13074. {
  13075. src += 3;
  13076. *left++ = bigEndian24Bit (src) << 8;
  13077. src += 3;
  13078. }
  13079. }
  13080. else
  13081. {
  13082. for (int i = numThisTime; --i >= 0;)
  13083. {
  13084. *left++ = bigEndian24Bit (src) << 8;
  13085. src += 3;
  13086. *right++ = bigEndian24Bit (src) << 8;
  13087. src += 3;
  13088. }
  13089. }
  13090. }
  13091. else
  13092. {
  13093. for (int i = numThisTime; --i >= 0;)
  13094. {
  13095. *left++ = bigEndian24Bit (src) << 8;
  13096. src += 3;
  13097. }
  13098. }
  13099. }
  13100. }
  13101. else if (bitsPerSample == 32)
  13102. {
  13103. const unsigned int* src = (const unsigned int*) tempBuffer;
  13104. unsigned int* l = (unsigned int*) left;
  13105. unsigned int* r = (unsigned int*) right;
  13106. if (littleEndian)
  13107. {
  13108. if (numChannels > 1)
  13109. {
  13110. if (l == 0)
  13111. {
  13112. for (int i = numThisTime; --i >= 0;)
  13113. {
  13114. ++src;
  13115. *r++ = swapIfBigEndian (*src++);
  13116. }
  13117. }
  13118. else if (r == 0)
  13119. {
  13120. for (int i = numThisTime; --i >= 0;)
  13121. {
  13122. *l++ = swapIfBigEndian (*src++);
  13123. ++src;
  13124. }
  13125. }
  13126. else
  13127. {
  13128. for (int i = numThisTime; --i >= 0;)
  13129. {
  13130. *l++ = swapIfBigEndian (*src++);
  13131. *r++ = swapIfBigEndian (*src++);
  13132. }
  13133. }
  13134. }
  13135. else
  13136. {
  13137. for (int i = numThisTime; --i >= 0;)
  13138. {
  13139. *l++ = swapIfBigEndian (*src++);
  13140. }
  13141. }
  13142. }
  13143. else
  13144. {
  13145. if (numChannels > 1)
  13146. {
  13147. if (l == 0)
  13148. {
  13149. for (int i = numThisTime; --i >= 0;)
  13150. {
  13151. ++src;
  13152. *r++ = swapIfLittleEndian (*src++);
  13153. }
  13154. }
  13155. else if (r == 0)
  13156. {
  13157. for (int i = numThisTime; --i >= 0;)
  13158. {
  13159. *l++ = swapIfLittleEndian (*src++);
  13160. ++src;
  13161. }
  13162. }
  13163. else
  13164. {
  13165. for (int i = numThisTime; --i >= 0;)
  13166. {
  13167. *l++ = swapIfLittleEndian (*src++);
  13168. *r++ = swapIfLittleEndian (*src++);
  13169. }
  13170. }
  13171. }
  13172. else
  13173. {
  13174. for (int i = numThisTime; --i >= 0;)
  13175. {
  13176. *l++ = swapIfLittleEndian (*src++);
  13177. }
  13178. }
  13179. }
  13180. left = (int*) l;
  13181. right = (int*) r;
  13182. }
  13183. else if (bitsPerSample == 8)
  13184. {
  13185. const char* src = (const char*) tempBuffer;
  13186. if (numChannels > 1)
  13187. {
  13188. if (left == 0)
  13189. {
  13190. for (int i = numThisTime; --i >= 0;)
  13191. {
  13192. *right++ = ((int) *src++) << 24;
  13193. ++src;
  13194. }
  13195. }
  13196. else if (right == 0)
  13197. {
  13198. for (int i = numThisTime; --i >= 0;)
  13199. {
  13200. ++src;
  13201. *left++ = ((int) *src++) << 24;
  13202. }
  13203. }
  13204. else
  13205. {
  13206. for (int i = numThisTime; --i >= 0;)
  13207. {
  13208. *left++ = ((int) *src++) << 24;
  13209. *right++ = ((int) *src++) << 24;
  13210. }
  13211. }
  13212. }
  13213. else
  13214. {
  13215. for (int i = numThisTime; --i >= 0;)
  13216. {
  13217. *left++ = ((int) *src++) << 24;
  13218. }
  13219. }
  13220. }
  13221. num -= numThisTime;
  13222. }
  13223. }
  13224. if (numToDo < numSamples)
  13225. {
  13226. int** destChan = destSamples;
  13227. while (*destChan != 0)
  13228. {
  13229. zeromem ((*destChan) + (startOffsetInDestBuffer + numToDo),
  13230. sizeof (int) * (numSamples - numToDo));
  13231. ++destChan;
  13232. }
  13233. }
  13234. return true;
  13235. }
  13236. juce_UseDebuggingNewOperator
  13237. private:
  13238. AiffAudioFormatReader (const AiffAudioFormatReader&);
  13239. const AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  13240. };
  13241. class AiffAudioFormatWriter : public AudioFormatWriter
  13242. {
  13243. MemoryBlock tempBlock;
  13244. uint32 lengthInSamples, bytesWritten;
  13245. int64 headerPosition;
  13246. bool writeFailed;
  13247. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  13248. const AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  13249. void writeHeader()
  13250. {
  13251. const bool couldSeekOk = output->setPosition (headerPosition);
  13252. (void) couldSeekOk;
  13253. // if this fails, you've given it an output stream that can't seek! It needs
  13254. // to be able to seek back to write the header
  13255. jassert (couldSeekOk);
  13256. const int headerLen = 54;
  13257. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  13258. audioBytes += (audioBytes & 1);
  13259. output->writeInt (chunkName ("FORM"));
  13260. output->writeIntBigEndian (headerLen + audioBytes - 8);
  13261. output->writeInt (chunkName ("AIFF"));
  13262. output->writeInt (chunkName ("COMM"));
  13263. output->writeIntBigEndian (18);
  13264. output->writeShortBigEndian ((short) numChannels);
  13265. output->writeIntBigEndian (lengthInSamples);
  13266. output->writeShortBigEndian ((short) bitsPerSample);
  13267. uint8 sampleRateBytes[10];
  13268. zeromem (sampleRateBytes, 10);
  13269. if (sampleRate <= 1)
  13270. {
  13271. sampleRateBytes[0] = 0x3f;
  13272. sampleRateBytes[1] = 0xff;
  13273. sampleRateBytes[2] = 0x80;
  13274. }
  13275. else
  13276. {
  13277. int mask = 0x40000000;
  13278. sampleRateBytes[0] = 0x40;
  13279. if (sampleRate >= mask)
  13280. {
  13281. jassertfalse
  13282. sampleRateBytes[1] = 0x1d;
  13283. }
  13284. else
  13285. {
  13286. int n = (int) sampleRate;
  13287. int i;
  13288. for (i = 0; i <= 32 ; ++i)
  13289. {
  13290. if ((n & mask) != 0)
  13291. break;
  13292. mask >>= 1;
  13293. }
  13294. n = n << (i + 1);
  13295. sampleRateBytes[1] = (uint8) (29 - i);
  13296. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  13297. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  13298. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  13299. sampleRateBytes[5] = (uint8) (n & 0xff);
  13300. }
  13301. }
  13302. output->write (sampleRateBytes, 10);
  13303. output->writeInt (chunkName ("SSND"));
  13304. output->writeIntBigEndian (audioBytes + 8);
  13305. output->writeInt (0);
  13306. output->writeInt (0);
  13307. jassert (output->getPosition() == headerLen);
  13308. }
  13309. public:
  13310. AiffAudioFormatWriter (OutputStream* out,
  13311. const double sampleRate,
  13312. const unsigned int chans,
  13313. const int bits)
  13314. : AudioFormatWriter (out,
  13315. aiffFormatName,
  13316. sampleRate,
  13317. chans,
  13318. bits),
  13319. lengthInSamples (0),
  13320. bytesWritten (0),
  13321. writeFailed (false)
  13322. {
  13323. headerPosition = out->getPosition();
  13324. writeHeader();
  13325. }
  13326. ~AiffAudioFormatWriter()
  13327. {
  13328. if ((bytesWritten & 1) != 0)
  13329. output->writeByte (0);
  13330. writeHeader();
  13331. }
  13332. bool write (const int** data, int numSamples)
  13333. {
  13334. if (writeFailed)
  13335. return false;
  13336. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  13337. tempBlock.ensureSize (bytes, false);
  13338. char* buffer = (char*) tempBlock.getData();
  13339. const int* left = data[0];
  13340. const int* right = data[1];
  13341. if (right == 0)
  13342. right = left;
  13343. if (bitsPerSample == 16)
  13344. {
  13345. short* b = (short*) buffer;
  13346. if (numChannels > 1)
  13347. {
  13348. for (int i = numSamples; --i >= 0;)
  13349. {
  13350. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  13351. *b++ = (short) swapIfLittleEndian ((unsigned short) (*right++ >> 16));
  13352. }
  13353. }
  13354. else
  13355. {
  13356. for (int i = numSamples; --i >= 0;)
  13357. {
  13358. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  13359. }
  13360. }
  13361. }
  13362. else if (bitsPerSample == 24)
  13363. {
  13364. char* b = (char*) buffer;
  13365. if (numChannels > 1)
  13366. {
  13367. for (int i = numSamples; --i >= 0;)
  13368. {
  13369. bigEndian24BitToChars (*left++ >> 8, b);
  13370. b += 3;
  13371. bigEndian24BitToChars (*right++ >> 8, b);
  13372. b += 3;
  13373. }
  13374. }
  13375. else
  13376. {
  13377. for (int i = numSamples; --i >= 0;)
  13378. {
  13379. bigEndian24BitToChars (*left++ >> 8, b);
  13380. b += 3;
  13381. }
  13382. }
  13383. }
  13384. else if (bitsPerSample == 32)
  13385. {
  13386. unsigned int* b = (unsigned int*) buffer;
  13387. if (numChannels > 1)
  13388. {
  13389. for (int i = numSamples; --i >= 0;)
  13390. {
  13391. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  13392. *b++ = swapIfLittleEndian ((unsigned int) *right++);
  13393. }
  13394. }
  13395. else
  13396. {
  13397. for (int i = numSamples; --i >= 0;)
  13398. {
  13399. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  13400. }
  13401. }
  13402. }
  13403. else if (bitsPerSample == 8)
  13404. {
  13405. char* b = (char*)buffer;
  13406. if (numChannels > 1)
  13407. {
  13408. for (int i = numSamples; --i >= 0;)
  13409. {
  13410. *b++ = (char) (*left++ >> 24);
  13411. *b++ = (char) (*right++ >> 24);
  13412. }
  13413. }
  13414. else
  13415. {
  13416. for (int i = numSamples; --i >= 0;)
  13417. {
  13418. *b++ = (char) (*left++ >> 24);
  13419. }
  13420. }
  13421. }
  13422. if (bytesWritten + bytes >= (uint32) 0xfff00000
  13423. || ! output->write (buffer, bytes))
  13424. {
  13425. // failed to write to disk, so let's try writing the header.
  13426. // If it's just run out of disk space, then if it does manage
  13427. // to write the header, we'll still have a useable file..
  13428. writeHeader();
  13429. writeFailed = true;
  13430. return false;
  13431. }
  13432. else
  13433. {
  13434. bytesWritten += bytes;
  13435. lengthInSamples += numSamples;
  13436. return true;
  13437. }
  13438. }
  13439. juce_UseDebuggingNewOperator
  13440. };
  13441. AiffAudioFormat::AiffAudioFormat()
  13442. : AudioFormat (aiffFormatName, (const tchar**) aiffExtensions)
  13443. {
  13444. }
  13445. AiffAudioFormat::~AiffAudioFormat()
  13446. {
  13447. }
  13448. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  13449. {
  13450. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  13451. return Array <int> (rates);
  13452. }
  13453. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  13454. {
  13455. const int depths[] = { 8, 16, 24, 0 };
  13456. return Array <int> (depths);
  13457. }
  13458. bool AiffAudioFormat::canDoStereo()
  13459. {
  13460. return true;
  13461. }
  13462. bool AiffAudioFormat::canDoMono()
  13463. {
  13464. return true;
  13465. }
  13466. #if JUCE_MAC
  13467. bool AiffAudioFormat::canHandleFile (const File& f)
  13468. {
  13469. if (AudioFormat::canHandleFile (f))
  13470. return true;
  13471. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  13472. return type == 'AIFF' || type == 'AIFC'
  13473. || type == 'aiff' || type == 'aifc';
  13474. }
  13475. #endif
  13476. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  13477. const bool deleteStreamIfOpeningFails)
  13478. {
  13479. AiffAudioFormatReader* w = new AiffAudioFormatReader (sourceStream);
  13480. if (w->sampleRate == 0)
  13481. {
  13482. if (! deleteStreamIfOpeningFails)
  13483. w->input = 0;
  13484. deleteAndZero (w);
  13485. }
  13486. return w;
  13487. }
  13488. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  13489. double sampleRate,
  13490. unsigned int chans,
  13491. int bitsPerSample,
  13492. const StringPairArray& /*metadataValues*/,
  13493. int /*qualityOptionIndex*/)
  13494. {
  13495. if (getPossibleBitDepths().contains (bitsPerSample))
  13496. {
  13497. return new AiffAudioFormatWriter (out,
  13498. sampleRate,
  13499. chans,
  13500. bitsPerSample);
  13501. }
  13502. return 0;
  13503. }
  13504. END_JUCE_NAMESPACE
  13505. /********* End of inlined file: juce_AiffAudioFormat.cpp *********/
  13506. /********* Start of inlined file: juce_AudioCDReader.cpp *********/
  13507. BEGIN_JUCE_NAMESPACE
  13508. #if JUCE_MAC
  13509. // Mac version doesn't need any native code because it's all done with files..
  13510. // Windows + Linux versions are in the platform-dependent code sections.
  13511. static void findCDs (OwnedArray<File>& cds)
  13512. {
  13513. File volumes ("/Volumes");
  13514. volumes.findChildFiles (cds, File::findDirectories, false);
  13515. for (int i = cds.size(); --i >= 0;)
  13516. if (! cds[i]->getChildFile (".TOC.plist").exists())
  13517. cds.remove (i);
  13518. }
  13519. const StringArray AudioCDReader::getAvailableCDNames()
  13520. {
  13521. OwnedArray<File> cds;
  13522. findCDs (cds);
  13523. StringArray names;
  13524. for (int i = 0; i < cds.size(); ++i)
  13525. names.add (cds[i]->getFileName());
  13526. return names;
  13527. }
  13528. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  13529. {
  13530. OwnedArray<File> cds;
  13531. findCDs (cds);
  13532. if (cds[index] != 0)
  13533. return new AudioCDReader (*cds[index]);
  13534. else
  13535. return 0;
  13536. }
  13537. AudioCDReader::AudioCDReader (const File& volume)
  13538. : AudioFormatReader (0, "CD Audio"),
  13539. volumeDir (volume),
  13540. currentReaderTrack (-1),
  13541. reader (0)
  13542. {
  13543. sampleRate = 44100.0;
  13544. bitsPerSample = 16;
  13545. numChannels = 2;
  13546. usesFloatingPointData = false;
  13547. refreshTrackLengths();
  13548. }
  13549. AudioCDReader::~AudioCDReader()
  13550. {
  13551. if (reader != 0)
  13552. delete reader;
  13553. }
  13554. static int getTrackNumber (const File& file)
  13555. {
  13556. return file.getFileName()
  13557. .initialSectionContainingOnly (T("0123456789"))
  13558. .getIntValue();
  13559. }
  13560. int AudioCDReader::compareElements (const File* const first, const File* const second) throw()
  13561. {
  13562. const int firstTrack = getTrackNumber (*first);
  13563. const int secondTrack = getTrackNumber (*second);
  13564. jassert (firstTrack > 0 && secondTrack > 0);
  13565. return firstTrack - secondTrack;
  13566. }
  13567. void AudioCDReader::refreshTrackLengths()
  13568. {
  13569. tracks.clear();
  13570. trackStartSamples.clear();
  13571. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, T("*.aiff"));
  13572. tracks.sort (*this);
  13573. AiffAudioFormat format;
  13574. int sample = 0;
  13575. for (int i = 0; i < tracks.size(); ++i)
  13576. {
  13577. trackStartSamples.add (sample);
  13578. FileInputStream* const in = tracks[i]->createInputStream();
  13579. if (in != 0)
  13580. {
  13581. AudioFormatReader* const r = format.createReaderFor (in, true);
  13582. if (r != 0)
  13583. {
  13584. sample += r->lengthInSamples;
  13585. delete r;
  13586. }
  13587. }
  13588. }
  13589. trackStartSamples.add (sample);
  13590. lengthInSamples = sample;
  13591. }
  13592. bool AudioCDReader::read (int** destSamples,
  13593. int64 startSampleInFile,
  13594. int numSamples)
  13595. {
  13596. while (numSamples > 0)
  13597. {
  13598. int track = -1;
  13599. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  13600. {
  13601. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  13602. {
  13603. track = i;
  13604. break;
  13605. }
  13606. }
  13607. if (track < 0)
  13608. return false;
  13609. if (track != currentReaderTrack)
  13610. {
  13611. deleteAndZero (reader);
  13612. if (tracks [track] != 0)
  13613. {
  13614. FileInputStream* const in = tracks [track]->createInputStream();
  13615. if (in != 0)
  13616. {
  13617. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  13618. AiffAudioFormat format;
  13619. reader = format.createReaderFor (bin, true);
  13620. if (reader == 0)
  13621. currentReaderTrack = -1;
  13622. else
  13623. currentReaderTrack = track;
  13624. }
  13625. }
  13626. }
  13627. if (reader == 0)
  13628. return false;
  13629. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  13630. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  13631. reader->read (destSamples, startPos, numAvailable);
  13632. numSamples -= numAvailable;
  13633. startSampleInFile += numAvailable;
  13634. }
  13635. return true;
  13636. }
  13637. bool AudioCDReader::isCDStillPresent() const
  13638. {
  13639. return volumeDir.exists();
  13640. }
  13641. int AudioCDReader::getNumTracks() const
  13642. {
  13643. return tracks.size();
  13644. }
  13645. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  13646. {
  13647. return trackStartSamples [trackNum];
  13648. }
  13649. bool AudioCDReader::isTrackAudio (int trackNum) const
  13650. {
  13651. return tracks [trackNum] != 0;
  13652. }
  13653. void AudioCDReader::enableIndexScanning (bool b)
  13654. {
  13655. // any way to do this on a Mac??
  13656. }
  13657. int AudioCDReader::getLastIndex() const
  13658. {
  13659. return 0;
  13660. }
  13661. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  13662. {
  13663. return Array <int>();
  13664. }
  13665. int AudioCDReader::getCDDBId()
  13666. {
  13667. return 0; //xxx
  13668. }
  13669. #endif
  13670. END_JUCE_NAMESPACE
  13671. /********* End of inlined file: juce_AudioCDReader.cpp *********/
  13672. /********* Start of inlined file: juce_AudioFormat.cpp *********/
  13673. BEGIN_JUCE_NAMESPACE
  13674. AudioFormatReader::AudioFormatReader (InputStream* const in,
  13675. const String& formatName_)
  13676. : sampleRate (0),
  13677. bitsPerSample (0),
  13678. lengthInSamples (0),
  13679. numChannels (0),
  13680. usesFloatingPointData (false),
  13681. input (in),
  13682. formatName (formatName_)
  13683. {
  13684. }
  13685. AudioFormatReader::~AudioFormatReader()
  13686. {
  13687. delete input;
  13688. }
  13689. static void findMaxMin (const float* src, const int num,
  13690. float& maxVal, float& minVal)
  13691. {
  13692. float mn = src[0];
  13693. float mx = mn;
  13694. for (int i = 1; i < num; ++i)
  13695. {
  13696. const float s = src[i];
  13697. if (s > mx)
  13698. mx = s;
  13699. if (s < mn)
  13700. mn = s;
  13701. }
  13702. maxVal = mx;
  13703. minVal = mn;
  13704. }
  13705. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  13706. int64 numSamples,
  13707. float& lowestLeft, float& highestLeft,
  13708. float& lowestRight, float& highestRight)
  13709. {
  13710. if (numSamples <= 0)
  13711. {
  13712. lowestLeft = 0;
  13713. lowestRight = 0;
  13714. highestLeft = 0;
  13715. highestRight = 0;
  13716. return;
  13717. }
  13718. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  13719. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  13720. int* tempBuffer[3];
  13721. tempBuffer[0] = (int*) tempSpace.getData();
  13722. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  13723. tempBuffer[2] = 0;
  13724. if (usesFloatingPointData)
  13725. {
  13726. float lmin = 1.0e6;
  13727. float lmax = -lmin;
  13728. float rmin = lmin;
  13729. float rmax = lmax;
  13730. while (numSamples > 0)
  13731. {
  13732. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  13733. read ((int**) tempBuffer, startSampleInFile, numToDo);
  13734. numSamples -= numToDo;
  13735. float bufmin, bufmax;
  13736. findMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  13737. lmin = jmin (lmin, bufmin);
  13738. lmax = jmax (lmax, bufmax);
  13739. if (numChannels > 1)
  13740. {
  13741. findMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  13742. rmin = jmin (rmin, bufmin);
  13743. rmax = jmax (rmax, bufmax);
  13744. }
  13745. }
  13746. if (numChannels <= 1)
  13747. {
  13748. rmax = lmax;
  13749. rmin = lmin;
  13750. }
  13751. lowestLeft = lmin;
  13752. highestLeft = lmax;
  13753. lowestRight = rmin;
  13754. highestRight = rmax;
  13755. }
  13756. else
  13757. {
  13758. int lmax = INT_MIN;
  13759. int lmin = INT_MAX;
  13760. int rmax = INT_MIN;
  13761. int rmin = INT_MAX;
  13762. while (numSamples > 0)
  13763. {
  13764. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  13765. read ((int**) tempBuffer, startSampleInFile, numToDo);
  13766. numSamples -= numToDo;
  13767. for (int j = numChannels; --j >= 0;)
  13768. {
  13769. int bufMax = INT_MIN;
  13770. int bufMin = INT_MAX;
  13771. const int* const b = tempBuffer[j];
  13772. for (int i = 0; i < numToDo; ++i)
  13773. {
  13774. const int samp = b[i];
  13775. if (samp < bufMin)
  13776. bufMin = samp;
  13777. if (samp > bufMax)
  13778. bufMax = samp;
  13779. }
  13780. if (j == 0)
  13781. {
  13782. lmax = jmax (lmax, bufMax);
  13783. lmin = jmin (lmin, bufMin);
  13784. }
  13785. else
  13786. {
  13787. rmax = jmax (rmax, bufMax);
  13788. rmin = jmin (rmin, bufMin);
  13789. }
  13790. }
  13791. }
  13792. if (numChannels <= 1)
  13793. {
  13794. rmax = lmax;
  13795. rmin = lmin;
  13796. }
  13797. lowestLeft = lmin / (float)INT_MAX;
  13798. highestLeft = lmax / (float)INT_MAX;
  13799. lowestRight = rmin / (float)INT_MAX;
  13800. highestRight = rmax / (float)INT_MAX;
  13801. }
  13802. }
  13803. int64 AudioFormatReader::searchForLevel (int64 startSample,
  13804. int64 numSamplesToSearch,
  13805. const double magnitudeRangeMinimum,
  13806. const double magnitudeRangeMaximum,
  13807. const int minimumConsecutiveSamples)
  13808. {
  13809. if (numSamplesToSearch == 0)
  13810. return -1;
  13811. const int bufferSize = 4096;
  13812. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  13813. int* tempBuffer[3];
  13814. tempBuffer[0] = (int*) tempSpace.getData();
  13815. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  13816. tempBuffer[2] = 0;
  13817. int consecutive = 0;
  13818. int64 firstMatchPos = -1;
  13819. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  13820. const double doubleMin = jlimit (0.0, (double) INT_MAX, magnitudeRangeMinimum * INT_MAX);
  13821. const double doubleMax = jlimit (doubleMin, (double) INT_MAX, magnitudeRangeMaximum * INT_MAX);
  13822. const int intMagnitudeRangeMinimum = roundDoubleToInt (doubleMin);
  13823. const int intMagnitudeRangeMaximum = roundDoubleToInt (doubleMax);
  13824. while (numSamplesToSearch != 0)
  13825. {
  13826. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  13827. int64 bufferStart = startSample;
  13828. if (numSamplesToSearch < 0)
  13829. bufferStart -= numThisTime;
  13830. if (bufferStart >= (int) lengthInSamples)
  13831. break;
  13832. read ((int**) tempBuffer, bufferStart, numThisTime);
  13833. int num = numThisTime;
  13834. while (--num >= 0)
  13835. {
  13836. if (numSamplesToSearch < 0)
  13837. --startSample;
  13838. bool matches = false;
  13839. const int index = (int) (startSample - bufferStart);
  13840. if (usesFloatingPointData)
  13841. {
  13842. const float sample1 = fabsf (((float*) tempBuffer[0]) [index]);
  13843. if (sample1 >= magnitudeRangeMinimum
  13844. && sample1 <= magnitudeRangeMaximum)
  13845. {
  13846. matches = true;
  13847. }
  13848. else if (numChannels > 1)
  13849. {
  13850. const float sample2 = fabsf (((float*) tempBuffer[1]) [index]);
  13851. matches = (sample2 >= magnitudeRangeMinimum
  13852. && sample2 <= magnitudeRangeMaximum);
  13853. }
  13854. }
  13855. else
  13856. {
  13857. const int sample1 = abs (tempBuffer[0] [index]);
  13858. if (sample1 >= intMagnitudeRangeMinimum
  13859. && sample1 <= intMagnitudeRangeMaximum)
  13860. {
  13861. matches = true;
  13862. }
  13863. else if (numChannels > 1)
  13864. {
  13865. const int sample2 = abs (tempBuffer[1][index]);
  13866. matches = (sample2 >= intMagnitudeRangeMinimum
  13867. && sample2 <= intMagnitudeRangeMaximum);
  13868. }
  13869. }
  13870. if (matches)
  13871. {
  13872. if (firstMatchPos < 0)
  13873. firstMatchPos = startSample;
  13874. if (++consecutive >= minimumConsecutiveSamples)
  13875. {
  13876. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  13877. return -1;
  13878. return firstMatchPos;
  13879. }
  13880. }
  13881. else
  13882. {
  13883. consecutive = 0;
  13884. firstMatchPos = -1;
  13885. }
  13886. if (numSamplesToSearch > 0)
  13887. ++startSample;
  13888. }
  13889. if (numSamplesToSearch > 0)
  13890. numSamplesToSearch -= numThisTime;
  13891. else
  13892. numSamplesToSearch += numThisTime;
  13893. }
  13894. return -1;
  13895. }
  13896. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  13897. const String& formatName_,
  13898. const double rate,
  13899. const unsigned int numChannels_,
  13900. const unsigned int bitsPerSample_)
  13901. : sampleRate (rate),
  13902. numChannels (numChannels_),
  13903. bitsPerSample (bitsPerSample_),
  13904. usesFloatingPointData (false),
  13905. output (out),
  13906. formatName (formatName_)
  13907. {
  13908. }
  13909. AudioFormatWriter::~AudioFormatWriter()
  13910. {
  13911. delete output;
  13912. }
  13913. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  13914. int64 startSample,
  13915. int numSamplesToRead)
  13916. {
  13917. const int bufferSize = 16384;
  13918. const int maxChans = 128;
  13919. AudioSampleBuffer tempBuffer (reader.numChannels, bufferSize);
  13920. int* buffers [maxChans];
  13921. for (int i = maxChans; --i >= 0;)
  13922. buffers[i] = 0;
  13923. while (numSamplesToRead > 0)
  13924. {
  13925. const int numToDo = jmin (numSamplesToRead, bufferSize);
  13926. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  13927. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  13928. if (! reader.read (buffers, startSample, numToDo))
  13929. return false;
  13930. if (reader.usesFloatingPointData != isFloatingPoint())
  13931. {
  13932. int** bufferChan = buffers;
  13933. while (*bufferChan != 0)
  13934. {
  13935. int* b = *bufferChan++;
  13936. if (isFloatingPoint())
  13937. {
  13938. // int -> float
  13939. const double factor = 1.0 / INT_MAX;
  13940. for (int i = 0; i < numToDo; ++i)
  13941. ((float*)b)[i] = (float) (factor * b[i]);
  13942. }
  13943. else
  13944. {
  13945. // float -> int
  13946. for (int i = 0; i < numToDo; ++i)
  13947. {
  13948. const double samp = *(const float*) b;
  13949. if (samp <= -1.0)
  13950. *b++ = INT_MIN;
  13951. else if (samp >= 1.0)
  13952. *b++ = INT_MAX;
  13953. else
  13954. *b++ = roundDoubleToInt (INT_MAX * samp);
  13955. }
  13956. }
  13957. }
  13958. }
  13959. if (! write ((const int**) buffers, numToDo))
  13960. return false;
  13961. numSamplesToRead -= numToDo;
  13962. startSample += numToDo;
  13963. }
  13964. return true;
  13965. }
  13966. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  13967. int numSamplesToRead,
  13968. const int samplesPerBlock)
  13969. {
  13970. const int maxChans = 128;
  13971. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  13972. int* buffers [maxChans];
  13973. while (numSamplesToRead > 0)
  13974. {
  13975. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  13976. AudioSourceChannelInfo info;
  13977. info.buffer = &tempBuffer;
  13978. info.startSample = 0;
  13979. info.numSamples = numToDo;
  13980. info.clearActiveBufferRegion();
  13981. source.getNextAudioBlock (info);
  13982. int i;
  13983. for (i = maxChans; --i >= 0;)
  13984. buffers[i] = 0;
  13985. for (i = tempBuffer.getNumChannels(); --i >= 0;)
  13986. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  13987. if (! isFloatingPoint())
  13988. {
  13989. int** bufferChan = buffers;
  13990. while (*bufferChan != 0)
  13991. {
  13992. int* b = *bufferChan++;
  13993. // float -> int
  13994. for (int j = numToDo; --j >= 0;)
  13995. {
  13996. const double samp = *(const float*) b;
  13997. if (samp <= -1.0)
  13998. *b++ = INT_MIN;
  13999. else if (samp >= 1.0)
  14000. *b++ = INT_MAX;
  14001. else
  14002. *b++ = roundDoubleToInt (INT_MAX * samp);
  14003. }
  14004. }
  14005. }
  14006. if (! write ((const int**) buffers, numToDo))
  14007. return false;
  14008. numSamplesToRead -= numToDo;
  14009. }
  14010. return true;
  14011. }
  14012. AudioFormat::AudioFormat (const String& name,
  14013. const tchar** const extensions)
  14014. : formatName (name),
  14015. fileExtensions (extensions)
  14016. {
  14017. }
  14018. AudioFormat::~AudioFormat()
  14019. {
  14020. }
  14021. const String& AudioFormat::getFormatName() const
  14022. {
  14023. return formatName;
  14024. }
  14025. const StringArray& AudioFormat::getFileExtensions() const
  14026. {
  14027. return fileExtensions;
  14028. }
  14029. bool AudioFormat::canHandleFile (const File& f)
  14030. {
  14031. for (int i = 0; i < fileExtensions.size(); ++i)
  14032. if (f.hasFileExtension (fileExtensions[i]))
  14033. return true;
  14034. return false;
  14035. }
  14036. bool AudioFormat::isCompressed()
  14037. {
  14038. return false;
  14039. }
  14040. const StringArray AudioFormat::getQualityOptions()
  14041. {
  14042. return StringArray();
  14043. }
  14044. END_JUCE_NAMESPACE
  14045. /********* End of inlined file: juce_AudioFormat.cpp *********/
  14046. /********* Start of inlined file: juce_AudioFormatManager.cpp *********/
  14047. BEGIN_JUCE_NAMESPACE
  14048. AudioFormatManager::AudioFormatManager()
  14049. : knownFormats (4),
  14050. defaultFormatIndex (0)
  14051. {
  14052. }
  14053. AudioFormatManager::~AudioFormatManager()
  14054. {
  14055. clearFormats();
  14056. clearSingletonInstance();
  14057. }
  14058. juce_ImplementSingleton (AudioFormatManager);
  14059. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  14060. const bool makeThisTheDefaultFormat)
  14061. {
  14062. jassert (newFormat != 0);
  14063. if (newFormat != 0)
  14064. {
  14065. #ifdef JUCE_DEBUG
  14066. for (int i = getNumKnownFormats(); --i >= 0;)
  14067. {
  14068. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  14069. {
  14070. jassertfalse // trying to add the same format twice!
  14071. }
  14072. }
  14073. #endif
  14074. if (makeThisTheDefaultFormat)
  14075. defaultFormatIndex = knownFormats.size();
  14076. knownFormats.add (newFormat);
  14077. }
  14078. }
  14079. void AudioFormatManager::registerBasicFormats()
  14080. {
  14081. #if JUCE_MAC
  14082. registerFormat (new AiffAudioFormat(), true);
  14083. registerFormat (new WavAudioFormat(), false);
  14084. #else
  14085. registerFormat (new WavAudioFormat(), true);
  14086. registerFormat (new AiffAudioFormat(), false);
  14087. #endif
  14088. #if JUCE_USE_FLAC
  14089. registerFormat (new FlacAudioFormat(), false);
  14090. #endif
  14091. #if JUCE_USE_OGGVORBIS
  14092. registerFormat (new OggVorbisAudioFormat(), false);
  14093. #endif
  14094. }
  14095. void AudioFormatManager::clearFormats()
  14096. {
  14097. for (int i = getNumKnownFormats(); --i >= 0;)
  14098. {
  14099. AudioFormat* const af = getKnownFormat(i);
  14100. delete af;
  14101. }
  14102. knownFormats.clear();
  14103. defaultFormatIndex = 0;
  14104. }
  14105. int AudioFormatManager::getNumKnownFormats() const
  14106. {
  14107. return knownFormats.size();
  14108. }
  14109. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  14110. {
  14111. return (AudioFormat*) knownFormats [index];
  14112. }
  14113. AudioFormat* AudioFormatManager::getDefaultFormat() const
  14114. {
  14115. return getKnownFormat (defaultFormatIndex);
  14116. }
  14117. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  14118. {
  14119. String e (fileExtension);
  14120. if (! e.startsWithChar (T('.')))
  14121. e = T(".") + e;
  14122. for (int i = 0; i < getNumKnownFormats(); ++i)
  14123. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  14124. return getKnownFormat(i);
  14125. return 0;
  14126. }
  14127. const String AudioFormatManager::getWildcardForAllFormats() const
  14128. {
  14129. StringArray allExtensions;
  14130. int i;
  14131. for (i = 0; i < getNumKnownFormats(); ++i)
  14132. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  14133. allExtensions.trim();
  14134. allExtensions.removeEmptyStrings();
  14135. String s;
  14136. for (i = 0; i < allExtensions.size(); ++i)
  14137. {
  14138. s << T('*');
  14139. if (! allExtensions[i].startsWithChar (T('.')))
  14140. s << T('.');
  14141. s << allExtensions[i];
  14142. if (i < allExtensions.size() - 1)
  14143. s << T(';');
  14144. }
  14145. return s;
  14146. }
  14147. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  14148. {
  14149. // you need to actually register some formats before the manager can
  14150. // use them to open a file!
  14151. jassert (knownFormats.size() > 0);
  14152. for (int i = 0; i < getNumKnownFormats(); ++i)
  14153. {
  14154. AudioFormat* const af = getKnownFormat(i);
  14155. if (af->canHandleFile (file))
  14156. {
  14157. InputStream* const in = file.createInputStream();
  14158. if (in != 0)
  14159. {
  14160. AudioFormatReader* const r = af->createReaderFor (in, true);
  14161. if (r != 0)
  14162. return r;
  14163. }
  14164. }
  14165. }
  14166. return 0;
  14167. }
  14168. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* in)
  14169. {
  14170. // you need to actually register some formats before the manager can
  14171. // use them to open a file!
  14172. jassert (knownFormats.size() > 0);
  14173. if (in != 0)
  14174. {
  14175. const int64 originalStreamPos = in->getPosition();
  14176. for (int i = 0; i < getNumKnownFormats(); ++i)
  14177. {
  14178. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  14179. if (r != 0)
  14180. return r;
  14181. in->setPosition (originalStreamPos);
  14182. // the stream that is passed-in must be capable of being repositioned so
  14183. // that all the formats can have a go at opening it.
  14184. jassert (in->getPosition() == originalStreamPos);
  14185. }
  14186. delete in;
  14187. }
  14188. return 0;
  14189. }
  14190. END_JUCE_NAMESPACE
  14191. /********* End of inlined file: juce_AudioFormatManager.cpp *********/
  14192. /********* Start of inlined file: juce_AudioSubsectionReader.cpp *********/
  14193. BEGIN_JUCE_NAMESPACE
  14194. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  14195. const int64 startSample_,
  14196. const int64 length_,
  14197. const bool deleteSourceWhenDeleted_)
  14198. : AudioFormatReader (0, source_->getFormatName()),
  14199. source (source_),
  14200. startSample (startSample_),
  14201. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  14202. {
  14203. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  14204. sampleRate = source->sampleRate;
  14205. bitsPerSample = source->bitsPerSample;
  14206. lengthInSamples = length;
  14207. numChannels = source->numChannels;
  14208. usesFloatingPointData = source->usesFloatingPointData;
  14209. }
  14210. AudioSubsectionReader::~AudioSubsectionReader()
  14211. {
  14212. if (deleteSourceWhenDeleted)
  14213. delete source;
  14214. }
  14215. bool AudioSubsectionReader::read (int** destSamples,
  14216. int64 startSampleInFile,
  14217. int numSamples)
  14218. {
  14219. if (startSampleInFile < 0 || startSampleInFile + numSamples > length)
  14220. {
  14221. int** d = destSamples;
  14222. while (*d != 0)
  14223. {
  14224. zeromem (*d, sizeof (int) * numSamples);
  14225. ++d;
  14226. }
  14227. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  14228. numSamples = jmax (0, jmin (numSamples, (int) (length - startSampleInFile)));
  14229. }
  14230. return source->read (destSamples,
  14231. startSampleInFile + startSample,
  14232. numSamples);
  14233. }
  14234. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  14235. int64 numSamples,
  14236. float& lowestLeft,
  14237. float& highestLeft,
  14238. float& lowestRight,
  14239. float& highestRight)
  14240. {
  14241. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  14242. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  14243. source->readMaxLevels (startSampleInFile + startSample,
  14244. numSamples,
  14245. lowestLeft,
  14246. highestLeft,
  14247. lowestRight,
  14248. highestRight);
  14249. }
  14250. END_JUCE_NAMESPACE
  14251. /********* End of inlined file: juce_AudioSubsectionReader.cpp *********/
  14252. /********* Start of inlined file: juce_AudioThumbnail.cpp *********/
  14253. BEGIN_JUCE_NAMESPACE
  14254. const int timeBeforeDeletingReader = 2000;
  14255. struct AudioThumbnailDataFormat
  14256. {
  14257. char thumbnailMagic[4];
  14258. int samplesPerThumbSample;
  14259. int64 totalSamples; // source samples
  14260. int64 numFinishedSamples; // source samples
  14261. int numThumbnailSamples;
  14262. int numChannels;
  14263. int sampleRate;
  14264. char future[16];
  14265. char data[1];
  14266. };
  14267. #if JUCE_BIG_ENDIAN
  14268. static void swap (int& n) { n = (int) swapByteOrder ((uint32) n); }
  14269. static void swap (int64& n) { n = (int64) swapByteOrder ((uint64) n); }
  14270. #endif
  14271. static void swapEndiannessIfNeeded (AudioThumbnailDataFormat* const d)
  14272. {
  14273. (void) d;
  14274. #if JUCE_BIG_ENDIAN
  14275. swap (d->samplesPerThumbSample);
  14276. swap (d->totalSamples);
  14277. swap (d->numFinishedSamples);
  14278. swap (d->numThumbnailSamples);
  14279. swap (d->numChannels);
  14280. swap (d->sampleRate);
  14281. #endif
  14282. }
  14283. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  14284. AudioFormatManager& formatManagerToUse_,
  14285. AudioThumbnailCache& cacheToUse)
  14286. : formatManagerToUse (formatManagerToUse_),
  14287. cache (cacheToUse),
  14288. source (0),
  14289. reader (0),
  14290. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  14291. {
  14292. clear();
  14293. }
  14294. AudioThumbnail::~AudioThumbnail()
  14295. {
  14296. cache.removeThumbnail (this);
  14297. const ScopedLock sl (readerLock);
  14298. deleteAndZero (reader);
  14299. delete source;
  14300. }
  14301. void AudioThumbnail::setSource (InputSource* const newSource)
  14302. {
  14303. cache.removeThumbnail (this);
  14304. timerCallback(); // stops the timer and deletes the reader
  14305. delete source;
  14306. source = newSource;
  14307. clear();
  14308. if (! (cache.loadThumb (*this, newSource->hashCode())
  14309. && isFullyLoaded()))
  14310. {
  14311. {
  14312. const ScopedLock sl (readerLock);
  14313. reader = createReader();
  14314. }
  14315. if (reader != 0)
  14316. {
  14317. initialiseFromAudioFile (*reader);
  14318. cache.addThumbnail (this);
  14319. }
  14320. }
  14321. sendChangeMessage (this);
  14322. }
  14323. bool AudioThumbnail::useTimeSlice()
  14324. {
  14325. const ScopedLock sl (readerLock);
  14326. if (isFullyLoaded())
  14327. {
  14328. if (reader != 0)
  14329. startTimer (timeBeforeDeletingReader);
  14330. cache.removeThumbnail (this);
  14331. return false;
  14332. }
  14333. if (reader == 0)
  14334. reader = createReader();
  14335. if (reader != 0)
  14336. {
  14337. readNextBlockFromAudioFile (*reader);
  14338. stopTimer();
  14339. sendChangeMessage (this);
  14340. const bool justFinished = isFullyLoaded();
  14341. if (justFinished)
  14342. cache.storeThumb (*this, source->hashCode());
  14343. return ! justFinished;
  14344. }
  14345. return false;
  14346. }
  14347. AudioFormatReader* AudioThumbnail::createReader() const
  14348. {
  14349. if (source != 0)
  14350. {
  14351. InputStream* const audioFileStream = source->createInputStream();
  14352. if (audioFileStream != 0)
  14353. return formatManagerToUse.createReaderFor (audioFileStream);
  14354. }
  14355. return 0;
  14356. }
  14357. void AudioThumbnail::timerCallback()
  14358. {
  14359. stopTimer();
  14360. const ScopedLock sl (readerLock);
  14361. deleteAndZero (reader);
  14362. }
  14363. void AudioThumbnail::clear()
  14364. {
  14365. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  14366. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14367. d->thumbnailMagic[0] = 'j';
  14368. d->thumbnailMagic[1] = 'a';
  14369. d->thumbnailMagic[2] = 't';
  14370. d->thumbnailMagic[3] = 'm';
  14371. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  14372. d->totalSamples = 0;
  14373. d->numFinishedSamples = 0;
  14374. d->numThumbnailSamples = 0;
  14375. d->numChannels = 0;
  14376. d->sampleRate = 0;
  14377. numSamplesCached = 0;
  14378. cacheNeedsRefilling = true;
  14379. }
  14380. void AudioThumbnail::loadFrom (InputStream& input)
  14381. {
  14382. data.setSize (0);
  14383. input.readIntoMemoryBlock (data);
  14384. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14385. swapEndiannessIfNeeded (d);
  14386. if (! (d->thumbnailMagic[0] == 'j'
  14387. && d->thumbnailMagic[1] == 'a'
  14388. && d->thumbnailMagic[2] == 't'
  14389. && d->thumbnailMagic[3] == 'm'))
  14390. {
  14391. clear();
  14392. }
  14393. numSamplesCached = 0;
  14394. cacheNeedsRefilling = true;
  14395. }
  14396. void AudioThumbnail::saveTo (OutputStream& output) const
  14397. {
  14398. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14399. swapEndiannessIfNeeded (d);
  14400. output.write (data.getData(), data.getSize());
  14401. swapEndiannessIfNeeded (d);
  14402. }
  14403. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& reader)
  14404. {
  14405. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  14406. d->totalSamples = reader.lengthInSamples;
  14407. d->numChannels = jmin (2, reader.numChannels);
  14408. d->numFinishedSamples = 0;
  14409. d->sampleRate = roundDoubleToInt (reader.sampleRate);
  14410. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  14411. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  14412. d = (AudioThumbnailDataFormat*) data.getData();
  14413. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  14414. return d->totalSamples > 0;
  14415. }
  14416. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& reader)
  14417. {
  14418. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14419. if (d->numFinishedSamples < d->totalSamples)
  14420. {
  14421. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  14422. generateSection (reader,
  14423. d->numFinishedSamples,
  14424. numToDo);
  14425. d->numFinishedSamples += numToDo;
  14426. }
  14427. cacheNeedsRefilling = true;
  14428. return (d->numFinishedSamples < d->totalSamples);
  14429. }
  14430. int AudioThumbnail::getNumChannels() const throw()
  14431. {
  14432. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14433. jassert (d != 0);
  14434. return d->numChannels;
  14435. }
  14436. double AudioThumbnail::getTotalLength() const throw()
  14437. {
  14438. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14439. jassert (d != 0);
  14440. if (d->sampleRate > 0)
  14441. return d->totalSamples / (double)d->sampleRate;
  14442. else
  14443. return 0.0;
  14444. }
  14445. void AudioThumbnail::generateSection (AudioFormatReader& reader,
  14446. int64 startSample,
  14447. int numSamples)
  14448. {
  14449. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14450. jassert (d != 0);
  14451. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  14452. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  14453. char* l = getChannelData (0);
  14454. char* r = getChannelData (1);
  14455. for (int i = firstDataPos; i < lastDataPos; ++i)
  14456. {
  14457. const int sourceStart = i * d->samplesPerThumbSample;
  14458. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  14459. float lowestLeft, highestLeft, lowestRight, highestRight;
  14460. reader.readMaxLevels (sourceStart,
  14461. sourceEnd - sourceStart,
  14462. lowestLeft,
  14463. highestLeft,
  14464. lowestRight,
  14465. highestRight);
  14466. int n = i * 2;
  14467. if (r != 0)
  14468. {
  14469. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  14470. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  14471. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  14472. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  14473. }
  14474. else
  14475. {
  14476. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  14477. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  14478. }
  14479. }
  14480. }
  14481. char* AudioThumbnail::getChannelData (int channel) const
  14482. {
  14483. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14484. jassert (d != 0);
  14485. if (channel >= 0 && channel < d->numChannels)
  14486. return d->data + (channel * 2 * d->numThumbnailSamples);
  14487. return 0;
  14488. }
  14489. bool AudioThumbnail::isFullyLoaded() const throw()
  14490. {
  14491. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14492. jassert (d != 0);
  14493. return d->numFinishedSamples >= d->totalSamples;
  14494. }
  14495. void AudioThumbnail::refillCache (const int numSamples,
  14496. double startTime,
  14497. const double timePerPixel)
  14498. {
  14499. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14500. jassert (d != 0);
  14501. if (numSamples <= 0
  14502. || timePerPixel <= 0.0
  14503. || d->sampleRate <= 0)
  14504. {
  14505. numSamplesCached = 0;
  14506. cacheNeedsRefilling = true;
  14507. return;
  14508. }
  14509. if (numSamples == numSamplesCached
  14510. && numChannelsCached == d->numChannels
  14511. && startTime == cachedStart
  14512. && timePerPixel == cachedTimePerPixel
  14513. && ! cacheNeedsRefilling)
  14514. {
  14515. return;
  14516. }
  14517. numSamplesCached = numSamples;
  14518. numChannelsCached = d->numChannels;
  14519. cachedStart = startTime;
  14520. cachedTimePerPixel = timePerPixel;
  14521. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  14522. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  14523. const ScopedLock sl (readerLock);
  14524. cacheNeedsRefilling = false;
  14525. if (needExtraDetail && reader == 0)
  14526. reader = createReader();
  14527. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  14528. {
  14529. startTimer (timeBeforeDeletingReader);
  14530. char* cacheData = (char*) cachedLevels.getData();
  14531. int sample = roundDoubleToInt (startTime * d->sampleRate);
  14532. for (int i = numSamples; --i >= 0;)
  14533. {
  14534. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * d->sampleRate);
  14535. if (sample >= 0)
  14536. {
  14537. if (sample >= reader->lengthInSamples)
  14538. break;
  14539. float lmin, lmax, rmin, rmax;
  14540. reader->readMaxLevels (sample,
  14541. jmax (1, nextSample - sample),
  14542. lmin, lmax, rmin, rmax);
  14543. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  14544. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  14545. if (numChannelsCached > 1)
  14546. {
  14547. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  14548. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  14549. }
  14550. cacheData += 2 * numChannelsCached;
  14551. }
  14552. startTime += timePerPixel;
  14553. sample = nextSample;
  14554. }
  14555. }
  14556. else
  14557. {
  14558. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  14559. {
  14560. char* const data = getChannelData (channelNum);
  14561. char* cacheData = ((char*) cachedLevels.getData()) + channelNum * 2;
  14562. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  14563. startTime = cachedStart;
  14564. int sample = roundDoubleToInt (startTime * timeToThumbSampleFactor);
  14565. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  14566. for (int i = numSamples; --i >= 0;)
  14567. {
  14568. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  14569. if (sample >= 0 && data != 0)
  14570. {
  14571. char mx = -128;
  14572. char mn = 127;
  14573. while (sample <= nextSample)
  14574. {
  14575. if (sample >= numFinished)
  14576. break;
  14577. const int n = sample << 1;
  14578. const char sampMin = data [n];
  14579. const char sampMax = data [n + 1];
  14580. if (sampMin < mn)
  14581. mn = sampMin;
  14582. if (sampMax > mx)
  14583. mx = sampMax;
  14584. ++sample;
  14585. }
  14586. if (mn <= mx)
  14587. {
  14588. cacheData[0] = mn;
  14589. cacheData[1] = mx;
  14590. }
  14591. else
  14592. {
  14593. cacheData[0] = 1;
  14594. cacheData[1] = 0;
  14595. }
  14596. }
  14597. else
  14598. {
  14599. cacheData[0] = 1;
  14600. cacheData[1] = 0;
  14601. }
  14602. cacheData += numChannelsCached * 2;
  14603. startTime += timePerPixel;
  14604. sample = nextSample;
  14605. }
  14606. }
  14607. }
  14608. }
  14609. void AudioThumbnail::drawChannel (Graphics& g,
  14610. int x, int y, int w, int h,
  14611. double startTime,
  14612. double endTime,
  14613. int channelNum,
  14614. const float verticalZoomFactor)
  14615. {
  14616. refillCache (w, startTime, (endTime - startTime) / w);
  14617. if (numSamplesCached >= w
  14618. && channelNum >= 0
  14619. && channelNum < numChannelsCached)
  14620. {
  14621. const float topY = (float) y;
  14622. const float bottomY = topY + h;
  14623. const float midY = topY + h * 0.5f;
  14624. const float vscale = verticalZoomFactor * h / 256.0f;
  14625. const Rectangle clip (g.getClipBounds());
  14626. const int skipLeft = clip.getX() - x;
  14627. w -= skipLeft;
  14628. x += skipLeft;
  14629. const char* cacheData = ((const char*) cachedLevels.getData())
  14630. + (channelNum << 1)
  14631. + skipLeft * (numChannelsCached << 1);
  14632. while (--w >= 0)
  14633. {
  14634. const char mn = cacheData[0];
  14635. const char mx = cacheData[1];
  14636. cacheData += numChannelsCached << 1;
  14637. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  14638. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  14639. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  14640. ++x;
  14641. if (x >= clip.getRight())
  14642. break;
  14643. }
  14644. }
  14645. }
  14646. END_JUCE_NAMESPACE
  14647. /********* End of inlined file: juce_AudioThumbnail.cpp *********/
  14648. /********* Start of inlined file: juce_AudioThumbnailCache.cpp *********/
  14649. BEGIN_JUCE_NAMESPACE
  14650. struct ThumbnailCacheEntry
  14651. {
  14652. int64 hash;
  14653. uint32 lastUsed;
  14654. MemoryBlock data;
  14655. juce_UseDebuggingNewOperator
  14656. };
  14657. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  14658. : TimeSliceThread (T("thumb cache")),
  14659. maxNumThumbsToStore (maxNumThumbsToStore_)
  14660. {
  14661. startThread (2);
  14662. }
  14663. AudioThumbnailCache::~AudioThumbnailCache()
  14664. {
  14665. }
  14666. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  14667. {
  14668. for (int i = thumbs.size(); --i >= 0;)
  14669. {
  14670. if (thumbs[i]->hash == hashCode)
  14671. {
  14672. MemoryInputStream in ((const char*) thumbs[i]->data.getData(),
  14673. thumbs[i]->data.getSize(),
  14674. false);
  14675. thumb.loadFrom (in);
  14676. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  14677. return true;
  14678. }
  14679. }
  14680. return false;
  14681. }
  14682. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  14683. const int64 hashCode)
  14684. {
  14685. MemoryOutputStream out;
  14686. thumb.saveTo (out);
  14687. ThumbnailCacheEntry* te = 0;
  14688. for (int i = thumbs.size(); --i >= 0;)
  14689. {
  14690. if (thumbs[i]->hash == hashCode)
  14691. {
  14692. te = thumbs[i];
  14693. break;
  14694. }
  14695. }
  14696. if (te == 0)
  14697. {
  14698. te = new ThumbnailCacheEntry();
  14699. te->hash = hashCode;
  14700. if (thumbs.size() < maxNumThumbsToStore)
  14701. {
  14702. thumbs.add (te);
  14703. }
  14704. else
  14705. {
  14706. int oldest = 0;
  14707. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  14708. int i;
  14709. for (i = thumbs.size(); --i >= 0;)
  14710. if (thumbs[i]->lastUsed < oldestTime)
  14711. oldest = i;
  14712. thumbs.set (i, te);
  14713. }
  14714. }
  14715. te->lastUsed = Time::getMillisecondCounter();
  14716. te->data.setSize (0);
  14717. te->data.append (out.getData(), out.getDataSize());
  14718. }
  14719. void AudioThumbnailCache::clear()
  14720. {
  14721. thumbs.clear();
  14722. }
  14723. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  14724. {
  14725. addTimeSliceClient (thumb);
  14726. }
  14727. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  14728. {
  14729. removeTimeSliceClient (thumb);
  14730. }
  14731. END_JUCE_NAMESPACE
  14732. /********* End of inlined file: juce_AudioThumbnailCache.cpp *********/
  14733. /********* Start of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  14734. #if JUCE_QUICKTIME
  14735. #if ! defined (_WIN32)
  14736. #include <Quicktime/Movies.h>
  14737. #include <Quicktime/QTML.h>
  14738. #include <Quicktime/QuickTimeComponents.h>
  14739. #include <Quicktime/MediaHandlers.h>
  14740. #include <Quicktime/ImageCodec.h>
  14741. #else
  14742. #ifdef _MSC_VER
  14743. #pragma warning (push)
  14744. #pragma warning (disable : 4100)
  14745. #endif
  14746. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  14747. add its header directory to your include path.
  14748. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  14749. flag in juce_Config.h
  14750. */
  14751. #include <Movies.h>
  14752. #include <QTML.h>
  14753. #include <QuickTimeComponents.h>
  14754. #include <MediaHandlers.h>
  14755. #include <ImageCodec.h>
  14756. #ifdef _MSC_VER
  14757. #pragma warning (pop)
  14758. #endif
  14759. #endif
  14760. BEGIN_JUCE_NAMESPACE
  14761. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  14762. #define quickTimeFormatName TRANS("QuickTime file")
  14763. static const tchar* const quickTimeExtensions[] = { T(".mov"), T(".mp3"), T(".mp4"), 0 };
  14764. class QTAudioReader : public AudioFormatReader
  14765. {
  14766. public:
  14767. QTAudioReader (InputStream* const input_, const int trackNum_)
  14768. : AudioFormatReader (input_, quickTimeFormatName),
  14769. ok (false),
  14770. movie (0),
  14771. trackNum (trackNum_),
  14772. extractor (0),
  14773. lastSampleRead (0),
  14774. lastThreadId (0),
  14775. dataHandle (0)
  14776. {
  14777. bufferList = (AudioBufferList*) juce_calloc (256);
  14778. #ifdef WIN32
  14779. if (InitializeQTML (0) != noErr)
  14780. return;
  14781. #elif JUCE_MAC
  14782. EnterMoviesOnThread (0);
  14783. #endif
  14784. if (EnterMovies() != noErr)
  14785. return;
  14786. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  14787. if (! opened)
  14788. return;
  14789. {
  14790. const int numTracks = GetMovieTrackCount (movie);
  14791. int trackCount = 0;
  14792. for (int i = 1; i <= numTracks; ++i)
  14793. {
  14794. track = GetMovieIndTrack (movie, i);
  14795. media = GetTrackMedia (track);
  14796. OSType mediaType;
  14797. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  14798. if (mediaType == SoundMediaType
  14799. && trackCount++ == trackNum_)
  14800. {
  14801. ok = true;
  14802. break;
  14803. }
  14804. }
  14805. }
  14806. if (! ok)
  14807. return;
  14808. ok = false;
  14809. lengthInSamples = GetMediaDecodeDuration (media);
  14810. usesFloatingPointData = false;
  14811. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  14812. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  14813. / GetMediaTimeScale (media);
  14814. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  14815. unsigned long output_layout_size;
  14816. err = MovieAudioExtractionGetPropertyInfo (extractor,
  14817. kQTPropertyClass_MovieAudioExtraction_Audio,
  14818. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  14819. 0, &output_layout_size, 0);
  14820. if (err != noErr)
  14821. return;
  14822. AudioChannelLayout* const qt_audio_channel_layout
  14823. = (AudioChannelLayout*) juce_calloc (output_layout_size);
  14824. err = MovieAudioExtractionGetProperty (extractor,
  14825. kQTPropertyClass_MovieAudioExtraction_Audio,
  14826. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  14827. output_layout_size, qt_audio_channel_layout, 0);
  14828. qt_audio_channel_layout->mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  14829. err = MovieAudioExtractionSetProperty (extractor,
  14830. kQTPropertyClass_MovieAudioExtraction_Audio,
  14831. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  14832. sizeof (qt_audio_channel_layout),
  14833. qt_audio_channel_layout);
  14834. juce_free (qt_audio_channel_layout);
  14835. err = MovieAudioExtractionGetProperty (extractor,
  14836. kQTPropertyClass_MovieAudioExtraction_Audio,
  14837. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  14838. sizeof (inputStreamDesc),
  14839. &inputStreamDesc, 0);
  14840. if (err != noErr)
  14841. return;
  14842. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  14843. | kAudioFormatFlagIsPacked
  14844. | kAudioFormatFlagsNativeEndian;
  14845. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  14846. inputStreamDesc.mChannelsPerFrame = jmin (2, inputStreamDesc.mChannelsPerFrame);
  14847. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  14848. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  14849. err = MovieAudioExtractionSetProperty (extractor,
  14850. kQTPropertyClass_MovieAudioExtraction_Audio,
  14851. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  14852. sizeof (inputStreamDesc),
  14853. &inputStreamDesc);
  14854. if (err != noErr)
  14855. return;
  14856. Boolean allChannelsDiscrete = false;
  14857. err = MovieAudioExtractionSetProperty (extractor,
  14858. kQTPropertyClass_MovieAudioExtraction_Movie,
  14859. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  14860. sizeof (allChannelsDiscrete),
  14861. &allChannelsDiscrete);
  14862. if (err != noErr)
  14863. return;
  14864. bufferList->mNumberBuffers = 1;
  14865. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  14866. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  14867. bufferList->mBuffers[0].mData = malloc (bufferList->mBuffers[0].mDataByteSize);
  14868. sampleRate = inputStreamDesc.mSampleRate;
  14869. bitsPerSample = 16;
  14870. numChannels = inputStreamDesc.mChannelsPerFrame;
  14871. detachThread();
  14872. ok = true;
  14873. }
  14874. ~QTAudioReader()
  14875. {
  14876. if (dataHandle != 0)
  14877. DisposeHandle (dataHandle);
  14878. if (extractor != 0)
  14879. {
  14880. MovieAudioExtractionEnd (extractor);
  14881. extractor = 0;
  14882. }
  14883. checkThreadIsAttached();
  14884. DisposeMovie (movie);
  14885. juce_free (bufferList->mBuffers[0].mData);
  14886. juce_free (bufferList);
  14887. #if JUCE_MAC
  14888. ExitMoviesOnThread ();
  14889. #endif
  14890. }
  14891. bool read (int** destSamples,
  14892. int64 startSample,
  14893. int numSamples)
  14894. {
  14895. checkThreadIsAttached();
  14896. int done = 0;
  14897. while (numSamples > 0)
  14898. {
  14899. if (! loadFrame ((int) startSample))
  14900. return false;
  14901. const int numToDo = jmin (numSamples, samplesPerFrame);
  14902. for (unsigned int j = 0; j < inputStreamDesc.mChannelsPerFrame; ++j)
  14903. {
  14904. if (destSamples[j] != 0)
  14905. {
  14906. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  14907. for (int i = 0; i < numToDo; ++i)
  14908. destSamples[j][done + i] = src [i << 1] << 16;
  14909. }
  14910. }
  14911. done += numToDo;
  14912. startSample += numToDo;
  14913. numSamples -= numToDo;
  14914. }
  14915. detachThread();
  14916. return true;
  14917. }
  14918. bool loadFrame (const int sampleNum)
  14919. {
  14920. if (lastSampleRead != sampleNum)
  14921. {
  14922. TimeRecord time;
  14923. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  14924. time.base = 0;
  14925. time.value.hi = 0;
  14926. time.value.lo = (UInt32) sampleNum;
  14927. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  14928. kQTPropertyClass_MovieAudioExtraction_Movie,
  14929. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  14930. sizeof (time), &time);
  14931. if (err != noErr)
  14932. return false;
  14933. }
  14934. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  14935. UInt32 outFlags = 0;
  14936. UInt32 actualNumSamples = samplesPerFrame;
  14937. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  14938. bufferList, &outFlags);
  14939. lastSampleRead = sampleNum + samplesPerFrame;
  14940. return err == noErr;
  14941. }
  14942. juce_UseDebuggingNewOperator
  14943. bool ok;
  14944. private:
  14945. Movie movie;
  14946. Media media;
  14947. Track track;
  14948. const int trackNum;
  14949. double trackUnitsPerFrame;
  14950. int samplesPerFrame;
  14951. int lastSampleRead, lastThreadId;
  14952. MovieAudioExtractionRef extractor;
  14953. AudioStreamBasicDescription inputStreamDesc;
  14954. AudioBufferList* bufferList;
  14955. Handle dataHandle;
  14956. /*OSErr readMovieStream (long offset, long size, void* dataPtr)
  14957. {
  14958. input->setPosition (offset);
  14959. input->read (dataPtr, size);
  14960. return noErr;
  14961. }
  14962. static OSErr readMovieStreamProc (long offset, long size, void* dataPtr, void* userRef)
  14963. {
  14964. return ((QTAudioReader*) userRef)->readMovieStream (offset, size, dataPtr);
  14965. }*/
  14966. void checkThreadIsAttached()
  14967. {
  14968. #if JUCE_MAC
  14969. if (Thread::getCurrentThreadId() != lastThreadId)
  14970. EnterMoviesOnThread (0);
  14971. AttachMovieToCurrentThread (movie);
  14972. #endif
  14973. }
  14974. void detachThread()
  14975. {
  14976. #if JUCE_MAC
  14977. DetachMovieFromCurrentThread (movie);
  14978. #endif
  14979. }
  14980. };
  14981. QuickTimeAudioFormat::QuickTimeAudioFormat()
  14982. : AudioFormat (quickTimeFormatName, (const tchar**) quickTimeExtensions)
  14983. {
  14984. }
  14985. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  14986. {
  14987. }
  14988. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  14989. {
  14990. return Array<int>();
  14991. }
  14992. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  14993. {
  14994. return Array<int>();
  14995. }
  14996. bool QuickTimeAudioFormat::canDoStereo()
  14997. {
  14998. return true;
  14999. }
  15000. bool QuickTimeAudioFormat::canDoMono()
  15001. {
  15002. return true;
  15003. }
  15004. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  15005. const bool deleteStreamIfOpeningFails)
  15006. {
  15007. QTAudioReader* r = new QTAudioReader (sourceStream, 0);
  15008. if (! r->ok)
  15009. {
  15010. if (! deleteStreamIfOpeningFails)
  15011. r->input = 0;
  15012. deleteAndZero (r);
  15013. }
  15014. return r;
  15015. }
  15016. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  15017. double /*sampleRateToUse*/,
  15018. unsigned int /*numberOfChannels*/,
  15019. int /*bitsPerSample*/,
  15020. const StringPairArray& /*metadataValues*/,
  15021. int /*qualityOptionIndex*/)
  15022. {
  15023. jassertfalse // not yet implemented!
  15024. return 0;
  15025. }
  15026. END_JUCE_NAMESPACE
  15027. #endif
  15028. /********* End of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  15029. /********* Start of inlined file: juce_WavAudioFormat.cpp *********/
  15030. BEGIN_JUCE_NAMESPACE
  15031. #define wavFormatName TRANS("WAV file")
  15032. static const tchar* const wavExtensions[] = { T(".wav"), T(".bwf"), 0 };
  15033. const tchar* const WavAudioFormat::bwavDescription = T("bwav description");
  15034. const tchar* const WavAudioFormat::bwavOriginator = T("bwav originator");
  15035. const tchar* const WavAudioFormat::bwavOriginatorRef = T("bwav originator ref");
  15036. const tchar* const WavAudioFormat::bwavOriginationDate = T("bwav origination date");
  15037. const tchar* const WavAudioFormat::bwavOriginationTime = T("bwav origination time");
  15038. const tchar* const WavAudioFormat::bwavTimeReference = T("bwav time reference");
  15039. const tchar* const WavAudioFormat::bwavCodingHistory = T("bwav coding history");
  15040. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  15041. const String& originator,
  15042. const String& originatorRef,
  15043. const Time& date,
  15044. const int64 timeReferenceSamples,
  15045. const String& codingHistory)
  15046. {
  15047. StringPairArray m;
  15048. m.set (bwavDescription, description);
  15049. m.set (bwavOriginator, originator);
  15050. m.set (bwavOriginatorRef, originatorRef);
  15051. m.set (bwavOriginationDate, date.formatted (T("%Y-%m-%d")));
  15052. m.set (bwavOriginationTime, date.formatted (T("%H:%M:%S")));
  15053. m.set (bwavTimeReference, String (timeReferenceSamples));
  15054. m.set (bwavCodingHistory, codingHistory);
  15055. return m;
  15056. }
  15057. #if JUCE_MSVC
  15058. #pragma pack (push, 1)
  15059. #define PACKED
  15060. #elif defined (JUCE_GCC)
  15061. #define PACKED __attribute__((packed))
  15062. #else
  15063. #define PACKED
  15064. #endif
  15065. struct BWAVChunk
  15066. {
  15067. char description [256];
  15068. char originator [32];
  15069. char originatorRef [32];
  15070. char originationDate [10];
  15071. char originationTime [8];
  15072. uint32 timeRefLow;
  15073. uint32 timeRefHigh;
  15074. uint16 version;
  15075. uint8 umid[64];
  15076. uint8 reserved[190];
  15077. char codingHistory[1];
  15078. void copyTo (StringPairArray& values) const
  15079. {
  15080. values.set (WavAudioFormat::bwavDescription, String (description, 256));
  15081. values.set (WavAudioFormat::bwavOriginator, String (originator, 32));
  15082. values.set (WavAudioFormat::bwavOriginatorRef, String (originatorRef, 32));
  15083. values.set (WavAudioFormat::bwavOriginationDate, String (originationDate, 10));
  15084. values.set (WavAudioFormat::bwavOriginationTime, String (originationTime, 8));
  15085. const uint32 timeLow = swapIfBigEndian (timeRefLow);
  15086. const uint32 timeHigh = swapIfBigEndian (timeRefHigh);
  15087. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  15088. values.set (WavAudioFormat::bwavTimeReference, String (time));
  15089. values.set (WavAudioFormat::bwavCodingHistory, String (codingHistory));
  15090. }
  15091. static MemoryBlock createFrom (const StringPairArray& values)
  15092. {
  15093. const int sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].length();
  15094. MemoryBlock data ((sizeNeeded + 3) & ~3);
  15095. data.fillWith (0);
  15096. BWAVChunk* b = (BWAVChunk*) data.getData();
  15097. // although copyToBuffer may overrun by one byte, that's ok as long as these
  15098. // operations get done in the right order
  15099. values [WavAudioFormat::bwavDescription].copyToBuffer (b->description, 256);
  15100. values [WavAudioFormat::bwavOriginator].copyToBuffer (b->originator, 32);
  15101. values [WavAudioFormat::bwavOriginatorRef].copyToBuffer (b->originatorRef, 32);
  15102. values [WavAudioFormat::bwavOriginationDate].copyToBuffer (b->originationDate, 10);
  15103. values [WavAudioFormat::bwavOriginationTime].copyToBuffer (b->originationTime, 8);
  15104. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  15105. b->timeRefLow = swapIfBigEndian ((uint32) (time & 0xffffffff));
  15106. b->timeRefHigh = swapIfBigEndian ((uint32) (time >> 32));
  15107. values [WavAudioFormat::bwavCodingHistory].copyToBuffer (b->codingHistory, 256 * 1024);
  15108. if (b->description[0] != 0
  15109. || b->originator[0] != 0
  15110. || b->originationDate[0] != 0
  15111. || b->originationTime[0] != 0
  15112. || b->codingHistory[0] != 0
  15113. || time != 0)
  15114. {
  15115. return data;
  15116. }
  15117. return MemoryBlock();
  15118. }
  15119. } PACKED;
  15120. #if JUCE_MSVC
  15121. #pragma pack (pop)
  15122. #endif
  15123. #undef PACKED
  15124. #undef chunkName
  15125. #define chunkName(a) ((int) littleEndianInt(a))
  15126. class WavAudioFormatReader : public AudioFormatReader
  15127. {
  15128. int bytesPerFrame;
  15129. int64 dataChunkStart, dataLength;
  15130. WavAudioFormatReader (const WavAudioFormatReader&);
  15131. const WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  15132. public:
  15133. WavAudioFormatReader (InputStream* const in)
  15134. : AudioFormatReader (in, wavFormatName),
  15135. dataLength (0)
  15136. {
  15137. if (input->readInt() == chunkName ("RIFF"))
  15138. {
  15139. const uint32 len = (uint32) input->readInt();
  15140. const int64 end = input->getPosition() + len;
  15141. bool hasGotType = false;
  15142. bool hasGotData = false;
  15143. if (input->readInt() == chunkName ("WAVE"))
  15144. {
  15145. while (input->getPosition() < end
  15146. && ! input->isExhausted())
  15147. {
  15148. const int chunkType = input->readInt();
  15149. uint32 length = (uint32) input->readInt();
  15150. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  15151. if (chunkType == chunkName ("fmt "))
  15152. {
  15153. // read the format chunk
  15154. const short format = input->readShort();
  15155. const short numChans = input->readShort();
  15156. sampleRate = input->readInt();
  15157. const int bytesPerSec = input->readInt();
  15158. numChannels = numChans;
  15159. bytesPerFrame = bytesPerSec / (int)sampleRate;
  15160. bitsPerSample = 8 * bytesPerFrame / numChans;
  15161. if (format == 3)
  15162. usesFloatingPointData = true;
  15163. else if (format != 1)
  15164. bytesPerFrame = 0;
  15165. hasGotType = true;
  15166. }
  15167. else if (chunkType == chunkName ("data"))
  15168. {
  15169. // get the data chunk's position
  15170. dataLength = length;
  15171. dataChunkStart = input->getPosition();
  15172. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  15173. hasGotData = true;
  15174. }
  15175. else if (chunkType == chunkName ("bext"))
  15176. {
  15177. // Broadcast-wav extension chunk..
  15178. BWAVChunk* const bwav = (BWAVChunk*) juce_calloc (jmax (length + 1, (int) sizeof (BWAVChunk)));
  15179. if (bwav != 0)
  15180. {
  15181. input->read (bwav, length);
  15182. bwav->copyTo (metadataValues);
  15183. juce_free (bwav);
  15184. }
  15185. }
  15186. else if ((hasGotType && hasGotData) || chunkEnd <= input->getPosition())
  15187. {
  15188. break;
  15189. }
  15190. input->setPosition (chunkEnd);
  15191. }
  15192. }
  15193. }
  15194. }
  15195. ~WavAudioFormatReader()
  15196. {
  15197. }
  15198. bool read (int** destSamples,
  15199. int64 startSampleInFile,
  15200. int numSamples)
  15201. {
  15202. int64 start = startSampleInFile;
  15203. int startOffsetInDestBuffer = 0;
  15204. if (startSampleInFile < 0)
  15205. {
  15206. const int silence = (int) jmin (-startSampleInFile, (int64) numSamples);
  15207. int** destChan = destSamples;
  15208. for (int i = 2; --i >= 0;)
  15209. {
  15210. if (*destChan != 0)
  15211. {
  15212. zeromem (*destChan, sizeof (int) * silence);
  15213. ++destChan;
  15214. }
  15215. }
  15216. startOffsetInDestBuffer += silence;
  15217. numSamples -= silence;
  15218. start = 0;
  15219. }
  15220. const int numToDo = (int) jlimit ((int64) 0, (int64) numSamples, lengthInSamples - start);
  15221. if (numToDo > 0)
  15222. {
  15223. input->setPosition (dataChunkStart + start * bytesPerFrame);
  15224. int num = numToDo;
  15225. int* left = destSamples[0];
  15226. if (left != 0)
  15227. left += startOffsetInDestBuffer;
  15228. int* right = destSamples[1];
  15229. if (right != 0)
  15230. right += startOffsetInDestBuffer;
  15231. // (keep this a multiple of 3)
  15232. const int tempBufSize = 1440 * 4;
  15233. char tempBuffer [tempBufSize];
  15234. while (num > 0)
  15235. {
  15236. const int numThisTime = jmin (tempBufSize / bytesPerFrame, num);
  15237. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  15238. if (bytesRead < numThisTime * bytesPerFrame)
  15239. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  15240. if (bitsPerSample == 16)
  15241. {
  15242. const short* src = (const short*) tempBuffer;
  15243. if (numChannels > 1)
  15244. {
  15245. if (left == 0)
  15246. {
  15247. for (int i = numThisTime; --i >= 0;)
  15248. {
  15249. ++src;
  15250. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15251. }
  15252. }
  15253. else if (right == 0)
  15254. {
  15255. for (int i = numThisTime; --i >= 0;)
  15256. {
  15257. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15258. ++src;
  15259. }
  15260. }
  15261. else
  15262. {
  15263. for (int i = numThisTime; --i >= 0;)
  15264. {
  15265. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15266. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15267. }
  15268. }
  15269. }
  15270. else
  15271. {
  15272. for (int i = numThisTime; --i >= 0;)
  15273. {
  15274. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15275. }
  15276. }
  15277. }
  15278. else if (bitsPerSample == 24)
  15279. {
  15280. const char* src = (const char*) tempBuffer;
  15281. if (numChannels > 1)
  15282. {
  15283. if (left == 0)
  15284. {
  15285. for (int i = numThisTime; --i >= 0;)
  15286. {
  15287. src += 6;
  15288. *right++ = littleEndian24Bit (src) << 8;
  15289. }
  15290. }
  15291. else if (right == 0)
  15292. {
  15293. for (int i = numThisTime; --i >= 0;)
  15294. {
  15295. *left++ = littleEndian24Bit (src) << 8;
  15296. src += 6;
  15297. }
  15298. }
  15299. else
  15300. {
  15301. for (int i = 0; i < numThisTime; ++i)
  15302. {
  15303. *left++ = littleEndian24Bit (src) << 8;
  15304. src += 3;
  15305. *right++ = littleEndian24Bit (src) << 8;
  15306. src += 3;
  15307. }
  15308. }
  15309. }
  15310. else
  15311. {
  15312. for (int i = 0; i < numThisTime; ++i)
  15313. {
  15314. *left++ = littleEndian24Bit (src) << 8;
  15315. src += 3;
  15316. }
  15317. }
  15318. }
  15319. else if (bitsPerSample == 32)
  15320. {
  15321. const unsigned int* src = (const unsigned int*) tempBuffer;
  15322. unsigned int* l = (unsigned int*) left;
  15323. unsigned int* r = (unsigned int*) right;
  15324. if (numChannels > 1)
  15325. {
  15326. if (l == 0)
  15327. {
  15328. for (int i = numThisTime; --i >= 0;)
  15329. {
  15330. ++src;
  15331. *r++ = swapIfBigEndian (*src++);
  15332. }
  15333. }
  15334. else if (r == 0)
  15335. {
  15336. for (int i = numThisTime; --i >= 0;)
  15337. {
  15338. *l++ = swapIfBigEndian (*src++);
  15339. ++src;
  15340. }
  15341. }
  15342. else
  15343. {
  15344. for (int i = numThisTime; --i >= 0;)
  15345. {
  15346. *l++ = swapIfBigEndian (*src++);
  15347. *r++ = swapIfBigEndian (*src++);
  15348. }
  15349. }
  15350. }
  15351. else
  15352. {
  15353. for (int i = numThisTime; --i >= 0;)
  15354. {
  15355. *l++ = swapIfBigEndian (*src++);
  15356. }
  15357. }
  15358. left = (int*)l;
  15359. right = (int*)r;
  15360. }
  15361. else if (bitsPerSample == 8)
  15362. {
  15363. const unsigned char* src = (const unsigned char*) tempBuffer;
  15364. if (numChannels > 1)
  15365. {
  15366. if (left == 0)
  15367. {
  15368. for (int i = numThisTime; --i >= 0;)
  15369. {
  15370. ++src;
  15371. *right++ = ((int) *src++ - 128) << 24;
  15372. }
  15373. }
  15374. else if (right == 0)
  15375. {
  15376. for (int i = numThisTime; --i >= 0;)
  15377. {
  15378. *left++ = ((int) *src++ - 128) << 24;
  15379. ++src;
  15380. }
  15381. }
  15382. else
  15383. {
  15384. for (int i = numThisTime; --i >= 0;)
  15385. {
  15386. *left++ = ((int) *src++ - 128) << 24;
  15387. *right++ = ((int) *src++ - 128) << 24;
  15388. }
  15389. }
  15390. }
  15391. else
  15392. {
  15393. for (int i = numThisTime; --i >= 0;)
  15394. {
  15395. *left++ = ((int)*src++ - 128) << 24;
  15396. }
  15397. }
  15398. }
  15399. num -= numThisTime;
  15400. }
  15401. }
  15402. if (numToDo < numSamples)
  15403. {
  15404. int** destChan = destSamples;
  15405. while (*destChan != 0)
  15406. {
  15407. zeromem ((*destChan) + (startOffsetInDestBuffer + numToDo),
  15408. sizeof (int) * (numSamples - numToDo));
  15409. ++destChan;
  15410. }
  15411. }
  15412. return true;
  15413. }
  15414. juce_UseDebuggingNewOperator
  15415. };
  15416. class WavAudioFormatWriter : public AudioFormatWriter
  15417. {
  15418. MemoryBlock tempBlock, bwavChunk;
  15419. uint32 lengthInSamples, bytesWritten;
  15420. int64 headerPosition;
  15421. bool writeFailed;
  15422. WavAudioFormatWriter (const WavAudioFormatWriter&);
  15423. const WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  15424. void writeHeader()
  15425. {
  15426. const bool seekedOk = output->setPosition (headerPosition);
  15427. (void) seekedOk;
  15428. // if this fails, you've given it an output stream that can't seek! It needs
  15429. // to be able to seek back to write the header
  15430. jassert (seekedOk);
  15431. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  15432. output->writeInt (chunkName ("RIFF"));
  15433. output->writeInt (lengthInSamples * bytesPerFrame
  15434. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36));
  15435. output->writeInt (chunkName ("WAVE"));
  15436. output->writeInt (chunkName ("fmt "));
  15437. output->writeInt (16);
  15438. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  15439. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  15440. output->writeShort ((short) numChannels);
  15441. output->writeInt ((int) sampleRate);
  15442. output->writeInt (bytesPerFrame * (int) sampleRate);
  15443. output->writeShort ((short) bytesPerFrame);
  15444. output->writeShort ((short) bitsPerSample);
  15445. if (bwavChunk.getSize() > 0)
  15446. {
  15447. output->writeInt (chunkName ("bext"));
  15448. output->writeInt (bwavChunk.getSize());
  15449. output->write (bwavChunk.getData(), bwavChunk.getSize());
  15450. }
  15451. output->writeInt (chunkName ("data"));
  15452. output->writeInt (lengthInSamples * bytesPerFrame);
  15453. usesFloatingPointData = (bitsPerSample == 32);
  15454. }
  15455. public:
  15456. WavAudioFormatWriter (OutputStream* const out,
  15457. const double sampleRate,
  15458. const unsigned int numChannels_,
  15459. const int bits,
  15460. const StringPairArray& metadataValues)
  15461. : AudioFormatWriter (out,
  15462. wavFormatName,
  15463. sampleRate,
  15464. numChannels_,
  15465. bits),
  15466. lengthInSamples (0),
  15467. bytesWritten (0),
  15468. writeFailed (false)
  15469. {
  15470. if (metadataValues.size() > 0)
  15471. bwavChunk = BWAVChunk::createFrom (metadataValues);
  15472. headerPosition = out->getPosition();
  15473. writeHeader();
  15474. }
  15475. ~WavAudioFormatWriter()
  15476. {
  15477. writeHeader();
  15478. }
  15479. bool write (const int** data, int numSamples)
  15480. {
  15481. if (writeFailed)
  15482. return false;
  15483. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  15484. tempBlock.ensureSize (bytes, false);
  15485. char* buffer = (char*) tempBlock.getData();
  15486. const int* left = data[0];
  15487. const int* right = data[1];
  15488. if (right == 0)
  15489. right = left;
  15490. if (bitsPerSample == 16)
  15491. {
  15492. short* b = (short*) buffer;
  15493. if (numChannels > 1)
  15494. {
  15495. for (int i = numSamples; --i >= 0;)
  15496. {
  15497. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  15498. *b++ = (short) swapIfBigEndian ((unsigned short) (*right++ >> 16));
  15499. }
  15500. }
  15501. else
  15502. {
  15503. for (int i = numSamples; --i >= 0;)
  15504. {
  15505. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  15506. }
  15507. }
  15508. }
  15509. else if (bitsPerSample == 24)
  15510. {
  15511. char* b = (char*) buffer;
  15512. if (numChannels > 1)
  15513. {
  15514. for (int i = numSamples; --i >= 0;)
  15515. {
  15516. littleEndian24BitToChars ((*left++) >> 8, b);
  15517. b += 3;
  15518. littleEndian24BitToChars ((*right++) >> 8, b);
  15519. b += 3;
  15520. }
  15521. }
  15522. else
  15523. {
  15524. for (int i = numSamples; --i >= 0;)
  15525. {
  15526. littleEndian24BitToChars ((*left++) >> 8, b);
  15527. b += 3;
  15528. }
  15529. }
  15530. }
  15531. else if (bitsPerSample == 32)
  15532. {
  15533. unsigned int* b = (unsigned int*) buffer;
  15534. if (numChannels > 1)
  15535. {
  15536. for (int i = numSamples; --i >= 0;)
  15537. {
  15538. *b++ = swapIfBigEndian ((unsigned int) *left++);
  15539. *b++ = swapIfBigEndian ((unsigned int) *right++);
  15540. }
  15541. }
  15542. else
  15543. {
  15544. for (int i = numSamples; --i >= 0;)
  15545. {
  15546. *b++ = swapIfBigEndian ((unsigned int) *left++);
  15547. }
  15548. }
  15549. }
  15550. else if (bitsPerSample == 8)
  15551. {
  15552. unsigned char* b = (unsigned char*) buffer;
  15553. if (numChannels > 1)
  15554. {
  15555. for (int i = numSamples; --i >= 0;)
  15556. {
  15557. *b++ = (unsigned char) (128 + (*left++ >> 24));
  15558. *b++ = (unsigned char) (128 + (*right++ >> 24));
  15559. }
  15560. }
  15561. else
  15562. {
  15563. for (int i = numSamples; --i >= 0;)
  15564. {
  15565. *b++ = (unsigned char) (128 + (*left++ >> 24));
  15566. }
  15567. }
  15568. }
  15569. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15570. || ! output->write (buffer, bytes))
  15571. {
  15572. // failed to write to disk, so let's try writing the header.
  15573. // If it's just run out of disk space, then if it does manage
  15574. // to write the header, we'll still have a useable file..
  15575. writeHeader();
  15576. writeFailed = true;
  15577. return false;
  15578. }
  15579. else
  15580. {
  15581. bytesWritten += bytes;
  15582. lengthInSamples += numSamples;
  15583. return true;
  15584. }
  15585. }
  15586. juce_UseDebuggingNewOperator
  15587. };
  15588. WavAudioFormat::WavAudioFormat()
  15589. : AudioFormat (wavFormatName, (const tchar**) wavExtensions)
  15590. {
  15591. }
  15592. WavAudioFormat::~WavAudioFormat()
  15593. {
  15594. }
  15595. const Array <int> WavAudioFormat::getPossibleSampleRates()
  15596. {
  15597. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15598. return Array <int> (rates);
  15599. }
  15600. const Array <int> WavAudioFormat::getPossibleBitDepths()
  15601. {
  15602. const int depths[] = { 8, 16, 24, 32, 0 };
  15603. return Array <int> (depths);
  15604. }
  15605. bool WavAudioFormat::canDoStereo()
  15606. {
  15607. return true;
  15608. }
  15609. bool WavAudioFormat::canDoMono()
  15610. {
  15611. return true;
  15612. }
  15613. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  15614. const bool deleteStreamIfOpeningFails)
  15615. {
  15616. WavAudioFormatReader* r = new WavAudioFormatReader (sourceStream);
  15617. if (r->sampleRate == 0)
  15618. {
  15619. if (! deleteStreamIfOpeningFails)
  15620. r->input = 0;
  15621. deleteAndZero (r);
  15622. }
  15623. return r;
  15624. }
  15625. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  15626. double sampleRate,
  15627. unsigned int numChannels,
  15628. int bitsPerSample,
  15629. const StringPairArray& metadataValues,
  15630. int /*qualityOptionIndex*/)
  15631. {
  15632. if (getPossibleBitDepths().contains (bitsPerSample))
  15633. {
  15634. return new WavAudioFormatWriter (out,
  15635. sampleRate,
  15636. numChannels,
  15637. bitsPerSample,
  15638. metadataValues);
  15639. }
  15640. return 0;
  15641. }
  15642. END_JUCE_NAMESPACE
  15643. /********* End of inlined file: juce_WavAudioFormat.cpp *********/
  15644. /********* Start of inlined file: juce_AudioFormatReaderSource.cpp *********/
  15645. BEGIN_JUCE_NAMESPACE
  15646. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  15647. const bool deleteReaderWhenThisIsDeleted)
  15648. : reader (reader_),
  15649. deleteReader (deleteReaderWhenThisIsDeleted),
  15650. nextPlayPos (0),
  15651. looping (false)
  15652. {
  15653. jassert (reader != 0);
  15654. }
  15655. AudioFormatReaderSource::~AudioFormatReaderSource()
  15656. {
  15657. releaseResources();
  15658. if (deleteReader)
  15659. delete reader;
  15660. }
  15661. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  15662. {
  15663. nextPlayPos = newPosition;
  15664. }
  15665. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  15666. {
  15667. looping = shouldLoop;
  15668. }
  15669. int AudioFormatReaderSource::getNextReadPosition() const
  15670. {
  15671. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  15672. : nextPlayPos;
  15673. }
  15674. int AudioFormatReaderSource::getTotalLength() const
  15675. {
  15676. return (int) reader->lengthInSamples;
  15677. }
  15678. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  15679. double /*sampleRate*/)
  15680. {
  15681. }
  15682. void AudioFormatReaderSource::releaseResources()
  15683. {
  15684. }
  15685. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  15686. {
  15687. if (info.numSamples > 0)
  15688. {
  15689. const int start = nextPlayPos;
  15690. if (looping)
  15691. {
  15692. const int newStart = start % (int) reader->lengthInSamples;
  15693. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  15694. if (newEnd > newStart)
  15695. {
  15696. info.buffer->readFromAudioReader (reader,
  15697. info.startSample,
  15698. newEnd - newStart,
  15699. newStart,
  15700. true, true);
  15701. }
  15702. else
  15703. {
  15704. const int endSamps = (int) reader->lengthInSamples - newStart;
  15705. info.buffer->readFromAudioReader (reader,
  15706. info.startSample,
  15707. endSamps,
  15708. newStart,
  15709. true, true);
  15710. info.buffer->readFromAudioReader (reader,
  15711. info.startSample + endSamps,
  15712. newEnd,
  15713. 0,
  15714. true, true);
  15715. }
  15716. nextPlayPos = newEnd;
  15717. }
  15718. else
  15719. {
  15720. info.buffer->readFromAudioReader (reader,
  15721. info.startSample,
  15722. info.numSamples,
  15723. start,
  15724. true, true);
  15725. nextPlayPos += info.numSamples;
  15726. }
  15727. }
  15728. }
  15729. END_JUCE_NAMESPACE
  15730. /********* End of inlined file: juce_AudioFormatReaderSource.cpp *********/
  15731. /********* Start of inlined file: juce_AudioSourcePlayer.cpp *********/
  15732. BEGIN_JUCE_NAMESPACE
  15733. AudioSourcePlayer::AudioSourcePlayer()
  15734. : source (0),
  15735. sampleRate (0),
  15736. bufferSize (0),
  15737. tempBuffer (2, 8),
  15738. lastGain (1.0f),
  15739. gain (1.0f)
  15740. {
  15741. }
  15742. AudioSourcePlayer::~AudioSourcePlayer()
  15743. {
  15744. setSource (0);
  15745. }
  15746. void AudioSourcePlayer::setSource (AudioSource* newSource)
  15747. {
  15748. if (source != newSource)
  15749. {
  15750. AudioSource* const oldSource = source;
  15751. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  15752. newSource->prepareToPlay (bufferSize, sampleRate);
  15753. {
  15754. const ScopedLock sl (readLock);
  15755. source = newSource;
  15756. }
  15757. if (oldSource != 0)
  15758. oldSource->releaseResources();
  15759. }
  15760. }
  15761. void AudioSourcePlayer::setGain (const float newGain) throw()
  15762. {
  15763. gain = newGain;
  15764. }
  15765. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  15766. int totalNumInputChannels,
  15767. float** outputChannelData,
  15768. int totalNumOutputChannels,
  15769. int numSamples)
  15770. {
  15771. // these should have been prepared by audioDeviceAboutToStart()...
  15772. jassert (sampleRate > 0 && bufferSize > 0);
  15773. const ScopedLock sl (readLock);
  15774. if (source != 0)
  15775. {
  15776. AudioSourceChannelInfo info;
  15777. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  15778. // messy stuff needed to compact the channels down into an array
  15779. // of non-zero pointers..
  15780. for (i = 0; i < totalNumInputChannels; ++i)
  15781. {
  15782. if (inputChannelData[i] != 0)
  15783. {
  15784. inputChans [numInputs++] = inputChannelData[i];
  15785. if (numInputs >= numElementsInArray (inputChans))
  15786. break;
  15787. }
  15788. }
  15789. for (i = 0; i < totalNumOutputChannels; ++i)
  15790. {
  15791. if (outputChannelData[i] != 0)
  15792. {
  15793. outputChans [numOutputs++] = outputChannelData[i];
  15794. if (numOutputs >= numElementsInArray (outputChans))
  15795. break;
  15796. }
  15797. }
  15798. if (numInputs > numOutputs)
  15799. {
  15800. // if there aren't enough output channels for the number of
  15801. // inputs, we need to create some temporary extra ones (can't
  15802. // use the input data in case it gets written to)
  15803. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  15804. false, false, true);
  15805. for (i = 0; i < numOutputs; ++i)
  15806. {
  15807. channels[numActiveChans] = outputChans[i];
  15808. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  15809. ++numActiveChans;
  15810. }
  15811. for (i = numOutputs; i < numInputs; ++i)
  15812. {
  15813. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  15814. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  15815. ++numActiveChans;
  15816. }
  15817. }
  15818. else
  15819. {
  15820. for (i = 0; i < numInputs; ++i)
  15821. {
  15822. channels[numActiveChans] = outputChans[i];
  15823. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  15824. ++numActiveChans;
  15825. }
  15826. for (i = numInputs; i < numOutputs; ++i)
  15827. {
  15828. channels[numActiveChans] = outputChans[i];
  15829. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  15830. ++numActiveChans;
  15831. }
  15832. }
  15833. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  15834. info.buffer = &buffer;
  15835. info.startSample = 0;
  15836. info.numSamples = numSamples;
  15837. source->getNextAudioBlock (info);
  15838. for (i = info.buffer->getNumChannels(); --i >= 0;)
  15839. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  15840. lastGain = gain;
  15841. }
  15842. else
  15843. {
  15844. for (int i = 0; i < totalNumOutputChannels; ++i)
  15845. if (outputChannelData[i] != 0)
  15846. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  15847. }
  15848. }
  15849. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  15850. {
  15851. sampleRate = device->getCurrentSampleRate();
  15852. bufferSize = device->getCurrentBufferSizeSamples();
  15853. zeromem (channels, sizeof (channels));
  15854. if (source != 0)
  15855. source->prepareToPlay (bufferSize, sampleRate);
  15856. }
  15857. void AudioSourcePlayer::audioDeviceStopped()
  15858. {
  15859. if (source != 0)
  15860. source->releaseResources();
  15861. sampleRate = 0.0;
  15862. bufferSize = 0;
  15863. tempBuffer.setSize (2, 8);
  15864. }
  15865. END_JUCE_NAMESPACE
  15866. /********* End of inlined file: juce_AudioSourcePlayer.cpp *********/
  15867. /********* Start of inlined file: juce_AudioTransportSource.cpp *********/
  15868. BEGIN_JUCE_NAMESPACE
  15869. AudioTransportSource::AudioTransportSource()
  15870. : source (0),
  15871. resamplerSource (0),
  15872. bufferingSource (0),
  15873. positionableSource (0),
  15874. masterSource (0),
  15875. gain (1.0f),
  15876. lastGain (1.0f),
  15877. playing (false),
  15878. stopped (true),
  15879. sampleRate (44100.0),
  15880. sourceSampleRate (0.0),
  15881. blockSize (128),
  15882. readAheadBufferSize (0),
  15883. isPrepared (false),
  15884. inputStreamEOF (false)
  15885. {
  15886. }
  15887. AudioTransportSource::~AudioTransportSource()
  15888. {
  15889. setSource (0);
  15890. releaseResources();
  15891. }
  15892. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  15893. int readAheadBufferSize_,
  15894. double sourceSampleRateToCorrectFor)
  15895. {
  15896. if (source == newSource)
  15897. {
  15898. if (source == 0)
  15899. return;
  15900. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  15901. }
  15902. readAheadBufferSize = readAheadBufferSize_;
  15903. sourceSampleRate = sourceSampleRateToCorrectFor;
  15904. ResamplingAudioSource* newResamplerSource = 0;
  15905. BufferingAudioSource* newBufferingSource = 0;
  15906. PositionableAudioSource* newPositionableSource = 0;
  15907. AudioSource* newMasterSource = 0;
  15908. ResamplingAudioSource* oldResamplerSource = resamplerSource;
  15909. BufferingAudioSource* oldBufferingSource = bufferingSource;
  15910. AudioSource* oldMasterSource = masterSource;
  15911. if (newSource != 0)
  15912. {
  15913. newPositionableSource = newSource;
  15914. if (readAheadBufferSize_ > 0)
  15915. newPositionableSource = newBufferingSource
  15916. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  15917. newPositionableSource->setNextReadPosition (0);
  15918. if (sourceSampleRateToCorrectFor != 0)
  15919. newMasterSource = newResamplerSource
  15920. = new ResamplingAudioSource (newPositionableSource, false);
  15921. else
  15922. newMasterSource = newPositionableSource;
  15923. if (isPrepared)
  15924. {
  15925. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  15926. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  15927. newMasterSource->prepareToPlay (blockSize, sampleRate);
  15928. }
  15929. }
  15930. {
  15931. const ScopedLock sl (callbackLock);
  15932. source = newSource;
  15933. resamplerSource = newResamplerSource;
  15934. bufferingSource = newBufferingSource;
  15935. masterSource = newMasterSource;
  15936. positionableSource = newPositionableSource;
  15937. playing = false;
  15938. }
  15939. if (oldMasterSource != 0)
  15940. oldMasterSource->releaseResources();
  15941. if (oldResamplerSource != 0)
  15942. delete oldResamplerSource;
  15943. if (oldBufferingSource != 0)
  15944. delete oldBufferingSource;
  15945. }
  15946. void AudioTransportSource::start()
  15947. {
  15948. if ((! playing) && masterSource != 0)
  15949. {
  15950. callbackLock.enter();
  15951. playing = true;
  15952. stopped = false;
  15953. inputStreamEOF = false;
  15954. callbackLock.exit();
  15955. sendChangeMessage (this);
  15956. }
  15957. }
  15958. void AudioTransportSource::stop()
  15959. {
  15960. if (playing)
  15961. {
  15962. callbackLock.enter();
  15963. playing = false;
  15964. callbackLock.exit();
  15965. int n = 500;
  15966. while (--n >= 0 && ! stopped)
  15967. Thread::sleep (2);
  15968. sendChangeMessage (this);
  15969. }
  15970. }
  15971. void AudioTransportSource::setPosition (double newPosition)
  15972. {
  15973. if (sampleRate > 0.0)
  15974. setNextReadPosition (roundDoubleToInt (newPosition * sampleRate));
  15975. }
  15976. double AudioTransportSource::getCurrentPosition() const
  15977. {
  15978. if (sampleRate > 0.0)
  15979. return getNextReadPosition() / sampleRate;
  15980. else
  15981. return 0.0;
  15982. }
  15983. void AudioTransportSource::setNextReadPosition (int newPosition)
  15984. {
  15985. if (positionableSource != 0)
  15986. {
  15987. if (sampleRate > 0 && sourceSampleRate > 0)
  15988. newPosition = roundDoubleToInt (newPosition * sourceSampleRate / sampleRate);
  15989. positionableSource->setNextReadPosition (newPosition);
  15990. }
  15991. }
  15992. int AudioTransportSource::getNextReadPosition() const
  15993. {
  15994. if (positionableSource != 0)
  15995. {
  15996. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  15997. return roundDoubleToInt (positionableSource->getNextReadPosition() * ratio);
  15998. }
  15999. return 0;
  16000. }
  16001. int AudioTransportSource::getTotalLength() const
  16002. {
  16003. const ScopedLock sl (callbackLock);
  16004. if (positionableSource != 0)
  16005. {
  16006. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  16007. return roundDoubleToInt (positionableSource->getTotalLength() * ratio);
  16008. }
  16009. return 0;
  16010. }
  16011. bool AudioTransportSource::isLooping() const
  16012. {
  16013. const ScopedLock sl (callbackLock);
  16014. return positionableSource != 0
  16015. && positionableSource->isLooping();
  16016. }
  16017. void AudioTransportSource::setGain (const float newGain) throw()
  16018. {
  16019. gain = newGain;
  16020. }
  16021. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  16022. double sampleRate_)
  16023. {
  16024. const ScopedLock sl (callbackLock);
  16025. sampleRate = sampleRate_;
  16026. blockSize = samplesPerBlockExpected;
  16027. if (masterSource != 0)
  16028. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16029. if (resamplerSource != 0 && sourceSampleRate != 0)
  16030. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  16031. isPrepared = true;
  16032. }
  16033. void AudioTransportSource::releaseResources()
  16034. {
  16035. const ScopedLock sl (callbackLock);
  16036. if (masterSource != 0)
  16037. masterSource->releaseResources();
  16038. isPrepared = false;
  16039. }
  16040. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16041. {
  16042. const ScopedLock sl (callbackLock);
  16043. inputStreamEOF = false;
  16044. if (masterSource != 0 && ! stopped)
  16045. {
  16046. masterSource->getNextAudioBlock (info);
  16047. if (! playing)
  16048. {
  16049. // just stopped playing, so fade out the last block..
  16050. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  16051. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  16052. if (info.numSamples > 256)
  16053. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  16054. }
  16055. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  16056. && ! positionableSource->isLooping())
  16057. {
  16058. playing = false;
  16059. inputStreamEOF = true;
  16060. sendChangeMessage (this);
  16061. }
  16062. stopped = ! playing;
  16063. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  16064. {
  16065. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  16066. lastGain, gain);
  16067. }
  16068. }
  16069. else
  16070. {
  16071. info.clearActiveBufferRegion();
  16072. stopped = true;
  16073. }
  16074. lastGain = gain;
  16075. }
  16076. END_JUCE_NAMESPACE
  16077. /********* End of inlined file: juce_AudioTransportSource.cpp *********/
  16078. /********* Start of inlined file: juce_BufferingAudioSource.cpp *********/
  16079. BEGIN_JUCE_NAMESPACE
  16080. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  16081. public Thread,
  16082. private Timer
  16083. {
  16084. public:
  16085. SharedBufferingAudioSourceThread()
  16086. : Thread ("Audio Buffer"),
  16087. sources (8)
  16088. {
  16089. }
  16090. ~SharedBufferingAudioSourceThread()
  16091. {
  16092. stopThread (10000);
  16093. clearSingletonInstance();
  16094. }
  16095. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  16096. void addSource (BufferingAudioSource* source)
  16097. {
  16098. const ScopedLock sl (lock);
  16099. if (! sources.contains ((void*) source))
  16100. {
  16101. sources.add ((void*) source);
  16102. startThread();
  16103. stopTimer();
  16104. }
  16105. notify();
  16106. }
  16107. void removeSource (BufferingAudioSource* source)
  16108. {
  16109. const ScopedLock sl (lock);
  16110. sources.removeValue ((void*) source);
  16111. if (sources.size() == 0)
  16112. startTimer (5000);
  16113. }
  16114. private:
  16115. VoidArray sources;
  16116. CriticalSection lock;
  16117. void run()
  16118. {
  16119. while (! threadShouldExit())
  16120. {
  16121. bool busy = false;
  16122. for (int i = sources.size(); --i >= 0;)
  16123. {
  16124. if (threadShouldExit())
  16125. return;
  16126. const ScopedLock sl (lock);
  16127. BufferingAudioSource* const b = (BufferingAudioSource*) sources[i];
  16128. if (b != 0 && b->readNextBufferChunk())
  16129. busy = true;
  16130. }
  16131. if (! busy)
  16132. wait (500);
  16133. }
  16134. }
  16135. void timerCallback()
  16136. {
  16137. stopTimer();
  16138. if (sources.size() == 0)
  16139. deleteInstance();
  16140. }
  16141. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  16142. const SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  16143. };
  16144. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  16145. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  16146. const bool deleteSourceWhenDeleted_,
  16147. int numberOfSamplesToBuffer_)
  16148. : source (source_),
  16149. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  16150. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  16151. buffer (2, 0),
  16152. bufferValidStart (0),
  16153. bufferValidEnd (0),
  16154. nextPlayPos (0),
  16155. wasSourceLooping (false)
  16156. {
  16157. jassert (source_ != 0);
  16158. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  16159. // not using a larger buffer..
  16160. }
  16161. BufferingAudioSource::~BufferingAudioSource()
  16162. {
  16163. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16164. if (thread != 0)
  16165. thread->removeSource (this);
  16166. if (deleteSourceWhenDeleted)
  16167. delete source;
  16168. }
  16169. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  16170. {
  16171. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  16172. sampleRate = sampleRate_;
  16173. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  16174. buffer.clear();
  16175. bufferValidStart = 0;
  16176. bufferValidEnd = 0;
  16177. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  16178. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  16179. buffer.getNumSamples() / 2))
  16180. {
  16181. SharedBufferingAudioSourceThread::getInstance()->notify();
  16182. Thread::sleep (5);
  16183. }
  16184. }
  16185. void BufferingAudioSource::releaseResources()
  16186. {
  16187. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16188. if (thread != 0)
  16189. thread->removeSource (this);
  16190. buffer.setSize (2, 0);
  16191. source->releaseResources();
  16192. }
  16193. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16194. {
  16195. const ScopedLock sl (bufferStartPosLock);
  16196. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  16197. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  16198. if (validStart == validEnd)
  16199. {
  16200. // total cache miss
  16201. info.clearActiveBufferRegion();
  16202. }
  16203. else
  16204. {
  16205. if (validStart > 0)
  16206. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  16207. if (validEnd < info.numSamples)
  16208. info.buffer->clear (info.startSample + validEnd,
  16209. info.numSamples - validEnd); // partial cache miss at end
  16210. if (validStart < validEnd)
  16211. {
  16212. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  16213. {
  16214. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  16215. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  16216. if (startBufferIndex < endBufferIndex)
  16217. {
  16218. info.buffer->copyFrom (chan, info.startSample + validStart,
  16219. buffer,
  16220. chan, startBufferIndex,
  16221. validEnd - validStart);
  16222. }
  16223. else
  16224. {
  16225. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  16226. info.buffer->copyFrom (chan, info.startSample + validStart,
  16227. buffer,
  16228. chan, startBufferIndex,
  16229. initialSize);
  16230. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  16231. buffer,
  16232. chan, 0,
  16233. (validEnd - validStart) - initialSize);
  16234. }
  16235. }
  16236. }
  16237. nextPlayPos += info.numSamples;
  16238. }
  16239. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16240. if (thread != 0)
  16241. thread->notify();
  16242. }
  16243. int BufferingAudioSource::getNextReadPosition() const
  16244. {
  16245. return (source->isLooping() && nextPlayPos > 0)
  16246. ? nextPlayPos % source->getTotalLength()
  16247. : nextPlayPos;
  16248. }
  16249. void BufferingAudioSource::setNextReadPosition (int newPosition)
  16250. {
  16251. const ScopedLock sl (bufferStartPosLock);
  16252. nextPlayPos = newPosition;
  16253. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16254. if (thread != 0)
  16255. thread->notify();
  16256. }
  16257. bool BufferingAudioSource::readNextBufferChunk()
  16258. {
  16259. bufferStartPosLock.enter();
  16260. if (wasSourceLooping != isLooping())
  16261. {
  16262. wasSourceLooping = isLooping();
  16263. bufferValidStart = 0;
  16264. bufferValidEnd = 0;
  16265. }
  16266. int newBVS = jmax (0, nextPlayPos);
  16267. int newBVE = newBVS + buffer.getNumSamples() - 4;
  16268. int sectionToReadStart = 0;
  16269. int sectionToReadEnd = 0;
  16270. const int maxChunkSize = 2048;
  16271. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  16272. {
  16273. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  16274. sectionToReadStart = newBVS;
  16275. sectionToReadEnd = newBVE;
  16276. bufferValidStart = 0;
  16277. bufferValidEnd = 0;
  16278. }
  16279. else if (abs (newBVS - bufferValidStart) > 512
  16280. || abs (newBVE - bufferValidEnd) > 512)
  16281. {
  16282. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  16283. sectionToReadStart = bufferValidEnd;
  16284. sectionToReadEnd = newBVE;
  16285. bufferValidStart = newBVS;
  16286. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  16287. }
  16288. bufferStartPosLock.exit();
  16289. if (sectionToReadStart != sectionToReadEnd)
  16290. {
  16291. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  16292. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  16293. if (bufferIndexStart < bufferIndexEnd)
  16294. {
  16295. readBufferSection (sectionToReadStart,
  16296. sectionToReadEnd - sectionToReadStart,
  16297. bufferIndexStart);
  16298. }
  16299. else
  16300. {
  16301. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  16302. readBufferSection (sectionToReadStart,
  16303. initialSize,
  16304. bufferIndexStart);
  16305. readBufferSection (sectionToReadStart + initialSize,
  16306. (sectionToReadEnd - sectionToReadStart) - initialSize,
  16307. 0);
  16308. }
  16309. const ScopedLock sl2 (bufferStartPosLock);
  16310. bufferValidStart = newBVS;
  16311. bufferValidEnd = newBVE;
  16312. return true;
  16313. }
  16314. else
  16315. {
  16316. return false;
  16317. }
  16318. }
  16319. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  16320. {
  16321. if (source->getNextReadPosition() != start)
  16322. source->setNextReadPosition (start);
  16323. AudioSourceChannelInfo info;
  16324. info.buffer = &buffer;
  16325. info.startSample = bufferOffset;
  16326. info.numSamples = length;
  16327. source->getNextAudioBlock (info);
  16328. }
  16329. END_JUCE_NAMESPACE
  16330. /********* End of inlined file: juce_BufferingAudioSource.cpp *********/
  16331. /********* Start of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  16332. BEGIN_JUCE_NAMESPACE
  16333. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  16334. const bool deleteSourceWhenDeleted_)
  16335. : requiredNumberOfChannels (2),
  16336. source (source_),
  16337. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  16338. buffer (2, 16)
  16339. {
  16340. remappedInfo.buffer = &buffer;
  16341. remappedInfo.startSample = 0;
  16342. }
  16343. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  16344. {
  16345. if (deleteSourceWhenDeleted)
  16346. delete source;
  16347. }
  16348. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  16349. {
  16350. const ScopedLock sl (lock);
  16351. requiredNumberOfChannels = requiredNumberOfChannels_;
  16352. }
  16353. void ChannelRemappingAudioSource::clearAllMappings() throw()
  16354. {
  16355. const ScopedLock sl (lock);
  16356. remappedInputs.clear();
  16357. remappedOutputs.clear();
  16358. }
  16359. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  16360. {
  16361. const ScopedLock sl (lock);
  16362. while (remappedInputs.size() < destIndex)
  16363. remappedInputs.add (-1);
  16364. remappedInputs.set (destIndex, sourceIndex);
  16365. }
  16366. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  16367. {
  16368. const ScopedLock sl (lock);
  16369. while (remappedOutputs.size() < sourceIndex)
  16370. remappedOutputs.add (-1);
  16371. remappedOutputs.set (sourceIndex, destIndex);
  16372. }
  16373. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  16374. {
  16375. const ScopedLock sl (lock);
  16376. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  16377. return remappedInputs.getUnchecked (inputChannelIndex);
  16378. return -1;
  16379. }
  16380. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  16381. {
  16382. const ScopedLock sl (lock);
  16383. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  16384. return remappedOutputs .getUnchecked (outputChannelIndex);
  16385. return -1;
  16386. }
  16387. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  16388. {
  16389. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16390. }
  16391. void ChannelRemappingAudioSource::releaseResources()
  16392. {
  16393. source->releaseResources();
  16394. }
  16395. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  16396. {
  16397. const ScopedLock sl (lock);
  16398. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  16399. const int numChans = bufferToFill.buffer->getNumChannels();
  16400. int i;
  16401. for (i = 0; i < buffer.getNumChannels(); ++i)
  16402. {
  16403. const int remappedChan = getRemappedInputChannel (i);
  16404. if (remappedChan >= 0 && remappedChan < numChans)
  16405. {
  16406. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  16407. remappedChan,
  16408. bufferToFill.startSample,
  16409. bufferToFill.numSamples);
  16410. }
  16411. else
  16412. {
  16413. buffer.clear (i, 0, bufferToFill.numSamples);
  16414. }
  16415. }
  16416. remappedInfo.numSamples = bufferToFill.numSamples;
  16417. source->getNextAudioBlock (remappedInfo);
  16418. bufferToFill.clearActiveBufferRegion();
  16419. for (i = 0; i < requiredNumberOfChannels; ++i)
  16420. {
  16421. const int remappedChan = getRemappedOutputChannel (i);
  16422. if (remappedChan >= 0 && remappedChan < numChans)
  16423. {
  16424. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  16425. buffer, i, 0, bufferToFill.numSamples);
  16426. }
  16427. }
  16428. }
  16429. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  16430. {
  16431. XmlElement* e = new XmlElement (T("MAPPINGS"));
  16432. String ins, outs;
  16433. int i;
  16434. const ScopedLock sl (lock);
  16435. for (i = 0; i < remappedInputs.size(); ++i)
  16436. ins << remappedInputs.getUnchecked(i) << T(' ');
  16437. for (i = 0; i < remappedOutputs.size(); ++i)
  16438. outs << remappedOutputs.getUnchecked(i) << T(' ');
  16439. e->setAttribute (T("inputs"), ins.trimEnd());
  16440. e->setAttribute (T("outputs"), outs.trimEnd());
  16441. return e;
  16442. }
  16443. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  16444. {
  16445. if (e.hasTagName (T("MAPPINGS")))
  16446. {
  16447. const ScopedLock sl (lock);
  16448. clearAllMappings();
  16449. StringArray ins, outs;
  16450. ins.addTokens (e.getStringAttribute (T("inputs")), false);
  16451. outs.addTokens (e.getStringAttribute (T("outputs")), false);
  16452. int i;
  16453. for (i = 0; i < ins.size(); ++i)
  16454. remappedInputs.add (ins[i].getIntValue());
  16455. for (i = 0; i < outs.size(); ++i)
  16456. remappedOutputs.add (outs[i].getIntValue());
  16457. }
  16458. }
  16459. END_JUCE_NAMESPACE
  16460. /********* End of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  16461. /********* Start of inlined file: juce_IIRFilterAudioSource.cpp *********/
  16462. BEGIN_JUCE_NAMESPACE
  16463. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  16464. const bool deleteInputWhenDeleted_)
  16465. : input (inputSource),
  16466. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  16467. {
  16468. jassert (inputSource != 0);
  16469. for (int i = 2; --i >= 0;)
  16470. iirFilters.add (new IIRFilter());
  16471. }
  16472. IIRFilterAudioSource::~IIRFilterAudioSource()
  16473. {
  16474. if (deleteInputWhenDeleted)
  16475. delete input;
  16476. }
  16477. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  16478. {
  16479. for (int i = iirFilters.size(); --i >= 0;)
  16480. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  16481. }
  16482. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  16483. {
  16484. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16485. for (int i = iirFilters.size(); --i >= 0;)
  16486. iirFilters.getUnchecked(i)->reset();
  16487. }
  16488. void IIRFilterAudioSource::releaseResources()
  16489. {
  16490. input->releaseResources();
  16491. }
  16492. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  16493. {
  16494. input->getNextAudioBlock (bufferToFill);
  16495. const int numChannels = bufferToFill.buffer->getNumChannels();
  16496. while (numChannels > iirFilters.size())
  16497. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  16498. for (int i = 0; i < numChannels; ++i)
  16499. iirFilters.getUnchecked(i)
  16500. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  16501. bufferToFill.numSamples);
  16502. }
  16503. END_JUCE_NAMESPACE
  16504. /********* End of inlined file: juce_IIRFilterAudioSource.cpp *********/
  16505. /********* Start of inlined file: juce_MixerAudioSource.cpp *********/
  16506. BEGIN_JUCE_NAMESPACE
  16507. MixerAudioSource::MixerAudioSource()
  16508. : tempBuffer (2, 0),
  16509. currentSampleRate (0.0),
  16510. bufferSizeExpected (0)
  16511. {
  16512. }
  16513. MixerAudioSource::~MixerAudioSource()
  16514. {
  16515. removeAllInputs();
  16516. }
  16517. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  16518. {
  16519. if (input != 0 && ! inputs.contains (input))
  16520. {
  16521. lock.enter();
  16522. double localRate = currentSampleRate;
  16523. int localBufferSize = bufferSizeExpected;
  16524. lock.exit();
  16525. if (localRate != 0.0)
  16526. input->prepareToPlay (localBufferSize, localRate);
  16527. const ScopedLock sl (lock);
  16528. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  16529. inputs.add (input);
  16530. }
  16531. }
  16532. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  16533. {
  16534. if (input != 0)
  16535. {
  16536. lock.enter();
  16537. const int index = inputs.indexOf ((void*) input);
  16538. if (index >= 0)
  16539. {
  16540. inputsToDelete.shiftBits (index, 1);
  16541. inputs.remove (index);
  16542. }
  16543. lock.exit();
  16544. if (index >= 0)
  16545. {
  16546. input->releaseResources();
  16547. if (deleteInput)
  16548. delete input;
  16549. }
  16550. }
  16551. }
  16552. void MixerAudioSource::removeAllInputs()
  16553. {
  16554. lock.enter();
  16555. VoidArray inputsCopy (inputs);
  16556. BitArray inputsToDeleteCopy (inputsToDelete);
  16557. inputs.clear();
  16558. lock.exit();
  16559. for (int i = inputsCopy.size(); --i >= 0;)
  16560. if (inputsToDeleteCopy[i])
  16561. delete (AudioSource*) inputsCopy[i];
  16562. }
  16563. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  16564. {
  16565. tempBuffer.setSize (2, samplesPerBlockExpected);
  16566. const ScopedLock sl (lock);
  16567. currentSampleRate = sampleRate;
  16568. bufferSizeExpected = samplesPerBlockExpected;
  16569. for (int i = inputs.size(); --i >= 0;)
  16570. ((AudioSource*) inputs.getUnchecked(i))->prepareToPlay (samplesPerBlockExpected,
  16571. sampleRate);
  16572. }
  16573. void MixerAudioSource::releaseResources()
  16574. {
  16575. const ScopedLock sl (lock);
  16576. for (int i = inputs.size(); --i >= 0;)
  16577. ((AudioSource*) inputs.getUnchecked(i))->releaseResources();
  16578. tempBuffer.setSize (2, 0);
  16579. currentSampleRate = 0;
  16580. bufferSizeExpected = 0;
  16581. }
  16582. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16583. {
  16584. const ScopedLock sl (lock);
  16585. if (inputs.size() > 0)
  16586. {
  16587. ((AudioSource*) inputs.getUnchecked(0))->getNextAudioBlock (info);
  16588. if (inputs.size() > 1)
  16589. {
  16590. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  16591. info.buffer->getNumSamples());
  16592. AudioSourceChannelInfo info2;
  16593. info2.buffer = &tempBuffer;
  16594. info2.numSamples = info.numSamples;
  16595. info2.startSample = 0;
  16596. for (int i = 1; i < inputs.size(); ++i)
  16597. {
  16598. ((AudioSource*) inputs.getUnchecked(i))->getNextAudioBlock (info2);
  16599. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  16600. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  16601. }
  16602. }
  16603. }
  16604. else
  16605. {
  16606. info.clearActiveBufferRegion();
  16607. }
  16608. }
  16609. END_JUCE_NAMESPACE
  16610. /********* End of inlined file: juce_MixerAudioSource.cpp *********/
  16611. /********* Start of inlined file: juce_ResamplingAudioSource.cpp *********/
  16612. BEGIN_JUCE_NAMESPACE
  16613. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  16614. const bool deleteInputWhenDeleted_)
  16615. : input (inputSource),
  16616. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  16617. ratio (1.0),
  16618. lastRatio (1.0),
  16619. buffer (2, 0),
  16620. sampsInBuffer (0)
  16621. {
  16622. jassert (input != 0);
  16623. }
  16624. ResamplingAudioSource::~ResamplingAudioSource()
  16625. {
  16626. if (deleteInputWhenDeleted)
  16627. delete input;
  16628. }
  16629. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  16630. {
  16631. jassert (samplesInPerOutputSample > 0);
  16632. const ScopedLock sl (ratioLock);
  16633. ratio = jmax (0.0, samplesInPerOutputSample);
  16634. }
  16635. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  16636. double sampleRate)
  16637. {
  16638. const ScopedLock sl (ratioLock);
  16639. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16640. buffer.setSize (2, roundDoubleToInt (samplesPerBlockExpected * ratio) + 32);
  16641. buffer.clear();
  16642. sampsInBuffer = 0;
  16643. bufferPos = 0;
  16644. subSampleOffset = 0.0;
  16645. createLowPass (ratio);
  16646. resetFilters();
  16647. }
  16648. void ResamplingAudioSource::releaseResources()
  16649. {
  16650. input->releaseResources();
  16651. buffer.setSize (2, 0);
  16652. }
  16653. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16654. {
  16655. const ScopedLock sl (ratioLock);
  16656. if (lastRatio != ratio)
  16657. {
  16658. createLowPass (ratio);
  16659. lastRatio = ratio;
  16660. }
  16661. const int sampsNeeded = roundDoubleToInt (info.numSamples * ratio) + 2;
  16662. int bufferSize = buffer.getNumSamples();
  16663. if (bufferSize < sampsNeeded + 8)
  16664. {
  16665. bufferPos %= bufferSize;
  16666. bufferSize = sampsNeeded + 32;
  16667. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  16668. }
  16669. bufferPos %= bufferSize;
  16670. int endOfBufferPos = bufferPos + sampsInBuffer;
  16671. while (sampsNeeded > sampsInBuffer)
  16672. {
  16673. endOfBufferPos %= bufferSize;
  16674. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  16675. bufferSize - endOfBufferPos);
  16676. AudioSourceChannelInfo readInfo;
  16677. readInfo.buffer = &buffer;
  16678. readInfo.numSamples = numToDo;
  16679. readInfo.startSample = endOfBufferPos;
  16680. input->getNextAudioBlock (readInfo);
  16681. if (ratio > 1.0)
  16682. {
  16683. // for down-sampling, pre-apply the filter..
  16684. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  16685. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  16686. }
  16687. sampsInBuffer += numToDo;
  16688. endOfBufferPos += numToDo;
  16689. }
  16690. float* dl = info.buffer->getSampleData (0, info.startSample);
  16691. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  16692. const float* const bl = buffer.getSampleData (0, 0);
  16693. const float* const br = buffer.getSampleData (1, 0);
  16694. int nextPos = (bufferPos + 1) % bufferSize;
  16695. for (int m = info.numSamples; --m >= 0;)
  16696. {
  16697. const float alpha = (float) subSampleOffset;
  16698. const float invAlpha = 1.0f - alpha;
  16699. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  16700. if (dr != 0)
  16701. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  16702. subSampleOffset += ratio;
  16703. jassert (sampsInBuffer > 0);
  16704. while (subSampleOffset >= 1.0)
  16705. {
  16706. if (++bufferPos >= bufferSize)
  16707. bufferPos = 0;
  16708. --sampsInBuffer;
  16709. nextPos = (bufferPos + 1) % bufferSize;
  16710. subSampleOffset -= 1.0;
  16711. }
  16712. }
  16713. if (ratio < 1.0)
  16714. {
  16715. // for up-sampling, apply the filter after transposing..
  16716. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  16717. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  16718. }
  16719. jassert (sampsInBuffer >= 0);
  16720. }
  16721. void ResamplingAudioSource::createLowPass (const double ratio)
  16722. {
  16723. const double proportionalRate = (ratio > 1.0) ? 0.5 / ratio
  16724. : 0.5 * ratio;
  16725. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  16726. const double nSquared = n * n;
  16727. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  16728. setFilterCoefficients (c1,
  16729. c1 * 2.0f,
  16730. c1,
  16731. 1.0,
  16732. c1 * 2.0 * (1.0 - nSquared),
  16733. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  16734. }
  16735. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  16736. {
  16737. const double a = 1.0 / c4;
  16738. c1 *= a;
  16739. c2 *= a;
  16740. c3 *= a;
  16741. c5 *= a;
  16742. c6 *= a;
  16743. coefficients[0] = c1;
  16744. coefficients[1] = c2;
  16745. coefficients[2] = c3;
  16746. coefficients[3] = c4;
  16747. coefficients[4] = c5;
  16748. coefficients[5] = c6;
  16749. }
  16750. void ResamplingAudioSource::resetFilters()
  16751. {
  16752. zeromem (filterStates, sizeof (filterStates));
  16753. }
  16754. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  16755. {
  16756. while (--num >= 0)
  16757. {
  16758. const double in = *samples;
  16759. double out = coefficients[0] * in
  16760. + coefficients[1] * fs.x1
  16761. + coefficients[2] * fs.x2
  16762. - coefficients[4] * fs.y1
  16763. - coefficients[5] * fs.y2;
  16764. #if JUCE_INTEL
  16765. if (! (out < -1.0e-8 || out > 1.0e-8))
  16766. out = 0;
  16767. #endif
  16768. fs.x2 = fs.x1;
  16769. fs.x1 = in;
  16770. fs.y2 = fs.y1;
  16771. fs.y1 = out;
  16772. *samples++ = (float) out;
  16773. }
  16774. }
  16775. END_JUCE_NAMESPACE
  16776. /********* End of inlined file: juce_ResamplingAudioSource.cpp *********/
  16777. /********* Start of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  16778. BEGIN_JUCE_NAMESPACE
  16779. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  16780. : frequency (1000.0),
  16781. sampleRate (44100.0),
  16782. currentPhase (0.0),
  16783. phasePerSample (0.0),
  16784. amplitude (0.5f)
  16785. {
  16786. }
  16787. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  16788. {
  16789. }
  16790. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  16791. {
  16792. amplitude = newAmplitude;
  16793. }
  16794. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  16795. {
  16796. frequency = newFrequencyHz;
  16797. phasePerSample = 0.0;
  16798. }
  16799. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  16800. double sampleRate_)
  16801. {
  16802. currentPhase = 0.0;
  16803. phasePerSample = 0.0;
  16804. sampleRate = sampleRate_;
  16805. }
  16806. void ToneGeneratorAudioSource::releaseResources()
  16807. {
  16808. }
  16809. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16810. {
  16811. if (phasePerSample == 0.0)
  16812. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  16813. for (int i = 0; i < info.numSamples; ++i)
  16814. {
  16815. const float sample = amplitude * (float) sin (currentPhase);
  16816. currentPhase += phasePerSample;
  16817. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  16818. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  16819. }
  16820. }
  16821. END_JUCE_NAMESPACE
  16822. /********* End of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  16823. /********* Start of inlined file: juce_AudioDeviceManager.cpp *********/
  16824. BEGIN_JUCE_NAMESPACE
  16825. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  16826. : sampleRate (0),
  16827. bufferSize (0),
  16828. useDefaultInputChannels (true),
  16829. useDefaultOutputChannels (true)
  16830. {
  16831. }
  16832. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  16833. {
  16834. return outputDeviceName == other.outputDeviceName
  16835. && inputDeviceName == other.inputDeviceName
  16836. && sampleRate == other.sampleRate
  16837. && bufferSize == other.bufferSize
  16838. && inputChannels == other.inputChannels
  16839. && useDefaultInputChannels == other.useDefaultInputChannels
  16840. && outputChannels == other.outputChannels
  16841. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  16842. }
  16843. AudioDeviceManager::AudioDeviceManager()
  16844. : currentAudioDevice (0),
  16845. currentCallback (0),
  16846. numInputChansNeeded (0),
  16847. numOutputChansNeeded (2),
  16848. lastExplicitSettings (0),
  16849. listNeedsScanning (true),
  16850. useInputNames (false),
  16851. inputLevelMeasurementEnabled (false),
  16852. inputLevel (0),
  16853. testSound (0),
  16854. enabledMidiInputs (4),
  16855. midiCallbacks (4),
  16856. midiCallbackDevices (4),
  16857. defaultMidiOutput (0),
  16858. cpuUsageMs (0),
  16859. timeToCpuScale (0)
  16860. {
  16861. callbackHandler.owner = this;
  16862. }
  16863. AudioDeviceManager::~AudioDeviceManager()
  16864. {
  16865. deleteAndZero (currentAudioDevice);
  16866. deleteAndZero (defaultMidiOutput);
  16867. delete lastExplicitSettings;
  16868. delete testSound;
  16869. }
  16870. void AudioDeviceManager::createDeviceTypesIfNeeded()
  16871. {
  16872. if (availableDeviceTypes.size() == 0)
  16873. {
  16874. createAudioDeviceTypes (availableDeviceTypes);
  16875. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  16876. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  16877. if (availableDeviceTypes.size() > 0)
  16878. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  16879. }
  16880. }
  16881. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  16882. {
  16883. scanDevicesIfNeeded();
  16884. return availableDeviceTypes;
  16885. }
  16886. extern AudioIODeviceType* juce_createDefaultAudioIODeviceType();
  16887. #if JUCE_WIN32 && JUCE_ASIO
  16888. extern AudioIODeviceType* juce_createASIOAudioIODeviceType();
  16889. #endif
  16890. #if JUCE_WIN32 && JUCE_WDM_AUDIO
  16891. extern AudioIODeviceType* juce_createWDMAudioIODeviceType();
  16892. #endif
  16893. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  16894. {
  16895. AudioIODeviceType* const defaultDeviceType = juce_createDefaultAudioIODeviceType();
  16896. if (defaultDeviceType != 0)
  16897. list.add (defaultDeviceType);
  16898. #if JUCE_WIN32 && JUCE_ASIO
  16899. list.add (juce_createASIOAudioIODeviceType());
  16900. #endif
  16901. #if JUCE_WIN32 && JUCE_WDM_AUDIO
  16902. list.add (juce_createWDMAudioIODeviceType());
  16903. #endif
  16904. }
  16905. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  16906. const int numOutputChannelsNeeded,
  16907. const XmlElement* const e,
  16908. const bool selectDefaultDeviceOnFailure,
  16909. const String& preferredDefaultDeviceName)
  16910. {
  16911. scanDevicesIfNeeded();
  16912. numInputChansNeeded = numInputChannelsNeeded;
  16913. numOutputChansNeeded = numOutputChannelsNeeded;
  16914. if (e != 0 && e->hasTagName (T("DEVICESETUP")))
  16915. {
  16916. delete lastExplicitSettings;
  16917. lastExplicitSettings = new XmlElement (*e);
  16918. String error;
  16919. AudioDeviceSetup setup;
  16920. if (e->getStringAttribute (T("audioDeviceName")).isNotEmpty())
  16921. {
  16922. setup.inputDeviceName = setup.outputDeviceName
  16923. = e->getStringAttribute (T("audioDeviceName"));
  16924. }
  16925. else
  16926. {
  16927. setup.inputDeviceName = e->getStringAttribute (T("audioInputDeviceName"));
  16928. setup.outputDeviceName = e->getStringAttribute (T("audioOutputDeviceName"));
  16929. }
  16930. currentDeviceType = e->getStringAttribute (T("deviceType"));
  16931. if (currentDeviceType.isEmpty())
  16932. {
  16933. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  16934. if (type != 0)
  16935. currentDeviceType = type->getTypeName();
  16936. else if (availableDeviceTypes.size() > 0)
  16937. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  16938. }
  16939. setup.bufferSize = e->getIntAttribute (T("audioDeviceBufferSize"));
  16940. setup.sampleRate = e->getDoubleAttribute (T("audioDeviceRate"));
  16941. setup.inputChannels.parseString (e->getStringAttribute (T("audioDeviceInChans"), T("11")), 2);
  16942. setup.outputChannels.parseString (e->getStringAttribute (T("audioDeviceOutChans"), T("11")), 2);
  16943. setup.useDefaultInputChannels = ! e->hasAttribute (T("audioDeviceInChans"));
  16944. setup.useDefaultOutputChannels = ! e->hasAttribute (T("audioDeviceOutChans"));
  16945. error = setAudioDeviceSetup (setup, true);
  16946. midiInsFromXml.clear();
  16947. forEachXmlChildElementWithTagName (*e, c, T("MIDIINPUT"))
  16948. midiInsFromXml.add (c->getStringAttribute (T("name")));
  16949. const StringArray allMidiIns (MidiInput::getDevices());
  16950. for (int i = allMidiIns.size(); --i >= 0;)
  16951. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  16952. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  16953. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  16954. false, preferredDefaultDeviceName);
  16955. setDefaultMidiOutput (e->getStringAttribute (T("defaultMidiOutput")));
  16956. return error;
  16957. }
  16958. else
  16959. {
  16960. AudioDeviceSetup setup;
  16961. if (preferredDefaultDeviceName.isNotEmpty())
  16962. {
  16963. for (int j = availableDeviceTypes.size(); --j >= 0;)
  16964. {
  16965. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  16966. StringArray outs (type->getDeviceNames (false));
  16967. int i;
  16968. for (i = 0; i < outs.size(); ++i)
  16969. {
  16970. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  16971. {
  16972. setup.outputDeviceName = outs[i];
  16973. break;
  16974. }
  16975. }
  16976. StringArray ins (type->getDeviceNames (true));
  16977. for (i = 0; i < ins.size(); ++i)
  16978. {
  16979. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  16980. {
  16981. setup.inputDeviceName = ins[i];
  16982. break;
  16983. }
  16984. }
  16985. }
  16986. }
  16987. insertDefaultDeviceNames (setup);
  16988. return setAudioDeviceSetup (setup, false);
  16989. }
  16990. }
  16991. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  16992. {
  16993. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  16994. if (type != 0)
  16995. {
  16996. if (setup.outputDeviceName.isEmpty())
  16997. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  16998. if (setup.inputDeviceName.isEmpty())
  16999. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  17000. }
  17001. }
  17002. XmlElement* AudioDeviceManager::createStateXml() const
  17003. {
  17004. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  17005. }
  17006. void AudioDeviceManager::scanDevicesIfNeeded()
  17007. {
  17008. if (listNeedsScanning)
  17009. {
  17010. listNeedsScanning = false;
  17011. createDeviceTypesIfNeeded();
  17012. for (int i = availableDeviceTypes.size(); --i >= 0;)
  17013. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  17014. }
  17015. }
  17016. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  17017. {
  17018. scanDevicesIfNeeded();
  17019. for (int i = availableDeviceTypes.size(); --i >= 0;)
  17020. {
  17021. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  17022. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  17023. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  17024. {
  17025. return type;
  17026. }
  17027. }
  17028. return 0;
  17029. }
  17030. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  17031. {
  17032. setup = currentSetup;
  17033. }
  17034. void AudioDeviceManager::deleteCurrentDevice()
  17035. {
  17036. deleteAndZero (currentAudioDevice);
  17037. currentSetup.inputDeviceName = String::empty;
  17038. currentSetup.outputDeviceName = String::empty;
  17039. }
  17040. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  17041. const bool treatAsChosenDevice)
  17042. {
  17043. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  17044. {
  17045. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  17046. && currentDeviceType != type)
  17047. {
  17048. currentDeviceType = type;
  17049. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  17050. insertDefaultDeviceNames (s);
  17051. setAudioDeviceSetup (s, treatAsChosenDevice);
  17052. sendChangeMessage (this);
  17053. break;
  17054. }
  17055. }
  17056. }
  17057. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  17058. {
  17059. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  17060. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  17061. return availableDeviceTypes[i];
  17062. return availableDeviceTypes[0];
  17063. }
  17064. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  17065. const bool treatAsChosenDevice)
  17066. {
  17067. jassert (&newSetup != &currentSetup); // this will have no effect
  17068. if (newSetup == currentSetup && currentAudioDevice != 0)
  17069. return String::empty;
  17070. if (! (newSetup == currentSetup))
  17071. sendChangeMessage (this);
  17072. stopDevice();
  17073. String error;
  17074. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  17075. if (type == 0 || (newSetup.inputDeviceName.isEmpty()
  17076. && newSetup.outputDeviceName.isEmpty()))
  17077. {
  17078. deleteCurrentDevice();
  17079. if (treatAsChosenDevice)
  17080. updateXml();
  17081. return String::empty;
  17082. }
  17083. if (currentSetup.inputDeviceName != newSetup.inputDeviceName
  17084. || currentSetup.outputDeviceName != newSetup.outputDeviceName
  17085. || currentAudioDevice == 0)
  17086. {
  17087. deleteCurrentDevice();
  17088. scanDevicesIfNeeded();
  17089. if (newSetup.outputDeviceName.isNotEmpty()
  17090. && ! type->getDeviceNames (false).contains (newSetup.outputDeviceName))
  17091. {
  17092. return "No such device: " + newSetup.outputDeviceName;
  17093. }
  17094. if (newSetup.inputDeviceName.isNotEmpty()
  17095. && ! type->getDeviceNames (true).contains (newSetup.inputDeviceName))
  17096. {
  17097. return "No such device: " + newSetup.outputDeviceName;
  17098. }
  17099. currentAudioDevice = type->createDevice (newSetup.outputDeviceName,
  17100. newSetup.inputDeviceName);
  17101. if (currentAudioDevice == 0)
  17102. error = "Can't open device";
  17103. else
  17104. error = currentAudioDevice->getLastError();
  17105. if (error.isNotEmpty())
  17106. {
  17107. deleteCurrentDevice();
  17108. return error;
  17109. }
  17110. if (newSetup.useDefaultInputChannels)
  17111. {
  17112. inputChannels.clear();
  17113. inputChannels.setRange (0, numInputChansNeeded, true);
  17114. }
  17115. if (newSetup.useDefaultOutputChannels)
  17116. {
  17117. outputChannels.clear();
  17118. outputChannels.setRange (0, numOutputChansNeeded, true);
  17119. }
  17120. }
  17121. if (! newSetup.useDefaultInputChannels)
  17122. inputChannels = newSetup.inputChannels;
  17123. if (! newSetup.useDefaultOutputChannels)
  17124. outputChannels = newSetup.outputChannels;
  17125. currentSetup = newSetup;
  17126. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  17127. error = currentAudioDevice->open (inputChannels,
  17128. outputChannels,
  17129. currentSetup.sampleRate,
  17130. currentSetup.bufferSize);
  17131. if (error.isEmpty())
  17132. {
  17133. currentDeviceType = currentAudioDevice->getTypeName();
  17134. currentAudioDevice->start (&callbackHandler);
  17135. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  17136. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  17137. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  17138. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  17139. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  17140. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  17141. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  17142. if (treatAsChosenDevice)
  17143. updateXml();
  17144. }
  17145. else
  17146. {
  17147. deleteCurrentDevice();
  17148. }
  17149. return error;
  17150. }
  17151. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  17152. {
  17153. jassert (currentAudioDevice != 0);
  17154. if (rate > 0)
  17155. {
  17156. bool ok = false;
  17157. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  17158. {
  17159. const double sr = currentAudioDevice->getSampleRate (i);
  17160. if (sr == rate)
  17161. ok = true;
  17162. }
  17163. if (! ok)
  17164. rate = 0;
  17165. }
  17166. if (rate == 0)
  17167. {
  17168. double lowestAbove44 = 0.0;
  17169. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  17170. {
  17171. const double sr = currentAudioDevice->getSampleRate (i);
  17172. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  17173. lowestAbove44 = sr;
  17174. }
  17175. if (lowestAbove44 == 0.0)
  17176. rate = currentAudioDevice->getSampleRate (0);
  17177. else
  17178. rate = lowestAbove44;
  17179. }
  17180. return rate;
  17181. }
  17182. void AudioDeviceManager::stopDevice()
  17183. {
  17184. if (currentAudioDevice != 0)
  17185. currentAudioDevice->stop();
  17186. }
  17187. void AudioDeviceManager::closeAudioDevice()
  17188. {
  17189. stopDevice();
  17190. deleteAndZero (currentAudioDevice);
  17191. }
  17192. void AudioDeviceManager::restartLastAudioDevice()
  17193. {
  17194. if (currentAudioDevice == 0)
  17195. {
  17196. if (currentSetup.inputDeviceName.isEmpty()
  17197. && currentSetup.outputDeviceName.isEmpty())
  17198. {
  17199. // This method will only reload the last device that was running
  17200. // before closeAudioDevice() was called - you need to actually open
  17201. // one first, with setAudioDevice().
  17202. jassertfalse
  17203. return;
  17204. }
  17205. AudioDeviceSetup s (currentSetup);
  17206. setAudioDeviceSetup (s, false);
  17207. }
  17208. }
  17209. void AudioDeviceManager::updateXml()
  17210. {
  17211. delete lastExplicitSettings;
  17212. lastExplicitSettings = new XmlElement (T("DEVICESETUP"));
  17213. lastExplicitSettings->setAttribute (T("deviceType"), currentDeviceType);
  17214. lastExplicitSettings->setAttribute (T("audioOutputDeviceName"), currentSetup.outputDeviceName);
  17215. lastExplicitSettings->setAttribute (T("audioInputDeviceName"), currentSetup.inputDeviceName);
  17216. if (currentAudioDevice != 0)
  17217. {
  17218. lastExplicitSettings->setAttribute (T("audioDeviceRate"), currentAudioDevice->getCurrentSampleRate());
  17219. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  17220. lastExplicitSettings->setAttribute (T("audioDeviceBufferSize"), currentAudioDevice->getCurrentBufferSizeSamples());
  17221. if (! currentSetup.useDefaultInputChannels)
  17222. lastExplicitSettings->setAttribute (T("audioDeviceInChans"), currentSetup.inputChannels.toString (2));
  17223. if (! currentSetup.useDefaultOutputChannels)
  17224. lastExplicitSettings->setAttribute (T("audioDeviceOutChans"), currentSetup.outputChannels.toString (2));
  17225. }
  17226. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  17227. {
  17228. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  17229. m->setAttribute (T("name"), enabledMidiInputs[i]->getName());
  17230. lastExplicitSettings->addChildElement (m);
  17231. }
  17232. if (midiInsFromXml.size() > 0)
  17233. {
  17234. // Add any midi devices that have been enabled before, but which aren't currently
  17235. // open because the device has been disconnected.
  17236. const StringArray availableMidiDevices (MidiInput::getDevices());
  17237. for (int i = 0; i < midiInsFromXml.size(); ++i)
  17238. {
  17239. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  17240. {
  17241. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  17242. m->setAttribute (T("name"), midiInsFromXml[i]);
  17243. lastExplicitSettings->addChildElement (m);
  17244. }
  17245. }
  17246. }
  17247. if (defaultMidiOutputName.isNotEmpty())
  17248. lastExplicitSettings->setAttribute (T("defaultMidiOutput"), defaultMidiOutputName);
  17249. }
  17250. void AudioDeviceManager::setAudioCallback (AudioIODeviceCallback* newCallback)
  17251. {
  17252. if (newCallback != currentCallback)
  17253. {
  17254. AudioIODeviceCallback* lastCallback = currentCallback;
  17255. audioCallbackLock.enter();
  17256. currentCallback = 0;
  17257. audioCallbackLock.exit();
  17258. if (currentAudioDevice != 0)
  17259. {
  17260. if (lastCallback != 0)
  17261. lastCallback->audioDeviceStopped();
  17262. if (newCallback != 0)
  17263. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  17264. }
  17265. currentCallback = newCallback;
  17266. }
  17267. }
  17268. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  17269. int numInputChannels,
  17270. float** outputChannelData,
  17271. int numOutputChannels,
  17272. int numSamples)
  17273. {
  17274. const ScopedLock sl (audioCallbackLock);
  17275. if (inputLevelMeasurementEnabled)
  17276. {
  17277. for (int j = 0; j < numSamples; ++j)
  17278. {
  17279. float s = 0;
  17280. for (int i = 0; i < numInputChannels; ++i)
  17281. s += fabsf (inputChannelData[i][j]);
  17282. s /= numInputChannels;
  17283. const double decayFactor = 0.99992;
  17284. if (s > inputLevel)
  17285. inputLevel = s;
  17286. else if (inputLevel > 0.001f)
  17287. inputLevel *= decayFactor;
  17288. else
  17289. inputLevel = 0;
  17290. }
  17291. }
  17292. if (currentCallback != 0)
  17293. {
  17294. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  17295. currentCallback->audioDeviceIOCallback (inputChannelData,
  17296. numInputChannels,
  17297. outputChannelData,
  17298. numOutputChannels,
  17299. numSamples);
  17300. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  17301. const double filterAmount = 0.2;
  17302. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  17303. }
  17304. else
  17305. {
  17306. for (int i = 0; i < numOutputChannels; ++i)
  17307. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  17308. }
  17309. if (testSound != 0)
  17310. {
  17311. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  17312. const float* const src = testSound->getSampleData (0, testSoundPosition);
  17313. for (int i = 0; i < numOutputChannels; ++i)
  17314. for (int j = 0; j < numSamps; ++j)
  17315. outputChannelData [i][j] += src[j];
  17316. testSoundPosition += numSamps;
  17317. if (testSoundPosition >= testSound->getNumSamples())
  17318. {
  17319. delete testSound;
  17320. testSound = 0;
  17321. }
  17322. }
  17323. }
  17324. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  17325. {
  17326. cpuUsageMs = 0;
  17327. const double sampleRate = device->getCurrentSampleRate();
  17328. const int blockSize = device->getCurrentBufferSizeSamples();
  17329. if (sampleRate > 0.0 && blockSize > 0)
  17330. {
  17331. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  17332. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  17333. }
  17334. if (currentCallback != 0)
  17335. currentCallback->audioDeviceAboutToStart (device);
  17336. sendChangeMessage (this);
  17337. }
  17338. void AudioDeviceManager::audioDeviceStoppedInt()
  17339. {
  17340. cpuUsageMs = 0;
  17341. timeToCpuScale = 0;
  17342. sendChangeMessage (this);
  17343. if (currentCallback != 0)
  17344. currentCallback->audioDeviceStopped();
  17345. }
  17346. double AudioDeviceManager::getCpuUsage() const
  17347. {
  17348. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  17349. }
  17350. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  17351. const bool enabled)
  17352. {
  17353. if (enabled != isMidiInputEnabled (name))
  17354. {
  17355. if (enabled)
  17356. {
  17357. const int index = MidiInput::getDevices().indexOf (name);
  17358. if (index >= 0)
  17359. {
  17360. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  17361. if (min != 0)
  17362. {
  17363. enabledMidiInputs.add (min);
  17364. min->start();
  17365. }
  17366. }
  17367. }
  17368. else
  17369. {
  17370. for (int i = enabledMidiInputs.size(); --i >= 0;)
  17371. if (enabledMidiInputs[i]->getName() == name)
  17372. enabledMidiInputs.remove (i);
  17373. }
  17374. updateXml();
  17375. sendChangeMessage (this);
  17376. }
  17377. }
  17378. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  17379. {
  17380. for (int i = enabledMidiInputs.size(); --i >= 0;)
  17381. if (enabledMidiInputs[i]->getName() == name)
  17382. return true;
  17383. return false;
  17384. }
  17385. void AudioDeviceManager::addMidiInputCallback (const String& name,
  17386. MidiInputCallback* callback)
  17387. {
  17388. removeMidiInputCallback (name, callback);
  17389. if (name.isEmpty())
  17390. {
  17391. midiCallbacks.add (callback);
  17392. midiCallbackDevices.add (0);
  17393. }
  17394. else
  17395. {
  17396. for (int i = enabledMidiInputs.size(); --i >= 0;)
  17397. {
  17398. if (enabledMidiInputs[i]->getName() == name)
  17399. {
  17400. const ScopedLock sl (midiCallbackLock);
  17401. midiCallbacks.add (callback);
  17402. midiCallbackDevices.add (enabledMidiInputs[i]);
  17403. break;
  17404. }
  17405. }
  17406. }
  17407. }
  17408. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  17409. MidiInputCallback* /*callback*/)
  17410. {
  17411. const ScopedLock sl (midiCallbackLock);
  17412. for (int i = midiCallbacks.size(); --i >= 0;)
  17413. {
  17414. String devName;
  17415. if (midiCallbackDevices.getUnchecked(i) != 0)
  17416. devName = midiCallbackDevices.getUnchecked(i)->getName();
  17417. if (devName == name)
  17418. {
  17419. midiCallbacks.remove (i);
  17420. midiCallbackDevices.remove (i);
  17421. }
  17422. }
  17423. }
  17424. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  17425. const MidiMessage& message)
  17426. {
  17427. if (! message.isActiveSense())
  17428. {
  17429. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  17430. const ScopedLock sl (midiCallbackLock);
  17431. for (int i = midiCallbackDevices.size(); --i >= 0;)
  17432. {
  17433. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  17434. if (md == source || (md == 0 && isDefaultSource))
  17435. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  17436. }
  17437. }
  17438. }
  17439. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  17440. {
  17441. if (defaultMidiOutputName != deviceName)
  17442. {
  17443. deleteAndZero (defaultMidiOutput);
  17444. defaultMidiOutputName = deviceName;
  17445. if (deviceName.isNotEmpty())
  17446. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  17447. updateXml();
  17448. sendChangeMessage (this);
  17449. }
  17450. }
  17451. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  17452. int numInputChannels,
  17453. float** outputChannelData,
  17454. int numOutputChannels,
  17455. int numSamples)
  17456. {
  17457. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  17458. }
  17459. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  17460. {
  17461. owner->audioDeviceAboutToStartInt (device);
  17462. }
  17463. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  17464. {
  17465. owner->audioDeviceStoppedInt();
  17466. }
  17467. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  17468. {
  17469. owner->handleIncomingMidiMessageInt (source, message);
  17470. }
  17471. void AudioDeviceManager::playTestSound()
  17472. {
  17473. audioCallbackLock.enter();
  17474. AudioSampleBuffer* oldSound = testSound;
  17475. testSound = 0;
  17476. audioCallbackLock.exit();
  17477. delete oldSound;
  17478. testSoundPosition = 0;
  17479. if (currentAudioDevice != 0)
  17480. {
  17481. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  17482. const int soundLength = (int) sampleRate;
  17483. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  17484. float* samples = newSound->getSampleData (0);
  17485. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  17486. const float amplitude = 0.5f;
  17487. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  17488. for (int i = 0; i < soundLength; ++i)
  17489. samples[i] = amplitude * (float) sin (i * phasePerSample);
  17490. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  17491. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  17492. const ScopedLock sl (audioCallbackLock);
  17493. testSound = newSound;
  17494. }
  17495. }
  17496. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  17497. {
  17498. if (inputLevelMeasurementEnabled != enableMeasurement)
  17499. {
  17500. const ScopedLock sl (audioCallbackLock);
  17501. inputLevelMeasurementEnabled = enableMeasurement;
  17502. inputLevel = 0;
  17503. }
  17504. }
  17505. double AudioDeviceManager::getCurrentInputLevel() const
  17506. {
  17507. jassert (inputLevelMeasurementEnabled); // you need to call enableInputLevelMeasurement() before using this!
  17508. return inputLevel;
  17509. }
  17510. END_JUCE_NAMESPACE
  17511. /********* End of inlined file: juce_AudioDeviceManager.cpp *********/
  17512. /********* Start of inlined file: juce_AudioIODevice.cpp *********/
  17513. BEGIN_JUCE_NAMESPACE
  17514. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  17515. : name (deviceName),
  17516. typeName (typeName_)
  17517. {
  17518. }
  17519. AudioIODevice::~AudioIODevice()
  17520. {
  17521. }
  17522. bool AudioIODevice::hasControlPanel() const
  17523. {
  17524. return false;
  17525. }
  17526. bool AudioIODevice::showControlPanel()
  17527. {
  17528. jassertfalse // this should only be called for devices which return true from
  17529. // their hasControlPanel() method.
  17530. return false;
  17531. }
  17532. END_JUCE_NAMESPACE
  17533. /********* End of inlined file: juce_AudioIODevice.cpp *********/
  17534. /********* Start of inlined file: juce_AudioIODeviceType.cpp *********/
  17535. BEGIN_JUCE_NAMESPACE
  17536. AudioIODeviceType::AudioIODeviceType (const tchar* const name)
  17537. : typeName (name)
  17538. {
  17539. }
  17540. AudioIODeviceType::~AudioIODeviceType()
  17541. {
  17542. }
  17543. END_JUCE_NAMESPACE
  17544. /********* End of inlined file: juce_AudioIODeviceType.cpp *********/
  17545. /********* Start of inlined file: juce_MidiOutput.cpp *********/
  17546. BEGIN_JUCE_NAMESPACE
  17547. MidiOutput::MidiOutput() throw()
  17548. : Thread ("midi out"),
  17549. internal (0),
  17550. firstMessage (0)
  17551. {
  17552. }
  17553. MidiOutput::PendingMessage::PendingMessage (const uint8* const data,
  17554. const int len,
  17555. const double sampleNumber) throw()
  17556. : message (data, len, sampleNumber)
  17557. {
  17558. }
  17559. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  17560. const double millisecondCounterToStartAt,
  17561. double samplesPerSecondForBuffer) throw()
  17562. {
  17563. // You've got to call startBackgroundThread() for this to actually work..
  17564. jassert (isThreadRunning());
  17565. // this needs to be a value in the future - RTFM for this method!
  17566. jassert (millisecondCounterToStartAt > 0);
  17567. samplesPerSecondForBuffer *= 0.001;
  17568. MidiBuffer::Iterator i (buffer);
  17569. const uint8* data;
  17570. int len, time;
  17571. while (i.getNextEvent (data, len, time))
  17572. {
  17573. const double eventTime = millisecondCounterToStartAt + samplesPerSecondForBuffer * time;
  17574. PendingMessage* const m
  17575. = new PendingMessage (data, len, eventTime);
  17576. const ScopedLock sl (lock);
  17577. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  17578. {
  17579. m->next = firstMessage;
  17580. firstMessage = m;
  17581. }
  17582. else
  17583. {
  17584. PendingMessage* mm = firstMessage;
  17585. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  17586. mm = mm->next;
  17587. m->next = mm->next;
  17588. mm->next = m;
  17589. }
  17590. }
  17591. notify();
  17592. }
  17593. void MidiOutput::clearAllPendingMessages() throw()
  17594. {
  17595. const ScopedLock sl (lock);
  17596. while (firstMessage != 0)
  17597. {
  17598. PendingMessage* const m = firstMessage;
  17599. firstMessage = firstMessage->next;
  17600. delete m;
  17601. }
  17602. }
  17603. void MidiOutput::startBackgroundThread() throw()
  17604. {
  17605. startThread (9);
  17606. }
  17607. void MidiOutput::stopBackgroundThread() throw()
  17608. {
  17609. stopThread (5000);
  17610. }
  17611. void MidiOutput::run()
  17612. {
  17613. while (! threadShouldExit())
  17614. {
  17615. uint32 now = Time::getMillisecondCounter();
  17616. uint32 eventTime = 0;
  17617. uint32 timeToWait = 500;
  17618. lock.enter();
  17619. PendingMessage* message = firstMessage;
  17620. if (message != 0)
  17621. {
  17622. eventTime = roundDoubleToInt (message->message.getTimeStamp());
  17623. if (eventTime > now + 20)
  17624. {
  17625. timeToWait = jmax (10, eventTime - now - 100);
  17626. message = 0;
  17627. }
  17628. else
  17629. {
  17630. firstMessage = message->next;
  17631. }
  17632. }
  17633. lock.exit();
  17634. if (message != 0)
  17635. {
  17636. if (eventTime > now)
  17637. {
  17638. Time::waitForMillisecondCounter (eventTime);
  17639. if (threadShouldExit())
  17640. break;
  17641. }
  17642. if (eventTime > now - 200)
  17643. sendMessageNow (message->message);
  17644. delete message;
  17645. }
  17646. else
  17647. {
  17648. jassert (timeToWait < 1000 * 30);
  17649. wait (timeToWait);
  17650. }
  17651. }
  17652. clearAllPendingMessages();
  17653. }
  17654. END_JUCE_NAMESPACE
  17655. /********* End of inlined file: juce_MidiOutput.cpp *********/
  17656. /********* Start of inlined file: juce_AudioDataConverters.cpp *********/
  17657. BEGIN_JUCE_NAMESPACE
  17658. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17659. {
  17660. const double maxVal = (double) 0x7fff;
  17661. char* intData = (char*) dest;
  17662. for (int i = 0; i < numSamples; ++i)
  17663. {
  17664. *(uint16*)intData = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17665. intData += destBytesPerSample;
  17666. }
  17667. }
  17668. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17669. {
  17670. const double maxVal = (double) 0x7fff;
  17671. char* intData = (char*) dest;
  17672. for (int i = 0; i < numSamples; ++i)
  17673. {
  17674. *(uint16*)intData = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17675. intData += destBytesPerSample;
  17676. }
  17677. }
  17678. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17679. {
  17680. const double maxVal = (double) 0x7fffff;
  17681. char* intData = (char*) dest;
  17682. for (int i = 0; i < numSamples; ++i)
  17683. {
  17684. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  17685. intData += destBytesPerSample;
  17686. }
  17687. }
  17688. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17689. {
  17690. const double maxVal = (double) 0x7fffff;
  17691. char* intData = (char*) dest;
  17692. for (int i = 0; i < numSamples; ++i)
  17693. {
  17694. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  17695. intData += destBytesPerSample;
  17696. }
  17697. }
  17698. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17699. {
  17700. const double maxVal = (double) 0x7fffffff;
  17701. char* intData = (char*) dest;
  17702. for (int i = 0; i < numSamples; ++i)
  17703. {
  17704. *(uint32*)intData = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17705. intData += destBytesPerSample;
  17706. }
  17707. }
  17708. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17709. {
  17710. const double maxVal = (double) 0x7fffffff;
  17711. char* intData = (char*) dest;
  17712. for (int i = 0; i < numSamples; ++i)
  17713. {
  17714. *(uint32*)intData = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17715. intData += destBytesPerSample;
  17716. }
  17717. }
  17718. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17719. {
  17720. char* d = (char*) dest;
  17721. for (int i = 0; i < numSamples; ++i)
  17722. {
  17723. *(float*)d = source[i];
  17724. #if JUCE_BIG_ENDIAN
  17725. *(uint32*)d = swapByteOrder (*(uint32*)d);
  17726. #endif
  17727. d += destBytesPerSample;
  17728. }
  17729. }
  17730. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17731. {
  17732. char* d = (char*) dest;
  17733. for (int i = 0; i < numSamples; ++i)
  17734. {
  17735. *(float*)d = source[i];
  17736. #if JUCE_LITTLE_ENDIAN
  17737. *(uint32*)d = swapByteOrder (*(uint32*)d);
  17738. #endif
  17739. d += destBytesPerSample;
  17740. }
  17741. }
  17742. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17743. {
  17744. const float scale = 1.0f / 0x7fff;
  17745. const char* intData = (const char*) source;
  17746. for (int i = 0; i < numSamples; ++i)
  17747. {
  17748. dest[i] = scale * (short) swapIfBigEndian (*(uint16*)intData);
  17749. intData += srcBytesPerSample;
  17750. }
  17751. }
  17752. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17753. {
  17754. const float scale = 1.0f / 0x7fff;
  17755. const char* intData = (const char*) source;
  17756. for (int i = 0; i < numSamples; ++i)
  17757. {
  17758. dest[i] = scale * (short) swapIfLittleEndian (*(uint16*)intData);
  17759. intData += srcBytesPerSample;
  17760. }
  17761. }
  17762. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17763. {
  17764. const float scale = 1.0f / 0x7fffff;
  17765. const char* intData = (const char*) source;
  17766. for (int i = 0; i < numSamples; ++i)
  17767. {
  17768. dest[i] = scale * (short) littleEndian24Bit (intData);
  17769. intData += srcBytesPerSample;
  17770. }
  17771. }
  17772. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17773. {
  17774. const float scale = 1.0f / 0x7fffff;
  17775. const char* intData = (const char*) source;
  17776. for (int i = 0; i < numSamples; ++i)
  17777. {
  17778. dest[i] = scale * (short) bigEndian24Bit (intData);
  17779. intData += srcBytesPerSample;
  17780. }
  17781. }
  17782. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17783. {
  17784. const float scale = 1.0f / 0x7fffffff;
  17785. const char* intData = (const char*) source;
  17786. for (int i = 0; i < numSamples; ++i)
  17787. {
  17788. dest[i] = scale * (int) swapIfBigEndian (*(uint32*) intData);
  17789. intData += srcBytesPerSample;
  17790. }
  17791. }
  17792. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17793. {
  17794. const float scale = 1.0f / 0x7fffffff;
  17795. const char* intData = (const char*) source;
  17796. for (int i = 0; i < numSamples; ++i)
  17797. {
  17798. dest[i] = scale * (int) (swapIfLittleEndian (*(uint32*) intData));
  17799. intData += srcBytesPerSample;
  17800. }
  17801. }
  17802. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17803. {
  17804. const char* s = (const char*) source;
  17805. for (int i = 0; i < numSamples; ++i)
  17806. {
  17807. dest[i] = *(float*)s;
  17808. #if JUCE_BIG_ENDIAN
  17809. uint32* const d = (uint32*) (dest + i);
  17810. *d = swapByteOrder (*d);
  17811. #endif
  17812. s += srcBytesPerSample;
  17813. }
  17814. }
  17815. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17816. {
  17817. const char* s = (const char*) source;
  17818. for (int i = 0; i < numSamples; ++i)
  17819. {
  17820. dest[i] = *(float*)s;
  17821. #if JUCE_LITTLE_ENDIAN
  17822. uint32* const d = (uint32*) (dest + i);
  17823. *d = swapByteOrder (*d);
  17824. #endif
  17825. s += srcBytesPerSample;
  17826. }
  17827. }
  17828. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  17829. const float* const source,
  17830. void* const dest,
  17831. const int numSamples)
  17832. {
  17833. switch (destFormat)
  17834. {
  17835. case int16LE:
  17836. convertFloatToInt16LE (source, dest, numSamples);
  17837. break;
  17838. case int16BE:
  17839. convertFloatToInt16BE (source, dest, numSamples);
  17840. break;
  17841. case int24LE:
  17842. convertFloatToInt24LE (source, dest, numSamples);
  17843. break;
  17844. case int24BE:
  17845. convertFloatToInt24BE (source, dest, numSamples);
  17846. break;
  17847. case int32LE:
  17848. convertFloatToInt32LE (source, dest, numSamples);
  17849. break;
  17850. case int32BE:
  17851. convertFloatToInt32BE (source, dest, numSamples);
  17852. break;
  17853. case float32LE:
  17854. convertFloatToFloat32LE (source, dest, numSamples);
  17855. break;
  17856. case float32BE:
  17857. convertFloatToFloat32BE (source, dest, numSamples);
  17858. break;
  17859. default:
  17860. jassertfalse
  17861. break;
  17862. }
  17863. }
  17864. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  17865. const void* const source,
  17866. float* const dest,
  17867. const int numSamples)
  17868. {
  17869. switch (sourceFormat)
  17870. {
  17871. case int16LE:
  17872. convertInt16LEToFloat (source, dest, numSamples);
  17873. break;
  17874. case int16BE:
  17875. convertInt16BEToFloat (source, dest, numSamples);
  17876. break;
  17877. case int24LE:
  17878. convertInt24LEToFloat (source, dest, numSamples);
  17879. break;
  17880. case int24BE:
  17881. convertInt24BEToFloat (source, dest, numSamples);
  17882. break;
  17883. case int32LE:
  17884. convertInt32LEToFloat (source, dest, numSamples);
  17885. break;
  17886. case int32BE:
  17887. convertInt32BEToFloat (source, dest, numSamples);
  17888. break;
  17889. case float32LE:
  17890. convertFloat32LEToFloat (source, dest, numSamples);
  17891. break;
  17892. case float32BE:
  17893. convertFloat32BEToFloat (source, dest, numSamples);
  17894. break;
  17895. default:
  17896. jassertfalse
  17897. break;
  17898. }
  17899. }
  17900. void AudioDataConverters::interleaveSamples (const float** const source,
  17901. float* const dest,
  17902. const int numSamples,
  17903. const int numChannels)
  17904. {
  17905. for (int chan = 0; chan < numChannels; ++chan)
  17906. {
  17907. int i = chan;
  17908. const float* src = source [chan];
  17909. for (int j = 0; j < numSamples; ++j)
  17910. {
  17911. dest [i] = src [j];
  17912. i += numChannels;
  17913. }
  17914. }
  17915. }
  17916. void AudioDataConverters::deinterleaveSamples (const float* const source,
  17917. float** const dest,
  17918. const int numSamples,
  17919. const int numChannels)
  17920. {
  17921. for (int chan = 0; chan < numChannels; ++chan)
  17922. {
  17923. int i = chan;
  17924. float* dst = dest [chan];
  17925. for (int j = 0; j < numSamples; ++j)
  17926. {
  17927. dst [j] = source [i];
  17928. i += numChannels;
  17929. }
  17930. }
  17931. }
  17932. END_JUCE_NAMESPACE
  17933. /********* End of inlined file: juce_AudioDataConverters.cpp *********/
  17934. /********* Start of inlined file: juce_AudioSampleBuffer.cpp *********/
  17935. BEGIN_JUCE_NAMESPACE
  17936. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  17937. const int numSamples) throw()
  17938. : numChannels (numChannels_),
  17939. size (numSamples)
  17940. {
  17941. jassert (numSamples >= 0);
  17942. jassert (numChannels_ > 0 && numChannels_ <= maxNumAudioSampleBufferChannels);
  17943. allocatedBytes = numChannels * numSamples * sizeof (float) + 32;
  17944. allocatedData = (float*) juce_malloc (allocatedBytes);
  17945. float* chan = allocatedData;
  17946. for (int i = 0; i < numChannels_; ++i)
  17947. {
  17948. channels[i] = chan;
  17949. chan += numSamples;
  17950. }
  17951. channels [numChannels_] = 0;
  17952. }
  17953. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  17954. const int numChannels_,
  17955. const int numSamples) throw()
  17956. : numChannels (numChannels_),
  17957. size (numSamples),
  17958. allocatedBytes (0),
  17959. allocatedData (0)
  17960. {
  17961. jassert (((unsigned int) numChannels_) <= (unsigned int) maxNumAudioSampleBufferChannels);
  17962. for (int i = 0; i < numChannels_; ++i)
  17963. {
  17964. // you have to pass in the same number of valid pointers as numChannels
  17965. jassert (dataToReferTo[i] != 0);
  17966. channels[i] = dataToReferTo[i];
  17967. }
  17968. channels [numChannels_] = 0;
  17969. }
  17970. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  17971. const int numChannels_,
  17972. const int numSamples) throw()
  17973. {
  17974. jassert (((unsigned int) numChannels_) <= (unsigned int) maxNumAudioSampleBufferChannels);
  17975. juce_free (allocatedData);
  17976. allocatedData = 0;
  17977. allocatedBytes = 0;
  17978. numChannels = numChannels_;
  17979. size = numSamples;
  17980. for (int i = 0; i < numChannels_; ++i)
  17981. {
  17982. // you have to pass in the same number of valid pointers as numChannels
  17983. jassert (dataToReferTo[i] != 0);
  17984. channels[i] = dataToReferTo[i];
  17985. }
  17986. channels [numChannels_] = 0;
  17987. }
  17988. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  17989. : numChannels (other.numChannels),
  17990. size (other.size)
  17991. {
  17992. if (other.allocatedData != 0)
  17993. {
  17994. allocatedBytes = numChannels * size * sizeof (float) + 32;
  17995. allocatedData = (float*) juce_malloc (allocatedBytes);
  17996. memcpy (allocatedData, other.allocatedData, allocatedBytes);
  17997. float* chan = allocatedData;
  17998. for (int i = 0; i < numChannels; ++i)
  17999. {
  18000. channels[i] = chan;
  18001. chan += size;
  18002. }
  18003. channels [numChannels] = 0;
  18004. }
  18005. else
  18006. {
  18007. allocatedData = 0;
  18008. allocatedBytes = 0;
  18009. memcpy (channels, other.channels, sizeof (channels));
  18010. }
  18011. }
  18012. const AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  18013. {
  18014. if (this != &other)
  18015. {
  18016. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  18017. const int numBytes = size * sizeof (float);
  18018. for (int i = 0; i < numChannels; ++i)
  18019. memcpy (channels[i], other.channels[i], numBytes);
  18020. }
  18021. return *this;
  18022. }
  18023. AudioSampleBuffer::~AudioSampleBuffer() throw()
  18024. {
  18025. juce_free (allocatedData);
  18026. }
  18027. float* AudioSampleBuffer::getSampleData (const int channelNumber,
  18028. const int sampleOffset) const throw()
  18029. {
  18030. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  18031. jassert (((unsigned int) sampleOffset) < (unsigned int) size);
  18032. return channels [channelNumber] + sampleOffset;
  18033. }
  18034. void AudioSampleBuffer::setSize (const int newNumChannels,
  18035. const int newNumSamples,
  18036. const bool keepExistingContent,
  18037. const bool clearExtraSpace,
  18038. const bool avoidReallocating) throw()
  18039. {
  18040. jassert (newNumChannels > 0 && newNumChannels <= maxNumAudioSampleBufferChannels);
  18041. if (newNumSamples != size || newNumChannels != numChannels)
  18042. {
  18043. const int newTotalBytes = newNumChannels * newNumSamples * sizeof (float) + 32;
  18044. if (keepExistingContent)
  18045. {
  18046. float* const newData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  18047. : (float*) juce_malloc (newTotalBytes);
  18048. const int sizeToCopy = sizeof (float) * jmin (newNumSamples, size);
  18049. for (int i = jmin (newNumChannels, numChannels); --i >= 0;)
  18050. {
  18051. memcpy (newData + i * newNumSamples,
  18052. channels[i],
  18053. sizeToCopy);
  18054. }
  18055. juce_free (allocatedData);
  18056. allocatedData = newData;
  18057. allocatedBytes = newTotalBytes;
  18058. }
  18059. else
  18060. {
  18061. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  18062. {
  18063. if (clearExtraSpace)
  18064. zeromem (allocatedData, newTotalBytes);
  18065. }
  18066. else
  18067. {
  18068. juce_free (allocatedData);
  18069. allocatedData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  18070. : (float*) juce_malloc (newTotalBytes);
  18071. allocatedBytes = newTotalBytes;
  18072. }
  18073. }
  18074. size = newNumSamples;
  18075. numChannels = newNumChannels;
  18076. float* chan = allocatedData;
  18077. for (int i = 0; i < newNumChannels; ++i)
  18078. {
  18079. channels[i] = chan;
  18080. chan += size;
  18081. }
  18082. channels [newNumChannels] = 0;
  18083. }
  18084. }
  18085. void AudioSampleBuffer::clear() throw()
  18086. {
  18087. for (int i = 0; i < numChannels; ++i)
  18088. zeromem (channels[i], size * sizeof (float));
  18089. }
  18090. void AudioSampleBuffer::clear (const int startSample,
  18091. const int numSamples) throw()
  18092. {
  18093. jassert (startSample >= 0 && startSample + numSamples <= size);
  18094. for (int i = 0; i < numChannels; ++i)
  18095. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  18096. }
  18097. void AudioSampleBuffer::clear (const int channel,
  18098. const int startSample,
  18099. const int numSamples) throw()
  18100. {
  18101. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18102. jassert (startSample >= 0 && startSample + numSamples <= size);
  18103. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  18104. }
  18105. void AudioSampleBuffer::applyGain (const int channel,
  18106. const int startSample,
  18107. int numSamples,
  18108. const float gain) throw()
  18109. {
  18110. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18111. jassert (startSample >= 0 && startSample + numSamples <= size);
  18112. if (gain != 1.0f)
  18113. {
  18114. float* d = channels [channel] + startSample;
  18115. if (gain == 0.0f)
  18116. {
  18117. zeromem (d, sizeof (float) * numSamples);
  18118. }
  18119. else
  18120. {
  18121. while (--numSamples >= 0)
  18122. *d++ *= gain;
  18123. }
  18124. }
  18125. }
  18126. void AudioSampleBuffer::applyGainRamp (const int channel,
  18127. const int startSample,
  18128. int numSamples,
  18129. float startGain,
  18130. float endGain) throw()
  18131. {
  18132. if (startGain == endGain)
  18133. {
  18134. applyGain (channel, startSample, numSamples, startGain);
  18135. }
  18136. else
  18137. {
  18138. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18139. jassert (startSample >= 0 && startSample + numSamples <= size);
  18140. const float increment = (endGain - startGain) / numSamples;
  18141. float* d = channels [channel] + startSample;
  18142. while (--numSamples >= 0)
  18143. {
  18144. *d++ *= startGain;
  18145. startGain += increment;
  18146. }
  18147. }
  18148. }
  18149. void AudioSampleBuffer::applyGain (const int startSample,
  18150. const int numSamples,
  18151. const float gain) throw()
  18152. {
  18153. for (int i = 0; i < numChannels; ++i)
  18154. applyGain (i, startSample, numSamples, gain);
  18155. }
  18156. void AudioSampleBuffer::addFrom (const int destChannel,
  18157. const int destStartSample,
  18158. const AudioSampleBuffer& source,
  18159. const int sourceChannel,
  18160. const int sourceStartSample,
  18161. int numSamples,
  18162. const float gain) throw()
  18163. {
  18164. jassert (&source != this || sourceChannel != destChannel);
  18165. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18166. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18167. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  18168. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  18169. if (gain != 0.0f && numSamples > 0)
  18170. {
  18171. float* d = channels [destChannel] + destStartSample;
  18172. const float* s = source.channels [sourceChannel] + sourceStartSample;
  18173. if (gain != 1.0f)
  18174. {
  18175. while (--numSamples >= 0)
  18176. *d++ += gain * *s++;
  18177. }
  18178. else
  18179. {
  18180. while (--numSamples >= 0)
  18181. *d++ += *s++;
  18182. }
  18183. }
  18184. }
  18185. void AudioSampleBuffer::addFrom (const int destChannel,
  18186. const int destStartSample,
  18187. const float* source,
  18188. int numSamples,
  18189. const float gain) throw()
  18190. {
  18191. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18192. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18193. jassert (source != 0);
  18194. if (gain != 0.0f && numSamples > 0)
  18195. {
  18196. float* d = channels [destChannel] + destStartSample;
  18197. if (gain != 1.0f)
  18198. {
  18199. while (--numSamples >= 0)
  18200. *d++ += gain * *source++;
  18201. }
  18202. else
  18203. {
  18204. while (--numSamples >= 0)
  18205. *d++ += *source++;
  18206. }
  18207. }
  18208. }
  18209. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  18210. const int destStartSample,
  18211. const float* source,
  18212. int numSamples,
  18213. float startGain,
  18214. const float endGain) throw()
  18215. {
  18216. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18217. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18218. jassert (source != 0);
  18219. if (startGain == endGain)
  18220. {
  18221. addFrom (destChannel,
  18222. destStartSample,
  18223. source,
  18224. numSamples,
  18225. startGain);
  18226. }
  18227. else
  18228. {
  18229. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  18230. {
  18231. const float increment = (endGain - startGain) / numSamples;
  18232. float* d = channels [destChannel] + destStartSample;
  18233. while (--numSamples >= 0)
  18234. {
  18235. *d++ += startGain * *source++;
  18236. startGain += increment;
  18237. }
  18238. }
  18239. }
  18240. }
  18241. void AudioSampleBuffer::copyFrom (const int destChannel,
  18242. const int destStartSample,
  18243. const AudioSampleBuffer& source,
  18244. const int sourceChannel,
  18245. const int sourceStartSample,
  18246. int numSamples) throw()
  18247. {
  18248. jassert (&source != this || sourceChannel != destChannel);
  18249. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18250. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18251. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  18252. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  18253. if (numSamples > 0)
  18254. {
  18255. memcpy (channels [destChannel] + destStartSample,
  18256. source.channels [sourceChannel] + sourceStartSample,
  18257. sizeof (float) * numSamples);
  18258. }
  18259. }
  18260. void AudioSampleBuffer::copyFrom (const int destChannel,
  18261. const int destStartSample,
  18262. const float* source,
  18263. int numSamples) throw()
  18264. {
  18265. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18266. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18267. jassert (source != 0);
  18268. if (numSamples > 0)
  18269. {
  18270. memcpy (channels [destChannel] + destStartSample,
  18271. source,
  18272. sizeof (float) * numSamples);
  18273. }
  18274. }
  18275. void AudioSampleBuffer::findMinMax (const int channel,
  18276. const int startSample,
  18277. int numSamples,
  18278. float& minVal,
  18279. float& maxVal) const throw()
  18280. {
  18281. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18282. jassert (startSample >= 0 && startSample + numSamples <= size);
  18283. if (numSamples <= 0)
  18284. {
  18285. minVal = 0.0f;
  18286. maxVal = 0.0f;
  18287. }
  18288. else
  18289. {
  18290. const float* d = channels [channel] + startSample;
  18291. float mn = *d++;
  18292. float mx = mn;
  18293. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  18294. {
  18295. const float samp = *d++;
  18296. if (samp > mx)
  18297. mx = samp;
  18298. if (samp < mn)
  18299. mn = samp;
  18300. }
  18301. maxVal = mx;
  18302. minVal = mn;
  18303. }
  18304. }
  18305. float AudioSampleBuffer::getMagnitude (const int channel,
  18306. const int startSample,
  18307. const int numSamples) const throw()
  18308. {
  18309. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18310. jassert (startSample >= 0 && startSample + numSamples <= size);
  18311. float mn, mx;
  18312. findMinMax (channel, startSample, numSamples, mn, mx);
  18313. return jmax (mn, -mn, mx, -mx);
  18314. }
  18315. float AudioSampleBuffer::getMagnitude (const int startSample,
  18316. const int numSamples) const throw()
  18317. {
  18318. float mag = 0.0f;
  18319. for (int i = 0; i < numChannels; ++i)
  18320. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  18321. return mag;
  18322. }
  18323. float AudioSampleBuffer::getRMSLevel (const int channel,
  18324. const int startSample,
  18325. const int numSamples) const throw()
  18326. {
  18327. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18328. jassert (startSample >= 0 && startSample + numSamples <= size);
  18329. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  18330. return 0.0f;
  18331. const float* const data = channels [channel] + startSample;
  18332. double sum = 0.0;
  18333. for (int i = 0; i < numSamples; ++i)
  18334. {
  18335. const float sample = data [i];
  18336. sum += sample * sample;
  18337. }
  18338. return (float) sqrt (sum / numSamples);
  18339. }
  18340. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  18341. const int startSample,
  18342. const int numSamples,
  18343. const int readerStartSample,
  18344. const bool useLeftChan,
  18345. const bool useRightChan) throw()
  18346. {
  18347. jassert (reader != 0);
  18348. jassert (startSample >= 0 && startSample + numSamples <= size);
  18349. if (numSamples > 0)
  18350. {
  18351. int* chans[3];
  18352. if (useLeftChan == useRightChan)
  18353. {
  18354. chans[0] = (int*) getSampleData (0, startSample);
  18355. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  18356. }
  18357. else if (useLeftChan || (reader->numChannels == 1))
  18358. {
  18359. chans[0] = (int*) getSampleData (0, startSample);
  18360. chans[1] = 0;
  18361. }
  18362. else if (useRightChan)
  18363. {
  18364. chans[0] = 0;
  18365. chans[1] = (int*) getSampleData (0, startSample);
  18366. }
  18367. chans[2] = 0;
  18368. reader->read (chans, readerStartSample, numSamples);
  18369. if (! reader->usesFloatingPointData)
  18370. {
  18371. for (int j = 0; j < 2; ++j)
  18372. {
  18373. float* const d = (float*) (chans[j]);
  18374. if (d != 0)
  18375. {
  18376. const float multiplier = 1.0f / 0x7fffffff;
  18377. for (int i = 0; i < numSamples; ++i)
  18378. d[i] = *(int*)(d + i) * multiplier;
  18379. }
  18380. }
  18381. }
  18382. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  18383. {
  18384. // if this is a stereo buffer and the source was mono, dupe the first channel..
  18385. memcpy (getSampleData (1, startSample),
  18386. getSampleData (0, startSample),
  18387. sizeof (float) * numSamples);
  18388. }
  18389. }
  18390. }
  18391. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  18392. const int startSample,
  18393. const int numSamples) const throw()
  18394. {
  18395. jassert (startSample >= 0 && startSample + numSamples <= size);
  18396. if (numSamples > 0)
  18397. {
  18398. int* chans [3];
  18399. if (writer->isFloatingPoint())
  18400. {
  18401. chans[0] = (int*) getSampleData (0, startSample);
  18402. if (numChannels > 1)
  18403. chans[1] = (int*) getSampleData (1, startSample);
  18404. else
  18405. chans[1] = 0;
  18406. chans[2] = 0;
  18407. writer->write ((const int**) chans, numSamples);
  18408. }
  18409. else
  18410. {
  18411. chans[0] = (int*) juce_malloc (sizeof (int) * numSamples * 2);
  18412. if (numChannels > 1)
  18413. chans[1] = chans[0] + numSamples;
  18414. else
  18415. chans[1] = 0;
  18416. chans[2] = 0;
  18417. for (int j = 0; j < 2; ++j)
  18418. {
  18419. int* const dest = chans[j];
  18420. if (dest != 0)
  18421. {
  18422. const float* const src = channels [j] + startSample;
  18423. for (int i = 0; i < numSamples; ++i)
  18424. {
  18425. const double samp = src[i];
  18426. if (samp <= -1.0)
  18427. dest[i] = INT_MIN;
  18428. else if (samp >= 1.0)
  18429. dest[i] = INT_MAX;
  18430. else
  18431. dest[i] = roundDoubleToInt (INT_MAX * samp);
  18432. }
  18433. }
  18434. }
  18435. writer->write ((const int**) chans, numSamples);
  18436. juce_free (chans[0]);
  18437. }
  18438. }
  18439. }
  18440. END_JUCE_NAMESPACE
  18441. /********* End of inlined file: juce_AudioSampleBuffer.cpp *********/
  18442. /********* Start of inlined file: juce_IIRFilter.cpp *********/
  18443. BEGIN_JUCE_NAMESPACE
  18444. IIRFilter::IIRFilter() throw()
  18445. : active (false)
  18446. {
  18447. reset();
  18448. }
  18449. IIRFilter::IIRFilter (const IIRFilter& other) throw()
  18450. : active (other.active)
  18451. {
  18452. const ScopedLock sl (other.processLock);
  18453. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  18454. reset();
  18455. }
  18456. IIRFilter::~IIRFilter() throw()
  18457. {
  18458. }
  18459. void IIRFilter::reset() throw()
  18460. {
  18461. const ScopedLock sl (processLock);
  18462. x1 = 0;
  18463. x2 = 0;
  18464. y1 = 0;
  18465. y2 = 0;
  18466. }
  18467. void IIRFilter::processSamples (float* const samples,
  18468. const int numSamples) throw()
  18469. {
  18470. const ScopedLock sl (processLock);
  18471. if (active)
  18472. {
  18473. for (int i = 0; i < numSamples; ++i)
  18474. {
  18475. const float in = samples[i];
  18476. float out = coefficients[0] * in
  18477. + coefficients[1] * x1
  18478. + coefficients[2] * x2
  18479. - coefficients[4] * y1
  18480. - coefficients[5] * y2;
  18481. #if JUCE_INTEL
  18482. if (! (out < -1.0e-8 || out > 1.0e-8))
  18483. out = 0;
  18484. #endif
  18485. x2 = x1;
  18486. x1 = in;
  18487. y2 = y1;
  18488. y1 = out;
  18489. samples[i] = out;
  18490. }
  18491. }
  18492. }
  18493. void IIRFilter::makeLowPass (const double sampleRate,
  18494. const double frequency) throw()
  18495. {
  18496. jassert (sampleRate > 0);
  18497. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  18498. const double nSquared = n * n;
  18499. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  18500. setCoefficients (c1,
  18501. c1 * 2.0f,
  18502. c1,
  18503. 1.0,
  18504. c1 * 2.0 * (1.0 - nSquared),
  18505. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  18506. }
  18507. void IIRFilter::makeHighPass (const double sampleRate,
  18508. const double frequency) throw()
  18509. {
  18510. const double n = tan (double_Pi * frequency / sampleRate);
  18511. const double nSquared = n * n;
  18512. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  18513. setCoefficients (c1,
  18514. c1 * -2.0f,
  18515. c1,
  18516. 1.0,
  18517. c1 * 2.0 * (nSquared - 1.0),
  18518. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  18519. }
  18520. void IIRFilter::makeLowShelf (const double sampleRate,
  18521. const double cutOffFrequency,
  18522. const double Q,
  18523. const float gainFactor) throw()
  18524. {
  18525. jassert (sampleRate > 0);
  18526. jassert (Q > 0);
  18527. const double A = jmax (0.0f, gainFactor);
  18528. const double aminus1 = A - 1.0;
  18529. const double aplus1 = A + 1.0;
  18530. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  18531. const double coso = cos (omega);
  18532. const double beta = sin (omega) * sqrt (A) / Q;
  18533. const double aminus1TimesCoso = aminus1 * coso;
  18534. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  18535. A * 2.0 * (aminus1 - aplus1 * coso),
  18536. A * (aplus1 - aminus1TimesCoso - beta),
  18537. aplus1 + aminus1TimesCoso + beta,
  18538. -2.0 * (aminus1 + aplus1 * coso),
  18539. aplus1 + aminus1TimesCoso - beta);
  18540. }
  18541. void IIRFilter::makeHighShelf (const double sampleRate,
  18542. const double cutOffFrequency,
  18543. const double Q,
  18544. const float gainFactor) throw()
  18545. {
  18546. jassert (sampleRate > 0);
  18547. jassert (Q > 0);
  18548. const double A = jmax (0.0f, gainFactor);
  18549. const double aminus1 = A - 1.0;
  18550. const double aplus1 = A + 1.0;
  18551. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  18552. const double coso = cos (omega);
  18553. const double beta = sin (omega) * sqrt (A) / Q;
  18554. const double aminus1TimesCoso = aminus1 * coso;
  18555. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  18556. A * -2.0 * (aminus1 + aplus1 * coso),
  18557. A * (aplus1 + aminus1TimesCoso - beta),
  18558. aplus1 - aminus1TimesCoso + beta,
  18559. 2.0 * (aminus1 - aplus1 * coso),
  18560. aplus1 - aminus1TimesCoso - beta);
  18561. }
  18562. void IIRFilter::makeBandPass (const double sampleRate,
  18563. const double centreFrequency,
  18564. const double Q,
  18565. const float gainFactor) throw()
  18566. {
  18567. jassert (sampleRate > 0);
  18568. jassert (Q > 0);
  18569. const double A = jmax (0.0f, gainFactor);
  18570. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  18571. const double alpha = 0.5 * sin (omega) / Q;
  18572. const double c2 = -2.0 * cos (omega);
  18573. const double alphaTimesA = alpha * A;
  18574. const double alphaOverA = alpha / A;
  18575. setCoefficients (1.0 + alphaTimesA,
  18576. c2,
  18577. 1.0 - alphaTimesA,
  18578. 1.0 + alphaOverA,
  18579. c2,
  18580. 1.0 - alphaOverA);
  18581. }
  18582. void IIRFilter::makeInactive() throw()
  18583. {
  18584. const ScopedLock sl (processLock);
  18585. active = false;
  18586. }
  18587. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  18588. {
  18589. const ScopedLock sl (processLock);
  18590. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  18591. active = other.active;
  18592. }
  18593. void IIRFilter::setCoefficients (double c1,
  18594. double c2,
  18595. double c3,
  18596. double c4,
  18597. double c5,
  18598. double c6) throw()
  18599. {
  18600. const double a = 1.0 / c4;
  18601. c1 *= a;
  18602. c2 *= a;
  18603. c3 *= a;
  18604. c5 *= a;
  18605. c6 *= a;
  18606. const ScopedLock sl (processLock);
  18607. coefficients[0] = (float) c1;
  18608. coefficients[1] = (float) c2;
  18609. coefficients[2] = (float) c3;
  18610. coefficients[3] = (float) c4;
  18611. coefficients[4] = (float) c5;
  18612. coefficients[5] = (float) c6;
  18613. active = true;
  18614. }
  18615. END_JUCE_NAMESPACE
  18616. /********* End of inlined file: juce_IIRFilter.cpp *********/
  18617. /********* Start of inlined file: juce_MidiBuffer.cpp *********/
  18618. BEGIN_JUCE_NAMESPACE
  18619. MidiBuffer::MidiBuffer() throw()
  18620. : ArrayAllocationBase <uint8> (32),
  18621. bytesUsed (0)
  18622. {
  18623. }
  18624. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  18625. : ArrayAllocationBase <uint8> (32),
  18626. bytesUsed (other.bytesUsed)
  18627. {
  18628. ensureAllocatedSize (bytesUsed);
  18629. memcpy (elements, other.elements, bytesUsed);
  18630. }
  18631. const MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  18632. {
  18633. if (this != &other)
  18634. {
  18635. bytesUsed = other.bytesUsed;
  18636. ensureAllocatedSize (bytesUsed);
  18637. if (bytesUsed > 0)
  18638. memcpy (elements, other.elements, bytesUsed);
  18639. }
  18640. return *this;
  18641. }
  18642. MidiBuffer::~MidiBuffer() throw()
  18643. {
  18644. }
  18645. void MidiBuffer::clear() throw()
  18646. {
  18647. bytesUsed = 0;
  18648. }
  18649. void MidiBuffer::clear (const int startSample,
  18650. const int numSamples) throw()
  18651. {
  18652. uint8* const start = findEventAfter (elements, startSample - 1);
  18653. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  18654. if (end > start)
  18655. {
  18656. const size_t bytesToMove = (size_t) (bytesUsed - (end - elements));
  18657. if (bytesToMove > 0)
  18658. memmove (start, end, bytesToMove);
  18659. bytesUsed -= (int) (end - start);
  18660. }
  18661. }
  18662. void MidiBuffer::addEvent (const MidiMessage& m,
  18663. const int sampleNumber) throw()
  18664. {
  18665. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  18666. }
  18667. static int findActualEventLength (const uint8* const data,
  18668. const int maxBytes) throw()
  18669. {
  18670. unsigned int byte = (unsigned int) *data;
  18671. int size = 0;
  18672. if (byte == 0xf0 || byte == 0xf7)
  18673. {
  18674. const uint8* d = data + 1;
  18675. while (d < data + maxBytes)
  18676. if (*d++ == 0xf7)
  18677. break;
  18678. size = (int) (d - data);
  18679. }
  18680. else if (byte == 0xff)
  18681. {
  18682. int n;
  18683. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  18684. size = jmin (maxBytes, n + 2 + bytesLeft);
  18685. }
  18686. else if (byte >= 0x80)
  18687. {
  18688. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  18689. }
  18690. return size;
  18691. }
  18692. void MidiBuffer::addEvent (const uint8* const newData,
  18693. const int maxBytes,
  18694. const int sampleNumber) throw()
  18695. {
  18696. const int numBytes = findActualEventLength (newData, maxBytes);
  18697. if (numBytes > 0)
  18698. {
  18699. ensureAllocatedSize (bytesUsed + numBytes + 6);
  18700. uint8* d = findEventAfter (elements, sampleNumber);
  18701. const size_t bytesToMove = (size_t) (bytesUsed - (d - elements));
  18702. if (bytesToMove > 0)
  18703. memmove (d + numBytes + 6,
  18704. d,
  18705. bytesToMove);
  18706. *(int*) d = sampleNumber;
  18707. d += 4;
  18708. *(uint16*) d = (uint16) numBytes;
  18709. d += 2;
  18710. memcpy (d, newData, numBytes);
  18711. bytesUsed += numBytes + 6;
  18712. }
  18713. }
  18714. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  18715. const int startSample,
  18716. const int numSamples,
  18717. const int sampleDeltaToAdd) throw()
  18718. {
  18719. Iterator i (otherBuffer);
  18720. i.setNextSamplePosition (startSample);
  18721. const uint8* data;
  18722. int size, position;
  18723. while (i.getNextEvent (data, size, position)
  18724. && (position < startSample + numSamples || numSamples < 0))
  18725. {
  18726. addEvent (data, size, position + sampleDeltaToAdd);
  18727. }
  18728. }
  18729. bool MidiBuffer::isEmpty() const throw()
  18730. {
  18731. return bytesUsed == 0;
  18732. }
  18733. int MidiBuffer::getNumEvents() const throw()
  18734. {
  18735. int n = 0;
  18736. const uint8* d = elements;
  18737. const uint8* const end = elements + bytesUsed;
  18738. while (d < end)
  18739. {
  18740. d += 4;
  18741. d += 2 + *(const uint16*) d;
  18742. ++n;
  18743. }
  18744. return n;
  18745. }
  18746. int MidiBuffer::getFirstEventTime() const throw()
  18747. {
  18748. return (bytesUsed > 0) ? *(const int*) elements : 0;
  18749. }
  18750. int MidiBuffer::getLastEventTime() const throw()
  18751. {
  18752. if (bytesUsed == 0)
  18753. return 0;
  18754. const uint8* d = elements;
  18755. const uint8* const endData = d + bytesUsed;
  18756. for (;;)
  18757. {
  18758. const uint8* nextOne = d + 6 + * (const uint16*) (d + 4);
  18759. if (nextOne >= endData)
  18760. return *(const int*) d;
  18761. d = nextOne;
  18762. }
  18763. }
  18764. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  18765. {
  18766. const uint8* const endData = elements + bytesUsed;
  18767. while (d < endData && *(int*) d <= samplePosition)
  18768. {
  18769. d += 4;
  18770. d += 2 + *(uint16*) d;
  18771. }
  18772. return d;
  18773. }
  18774. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer) throw()
  18775. : buffer (buffer),
  18776. data (buffer.elements)
  18777. {
  18778. }
  18779. MidiBuffer::Iterator::~Iterator() throw()
  18780. {
  18781. }
  18782. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  18783. {
  18784. data = buffer.elements;
  18785. const uint8* dataEnd = buffer.elements + buffer.bytesUsed;
  18786. while (data < dataEnd && *(int*) data < samplePosition)
  18787. {
  18788. data += 4;
  18789. data += 2 + *(uint16*) data;
  18790. }
  18791. }
  18792. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData,
  18793. int& numBytes,
  18794. int& samplePosition) throw()
  18795. {
  18796. if (data >= buffer.elements + buffer.bytesUsed)
  18797. return false;
  18798. samplePosition = *(int*) data;
  18799. data += 4;
  18800. numBytes = *(uint16*) data;
  18801. data += 2;
  18802. midiData = data;
  18803. data += numBytes;
  18804. return true;
  18805. }
  18806. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result,
  18807. int& samplePosition) throw()
  18808. {
  18809. if (data >= buffer.elements + buffer.bytesUsed)
  18810. return false;
  18811. samplePosition = *(int*) data;
  18812. data += 4;
  18813. const int numBytes = *(uint16*) data;
  18814. data += 2;
  18815. result = MidiMessage (data, numBytes, samplePosition);
  18816. data += numBytes;
  18817. return true;
  18818. }
  18819. END_JUCE_NAMESPACE
  18820. /********* End of inlined file: juce_MidiBuffer.cpp *********/
  18821. /********* Start of inlined file: juce_MidiFile.cpp *********/
  18822. BEGIN_JUCE_NAMESPACE
  18823. struct TempoInfo
  18824. {
  18825. double bpm, timestamp;
  18826. };
  18827. struct TimeSigInfo
  18828. {
  18829. int numerator, denominator;
  18830. double timestamp;
  18831. };
  18832. MidiFile::MidiFile() throw()
  18833. : numTracks (0),
  18834. timeFormat ((short)(unsigned short)0xe728)
  18835. {
  18836. }
  18837. MidiFile::~MidiFile() throw()
  18838. {
  18839. clear();
  18840. }
  18841. void MidiFile::clear() throw()
  18842. {
  18843. while (numTracks > 0)
  18844. delete tracks [--numTracks];
  18845. }
  18846. int MidiFile::getNumTracks() const throw()
  18847. {
  18848. return numTracks;
  18849. }
  18850. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  18851. {
  18852. return (((unsigned int) index) < (unsigned int) numTracks) ? tracks[index] : 0;
  18853. }
  18854. void MidiFile::addTrack (const MidiMessageSequence& trackSequence) throw()
  18855. {
  18856. jassert (numTracks < numElementsInArray (tracks));
  18857. if (numTracks < numElementsInArray (tracks))
  18858. tracks [numTracks++] = new MidiMessageSequence (trackSequence);
  18859. }
  18860. short MidiFile::getTimeFormat() const throw()
  18861. {
  18862. return timeFormat;
  18863. }
  18864. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  18865. {
  18866. timeFormat = (short)ticks;
  18867. }
  18868. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  18869. const int subframeResolution) throw()
  18870. {
  18871. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  18872. }
  18873. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  18874. {
  18875. for (int i = numTracks; --i >= 0;)
  18876. {
  18877. const int numEvents = tracks[i]->getNumEvents();
  18878. for (int j = 0; j < numEvents; ++j)
  18879. {
  18880. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  18881. if (m.isTempoMetaEvent())
  18882. tempoChangeEvents.addEvent (m);
  18883. }
  18884. }
  18885. }
  18886. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  18887. {
  18888. for (int i = numTracks; --i >= 0;)
  18889. {
  18890. const int numEvents = tracks[i]->getNumEvents();
  18891. for (int j = 0; j < numEvents; ++j)
  18892. {
  18893. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  18894. if (m.isTimeSignatureMetaEvent())
  18895. timeSigEvents.addEvent (m);
  18896. }
  18897. }
  18898. }
  18899. double MidiFile::getLastTimestamp() const
  18900. {
  18901. double t = 0.0;
  18902. for (int i = numTracks; --i >= 0;)
  18903. t = jmax (t, tracks[i]->getEndTime());
  18904. return t;
  18905. }
  18906. static bool parseMidiHeader (const char* &data,
  18907. short& timeFormat,
  18908. short& fileType,
  18909. short& numberOfTracks)
  18910. {
  18911. unsigned int ch = (int) bigEndianInt (data);
  18912. data += 4;
  18913. if (ch != bigEndianInt ("MThd"))
  18914. {
  18915. bool ok = false;
  18916. if (ch == bigEndianInt ("RIFF"))
  18917. {
  18918. for (int i = 0; i < 8; ++i)
  18919. {
  18920. ch = bigEndianInt (data);
  18921. data += 4;
  18922. if (ch == bigEndianInt ("MThd"))
  18923. {
  18924. ok = true;
  18925. break;
  18926. }
  18927. }
  18928. }
  18929. if (! ok)
  18930. return false;
  18931. }
  18932. unsigned int bytesRemaining = bigEndianInt (data);
  18933. data += 4;
  18934. fileType = (short)bigEndianShort (data);
  18935. data += 2;
  18936. numberOfTracks = (short)bigEndianShort (data);
  18937. data += 2;
  18938. timeFormat = (short)bigEndianShort (data);
  18939. data += 2;
  18940. bytesRemaining -= 6;
  18941. data += bytesRemaining;
  18942. return true;
  18943. }
  18944. bool MidiFile::readFrom (InputStream& sourceStream)
  18945. {
  18946. clear();
  18947. MemoryBlock data;
  18948. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  18949. // (put a sanity-check on the file size, as midi files are generally small)
  18950. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  18951. {
  18952. int size = data.getSize();
  18953. const char* d = (char*) data.getData();
  18954. short fileType, expectedTracks;
  18955. if (size > 16 && parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  18956. {
  18957. size -= (int) (d - (char*) data.getData());
  18958. int track = 0;
  18959. while (size > 0 && track < expectedTracks)
  18960. {
  18961. const int chunkType = (int)bigEndianInt (d);
  18962. d += 4;
  18963. const int chunkSize = (int)bigEndianInt (d);
  18964. d += 4;
  18965. if (chunkSize <= 0)
  18966. break;
  18967. if (size < 0)
  18968. return false;
  18969. if (chunkType == (int)bigEndianInt ("MTrk"))
  18970. {
  18971. readNextTrack (d, chunkSize);
  18972. }
  18973. size -= chunkSize + 8;
  18974. d += chunkSize;
  18975. ++track;
  18976. }
  18977. return true;
  18978. }
  18979. }
  18980. return false;
  18981. }
  18982. // a comparator that puts all the note-offs before note-ons that have the same time
  18983. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  18984. const MidiMessageSequence::MidiEventHolder* const second) throw()
  18985. {
  18986. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  18987. if (diff == 0)
  18988. {
  18989. if (first->message.isNoteOff() && second->message.isNoteOn())
  18990. return -1;
  18991. else if (first->message.isNoteOn() && second->message.isNoteOff())
  18992. return 1;
  18993. else
  18994. return 0;
  18995. }
  18996. else
  18997. {
  18998. return (diff > 0) ? 1 : -1;
  18999. }
  19000. }
  19001. void MidiFile::readNextTrack (const char* data, int size)
  19002. {
  19003. double time = 0;
  19004. char lastStatusByte = 0;
  19005. MidiMessageSequence result;
  19006. while (size > 0)
  19007. {
  19008. int bytesUsed;
  19009. const int delay = MidiMessage::readVariableLengthVal ((const uint8*) data, bytesUsed);
  19010. data += bytesUsed;
  19011. size -= bytesUsed;
  19012. time += delay;
  19013. int messSize = 0;
  19014. const MidiMessage mm ((const uint8*) data, size, messSize, lastStatusByte, time);
  19015. if (messSize <= 0)
  19016. break;
  19017. size -= messSize;
  19018. data += messSize;
  19019. result.addEvent (mm);
  19020. const char firstByte = *(mm.getRawData());
  19021. if ((firstByte & 0xf0) != 0xf0)
  19022. lastStatusByte = firstByte;
  19023. }
  19024. // use a sort that puts all the note-offs before note-ons that have the same time
  19025. result.list.sort (*this, true);
  19026. result.updateMatchedPairs();
  19027. addTrack (result);
  19028. }
  19029. static double convertTicksToSeconds (const double time,
  19030. const MidiMessageSequence& tempoEvents,
  19031. const int timeFormat)
  19032. {
  19033. if (timeFormat > 0)
  19034. {
  19035. int numer = 4, denom = 4;
  19036. double tempoTime = 0.0, correctedTempoTime = 0.0;
  19037. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  19038. double secsPerTick = 0.5 * tickLen;
  19039. const int numEvents = tempoEvents.getNumEvents();
  19040. for (int i = 0; i < numEvents; ++i)
  19041. {
  19042. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  19043. if (time <= m.getTimeStamp())
  19044. break;
  19045. if (timeFormat > 0)
  19046. {
  19047. correctedTempoTime = correctedTempoTime
  19048. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  19049. }
  19050. else
  19051. {
  19052. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  19053. }
  19054. tempoTime = m.getTimeStamp();
  19055. if (m.isTempoMetaEvent())
  19056. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  19057. else if (m.isTimeSignatureMetaEvent())
  19058. m.getTimeSignatureInfo (numer, denom);
  19059. while (i + 1 < numEvents)
  19060. {
  19061. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  19062. if (m2.getTimeStamp() == tempoTime)
  19063. {
  19064. ++i;
  19065. if (m2.isTempoMetaEvent())
  19066. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  19067. else if (m2.isTimeSignatureMetaEvent())
  19068. m2.getTimeSignatureInfo (numer, denom);
  19069. }
  19070. else
  19071. {
  19072. break;
  19073. }
  19074. }
  19075. }
  19076. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  19077. }
  19078. else
  19079. {
  19080. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  19081. }
  19082. }
  19083. void MidiFile::convertTimestampTicksToSeconds()
  19084. {
  19085. MidiMessageSequence tempoEvents;
  19086. findAllTempoEvents (tempoEvents);
  19087. findAllTimeSigEvents (tempoEvents);
  19088. for (int i = 0; i < numTracks; ++i)
  19089. {
  19090. MidiMessageSequence& ms = *tracks[i];
  19091. for (int j = ms.getNumEvents(); --j >= 0;)
  19092. {
  19093. MidiMessage& m = ms.getEventPointer(j)->message;
  19094. m.setTimeStamp (convertTicksToSeconds (m.getTimeStamp(),
  19095. tempoEvents,
  19096. timeFormat));
  19097. }
  19098. }
  19099. }
  19100. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  19101. {
  19102. unsigned int buffer = v & 0x7F;
  19103. while ((v >>= 7) != 0)
  19104. {
  19105. buffer <<= 8;
  19106. buffer |= ((v & 0x7F) | 0x80);
  19107. }
  19108. for (;;)
  19109. {
  19110. out.writeByte ((char) buffer);
  19111. if (buffer & 0x80)
  19112. buffer >>= 8;
  19113. else
  19114. break;
  19115. }
  19116. }
  19117. bool MidiFile::writeTo (OutputStream& out)
  19118. {
  19119. out.writeIntBigEndian ((int) bigEndianInt ("MThd"));
  19120. out.writeIntBigEndian (6);
  19121. out.writeShortBigEndian (1); // type
  19122. out.writeShortBigEndian (numTracks);
  19123. out.writeShortBigEndian (timeFormat);
  19124. for (int i = 0; i < numTracks; ++i)
  19125. writeTrack (out, i);
  19126. out.flush();
  19127. return true;
  19128. }
  19129. void MidiFile::writeTrack (OutputStream& mainOut,
  19130. const int trackNum)
  19131. {
  19132. MemoryOutputStream out;
  19133. const MidiMessageSequence& ms = *tracks[trackNum];
  19134. int lastTick = 0;
  19135. char lastStatusByte = 0;
  19136. for (int i = 0; i < ms.getNumEvents(); ++i)
  19137. {
  19138. const MidiMessage& mm = ms.getEventPointer(i)->message;
  19139. const int tick = roundDoubleToInt (mm.getTimeStamp());
  19140. const int delta = jmax (0, tick - lastTick);
  19141. writeVariableLengthInt (out, delta);
  19142. lastTick = tick;
  19143. const char statusByte = *(mm.getRawData());
  19144. if ((statusByte == lastStatusByte)
  19145. && ((statusByte & 0xf0) != 0xf0)
  19146. && i > 0
  19147. && mm.getRawDataSize() > 1)
  19148. {
  19149. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  19150. }
  19151. else
  19152. {
  19153. out.write (mm.getRawData(), mm.getRawDataSize());
  19154. }
  19155. lastStatusByte = statusByte;
  19156. }
  19157. out.writeByte (0);
  19158. const MidiMessage m (MidiMessage::endOfTrack());
  19159. out.write (m.getRawData(),
  19160. m.getRawDataSize());
  19161. mainOut.writeIntBigEndian ((int)bigEndianInt ("MTrk"));
  19162. mainOut.writeIntBigEndian (out.getDataSize());
  19163. mainOut.write (out.getData(), out.getDataSize());
  19164. }
  19165. END_JUCE_NAMESPACE
  19166. /********* End of inlined file: juce_MidiFile.cpp *********/
  19167. /********* Start of inlined file: juce_MidiKeyboardState.cpp *********/
  19168. BEGIN_JUCE_NAMESPACE
  19169. MidiKeyboardState::MidiKeyboardState()
  19170. : listeners (2)
  19171. {
  19172. zeromem (noteStates, sizeof (noteStates));
  19173. }
  19174. MidiKeyboardState::~MidiKeyboardState()
  19175. {
  19176. }
  19177. void MidiKeyboardState::reset()
  19178. {
  19179. const ScopedLock sl (lock);
  19180. zeromem (noteStates, sizeof (noteStates));
  19181. eventsToAdd.clear();
  19182. }
  19183. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  19184. {
  19185. jassert (midiChannel >= 0 && midiChannel <= 16);
  19186. return ((unsigned int) n) < 128
  19187. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  19188. }
  19189. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  19190. {
  19191. return ((unsigned int) n) < 128
  19192. && (noteStates[n] & midiChannelMask) != 0;
  19193. }
  19194. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  19195. {
  19196. jassert (midiChannel >= 0 && midiChannel <= 16);
  19197. jassert (((unsigned int) midiNoteNumber) < 128);
  19198. const ScopedLock sl (lock);
  19199. if (((unsigned int) midiNoteNumber) < 128)
  19200. {
  19201. const int timeNow = (int) Time::getMillisecondCounter();
  19202. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  19203. eventsToAdd.clear (0, timeNow - 500);
  19204. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  19205. }
  19206. }
  19207. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  19208. {
  19209. if (((unsigned int) midiNoteNumber) < 128)
  19210. {
  19211. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  19212. for (int i = listeners.size(); --i >= 0;)
  19213. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  19214. ->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  19215. }
  19216. }
  19217. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  19218. {
  19219. const ScopedLock sl (lock);
  19220. if (isNoteOn (midiChannel, midiNoteNumber))
  19221. {
  19222. const int timeNow = (int) Time::getMillisecondCounter();
  19223. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  19224. eventsToAdd.clear (0, timeNow - 500);
  19225. noteOffInternal (midiChannel, midiNoteNumber);
  19226. }
  19227. }
  19228. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  19229. {
  19230. if (isNoteOn (midiChannel, midiNoteNumber))
  19231. {
  19232. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  19233. for (int i = listeners.size(); --i >= 0;)
  19234. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  19235. ->handleNoteOff (this, midiChannel, midiNoteNumber);
  19236. }
  19237. }
  19238. void MidiKeyboardState::allNotesOff (const int midiChannel)
  19239. {
  19240. const ScopedLock sl (lock);
  19241. if (midiChannel <= 0)
  19242. {
  19243. for (int i = 1; i <= 16; ++i)
  19244. allNotesOff (i);
  19245. }
  19246. else
  19247. {
  19248. for (int i = 0; i < 128; ++i)
  19249. noteOff (midiChannel, i);
  19250. }
  19251. }
  19252. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  19253. {
  19254. if (message.isNoteOn())
  19255. {
  19256. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  19257. }
  19258. else if (message.isNoteOff())
  19259. {
  19260. noteOffInternal (message.getChannel(), message.getNoteNumber());
  19261. }
  19262. else if (message.isAllNotesOff())
  19263. {
  19264. for (int i = 0; i < 128; ++i)
  19265. noteOffInternal (message.getChannel(), i);
  19266. }
  19267. }
  19268. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  19269. const int startSample,
  19270. const int numSamples,
  19271. const bool injectIndirectEvents)
  19272. {
  19273. MidiBuffer::Iterator i (buffer);
  19274. MidiMessage message (0xf4, 0.0);
  19275. int time;
  19276. const ScopedLock sl (lock);
  19277. while (i.getNextEvent (message, time))
  19278. processNextMidiEvent (message);
  19279. if (injectIndirectEvents)
  19280. {
  19281. MidiBuffer::Iterator i2 (eventsToAdd);
  19282. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  19283. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  19284. while (i2.getNextEvent (message, time))
  19285. {
  19286. const int pos = jlimit (0, numSamples - 1, roundDoubleToInt ((time - firstEventToAdd) * scaleFactor));
  19287. buffer.addEvent (message, startSample + pos);
  19288. }
  19289. }
  19290. eventsToAdd.clear();
  19291. }
  19292. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  19293. {
  19294. const ScopedLock sl (lock);
  19295. listeners.addIfNotAlreadyThere (listener);
  19296. }
  19297. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  19298. {
  19299. const ScopedLock sl (lock);
  19300. listeners.removeValue (listener);
  19301. }
  19302. END_JUCE_NAMESPACE
  19303. /********* End of inlined file: juce_MidiKeyboardState.cpp *********/
  19304. /********* Start of inlined file: juce_MidiMessage.cpp *********/
  19305. BEGIN_JUCE_NAMESPACE
  19306. int MidiMessage::readVariableLengthVal (const uint8* data,
  19307. int& numBytesUsed) throw()
  19308. {
  19309. numBytesUsed = 0;
  19310. int v = 0;
  19311. int i;
  19312. do
  19313. {
  19314. i = (int) *data++;
  19315. if (++numBytesUsed > 6)
  19316. break;
  19317. v = (v << 7) + (i & 0x7f);
  19318. } while (i & 0x80);
  19319. return v;
  19320. }
  19321. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  19322. {
  19323. // this method only works for valid starting bytes of a short midi message
  19324. jassert (firstByte >= 0x80
  19325. && firstByte != 0xff
  19326. && firstByte != 0xf0
  19327. && firstByte != 0xf7);
  19328. static const char messageLengths[] =
  19329. {
  19330. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19331. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19332. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19333. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19334. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  19335. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  19336. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19337. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  19338. };
  19339. return messageLengths [firstByte & 0x7f];
  19340. }
  19341. MidiMessage::MidiMessage (const uint8* const d,
  19342. const int dataSize,
  19343. const double t) throw()
  19344. : timeStamp (t),
  19345. message (0),
  19346. size (dataSize)
  19347. {
  19348. jassert (dataSize > 0);
  19349. if (dataSize <= 4)
  19350. data = (uint8*) &message;
  19351. else
  19352. data = (uint8*) juce_malloc (dataSize);
  19353. memcpy (data, d, dataSize);
  19354. // check that the length matches the data..
  19355. jassert (size > 3 || *d >= 0xf0 || getMessageLengthFromFirstByte (*d) == size);
  19356. }
  19357. MidiMessage::MidiMessage (const int byte1,
  19358. const double t) throw()
  19359. : timeStamp (t),
  19360. data ((uint8*) &message),
  19361. size (1)
  19362. {
  19363. data[0] = (uint8) byte1;
  19364. // check that the length matches the data..
  19365. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  19366. }
  19367. MidiMessage::MidiMessage (const int byte1,
  19368. const int byte2,
  19369. const double t) throw()
  19370. : timeStamp (t),
  19371. data ((uint8*) &message),
  19372. size (2)
  19373. {
  19374. data[0] = (uint8) byte1;
  19375. data[1] = (uint8) byte2;
  19376. // check that the length matches the data..
  19377. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  19378. }
  19379. MidiMessage::MidiMessage (const int byte1,
  19380. const int byte2,
  19381. const int byte3,
  19382. const double t) throw()
  19383. : timeStamp (t),
  19384. data ((uint8*) &message),
  19385. size (3)
  19386. {
  19387. data[0] = (uint8) byte1;
  19388. data[1] = (uint8) byte2;
  19389. data[2] = (uint8) byte3;
  19390. // check that the length matches the data..
  19391. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  19392. }
  19393. MidiMessage::MidiMessage (const MidiMessage& other) throw()
  19394. : timeStamp (other.timeStamp),
  19395. message (other.message),
  19396. size (other.size)
  19397. {
  19398. if (other.data != (uint8*) &other.message)
  19399. {
  19400. data = (uint8*) juce_malloc (size);
  19401. memcpy (data, other.data, size);
  19402. }
  19403. else
  19404. {
  19405. data = (uint8*) &message;
  19406. }
  19407. }
  19408. MidiMessage::MidiMessage (const MidiMessage& other,
  19409. const double newTimeStamp) throw()
  19410. : timeStamp (newTimeStamp),
  19411. message (other.message),
  19412. size (other.size)
  19413. {
  19414. if (other.data != (uint8*) &other.message)
  19415. {
  19416. data = (uint8*) juce_malloc (size);
  19417. memcpy (data, other.data, size);
  19418. }
  19419. else
  19420. {
  19421. data = (uint8*) &message;
  19422. }
  19423. }
  19424. MidiMessage::MidiMessage (const uint8* src,
  19425. int sz,
  19426. int& numBytesUsed,
  19427. const uint8 lastStatusByte,
  19428. double t) throw()
  19429. : timeStamp (t),
  19430. data ((uint8*) &message),
  19431. message (0)
  19432. {
  19433. unsigned int byte = (unsigned int) *src;
  19434. if (byte < 0x80)
  19435. {
  19436. byte = (unsigned int) (uint8) lastStatusByte;
  19437. numBytesUsed = -1;
  19438. }
  19439. else
  19440. {
  19441. numBytesUsed = 0;
  19442. --sz;
  19443. ++src;
  19444. }
  19445. if (byte >= 0x80)
  19446. {
  19447. if (byte == 0xf0)
  19448. {
  19449. const uint8* d = (const uint8*) src;
  19450. while (d < src + sz)
  19451. {
  19452. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  19453. {
  19454. if (*d == 0xf7) // include an 0xf7 if we hit one
  19455. ++d;
  19456. break;
  19457. }
  19458. ++d;
  19459. }
  19460. size = 1 + (int) (d - src);
  19461. data = (uint8*) juce_malloc (size);
  19462. *data = (uint8) byte;
  19463. memcpy (data + 1, src, size - 1);
  19464. }
  19465. else if (byte == 0xff)
  19466. {
  19467. int n;
  19468. const int bytesLeft = readVariableLengthVal (src + 1, n);
  19469. size = jmin (sz + 1, n + 2 + bytesLeft);
  19470. data = (uint8*) juce_malloc (size);
  19471. *data = (uint8) byte;
  19472. memcpy (data + 1, src, size - 1);
  19473. }
  19474. else
  19475. {
  19476. size = getMessageLengthFromFirstByte ((uint8) byte);
  19477. *data = (uint8) byte;
  19478. if (size > 1)
  19479. {
  19480. data[1] = src[0];
  19481. if (size > 2)
  19482. data[2] = src[1];
  19483. }
  19484. }
  19485. numBytesUsed += size;
  19486. }
  19487. else
  19488. {
  19489. message = 0;
  19490. size = 0;
  19491. }
  19492. }
  19493. const MidiMessage& MidiMessage::operator= (const MidiMessage& other) throw()
  19494. {
  19495. if (this == &other)
  19496. return *this;
  19497. timeStamp = other.timeStamp;
  19498. size = other.size;
  19499. message = other.message;
  19500. if (data != (uint8*) &message)
  19501. juce_free (data);
  19502. if (other.data != (uint8*) &other.message)
  19503. {
  19504. data = (uint8*) juce_malloc (size);
  19505. memcpy (data, other.data, size);
  19506. }
  19507. else
  19508. {
  19509. data = (uint8*) &message;
  19510. }
  19511. return *this;
  19512. }
  19513. MidiMessage::~MidiMessage() throw()
  19514. {
  19515. if (data != (uint8*) &message)
  19516. juce_free (data);
  19517. }
  19518. int MidiMessage::getChannel() const throw()
  19519. {
  19520. if ((data[0] & 0xf0) != 0xf0)
  19521. return (data[0] & 0xf) + 1;
  19522. else
  19523. return 0;
  19524. }
  19525. bool MidiMessage::isForChannel (const int channel) const throw()
  19526. {
  19527. return ((data[0] & 0xf) == channel - 1)
  19528. && ((data[0] & 0xf0) != 0xf0);
  19529. }
  19530. void MidiMessage::setChannel (const int channel) throw()
  19531. {
  19532. if ((data[0] & 0xf0) != (uint8) 0xf0)
  19533. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  19534. | (uint8)(channel - 1));
  19535. }
  19536. bool MidiMessage::isNoteOn() const throw()
  19537. {
  19538. return ((data[0] & 0xf0) == 0x90)
  19539. && (data[2] != 0);
  19540. }
  19541. bool MidiMessage::isNoteOff() const throw()
  19542. {
  19543. return ((data[0] & 0xf0) == 0x80)
  19544. || ((data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  19545. }
  19546. bool MidiMessage::isNoteOnOrOff() const throw()
  19547. {
  19548. const int d = data[0] & 0xf0;
  19549. return (d == 0x90) || (d == 0x80);
  19550. }
  19551. int MidiMessage::getNoteNumber() const throw()
  19552. {
  19553. return data[1];
  19554. }
  19555. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  19556. {
  19557. if (isNoteOnOrOff())
  19558. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  19559. }
  19560. uint8 MidiMessage::getVelocity() const throw()
  19561. {
  19562. if (isNoteOnOrOff())
  19563. return data[2];
  19564. else
  19565. return 0;
  19566. }
  19567. float MidiMessage::getFloatVelocity() const throw()
  19568. {
  19569. return getVelocity() * (1.0f / 127.0f);
  19570. }
  19571. void MidiMessage::setVelocity (const float newVelocity) throw()
  19572. {
  19573. if (isNoteOnOrOff())
  19574. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (newVelocity * 127.0f));
  19575. }
  19576. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  19577. {
  19578. if (isNoteOnOrOff())
  19579. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (scaleFactor * data[2]));
  19580. }
  19581. bool MidiMessage::isAftertouch() const throw()
  19582. {
  19583. return (data[0] & 0xf0) == 0xa0;
  19584. }
  19585. int MidiMessage::getAfterTouchValue() const throw()
  19586. {
  19587. return data[2];
  19588. }
  19589. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  19590. const int noteNum,
  19591. const int aftertouchValue) throw()
  19592. {
  19593. jassert (channel > 0 && channel <= 16);
  19594. jassert (((unsigned int) noteNum) <= 127);
  19595. jassert (((unsigned int) aftertouchValue) <= 127);
  19596. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  19597. noteNum & 0x7f,
  19598. aftertouchValue & 0x7f);
  19599. }
  19600. bool MidiMessage::isChannelPressure() const throw()
  19601. {
  19602. return (data[0] & 0xf0) == 0xd0;
  19603. }
  19604. int MidiMessage::getChannelPressureValue() const throw()
  19605. {
  19606. jassert (isChannelPressure());
  19607. return data[1];
  19608. }
  19609. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  19610. const int pressure) throw()
  19611. {
  19612. jassert (channel > 0 && channel <= 16);
  19613. jassert (((unsigned int) pressure) <= 127);
  19614. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  19615. pressure & 0x7f);
  19616. }
  19617. bool MidiMessage::isProgramChange() const throw()
  19618. {
  19619. return (data[0] & 0xf0) == 0xc0;
  19620. }
  19621. int MidiMessage::getProgramChangeNumber() const throw()
  19622. {
  19623. return data[1];
  19624. }
  19625. const MidiMessage MidiMessage::programChange (const int channel,
  19626. const int programNumber) throw()
  19627. {
  19628. jassert (channel > 0 && channel <= 16);
  19629. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  19630. programNumber & 0x7f);
  19631. }
  19632. bool MidiMessage::isPitchWheel() const throw()
  19633. {
  19634. return (data[0] & 0xf0) == 0xe0;
  19635. }
  19636. int MidiMessage::getPitchWheelValue() const throw()
  19637. {
  19638. return data[1] | (data[2] << 7);
  19639. }
  19640. const MidiMessage MidiMessage::pitchWheel (const int channel,
  19641. const int position) throw()
  19642. {
  19643. jassert (channel > 0 && channel <= 16);
  19644. jassert (((unsigned int) position) <= 0x3fff);
  19645. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  19646. position & 127,
  19647. (position >> 7) & 127);
  19648. }
  19649. bool MidiMessage::isController() const throw()
  19650. {
  19651. return (data[0] & 0xf0) == 0xb0;
  19652. }
  19653. int MidiMessage::getControllerNumber() const throw()
  19654. {
  19655. jassert (isController());
  19656. return data[1];
  19657. }
  19658. int MidiMessage::getControllerValue() const throw()
  19659. {
  19660. jassert (isController());
  19661. return data[2];
  19662. }
  19663. const MidiMessage MidiMessage::controllerEvent (const int channel,
  19664. const int controllerType,
  19665. const int value) throw()
  19666. {
  19667. // the channel must be between 1 and 16 inclusive
  19668. jassert (channel > 0 && channel <= 16);
  19669. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  19670. controllerType & 127,
  19671. value & 127);
  19672. }
  19673. const MidiMessage MidiMessage::noteOn (const int channel,
  19674. const int noteNumber,
  19675. const float velocity) throw()
  19676. {
  19677. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  19678. }
  19679. const MidiMessage MidiMessage::noteOn (const int channel,
  19680. const int noteNumber,
  19681. const uint8 velocity) throw()
  19682. {
  19683. jassert (channel > 0 && channel <= 16);
  19684. jassert (((unsigned int) noteNumber) <= 127);
  19685. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  19686. noteNumber & 127,
  19687. jlimit (0, 127, roundFloatToInt (velocity)));
  19688. }
  19689. const MidiMessage MidiMessage::noteOff (const int channel,
  19690. const int noteNumber) throw()
  19691. {
  19692. jassert (channel > 0 && channel <= 16);
  19693. jassert (((unsigned int) noteNumber) <= 127);
  19694. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  19695. }
  19696. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  19697. {
  19698. jassert (channel > 0 && channel <= 16);
  19699. return controllerEvent (channel, 123, 0);
  19700. }
  19701. bool MidiMessage::isAllNotesOff() const throw()
  19702. {
  19703. return (data[0] & 0xf0) == 0xb0
  19704. && data[1] == 123;
  19705. }
  19706. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  19707. {
  19708. return controllerEvent (channel, 120, 0);
  19709. }
  19710. bool MidiMessage::isAllSoundOff() const throw()
  19711. {
  19712. return (data[0] & 0xf0) == 0xb0
  19713. && data[1] == 120;
  19714. }
  19715. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  19716. {
  19717. return controllerEvent (channel, 121, 0);
  19718. }
  19719. const MidiMessage MidiMessage::masterVolume (const float volume) throw()
  19720. {
  19721. const int vol = jlimit (0, 0x3fff, roundFloatToInt (volume * 0x4000));
  19722. uint8 buf[8];
  19723. buf[0] = 0xf0;
  19724. buf[1] = 0x7f;
  19725. buf[2] = 0x7f;
  19726. buf[3] = 0x04;
  19727. buf[4] = 0x01;
  19728. buf[5] = (uint8) (vol & 0x7f);
  19729. buf[6] = (uint8) (vol >> 7);
  19730. buf[7] = 0xf7;
  19731. return MidiMessage (buf, 8);
  19732. }
  19733. bool MidiMessage::isSysEx() const throw()
  19734. {
  19735. return *data == 0xf0;
  19736. }
  19737. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData,
  19738. const int dataSize) throw()
  19739. {
  19740. MemoryBlock mm (dataSize + 2);
  19741. uint8* const m = (uint8*) mm.getData();
  19742. m[0] = 0xf0;
  19743. memcpy (m + 1, sysexData, dataSize);
  19744. m[dataSize + 1] = 0xf7;
  19745. return MidiMessage (m, dataSize + 2);
  19746. }
  19747. const uint8* MidiMessage::getSysExData() const throw()
  19748. {
  19749. return (isSysEx()) ? getRawData() + 1
  19750. : 0;
  19751. }
  19752. int MidiMessage::getSysExDataSize() const throw()
  19753. {
  19754. return (isSysEx()) ? size - 2
  19755. : 0;
  19756. }
  19757. bool MidiMessage::isMetaEvent() const throw()
  19758. {
  19759. return *data == 0xff;
  19760. }
  19761. bool MidiMessage::isActiveSense() const throw()
  19762. {
  19763. return *data == 0xfe;
  19764. }
  19765. int MidiMessage::getMetaEventType() const throw()
  19766. {
  19767. if (*data != 0xff)
  19768. return -1;
  19769. else
  19770. return data[1];
  19771. }
  19772. int MidiMessage::getMetaEventLength() const throw()
  19773. {
  19774. if (*data == 0xff)
  19775. {
  19776. int n;
  19777. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  19778. }
  19779. return 0;
  19780. }
  19781. const uint8* MidiMessage::getMetaEventData() const throw()
  19782. {
  19783. int n;
  19784. const uint8* d = data + 2;
  19785. readVariableLengthVal (d, n);
  19786. return d + n;
  19787. }
  19788. bool MidiMessage::isTrackMetaEvent() const throw()
  19789. {
  19790. return getMetaEventType() == 0;
  19791. }
  19792. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  19793. {
  19794. return getMetaEventType() == 47;
  19795. }
  19796. bool MidiMessage::isTextMetaEvent() const throw()
  19797. {
  19798. const int t = getMetaEventType();
  19799. return t > 0 && t < 16;
  19800. }
  19801. const String MidiMessage::getTextFromTextMetaEvent() const throw()
  19802. {
  19803. return String ((const char*) getMetaEventData(),
  19804. getMetaEventLength());
  19805. }
  19806. bool MidiMessage::isTrackNameEvent() const throw()
  19807. {
  19808. return (data[1] == 3)
  19809. && (*data == 0xff);
  19810. }
  19811. bool MidiMessage::isTempoMetaEvent() const throw()
  19812. {
  19813. return (data[1] == 81)
  19814. && (*data == 0xff);
  19815. }
  19816. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  19817. {
  19818. return (data[1] == 0x20)
  19819. && (*data == 0xff)
  19820. && (data[2] == 1);
  19821. }
  19822. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  19823. {
  19824. return data[3] + 1;
  19825. }
  19826. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  19827. {
  19828. if (! isTempoMetaEvent())
  19829. return 0.0;
  19830. const uint8* const d = getMetaEventData();
  19831. return (((unsigned int) d[0] << 16)
  19832. | ((unsigned int) d[1] << 8)
  19833. | d[2])
  19834. / 1000000.0;
  19835. }
  19836. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  19837. {
  19838. if (timeFormat > 0)
  19839. {
  19840. if (! isTempoMetaEvent())
  19841. return 0.5 / timeFormat;
  19842. return getTempoSecondsPerQuarterNote() / timeFormat;
  19843. }
  19844. else
  19845. {
  19846. const int frameCode = (-timeFormat) >> 8;
  19847. double framesPerSecond;
  19848. switch (frameCode)
  19849. {
  19850. case 24: framesPerSecond = 24.0; break;
  19851. case 25: framesPerSecond = 25.0; break;
  19852. case 29: framesPerSecond = 29.97; break;
  19853. case 30: framesPerSecond = 30.0; break;
  19854. default: framesPerSecond = 30.0; break;
  19855. }
  19856. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  19857. }
  19858. }
  19859. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  19860. {
  19861. uint8 d[8];
  19862. d[0] = 0xff;
  19863. d[1] = 81;
  19864. d[2] = 3;
  19865. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  19866. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  19867. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  19868. return MidiMessage (d, 6, 0.0);
  19869. }
  19870. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  19871. {
  19872. return (data[1] == 0x58)
  19873. && (*data == (uint8) 0xff);
  19874. }
  19875. void MidiMessage::getTimeSignatureInfo (int& numerator,
  19876. int& denominator) const throw()
  19877. {
  19878. if (isTimeSignatureMetaEvent())
  19879. {
  19880. const uint8* const d = getMetaEventData();
  19881. numerator = d[0];
  19882. denominator = 1 << d[1];
  19883. }
  19884. else
  19885. {
  19886. numerator = 4;
  19887. denominator = 4;
  19888. }
  19889. }
  19890. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator,
  19891. const int denominator) throw()
  19892. {
  19893. uint8 d[8];
  19894. d[0] = 0xff;
  19895. d[1] = 0x58;
  19896. d[2] = 0x04;
  19897. d[3] = (uint8) numerator;
  19898. int n = 1;
  19899. int powerOfTwo = 0;
  19900. while (n < denominator)
  19901. {
  19902. n <<= 1;
  19903. ++powerOfTwo;
  19904. }
  19905. d[4] = (uint8) powerOfTwo;
  19906. d[5] = 0x01;
  19907. d[6] = 96;
  19908. return MidiMessage (d, 7, 0.0);
  19909. }
  19910. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  19911. {
  19912. uint8 d[8];
  19913. d[0] = 0xff;
  19914. d[1] = 0x20;
  19915. d[2] = 0x01;
  19916. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  19917. return MidiMessage (d, 4, 0.0);
  19918. }
  19919. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  19920. {
  19921. return getMetaEventType() == 89;
  19922. }
  19923. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  19924. {
  19925. return (int) *getMetaEventData();
  19926. }
  19927. const MidiMessage MidiMessage::endOfTrack() throw()
  19928. {
  19929. return MidiMessage (0xff, 0x2f, 0, 0.0);
  19930. }
  19931. bool MidiMessage::isSongPositionPointer() const throw()
  19932. {
  19933. return *data == 0xf2;
  19934. }
  19935. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  19936. {
  19937. return data[1] | (data[2] << 7);
  19938. }
  19939. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  19940. {
  19941. return MidiMessage (0xf2,
  19942. positionInMidiBeats & 127,
  19943. (positionInMidiBeats >> 7) & 127);
  19944. }
  19945. bool MidiMessage::isMidiStart() const throw()
  19946. {
  19947. return *data == 0xfa;
  19948. }
  19949. const MidiMessage MidiMessage::midiStart() throw()
  19950. {
  19951. return MidiMessage (0xfa);
  19952. }
  19953. bool MidiMessage::isMidiContinue() const throw()
  19954. {
  19955. return *data == 0xfb;
  19956. }
  19957. const MidiMessage MidiMessage::midiContinue() throw()
  19958. {
  19959. return MidiMessage (0xfb);
  19960. }
  19961. bool MidiMessage::isMidiStop() const throw()
  19962. {
  19963. return *data == 0xfc;
  19964. }
  19965. const MidiMessage MidiMessage::midiStop() throw()
  19966. {
  19967. return MidiMessage (0xfc);
  19968. }
  19969. bool MidiMessage::isMidiClock() const throw()
  19970. {
  19971. return *data == 0xf8;
  19972. }
  19973. const MidiMessage MidiMessage::midiClock() throw()
  19974. {
  19975. return MidiMessage (0xf8);
  19976. }
  19977. bool MidiMessage::isQuarterFrame() const throw()
  19978. {
  19979. return *data == 0xf1;
  19980. }
  19981. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  19982. {
  19983. return ((int) data[1]) >> 4;
  19984. }
  19985. int MidiMessage::getQuarterFrameValue() const throw()
  19986. {
  19987. return ((int) data[1]) & 0x0f;
  19988. }
  19989. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  19990. const int value) throw()
  19991. {
  19992. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  19993. }
  19994. bool MidiMessage::isFullFrame() const throw()
  19995. {
  19996. return data[0] == 0xf0
  19997. && data[1] == 0x7f
  19998. && size >= 10
  19999. && data[3] == 0x01
  20000. && data[4] == 0x01;
  20001. }
  20002. void MidiMessage::getFullFrameParameters (int& hours,
  20003. int& minutes,
  20004. int& seconds,
  20005. int& frames,
  20006. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  20007. {
  20008. jassert (isFullFrame());
  20009. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  20010. hours = data[5] & 0x1f;
  20011. minutes = data[6];
  20012. seconds = data[7];
  20013. frames = data[8];
  20014. }
  20015. const MidiMessage MidiMessage::fullFrame (const int hours,
  20016. const int minutes,
  20017. const int seconds,
  20018. const int frames,
  20019. MidiMessage::SmpteTimecodeType timecodeType)
  20020. {
  20021. uint8 d[10];
  20022. d[0] = 0xf0;
  20023. d[1] = 0x7f;
  20024. d[2] = 0x7f;
  20025. d[3] = 0x01;
  20026. d[4] = 0x01;
  20027. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  20028. d[6] = (uint8) minutes;
  20029. d[7] = (uint8) seconds;
  20030. d[8] = (uint8) frames;
  20031. d[9] = 0xf7;
  20032. return MidiMessage (d, 10, 0.0);
  20033. }
  20034. bool MidiMessage::isMidiMachineControlMessage() const throw()
  20035. {
  20036. return data[0] == 0xf0
  20037. && data[1] == 0x7f
  20038. && data[3] == 0x06
  20039. && size > 5;
  20040. }
  20041. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  20042. {
  20043. jassert (isMidiMachineControlMessage());
  20044. return (MidiMachineControlCommand) data[4];
  20045. }
  20046. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  20047. {
  20048. uint8 d[6];
  20049. d[0] = 0xf0;
  20050. d[1] = 0x7f;
  20051. d[2] = 0x00;
  20052. d[3] = 0x06;
  20053. d[4] = (uint8) command;
  20054. d[5] = 0xf7;
  20055. return MidiMessage (d, 6, 0.0);
  20056. }
  20057. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  20058. int& minutes,
  20059. int& seconds,
  20060. int& frames) const throw()
  20061. {
  20062. if (size >= 12
  20063. && data[0] == 0xf0
  20064. && data[1] == 0x7f
  20065. && data[3] == 0x06
  20066. && data[4] == 0x44
  20067. && data[5] == 0x06
  20068. && data[6] == 0x01)
  20069. {
  20070. hours = data[7] % 24; // (that some machines send out hours > 24)
  20071. minutes = data[8];
  20072. seconds = data[9];
  20073. frames = data[10];
  20074. return true;
  20075. }
  20076. return false;
  20077. }
  20078. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  20079. int minutes,
  20080. int seconds,
  20081. int frames)
  20082. {
  20083. uint8 d[12];
  20084. d[0] = 0xf0;
  20085. d[1] = 0x7f;
  20086. d[2] = 0x00;
  20087. d[3] = 0x06;
  20088. d[4] = 0x44;
  20089. d[5] = 0x06;
  20090. d[6] = 0x01;
  20091. d[7] = (uint8) hours;
  20092. d[8] = (uint8) minutes;
  20093. d[9] = (uint8) seconds;
  20094. d[10] = (uint8) frames;
  20095. d[11] = 0xf7;
  20096. return MidiMessage (d, 12, 0.0);
  20097. }
  20098. const String MidiMessage::getMidiNoteName (int note,
  20099. bool useSharps,
  20100. bool includeOctaveNumber,
  20101. int octaveNumForMiddleC) throw()
  20102. {
  20103. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  20104. "F", "F#", "G", "G#", "A",
  20105. "A#", "B" };
  20106. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  20107. "F", "Gb", "G", "Ab", "A",
  20108. "Bb", "B" };
  20109. if (((unsigned int) note) < 128)
  20110. {
  20111. const String s ((useSharps) ? sharpNoteNames [note % 12]
  20112. : flatNoteNames [note % 12]);
  20113. if (includeOctaveNumber)
  20114. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  20115. else
  20116. return s;
  20117. }
  20118. return String::empty;
  20119. }
  20120. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  20121. {
  20122. noteNumber -= 12 * 6 + 9; // now 0 = A440
  20123. return 440.0 * pow (2.0, noteNumber / 12.0);
  20124. }
  20125. const String MidiMessage::getGMInstrumentName (int n) throw()
  20126. {
  20127. const char *names[] =
  20128. {
  20129. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  20130. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  20131. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  20132. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  20133. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  20134. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  20135. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  20136. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  20137. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  20138. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  20139. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  20140. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  20141. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  20142. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  20143. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  20144. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  20145. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  20146. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  20147. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  20148. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  20149. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  20150. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  20151. "Applause", "Gunshot"
  20152. };
  20153. return (((unsigned int) n) < 128) ? names[n]
  20154. : (const char*)0;
  20155. }
  20156. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  20157. {
  20158. const char* names[] =
  20159. {
  20160. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  20161. "Bass", "Strings", "Ensemble", "Brass",
  20162. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  20163. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  20164. };
  20165. return (((unsigned int) n) <= 15) ? names[n]
  20166. : (const char*)0;
  20167. }
  20168. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  20169. {
  20170. const char* names[] =
  20171. {
  20172. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  20173. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  20174. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  20175. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  20176. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  20177. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  20178. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  20179. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  20180. "Mute Triangle", "Open Triangle"
  20181. };
  20182. return (n >= 35 && n <= 81) ? names [n - 35]
  20183. : (const char*)0;
  20184. }
  20185. const String MidiMessage::getControllerName (int n) throw()
  20186. {
  20187. const char* names[] =
  20188. {
  20189. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  20190. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  20191. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  20192. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  20193. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  20194. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  20195. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  20196. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  20197. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  20198. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  20199. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  20200. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  20201. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  20202. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  20203. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  20204. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  20205. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  20206. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  20207. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  20208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  20209. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  20210. "Poly Operation"
  20211. };
  20212. return (((unsigned int) n) < 128) ? names[n]
  20213. : (const char*)0;
  20214. }
  20215. END_JUCE_NAMESPACE
  20216. /********* End of inlined file: juce_MidiMessage.cpp *********/
  20217. /********* Start of inlined file: juce_MidiMessageCollector.cpp *********/
  20218. BEGIN_JUCE_NAMESPACE
  20219. MidiMessageCollector::MidiMessageCollector()
  20220. : lastCallbackTime (0),
  20221. sampleRate (44100.0001)
  20222. {
  20223. }
  20224. MidiMessageCollector::~MidiMessageCollector()
  20225. {
  20226. }
  20227. void MidiMessageCollector::reset (const double sampleRate_)
  20228. {
  20229. jassert (sampleRate_ > 0);
  20230. const ScopedLock sl (midiCallbackLock);
  20231. sampleRate = sampleRate_;
  20232. incomingMessages.clear();
  20233. lastCallbackTime = Time::getMillisecondCounterHiRes();
  20234. }
  20235. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  20236. {
  20237. // you need to call reset() to set the correct sample rate before using this object
  20238. jassert (sampleRate != 44100.0001);
  20239. // the messages that come in here need to be time-stamped correctly - see MidiInput
  20240. // for details of what the number should be.
  20241. jassert (message.getTimeStamp() != 0);
  20242. const ScopedLock sl (midiCallbackLock);
  20243. const int sampleNumber
  20244. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  20245. incomingMessages.addEvent (message, sampleNumber);
  20246. // if the messages don't get used for over a second, we'd better
  20247. // get rid of any old ones to avoid the queue getting too big
  20248. if (sampleNumber > sampleRate)
  20249. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  20250. }
  20251. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  20252. const int numSamples)
  20253. {
  20254. // you need to call reset() to set the correct sample rate before using this object
  20255. jassert (sampleRate != 44100.0001);
  20256. const double timeNow = Time::getMillisecondCounterHiRes();
  20257. const double msElapsed = timeNow - lastCallbackTime;
  20258. const ScopedLock sl (midiCallbackLock);
  20259. lastCallbackTime = timeNow;
  20260. if (! incomingMessages.isEmpty())
  20261. {
  20262. int numSourceSamples = jmax (1, roundDoubleToInt (msElapsed * 0.001 * sampleRate));
  20263. int startSample = 0;
  20264. int scale = 1 << 16;
  20265. const uint8* midiData;
  20266. int numBytes, samplePosition;
  20267. MidiBuffer::Iterator iter (incomingMessages);
  20268. if (numSourceSamples > numSamples)
  20269. {
  20270. // if our list of events is longer than the buffer we're being
  20271. // asked for, scale them down to squeeze them all in..
  20272. const int maxBlockLengthToUse = numSamples << 3;
  20273. if (numSourceSamples > maxBlockLengthToUse)
  20274. {
  20275. startSample = numSourceSamples - maxBlockLengthToUse;
  20276. numSourceSamples = maxBlockLengthToUse;
  20277. iter.setNextSamplePosition (startSample);
  20278. }
  20279. scale = (numSamples << 10) / numSourceSamples;
  20280. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  20281. {
  20282. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  20283. destBuffer.addEvent (midiData, numBytes,
  20284. jlimit (0, numSamples - 1, samplePosition));
  20285. }
  20286. }
  20287. else
  20288. {
  20289. // if our event list is shorter than the number we need, put them
  20290. // towards the end of the buffer
  20291. startSample = numSamples - numSourceSamples;
  20292. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  20293. {
  20294. destBuffer.addEvent (midiData, numBytes,
  20295. jlimit (0, numSamples - 1, samplePosition + startSample));
  20296. }
  20297. }
  20298. incomingMessages.clear();
  20299. }
  20300. }
  20301. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  20302. {
  20303. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  20304. m.setTimeStamp (Time::getMillisecondCounter() * 0.001);
  20305. addMessageToQueue (m);
  20306. }
  20307. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  20308. {
  20309. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  20310. m.setTimeStamp (Time::getMillisecondCounter() * 0.001);
  20311. addMessageToQueue (m);
  20312. }
  20313. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  20314. {
  20315. addMessageToQueue (message);
  20316. }
  20317. END_JUCE_NAMESPACE
  20318. /********* End of inlined file: juce_MidiMessageCollector.cpp *********/
  20319. /********* Start of inlined file: juce_MidiMessageSequence.cpp *********/
  20320. BEGIN_JUCE_NAMESPACE
  20321. MidiMessageSequence::MidiMessageSequence()
  20322. {
  20323. }
  20324. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  20325. {
  20326. list.ensureStorageAllocated (other.list.size());
  20327. for (int i = 0; i < other.list.size(); ++i)
  20328. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  20329. }
  20330. const MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  20331. {
  20332. if (this != &other)
  20333. {
  20334. clear();
  20335. for (int i = 0; i < other.list.size(); ++i)
  20336. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  20337. }
  20338. return *this;
  20339. }
  20340. MidiMessageSequence::~MidiMessageSequence()
  20341. {
  20342. }
  20343. void MidiMessageSequence::clear()
  20344. {
  20345. list.clear();
  20346. }
  20347. int MidiMessageSequence::getNumEvents() const
  20348. {
  20349. return list.size();
  20350. }
  20351. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  20352. {
  20353. return list [index];
  20354. }
  20355. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  20356. {
  20357. const MidiEventHolder* const meh = list [index];
  20358. if (meh != 0 && meh->noteOffObject != 0)
  20359. return meh->noteOffObject->message.getTimeStamp();
  20360. else
  20361. return 0.0;
  20362. }
  20363. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  20364. {
  20365. const MidiEventHolder* const meh = list [index];
  20366. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  20367. }
  20368. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  20369. {
  20370. return list.indexOf (event);
  20371. }
  20372. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  20373. {
  20374. const int numEvents = list.size();
  20375. int i;
  20376. for (i = 0; i < numEvents; ++i)
  20377. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  20378. break;
  20379. return i;
  20380. }
  20381. double MidiMessageSequence::getStartTime() const
  20382. {
  20383. if (list.size() > 0)
  20384. return list.getUnchecked(0)->message.getTimeStamp();
  20385. else
  20386. return 0;
  20387. }
  20388. double MidiMessageSequence::getEndTime() const
  20389. {
  20390. if (list.size() > 0)
  20391. return list.getLast()->message.getTimeStamp();
  20392. else
  20393. return 0;
  20394. }
  20395. double MidiMessageSequence::getEventTime (const int index) const
  20396. {
  20397. if (((unsigned int) index) < (unsigned int) list.size())
  20398. return list.getUnchecked (index)->message.getTimeStamp();
  20399. return 0.0;
  20400. }
  20401. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  20402. double timeAdjustment)
  20403. {
  20404. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  20405. timeAdjustment += newMessage.getTimeStamp();
  20406. newOne->message.setTimeStamp (timeAdjustment);
  20407. int i;
  20408. for (i = list.size(); --i >= 0;)
  20409. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  20410. break;
  20411. list.insert (i + 1, newOne);
  20412. }
  20413. void MidiMessageSequence::deleteEvent (const int index,
  20414. const bool deleteMatchingNoteUp)
  20415. {
  20416. if (((unsigned int) index) < (unsigned int) list.size())
  20417. {
  20418. if (deleteMatchingNoteUp)
  20419. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  20420. list.remove (index);
  20421. }
  20422. }
  20423. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  20424. double timeAdjustment,
  20425. double firstAllowableTime,
  20426. double endOfAllowableDestTimes)
  20427. {
  20428. firstAllowableTime -= timeAdjustment;
  20429. endOfAllowableDestTimes -= timeAdjustment;
  20430. for (int i = 0; i < other.list.size(); ++i)
  20431. {
  20432. const MidiMessage& m = other.list.getUnchecked(i)->message;
  20433. const double t = m.getTimeStamp();
  20434. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  20435. {
  20436. MidiEventHolder* const newOne = new MidiEventHolder (m);
  20437. newOne->message.setTimeStamp (timeAdjustment + t);
  20438. list.add (newOne);
  20439. }
  20440. }
  20441. sort();
  20442. }
  20443. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  20444. const MidiMessageSequence::MidiEventHolder* const second) throw()
  20445. {
  20446. const double diff = first->message.getTimeStamp()
  20447. - second->message.getTimeStamp();
  20448. return (diff == 0) ? 0
  20449. : ((diff > 0) ? 1
  20450. : -1);
  20451. }
  20452. void MidiMessageSequence::sort()
  20453. {
  20454. list.sort (*this, true);
  20455. }
  20456. void MidiMessageSequence::updateMatchedPairs()
  20457. {
  20458. for (int i = 0; i < list.size(); ++i)
  20459. {
  20460. const MidiMessage& m1 = list.getUnchecked(i)->message;
  20461. if (m1.isNoteOn())
  20462. {
  20463. list.getUnchecked(i)->noteOffObject = 0;
  20464. const int note = m1.getNoteNumber();
  20465. const int chan = m1.getChannel();
  20466. const int len = list.size();
  20467. for (int j = i + 1; j < len; ++j)
  20468. {
  20469. const MidiMessage& m = list.getUnchecked(j)->message;
  20470. if (m.getNoteNumber() == note && m.getChannel() == chan)
  20471. {
  20472. if (m.isNoteOff())
  20473. {
  20474. list.getUnchecked(i)->noteOffObject = list[j];
  20475. break;
  20476. }
  20477. else if (m.isNoteOn())
  20478. {
  20479. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  20480. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  20481. list.getUnchecked(i)->noteOffObject = list[j];
  20482. break;
  20483. }
  20484. }
  20485. }
  20486. }
  20487. }
  20488. }
  20489. void MidiMessageSequence::addTimeToMessages (const double delta)
  20490. {
  20491. for (int i = list.size(); --i >= 0;)
  20492. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  20493. + delta);
  20494. }
  20495. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  20496. MidiMessageSequence& destSequence,
  20497. const bool alsoIncludeMetaEvents) const
  20498. {
  20499. for (int i = 0; i < list.size(); ++i)
  20500. {
  20501. const MidiMessage& mm = list.getUnchecked(i)->message;
  20502. if (mm.isForChannel (channelNumberToExtract)
  20503. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  20504. {
  20505. destSequence.addEvent (mm);
  20506. }
  20507. }
  20508. }
  20509. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  20510. {
  20511. for (int i = 0; i < list.size(); ++i)
  20512. {
  20513. const MidiMessage& mm = list.getUnchecked(i)->message;
  20514. if (mm.isSysEx())
  20515. destSequence.addEvent (mm);
  20516. }
  20517. }
  20518. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  20519. {
  20520. for (int i = list.size(); --i >= 0;)
  20521. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  20522. list.remove(i);
  20523. }
  20524. void MidiMessageSequence::deleteSysExMessages()
  20525. {
  20526. for (int i = list.size(); --i >= 0;)
  20527. if (list.getUnchecked(i)->message.isSysEx())
  20528. list.remove(i);
  20529. }
  20530. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  20531. const double time,
  20532. OwnedArray<MidiMessage>& dest)
  20533. {
  20534. bool doneProg = false;
  20535. bool donePitchWheel = false;
  20536. Array <int> doneControllers (32);
  20537. for (int i = list.size(); --i >= 0;)
  20538. {
  20539. const MidiMessage& mm = list.getUnchecked(i)->message;
  20540. if (mm.isForChannel (channelNumber)
  20541. && mm.getTimeStamp() <= time)
  20542. {
  20543. if (mm.isProgramChange())
  20544. {
  20545. if (! doneProg)
  20546. {
  20547. dest.add (new MidiMessage (mm, 0.0));
  20548. doneProg = true;
  20549. }
  20550. }
  20551. else if (mm.isController())
  20552. {
  20553. if (! doneControllers.contains (mm.getControllerNumber()))
  20554. {
  20555. dest.add (new MidiMessage (mm, 0.0));
  20556. doneControllers.add (mm.getControllerNumber());
  20557. }
  20558. }
  20559. else if (mm.isPitchWheel())
  20560. {
  20561. if (! donePitchWheel)
  20562. {
  20563. dest.add (new MidiMessage (mm, 0.0));
  20564. donePitchWheel = true;
  20565. }
  20566. }
  20567. }
  20568. }
  20569. }
  20570. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  20571. : message (message_),
  20572. noteOffObject (0)
  20573. {
  20574. }
  20575. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  20576. {
  20577. }
  20578. END_JUCE_NAMESPACE
  20579. /********* End of inlined file: juce_MidiMessageSequence.cpp *********/
  20580. /********* Start of inlined file: juce_AudioPluginFormat.cpp *********/
  20581. BEGIN_JUCE_NAMESPACE
  20582. AudioPluginFormat::AudioPluginFormat() throw()
  20583. {
  20584. }
  20585. AudioPluginFormat::~AudioPluginFormat()
  20586. {
  20587. }
  20588. END_JUCE_NAMESPACE
  20589. /********* End of inlined file: juce_AudioPluginFormat.cpp *********/
  20590. /********* Start of inlined file: juce_AudioPluginFormatManager.cpp *********/
  20591. BEGIN_JUCE_NAMESPACE
  20592. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  20593. {
  20594. }
  20595. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  20596. {
  20597. }
  20598. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  20599. void AudioPluginFormatManager::addDefaultFormats()
  20600. {
  20601. #ifdef JUCE_DEBUG
  20602. // you should only call this method once!
  20603. for (int i = formats.size(); --i >= 0;)
  20604. {
  20605. #if JUCE_PLUGINHOST_VST
  20606. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  20607. #endif
  20608. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  20609. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  20610. #endif
  20611. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  20612. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  20613. #endif
  20614. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  20615. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  20616. #endif
  20617. }
  20618. #endif
  20619. #if JUCE_PLUGINHOST_VST
  20620. formats.add (new VSTPluginFormat());
  20621. #endif
  20622. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  20623. formats.add (new AudioUnitPluginFormat());
  20624. #endif
  20625. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  20626. formats.add (new DirectXPluginFormat());
  20627. #endif
  20628. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  20629. formats.add (new LADSPAPluginFormat());
  20630. #endif
  20631. }
  20632. int AudioPluginFormatManager::getNumFormats() throw()
  20633. {
  20634. return formats.size();
  20635. }
  20636. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  20637. {
  20638. return formats [index];
  20639. }
  20640. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  20641. {
  20642. formats.add (format);
  20643. }
  20644. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  20645. String& errorMessage) const
  20646. {
  20647. AudioPluginInstance* result = 0;
  20648. for (int i = 0; i < formats.size(); ++i)
  20649. {
  20650. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  20651. if (result != 0)
  20652. break;
  20653. }
  20654. if (result == 0)
  20655. {
  20656. if (description.file != File::nonexistent && ! description.file.exists())
  20657. errorMessage = TRANS ("This plug-in file no longer exists");
  20658. else
  20659. errorMessage = TRANS ("This plug-in failed to load correctly");
  20660. }
  20661. return result;
  20662. }
  20663. END_JUCE_NAMESPACE
  20664. /********* End of inlined file: juce_AudioPluginFormatManager.cpp *********/
  20665. /********* Start of inlined file: juce_AudioPluginInstance.cpp *********/
  20666. #define JUCE_PLUGIN_HOST 1
  20667. BEGIN_JUCE_NAMESPACE
  20668. AudioPluginInstance::AudioPluginInstance()
  20669. {
  20670. }
  20671. AudioPluginInstance::~AudioPluginInstance()
  20672. {
  20673. }
  20674. END_JUCE_NAMESPACE
  20675. /********* End of inlined file: juce_AudioPluginInstance.cpp *********/
  20676. /********* Start of inlined file: juce_KnownPluginList.cpp *********/
  20677. BEGIN_JUCE_NAMESPACE
  20678. KnownPluginList::KnownPluginList()
  20679. {
  20680. }
  20681. KnownPluginList::~KnownPluginList()
  20682. {
  20683. }
  20684. void KnownPluginList::clear()
  20685. {
  20686. if (types.size() > 0)
  20687. {
  20688. types.clear();
  20689. sendChangeMessage (this);
  20690. }
  20691. }
  20692. PluginDescription* KnownPluginList::getTypeForFile (const File& file) const throw()
  20693. {
  20694. for (int i = 0; i < types.size(); ++i)
  20695. if (types.getUnchecked(i)->file == file)
  20696. return types.getUnchecked(i);
  20697. return 0;
  20698. }
  20699. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  20700. {
  20701. for (int i = 0; i < types.size(); ++i)
  20702. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  20703. return types.getUnchecked(i);
  20704. return 0;
  20705. }
  20706. bool KnownPluginList::addType (const PluginDescription& type)
  20707. {
  20708. for (int i = types.size(); --i >= 0;)
  20709. {
  20710. if (types.getUnchecked(i)->isDuplicateOf (type))
  20711. {
  20712. // strange - found a duplicate plugin with different info..
  20713. jassert (types.getUnchecked(i)->name == type.name);
  20714. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  20715. *types.getUnchecked(i) = type;
  20716. return false;
  20717. }
  20718. }
  20719. types.add (new PluginDescription (type));
  20720. sendChangeMessage (this);
  20721. return true;
  20722. }
  20723. void KnownPluginList::removeType (const int index) throw()
  20724. {
  20725. types.remove (index);
  20726. sendChangeMessage (this);
  20727. }
  20728. bool KnownPluginList::isListingUpToDate (const File& possiblePluginFile) const throw()
  20729. {
  20730. if (getTypeForFile (possiblePluginFile) == 0)
  20731. return false;
  20732. for (int i = types.size(); --i >= 0;)
  20733. {
  20734. const PluginDescription* const d = types.getUnchecked(i);
  20735. if (d->file == possiblePluginFile
  20736. && d->lastFileModTime != possiblePluginFile.getLastModificationTime())
  20737. {
  20738. return false;
  20739. }
  20740. }
  20741. return true;
  20742. }
  20743. bool KnownPluginList::scanAndAddFile (const File& possiblePluginFile,
  20744. const bool dontRescanIfAlreadyInList,
  20745. OwnedArray <PluginDescription>& typesFound)
  20746. {
  20747. bool addedOne = false;
  20748. if (dontRescanIfAlreadyInList
  20749. && getTypeForFile (possiblePluginFile) != 0)
  20750. {
  20751. bool needsRescanning = false;
  20752. for (int i = types.size(); --i >= 0;)
  20753. {
  20754. const PluginDescription* const d = types.getUnchecked(i);
  20755. if (d->file == possiblePluginFile)
  20756. {
  20757. if (d->lastFileModTime != possiblePluginFile.getLastModificationTime())
  20758. needsRescanning = true;
  20759. else
  20760. typesFound.add (new PluginDescription (*d));
  20761. }
  20762. }
  20763. if (! needsRescanning)
  20764. return false;
  20765. }
  20766. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  20767. {
  20768. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  20769. OwnedArray <PluginDescription> found;
  20770. format->findAllTypesForFile (found, possiblePluginFile);
  20771. for (int i = 0; i < found.size(); ++i)
  20772. {
  20773. PluginDescription* const desc = found.getUnchecked(i);
  20774. jassert (desc != 0);
  20775. if (addType (*desc))
  20776. addedOne = true;
  20777. typesFound.add (new PluginDescription (*desc));
  20778. }
  20779. }
  20780. return addedOne;
  20781. }
  20782. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  20783. OwnedArray <PluginDescription>& typesFound)
  20784. {
  20785. for (int i = 0; i < files.size(); ++i)
  20786. {
  20787. const File f (files [i]);
  20788. if (! scanAndAddFile (f, true, typesFound))
  20789. {
  20790. if (f.isDirectory())
  20791. {
  20792. StringArray s;
  20793. {
  20794. OwnedArray <File> subFiles;
  20795. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  20796. for (int j = 0; j < subFiles.size(); ++j)
  20797. s.add (subFiles.getUnchecked (j)->getFullPathName());
  20798. }
  20799. scanAndAddDragAndDroppedFiles (s, typesFound);
  20800. }
  20801. }
  20802. }
  20803. }
  20804. class PluginSorter
  20805. {
  20806. public:
  20807. KnownPluginList::SortMethod method;
  20808. PluginSorter() throw() {}
  20809. int compareElements (const PluginDescription* const first,
  20810. const PluginDescription* const second) const throw()
  20811. {
  20812. int diff = 0;
  20813. if (method == KnownPluginList::sortByCategory)
  20814. diff = first->category.compareLexicographically (second->category);
  20815. else if (method == KnownPluginList::sortByManufacturer)
  20816. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  20817. else if (method == KnownPluginList::sortByFileSystemLocation)
  20818. diff = first->file.getParentDirectory().getFullPathName().compare (second->file.getParentDirectory().getFullPathName());
  20819. if (diff == 0)
  20820. diff = first->name.compareLexicographically (second->name);
  20821. return diff;
  20822. }
  20823. };
  20824. void KnownPluginList::sort (const SortMethod method)
  20825. {
  20826. if (method != defaultOrder)
  20827. {
  20828. PluginSorter sorter;
  20829. sorter.method = method;
  20830. types.sort (sorter, true);
  20831. sendChangeMessage (this);
  20832. }
  20833. }
  20834. XmlElement* KnownPluginList::createXml() const
  20835. {
  20836. XmlElement* const e = new XmlElement (T("KNOWNPLUGINS"));
  20837. for (int i = 0; i < types.size(); ++i)
  20838. e->addChildElement (types.getUnchecked(i)->createXml());
  20839. return e;
  20840. }
  20841. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  20842. {
  20843. clear();
  20844. if (xml.hasTagName (T("KNOWNPLUGINS")))
  20845. {
  20846. forEachXmlChildElement (xml, e)
  20847. {
  20848. PluginDescription info;
  20849. if (info.loadFromXml (*e))
  20850. addType (info);
  20851. }
  20852. }
  20853. }
  20854. const int menuIdBase = 0x324503f4;
  20855. // This is used to turn a bunch of paths into a nested menu structure.
  20856. struct PluginFilesystemTree
  20857. {
  20858. private:
  20859. String folder;
  20860. OwnedArray <PluginFilesystemTree> subFolders;
  20861. Array <PluginDescription*> plugins;
  20862. void addPlugin (PluginDescription* const pd, const String& path)
  20863. {
  20864. if (path.isEmpty())
  20865. {
  20866. plugins.add (pd);
  20867. }
  20868. else
  20869. {
  20870. const String firstSubFolder (path.upToFirstOccurrenceOf (T("/"), false, false));
  20871. const String remainingPath (path.fromFirstOccurrenceOf (T("/"), false, false));
  20872. for (int i = subFolders.size(); --i >= 0;)
  20873. {
  20874. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  20875. {
  20876. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  20877. return;
  20878. }
  20879. }
  20880. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  20881. newFolder->folder = firstSubFolder;
  20882. subFolders.add (newFolder);
  20883. newFolder->addPlugin (pd, remainingPath);
  20884. }
  20885. }
  20886. // removes any deeply nested folders that don't contain any actual plugins
  20887. void optimise()
  20888. {
  20889. for (int i = subFolders.size(); --i >= 0;)
  20890. {
  20891. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  20892. sub->optimise();
  20893. if (sub->plugins.size() == 0)
  20894. {
  20895. for (int j = 0; j < sub->subFolders.size(); ++j)
  20896. subFolders.add (sub->subFolders.getUnchecked(j));
  20897. sub->subFolders.clear (false);
  20898. subFolders.remove (i);
  20899. }
  20900. }
  20901. }
  20902. public:
  20903. void buildTree (const Array <PluginDescription*>& allPlugins)
  20904. {
  20905. for (int i = 0; i < allPlugins.size(); ++i)
  20906. {
  20907. String path (allPlugins.getUnchecked(i)->file.getParentDirectory().getFullPathName());
  20908. if (path.substring (1, 2) == T(":"))
  20909. path = path.substring (2);
  20910. path = path.replaceCharacter (T('\\'), T('/'));
  20911. addPlugin (allPlugins.getUnchecked(i), path);
  20912. }
  20913. optimise();
  20914. }
  20915. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  20916. {
  20917. int i;
  20918. for (i = 0; i < subFolders.size(); ++i)
  20919. {
  20920. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  20921. PopupMenu subMenu;
  20922. sub->addToMenu (subMenu, allPlugins);
  20923. m.addSubMenu (sub->folder, subMenu);
  20924. }
  20925. for (i = 0; i < plugins.size(); ++i)
  20926. {
  20927. PluginDescription* const plugin = plugins.getUnchecked(i);
  20928. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  20929. plugin->name, true, false);
  20930. }
  20931. }
  20932. };
  20933. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  20934. {
  20935. Array <PluginDescription*> sorted;
  20936. {
  20937. PluginSorter sorter;
  20938. sorter.method = sortMethod;
  20939. for (int i = 0; i < types.size(); ++i)
  20940. sorted.addSorted (sorter, types.getUnchecked(i));
  20941. }
  20942. if (sortMethod == sortByCategory
  20943. || sortMethod == sortByManufacturer)
  20944. {
  20945. String lastSubMenuName;
  20946. PopupMenu sub;
  20947. for (int i = 0; i < sorted.size(); ++i)
  20948. {
  20949. const PluginDescription* const pd = sorted.getUnchecked(i);
  20950. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  20951. : pd->manufacturerName);
  20952. if (thisSubMenuName.trim().isEmpty())
  20953. thisSubMenuName = T("Other");
  20954. if (thisSubMenuName != lastSubMenuName)
  20955. {
  20956. if (sub.getNumItems() > 0)
  20957. {
  20958. menu.addSubMenu (lastSubMenuName, sub);
  20959. sub.clear();
  20960. }
  20961. lastSubMenuName = thisSubMenuName;
  20962. }
  20963. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  20964. }
  20965. if (sub.getNumItems() > 0)
  20966. menu.addSubMenu (lastSubMenuName, sub);
  20967. }
  20968. else if (sortMethod == sortByFileSystemLocation)
  20969. {
  20970. PluginFilesystemTree root;
  20971. root.buildTree (sorted);
  20972. root.addToMenu (menu, types);
  20973. }
  20974. else
  20975. {
  20976. for (int i = 0; i < sorted.size(); ++i)
  20977. {
  20978. const PluginDescription* const pd = sorted.getUnchecked(i);
  20979. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  20980. }
  20981. }
  20982. }
  20983. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  20984. {
  20985. const int i = menuResultCode - menuIdBase;
  20986. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  20987. }
  20988. END_JUCE_NAMESPACE
  20989. /********* End of inlined file: juce_KnownPluginList.cpp *********/
  20990. /********* Start of inlined file: juce_PluginDescription.cpp *********/
  20991. BEGIN_JUCE_NAMESPACE
  20992. PluginDescription::PluginDescription() throw()
  20993. : uid (0),
  20994. isInstrument (false),
  20995. numInputChannels (0),
  20996. numOutputChannels (0)
  20997. {
  20998. }
  20999. PluginDescription::~PluginDescription() throw()
  21000. {
  21001. }
  21002. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  21003. : name (other.name),
  21004. pluginFormatName (other.pluginFormatName),
  21005. category (other.category),
  21006. manufacturerName (other.manufacturerName),
  21007. version (other.version),
  21008. file (other.file),
  21009. lastFileModTime (other.lastFileModTime),
  21010. uid (other.uid),
  21011. isInstrument (other.isInstrument),
  21012. numInputChannels (other.numInputChannels),
  21013. numOutputChannels (other.numOutputChannels)
  21014. {
  21015. }
  21016. const PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  21017. {
  21018. name = other.name;
  21019. pluginFormatName = other.pluginFormatName;
  21020. category = other.category;
  21021. manufacturerName = other.manufacturerName;
  21022. version = other.version;
  21023. file = other.file;
  21024. uid = other.uid;
  21025. isInstrument = other.isInstrument;
  21026. lastFileModTime = other.lastFileModTime;
  21027. numInputChannels = other.numInputChannels;
  21028. numOutputChannels = other.numOutputChannels;
  21029. return *this;
  21030. }
  21031. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  21032. {
  21033. return file == other.file
  21034. && uid == other.uid;
  21035. }
  21036. const String PluginDescription::createIdentifierString() const throw()
  21037. {
  21038. return pluginFormatName
  21039. + T("-") + name
  21040. + T("-") + String::toHexString (file.getFileName().hashCode())
  21041. + T("-") + String::toHexString (uid);
  21042. }
  21043. XmlElement* PluginDescription::createXml() const
  21044. {
  21045. XmlElement* const e = new XmlElement (T("PLUGIN"));
  21046. e->setAttribute (T("name"), name);
  21047. e->setAttribute (T("format"), pluginFormatName);
  21048. e->setAttribute (T("category"), category);
  21049. e->setAttribute (T("manufacturer"), manufacturerName);
  21050. e->setAttribute (T("version"), version);
  21051. e->setAttribute (T("file"), file.getFullPathName());
  21052. e->setAttribute (T("uid"), String::toHexString (uid));
  21053. e->setAttribute (T("isInstrument"), isInstrument);
  21054. e->setAttribute (T("fileTime"), String::toHexString (lastFileModTime.toMilliseconds()));
  21055. e->setAttribute (T("numInputs"), numInputChannels);
  21056. e->setAttribute (T("numOutputs"), numOutputChannels);
  21057. return e;
  21058. }
  21059. bool PluginDescription::loadFromXml (const XmlElement& xml)
  21060. {
  21061. if (xml.hasTagName (T("PLUGIN")))
  21062. {
  21063. name = xml.getStringAttribute (T("name"));
  21064. pluginFormatName = xml.getStringAttribute (T("format"));
  21065. category = xml.getStringAttribute (T("category"));
  21066. manufacturerName = xml.getStringAttribute (T("manufacturer"));
  21067. version = xml.getStringAttribute (T("version"));
  21068. file = File (xml.getStringAttribute (T("file")));
  21069. uid = xml.getStringAttribute (T("uid")).getHexValue32();
  21070. isInstrument = xml.getBoolAttribute (T("isInstrument"), false);
  21071. lastFileModTime = Time (xml.getStringAttribute (T("fileTime")).getHexValue64());
  21072. numInputChannels = xml.getIntAttribute (T("numInputs"));
  21073. numOutputChannels = xml.getIntAttribute (T("numOutputs"));
  21074. return true;
  21075. }
  21076. return false;
  21077. }
  21078. END_JUCE_NAMESPACE
  21079. /********* End of inlined file: juce_PluginDescription.cpp *********/
  21080. /********* Start of inlined file: juce_PluginDirectoryScanner.cpp *********/
  21081. BEGIN_JUCE_NAMESPACE
  21082. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  21083. AudioPluginFormat& formatToLookFor,
  21084. FileSearchPath directoriesToSearch,
  21085. const bool recursive,
  21086. const File& deadMansPedalFile_)
  21087. : list (listToAddTo),
  21088. format (formatToLookFor),
  21089. deadMansPedalFile (deadMansPedalFile_),
  21090. nextIndex (0),
  21091. progress (0)
  21092. {
  21093. directoriesToSearch.removeRedundantPaths();
  21094. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  21095. recursiveFileSearch (directoriesToSearch [j], recursive);
  21096. // If any plugins have crashed recently when being loaded, move them to the
  21097. // end of the list to give the others a chance to load correctly..
  21098. const StringArray crashedPlugins (getDeadMansPedalFile());
  21099. for (int i = 0; i < crashedPlugins.size(); ++i)
  21100. {
  21101. const File f (crashedPlugins[i]);
  21102. for (int j = filesToScan.size(); --j >= 0;)
  21103. if (f == *filesToScan.getUnchecked (j))
  21104. filesToScan.move (j, -1);
  21105. }
  21106. }
  21107. void PluginDirectoryScanner::recursiveFileSearch (const File& dir, const bool recursive)
  21108. {
  21109. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  21110. // .component or .vst directories.
  21111. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  21112. while (iter.next())
  21113. {
  21114. const File f (iter.getFile());
  21115. bool isPlugin = false;
  21116. if (format.fileMightContainThisPluginType (f))
  21117. {
  21118. isPlugin = true;
  21119. filesToScan.add (new File (f));
  21120. }
  21121. if (recursive && (! isPlugin) && f.isDirectory())
  21122. recursiveFileSearch (f, true);
  21123. }
  21124. }
  21125. PluginDirectoryScanner::~PluginDirectoryScanner()
  21126. {
  21127. }
  21128. const File PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  21129. {
  21130. File* const file = filesToScan [nextIndex];
  21131. if (file != 0)
  21132. return *file;
  21133. return File::nonexistent;
  21134. }
  21135. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  21136. {
  21137. File* const file = filesToScan [nextIndex];
  21138. if (file != 0)
  21139. {
  21140. if (! list.isListingUpToDate (*file))
  21141. {
  21142. OwnedArray <PluginDescription> typesFound;
  21143. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  21144. StringArray crashedPlugins (getDeadMansPedalFile());
  21145. crashedPlugins.removeString (file->getFullPathName());
  21146. crashedPlugins.add (file->getFullPathName());
  21147. setDeadMansPedalFile (crashedPlugins);
  21148. list.scanAndAddFile (*file,
  21149. dontRescanIfAlreadyInList,
  21150. typesFound);
  21151. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  21152. crashedPlugins.removeString (file->getFullPathName());
  21153. setDeadMansPedalFile (crashedPlugins);
  21154. if (typesFound.size() == 0)
  21155. failedFiles.add (file->getFullPathName());
  21156. }
  21157. ++nextIndex;
  21158. progress = nextIndex / (float) filesToScan.size();
  21159. }
  21160. return nextIndex < filesToScan.size();
  21161. }
  21162. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  21163. {
  21164. StringArray lines;
  21165. if (deadMansPedalFile != File::nonexistent)
  21166. {
  21167. lines.addLines (deadMansPedalFile.loadFileAsString());
  21168. lines.removeEmptyStrings();
  21169. }
  21170. return lines;
  21171. }
  21172. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  21173. {
  21174. if (deadMansPedalFile != File::nonexistent)
  21175. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  21176. }
  21177. END_JUCE_NAMESPACE
  21178. /********* End of inlined file: juce_PluginDirectoryScanner.cpp *********/
  21179. /********* Start of inlined file: juce_PluginListComponent.cpp *********/
  21180. BEGIN_JUCE_NAMESPACE
  21181. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  21182. const File& deadMansPedalFile_,
  21183. PropertiesFile* const propertiesToUse_)
  21184. : list (listToEdit),
  21185. deadMansPedalFile (deadMansPedalFile_),
  21186. propertiesToUse (propertiesToUse_)
  21187. {
  21188. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  21189. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  21190. optionsButton->addButtonListener (this);
  21191. optionsButton->setTriggeredOnMouseDown (true);
  21192. setSize (400, 600);
  21193. list.addChangeListener (this);
  21194. }
  21195. PluginListComponent::~PluginListComponent()
  21196. {
  21197. list.removeChangeListener (this);
  21198. deleteAllChildren();
  21199. }
  21200. void PluginListComponent::resized()
  21201. {
  21202. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  21203. optionsButton->changeWidthToFitText (24);
  21204. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  21205. }
  21206. void PluginListComponent::changeListenerCallback (void*)
  21207. {
  21208. listBox->updateContent();
  21209. listBox->repaint();
  21210. }
  21211. int PluginListComponent::getNumRows()
  21212. {
  21213. return list.getNumTypes();
  21214. }
  21215. void PluginListComponent::paintListBoxItem (int row,
  21216. Graphics& g,
  21217. int width, int height,
  21218. bool rowIsSelected)
  21219. {
  21220. if (rowIsSelected)
  21221. g.fillAll (findColour (TextEditor::highlightColourId));
  21222. const PluginDescription* const pd = list.getType (row);
  21223. if (pd != 0)
  21224. {
  21225. GlyphArrangement ga;
  21226. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  21227. g.setColour (Colours::black);
  21228. ga.draw (g);
  21229. float x, y, r, b;
  21230. ga.getBoundingBox (0, -1, x, y, r, b, false);
  21231. String desc;
  21232. desc << pd->pluginFormatName
  21233. << (pd->isInstrument ? " instrument" : " effect")
  21234. << " - "
  21235. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  21236. << " / "
  21237. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  21238. if (pd->manufacturerName.isNotEmpty())
  21239. desc << " - " << pd->manufacturerName;
  21240. if (pd->version.isNotEmpty())
  21241. desc << " - " << pd->version;
  21242. if (pd->category.isNotEmpty())
  21243. desc << " - category: '" << pd->category << '\'';
  21244. g.setColour (Colours::grey);
  21245. ga.clear();
  21246. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, r + 10.0f, height * 0.8f, width - r - 12.0f, true);
  21247. ga.draw (g);
  21248. }
  21249. }
  21250. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  21251. {
  21252. list.removeType (lastRowSelected);
  21253. }
  21254. void PluginListComponent::buttonClicked (Button* b)
  21255. {
  21256. if (optionsButton == b)
  21257. {
  21258. PopupMenu menu;
  21259. menu.addItem (1, TRANS("Clear list"));
  21260. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  21261. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  21262. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  21263. menu.addSeparator();
  21264. menu.addItem (2, TRANS("Sort alphabetically"));
  21265. menu.addItem (3, TRANS("Sort by category"));
  21266. menu.addItem (4, TRANS("Sort by manufacturer"));
  21267. menu.addSeparator();
  21268. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  21269. {
  21270. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  21271. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  21272. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  21273. }
  21274. const int r = menu.showAt (optionsButton);
  21275. if (r == 1)
  21276. {
  21277. list.clear();
  21278. }
  21279. else if (r == 2)
  21280. {
  21281. list.sort (KnownPluginList::sortAlphabetically);
  21282. }
  21283. else if (r == 3)
  21284. {
  21285. list.sort (KnownPluginList::sortByCategory);
  21286. }
  21287. else if (r == 4)
  21288. {
  21289. list.sort (KnownPluginList::sortByManufacturer);
  21290. }
  21291. else if (r == 5)
  21292. {
  21293. const SparseSet <int> selected (listBox->getSelectedRows());
  21294. for (int i = list.getNumTypes(); --i >= 0;)
  21295. if (selected.contains (i))
  21296. list.removeType (i);
  21297. }
  21298. else if (r == 6)
  21299. {
  21300. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  21301. if (desc != 0)
  21302. desc->file.getParentDirectory().startAsProcess();
  21303. }
  21304. else if (r == 7)
  21305. {
  21306. for (int i = list.getNumTypes(); --i >= 0;)
  21307. {
  21308. if (list.getType (i)->file != File::nonexistent
  21309. && ! list.getType (i)->file.exists())
  21310. {
  21311. list.removeType (i);
  21312. }
  21313. }
  21314. }
  21315. else if (r != 0)
  21316. {
  21317. typeToScan = r - 10;
  21318. startTimer (1);
  21319. }
  21320. }
  21321. }
  21322. void PluginListComponent::timerCallback()
  21323. {
  21324. stopTimer();
  21325. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  21326. }
  21327. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  21328. {
  21329. return true;
  21330. }
  21331. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  21332. {
  21333. OwnedArray <PluginDescription> typesFound;
  21334. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  21335. }
  21336. void PluginListComponent::scanFor (AudioPluginFormat* format)
  21337. {
  21338. if (format == 0)
  21339. return;
  21340. FileSearchPath path (format->getDefaultLocationsToSearch());
  21341. if (propertiesToUse != 0)
  21342. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  21343. {
  21344. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  21345. FileSearchPathListComponent pathList;
  21346. pathList.setSize (500, 300);
  21347. pathList.setPath (path);
  21348. aw.addCustomComponent (&pathList);
  21349. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  21350. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  21351. if (aw.runModalLoop() == 0)
  21352. return;
  21353. path = pathList.getPath();
  21354. }
  21355. if (propertiesToUse != 0)
  21356. {
  21357. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  21358. propertiesToUse->saveIfNeeded();
  21359. }
  21360. double progress = 0.0;
  21361. AlertWindow aw (TRANS("Scanning for plugins..."),
  21362. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  21363. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  21364. aw.addProgressBarComponent (progress);
  21365. aw.enterModalState();
  21366. MessageManager::getInstance()->dispatchPendingMessages();
  21367. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  21368. for (;;)
  21369. {
  21370. aw.setMessage (TRANS("Testing:\n\n")
  21371. + scanner.getNextPluginFileThatWillBeScanned().getFileName());
  21372. MessageManager::getInstance()->dispatchPendingMessages (500);
  21373. if (! scanner.scanNextFile (true))
  21374. break;
  21375. if (! aw.isCurrentlyModal())
  21376. break;
  21377. progress = scanner.getProgress();
  21378. }
  21379. if (scanner.getFailedFiles().size() > 0)
  21380. {
  21381. StringArray shortNames;
  21382. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  21383. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  21384. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  21385. TRANS("Scan complete"),
  21386. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  21387. + shortNames.joinIntoString (", "));
  21388. }
  21389. }
  21390. END_JUCE_NAMESPACE
  21391. /********* End of inlined file: juce_PluginListComponent.cpp *********/
  21392. /********* Start of inlined file: juce_AudioUnitPluginFormat.cpp *********/
  21393. #if JUCE_PLUGINHOST_AU && (! (defined (LINUX) || defined (_WIN32)))
  21394. #include <Carbon/Carbon.h>
  21395. #include <AudioToolbox/AudioToolbox.h>
  21396. #include <AudioUnit/AudioUnitCarbonView.h>
  21397. BEGIN_JUCE_NAMESPACE
  21398. #if JUCE_MAC
  21399. extern void juce_callAnyTimersSynchronously();
  21400. extern bool juce_isHIViewCreatedByJuce (HIViewRef view);
  21401. extern bool juce_isWindowCreatedByJuce (WindowRef window);
  21402. #if MACOS_10_3_OR_EARLIER
  21403. #define kAudioUnitType_Generator 'augn'
  21404. #endif
  21405. // Change this to disable logging of various activities
  21406. #ifndef AU_LOGGING
  21407. #define AU_LOGGING 1
  21408. #endif
  21409. #if AU_LOGGING
  21410. #define log(a) Logger::writeToLog(a);
  21411. #else
  21412. #define log(a)
  21413. #endif
  21414. static int insideCallback = 0;
  21415. class AudioUnitPluginWindow;
  21416. class AudioUnitPluginInstance : public AudioPluginInstance
  21417. {
  21418. public:
  21419. ~AudioUnitPluginInstance();
  21420. // AudioPluginInstance methods:
  21421. void fillInPluginDescription (PluginDescription& desc) const
  21422. {
  21423. desc.name = pluginName;
  21424. desc.file = file;
  21425. desc.uid = ((int) componentDesc.componentType)
  21426. ^ ((int) componentDesc.componentSubType)
  21427. ^ ((int) componentDesc.componentManufacturer);
  21428. desc.lastFileModTime = file.getLastModificationTime();
  21429. desc.pluginFormatName = "AudioUnit";
  21430. desc.category = getCategory();
  21431. desc.manufacturerName = manufacturer;
  21432. desc.version = version;
  21433. desc.numInputChannels = getNumInputChannels();
  21434. desc.numOutputChannels = getNumOutputChannels();
  21435. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  21436. }
  21437. const String getName() const { return pluginName; }
  21438. bool acceptsMidi() const { return wantsMidiMessages; }
  21439. bool producesMidi() const { return false; }
  21440. // AudioProcessor methods:
  21441. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  21442. void releaseResources();
  21443. void processBlock (AudioSampleBuffer& buffer,
  21444. MidiBuffer& midiMessages);
  21445. AudioProcessorEditor* createEditor();
  21446. const String getInputChannelName (const int index) const;
  21447. bool isInputChannelStereoPair (int index) const;
  21448. const String getOutputChannelName (const int index) const;
  21449. bool isOutputChannelStereoPair (int index) const;
  21450. int getNumParameters();
  21451. float getParameter (int index);
  21452. void setParameter (int index, float newValue);
  21453. const String getParameterName (int index);
  21454. const String getParameterText (int index);
  21455. bool isParameterAutomatable (int index) const;
  21456. int getNumPrograms();
  21457. int getCurrentProgram();
  21458. void setCurrentProgram (int index);
  21459. const String getProgramName (int index);
  21460. void changeProgramName (int index, const String& newName);
  21461. void getStateInformation (MemoryBlock& destData);
  21462. void getCurrentProgramStateInformation (MemoryBlock& destData);
  21463. void setStateInformation (const void* data, int sizeInBytes);
  21464. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  21465. juce_UseDebuggingNewOperator
  21466. private:
  21467. friend class AudioUnitPluginWindow;
  21468. friend class AudioUnitPluginFormat;
  21469. ComponentDescription componentDesc;
  21470. String pluginName, manufacturer, version;
  21471. File file;
  21472. CriticalSection lock;
  21473. bool initialised, wantsMidiMessages, wasPlaying;
  21474. AudioBufferList* outputBufferList;
  21475. AudioTimeStamp timeStamp;
  21476. AudioSampleBuffer* currentBuffer;
  21477. AudioUnit audioUnit;
  21478. Array <int> parameterIds;
  21479. bool getComponentDescFromFile (const File& file);
  21480. void initialise();
  21481. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  21482. const AudioTimeStamp* inTimeStamp,
  21483. UInt32 inBusNumber,
  21484. UInt32 inNumberFrames,
  21485. AudioBufferList* ioData) const;
  21486. static OSStatus renderGetInputCallback (void* inRefCon,
  21487. AudioUnitRenderActionFlags* ioActionFlags,
  21488. const AudioTimeStamp* inTimeStamp,
  21489. UInt32 inBusNumber,
  21490. UInt32 inNumberFrames,
  21491. AudioBufferList* ioData)
  21492. {
  21493. return ((AudioUnitPluginInstance*) inRefCon)
  21494. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  21495. }
  21496. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  21497. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  21498. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  21499. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  21500. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  21501. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  21502. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  21503. {
  21504. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  21505. }
  21506. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  21507. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  21508. Float64* outCurrentMeasureDownBeat)
  21509. {
  21510. return ((AudioUnitPluginInstance*) inHostUserData)
  21511. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  21512. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  21513. }
  21514. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  21515. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  21516. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  21517. {
  21518. return ((AudioUnitPluginInstance*) inHostUserData)
  21519. ->getTransportState (outIsPlaying, outTransportStateChanged,
  21520. outCurrentSampleInTimeLine, outIsCycling,
  21521. outCycleStartBeat, outCycleEndBeat);
  21522. }
  21523. void getNumChannels (int& numIns, int& numOuts)
  21524. {
  21525. numIns = 0;
  21526. numOuts = 0;
  21527. AUChannelInfo supportedChannels [128];
  21528. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  21529. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  21530. 0, supportedChannels, &supportedChannelsSize) == noErr
  21531. && supportedChannelsSize > 0)
  21532. {
  21533. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  21534. {
  21535. numIns = jmax (numIns, supportedChannels[i].inChannels);
  21536. numOuts = jmax (numOuts, supportedChannels[i].outChannels);
  21537. }
  21538. }
  21539. else
  21540. {
  21541. // (this really means the plugin will take any number of ins/outs as long
  21542. // as they are the same)
  21543. numIns = numOuts = 2;
  21544. }
  21545. }
  21546. const String getCategory() const;
  21547. AudioUnitPluginInstance (const File& file);
  21548. };
  21549. AudioUnitPluginInstance::AudioUnitPluginInstance (const File& file_)
  21550. : file (file_),
  21551. initialised (false),
  21552. wantsMidiMessages (false),
  21553. audioUnit (0),
  21554. outputBufferList (0),
  21555. currentBuffer (0)
  21556. {
  21557. try
  21558. {
  21559. ++insideCallback;
  21560. log (T("Opening AU: ") + file.getFullPathName());
  21561. if (getComponentDescFromFile (file))
  21562. {
  21563. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  21564. if (comp != 0)
  21565. {
  21566. audioUnit = (AudioUnit) OpenComponent (comp);
  21567. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  21568. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  21569. }
  21570. }
  21571. --insideCallback;
  21572. }
  21573. catch (...)
  21574. {
  21575. --insideCallback;
  21576. }
  21577. }
  21578. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  21579. {
  21580. {
  21581. const ScopedLock sl (lock);
  21582. jassert (insideCallback == 0);
  21583. if (audioUnit != 0)
  21584. {
  21585. AudioUnitUninitialize (audioUnit);
  21586. CloseComponent (audioUnit);
  21587. audioUnit = 0;
  21588. }
  21589. }
  21590. juce_free (outputBufferList);
  21591. }
  21592. bool AudioUnitPluginInstance::getComponentDescFromFile (const File& file)
  21593. {
  21594. zerostruct (componentDesc);
  21595. if (! file.hasFileExtension (T(".component")))
  21596. return false;
  21597. const String filename (file.getFullPathName());
  21598. const char* const utf8 = filename.toUTF8();
  21599. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  21600. strlen (utf8), file.isDirectory());
  21601. if (url != 0)
  21602. {
  21603. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  21604. CFRelease (url);
  21605. if (bundleRef != 0)
  21606. {
  21607. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  21608. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  21609. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  21610. if (pluginName.isEmpty())
  21611. pluginName = file.getFileNameWithoutExtension();
  21612. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  21613. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  21614. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  21615. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  21616. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  21617. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  21618. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  21619. UseResFile (resFileId);
  21620. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  21621. {
  21622. Handle h = Get1IndResource ('thng', i);
  21623. if (h != 0)
  21624. {
  21625. HLock (h);
  21626. const uint32* const types = (const uint32*) *h;
  21627. if (types[0] == kAudioUnitType_MusicDevice
  21628. || types[0] == kAudioUnitType_MusicEffect
  21629. || types[0] == kAudioUnitType_Effect
  21630. || types[0] == kAudioUnitType_Generator
  21631. || types[0] == kAudioUnitType_Panner)
  21632. {
  21633. componentDesc.componentType = types[0];
  21634. componentDesc.componentSubType = types[1];
  21635. componentDesc.componentManufacturer = types[2];
  21636. break;
  21637. }
  21638. HUnlock (h);
  21639. ReleaseResource (h);
  21640. }
  21641. }
  21642. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  21643. CFRelease (bundleRef);
  21644. }
  21645. }
  21646. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  21647. }
  21648. void AudioUnitPluginInstance::initialise()
  21649. {
  21650. if (initialised || audioUnit == 0)
  21651. return;
  21652. log (T("Initialising AU: ") + pluginName);
  21653. parameterIds.clear();
  21654. {
  21655. UInt32 paramListSize = 0;
  21656. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  21657. 0, 0, &paramListSize);
  21658. if (paramListSize > 0)
  21659. {
  21660. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  21661. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  21662. 0, &parameterIds.getReference(0), &paramListSize);
  21663. }
  21664. }
  21665. {
  21666. AURenderCallbackStruct info;
  21667. zerostruct (info);
  21668. info.inputProcRefCon = this;
  21669. info.inputProc = renderGetInputCallback;
  21670. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  21671. 0, &info, sizeof (info));
  21672. }
  21673. {
  21674. HostCallbackInfo info;
  21675. zerostruct (info);
  21676. info.hostUserData = this;
  21677. info.beatAndTempoProc = getBeatAndTempoCallback;
  21678. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  21679. info.transportStateProc = getTransportStateCallback;
  21680. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  21681. 0, &info, sizeof (info));
  21682. }
  21683. int numIns, numOuts;
  21684. getNumChannels (numIns, numOuts);
  21685. setPlayConfigDetails (numIns, numOuts, 0, 0);
  21686. initialised = AudioUnitInitialize (audioUnit) == noErr;
  21687. setLatencySamples (0);
  21688. }
  21689. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  21690. int samplesPerBlockExpected)
  21691. {
  21692. initialise();
  21693. if (initialised)
  21694. {
  21695. int numIns, numOuts;
  21696. getNumChannels (numIns, numOuts);
  21697. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  21698. Float64 latencySecs = 0.0;
  21699. UInt32 latencySize = sizeof (latencySecs);
  21700. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  21701. 0, &latencySecs, &latencySize);
  21702. setLatencySamples (roundDoubleToInt (latencySecs * sampleRate_));
  21703. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  21704. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  21705. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  21706. AudioStreamBasicDescription stream;
  21707. zerostruct (stream);
  21708. stream.mSampleRate = sampleRate_;
  21709. stream.mFormatID = kAudioFormatLinearPCM;
  21710. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  21711. stream.mFramesPerPacket = 1;
  21712. stream.mBytesPerPacket = 4;
  21713. stream.mBytesPerFrame = 4;
  21714. stream.mBitsPerChannel = 32;
  21715. stream.mChannelsPerFrame = numIns;
  21716. OSStatus err = AudioUnitSetProperty (audioUnit,
  21717. kAudioUnitProperty_StreamFormat,
  21718. kAudioUnitScope_Input,
  21719. 0, &stream, sizeof (stream));
  21720. stream.mChannelsPerFrame = numOuts;
  21721. err = AudioUnitSetProperty (audioUnit,
  21722. kAudioUnitProperty_StreamFormat,
  21723. kAudioUnitScope_Output,
  21724. 0, &stream, sizeof (stream));
  21725. juce_free (outputBufferList);
  21726. outputBufferList = (AudioBufferList*) juce_calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1));
  21727. outputBufferList->mNumberBuffers = numOuts;
  21728. for (int i = numOuts; --i >= 0;)
  21729. outputBufferList->mBuffers[i].mNumberChannels = 1;
  21730. zerostruct (timeStamp);
  21731. timeStamp.mSampleTime = 0;
  21732. timeStamp.mHostTime = AudioGetCurrentHostTime();
  21733. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  21734. currentBuffer = 0;
  21735. wasPlaying = false;
  21736. }
  21737. }
  21738. void AudioUnitPluginInstance::releaseResources()
  21739. {
  21740. if (initialised)
  21741. {
  21742. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  21743. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  21744. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  21745. juce_free (outputBufferList);
  21746. outputBufferList = 0;
  21747. currentBuffer = 0;
  21748. }
  21749. }
  21750. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  21751. const AudioTimeStamp* inTimeStamp,
  21752. UInt32 inBusNumber,
  21753. UInt32 inNumberFrames,
  21754. AudioBufferList* ioData) const
  21755. {
  21756. if (inBusNumber == 0
  21757. && currentBuffer != 0)
  21758. {
  21759. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  21760. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  21761. {
  21762. if (i < currentBuffer->getNumChannels())
  21763. {
  21764. memcpy (ioData->mBuffers[i].mData,
  21765. currentBuffer->getSampleData (i, 0),
  21766. sizeof (float) * inNumberFrames);
  21767. }
  21768. else
  21769. {
  21770. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  21771. }
  21772. }
  21773. }
  21774. return noErr;
  21775. }
  21776. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  21777. MidiBuffer& midiMessages)
  21778. {
  21779. const int numSamples = buffer.getNumSamples();
  21780. if (initialised)
  21781. {
  21782. AudioUnitRenderActionFlags flags = 0;
  21783. timeStamp.mHostTime = AudioGetCurrentHostTime();
  21784. for (int i = getNumOutputChannels(); --i >= 0;)
  21785. {
  21786. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  21787. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  21788. }
  21789. currentBuffer = &buffer;
  21790. if (wantsMidiMessages)
  21791. {
  21792. const uint8* midiEventData;
  21793. int midiEventSize, midiEventPosition;
  21794. MidiBuffer::Iterator i (midiMessages);
  21795. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  21796. {
  21797. if (midiEventSize <= 3)
  21798. MusicDeviceMIDIEvent (audioUnit,
  21799. midiEventData[0], midiEventData[1], midiEventData[2],
  21800. midiEventPosition);
  21801. else
  21802. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  21803. }
  21804. midiMessages.clear();
  21805. }
  21806. AudioUnitRender (audioUnit, &flags, &timeStamp,
  21807. 0, numSamples, outputBufferList);
  21808. timeStamp.mSampleTime += numSamples;
  21809. }
  21810. else
  21811. {
  21812. // Not initialised, so just bypass..
  21813. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  21814. buffer.clear (i, 0, buffer.getNumSamples());
  21815. }
  21816. }
  21817. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  21818. {
  21819. AudioPlayHead* const ph = getPlayHead();
  21820. AudioPlayHead::CurrentPositionInfo result;
  21821. if (ph != 0 && ph->getCurrentPosition (result))
  21822. {
  21823. *outCurrentBeat = result.ppqPosition;
  21824. *outCurrentTempo = result.bpm;
  21825. }
  21826. else
  21827. {
  21828. *outCurrentBeat = 0;
  21829. *outCurrentTempo = 120.0;
  21830. }
  21831. return noErr;
  21832. }
  21833. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  21834. Float32* outTimeSig_Numerator,
  21835. UInt32* outTimeSig_Denominator,
  21836. Float64* outCurrentMeasureDownBeat) const
  21837. {
  21838. AudioPlayHead* const ph = getPlayHead();
  21839. AudioPlayHead::CurrentPositionInfo result;
  21840. if (ph != 0 && ph->getCurrentPosition (result))
  21841. {
  21842. *outTimeSig_Numerator = result.timeSigNumerator;
  21843. *outTimeSig_Denominator = result.timeSigDenominator;
  21844. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  21845. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  21846. }
  21847. else
  21848. {
  21849. *outDeltaSampleOffsetToNextBeat = 0;
  21850. *outTimeSig_Numerator = 4;
  21851. *outTimeSig_Denominator = 4;
  21852. *outCurrentMeasureDownBeat = 0;
  21853. }
  21854. return noErr;
  21855. }
  21856. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  21857. Boolean* outTransportStateChanged,
  21858. Float64* outCurrentSampleInTimeLine,
  21859. Boolean* outIsCycling,
  21860. Float64* outCycleStartBeat,
  21861. Float64* outCycleEndBeat)
  21862. {
  21863. AudioPlayHead* const ph = getPlayHead();
  21864. AudioPlayHead::CurrentPositionInfo result;
  21865. if (ph != 0 && ph->getCurrentPosition (result))
  21866. {
  21867. *outIsPlaying = result.isPlaying;
  21868. *outTransportStateChanged = result.isPlaying != wasPlaying;
  21869. wasPlaying = result.isPlaying;
  21870. *outCurrentSampleInTimeLine = roundDoubleToInt (result.timeInSeconds * getSampleRate());
  21871. *outIsCycling = false;
  21872. *outCycleStartBeat = 0;
  21873. *outCycleEndBeat = 0;
  21874. }
  21875. else
  21876. {
  21877. *outIsPlaying = false;
  21878. *outTransportStateChanged = false;
  21879. *outCurrentSampleInTimeLine = 0;
  21880. *outIsCycling = false;
  21881. *outCycleStartBeat = 0;
  21882. *outCycleEndBeat = 0;
  21883. }
  21884. return noErr;
  21885. }
  21886. static VoidArray activeWindows;
  21887. class AudioUnitPluginWindow : public AudioProcessorEditor,
  21888. public Timer
  21889. {
  21890. public:
  21891. AudioUnitPluginWindow (AudioUnitPluginInstance& plugin_)
  21892. : AudioProcessorEditor (&plugin_),
  21893. plugin (plugin_),
  21894. isOpen (false),
  21895. pluginWantsKeys (false),
  21896. wasShowing (false),
  21897. recursiveResize (false),
  21898. viewComponent (0),
  21899. pluginViewRef (0)
  21900. {
  21901. movementWatcher = new CompMovementWatcher (this);
  21902. activeWindows.add (this);
  21903. setOpaque (true);
  21904. setVisible (true);
  21905. setSize (1, 1);
  21906. ComponentDescription viewList [16];
  21907. UInt32 viewListSize = sizeof (viewList);
  21908. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  21909. 0, &viewList, &viewListSize);
  21910. componentRecord = FindNextComponent (0, &viewList[0]);
  21911. }
  21912. ~AudioUnitPluginWindow()
  21913. {
  21914. deleteAndZero (movementWatcher);
  21915. closePluginWindow();
  21916. activeWindows.removeValue (this);
  21917. plugin.editorBeingDeleted (this);
  21918. }
  21919. bool isValid() const throw() { return componentRecord != 0; }
  21920. void componentMovedOrResized()
  21921. {
  21922. if (recursiveResize)
  21923. return;
  21924. Component* const topComp = getTopLevelComponent();
  21925. if (topComp->getPeer() != 0)
  21926. {
  21927. int x = 0, y = 0;
  21928. relativePositionToOtherComponent (topComp, x, y);
  21929. recursiveResize = true;
  21930. if (pluginViewRef != 0)
  21931. {
  21932. HIRect r;
  21933. r.origin.x = (float) x;
  21934. r.origin.y = (float) y;
  21935. r.size.width = (float) getWidth();
  21936. r.size.height = (float) getHeight();
  21937. HIViewSetFrame (pluginViewRef, &r);
  21938. }
  21939. recursiveResize = false;
  21940. }
  21941. }
  21942. void componentVisibilityChanged()
  21943. {
  21944. const bool isShowingNow = isShowing();
  21945. if (wasShowing != isShowingNow)
  21946. {
  21947. wasShowing = isShowingNow;
  21948. if (isShowingNow)
  21949. openPluginWindow();
  21950. else
  21951. closePluginWindow();
  21952. }
  21953. componentMovedOrResized();
  21954. }
  21955. void componentPeerChanged()
  21956. {
  21957. closePluginWindow();
  21958. openPluginWindow();
  21959. }
  21960. void timerCallback()
  21961. {
  21962. if (pluginViewRef != 0)
  21963. {
  21964. HIRect bounds;
  21965. HIViewGetBounds (pluginViewRef, &bounds);
  21966. const int w = jmax (32, (int) bounds.size.width);
  21967. const int h = jmax (32, (int) bounds.size.height);
  21968. if (w != getWidth() || h != getHeight())
  21969. {
  21970. setSize (w, h);
  21971. startTimer (50);
  21972. }
  21973. else
  21974. {
  21975. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  21976. }
  21977. }
  21978. }
  21979. bool keyStateChanged()
  21980. {
  21981. return pluginWantsKeys;
  21982. }
  21983. bool keyPressed (const KeyPress&)
  21984. {
  21985. return pluginWantsKeys;
  21986. }
  21987. void paint (Graphics& g)
  21988. {
  21989. if (isOpen)
  21990. {
  21991. ComponentPeer* const peer = getPeer();
  21992. if (peer != 0)
  21993. {
  21994. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  21995. getScreenY() - peer->getScreenY(),
  21996. getWidth(), getHeight());
  21997. }
  21998. }
  21999. else
  22000. {
  22001. g.fillAll (Colours::black);
  22002. }
  22003. }
  22004. void broughtToFront()
  22005. {
  22006. activeWindows.removeValue (this);
  22007. activeWindows.add (this);
  22008. }
  22009. juce_UseDebuggingNewOperator
  22010. private:
  22011. AudioUnitPluginInstance& plugin;
  22012. bool isOpen, wasShowing, recursiveResize;
  22013. bool pluginWantsKeys;
  22014. ComponentRecord* componentRecord;
  22015. AudioUnitCarbonView viewComponent;
  22016. HIViewRef pluginViewRef;
  22017. void openPluginWindow()
  22018. {
  22019. if (isOpen || getWindowHandle() == 0 || componentRecord == 0)
  22020. return;
  22021. log (T("Opening AU GUI: ") + plugin.getName());
  22022. isOpen = true;
  22023. pluginWantsKeys = true; //xxx any way to find this out? Does it matter?
  22024. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  22025. if (viewComponent != 0)
  22026. {
  22027. Float32Point pos = { getScreenX() - getTopLevelComponent()->getScreenX(),
  22028. getScreenY() - getTopLevelComponent()->getScreenY() };
  22029. Float32Point size = { 250, 200 };
  22030. AudioUnitCarbonViewCreate (viewComponent,
  22031. plugin.audioUnit,
  22032. (WindowRef) getWindowHandle(),
  22033. HIViewGetRoot ((WindowRef) getWindowHandle()),
  22034. &pos, &size,
  22035. (ControlRef*) &pluginViewRef);
  22036. }
  22037. timerCallback(); // to set our comp to the right size
  22038. repaint();
  22039. }
  22040. void closePluginWindow()
  22041. {
  22042. stopTimer();
  22043. if (isOpen)
  22044. {
  22045. log (T("Closing AU GUI: ") + plugin.getName());
  22046. isOpen = false;
  22047. if (viewComponent != 0)
  22048. CloseComponent (viewComponent);
  22049. pluginViewRef = 0;
  22050. }
  22051. }
  22052. class CompMovementWatcher : public ComponentMovementWatcher
  22053. {
  22054. public:
  22055. CompMovementWatcher (AudioUnitPluginWindow* const owner_)
  22056. : ComponentMovementWatcher (owner_),
  22057. owner (owner_)
  22058. {
  22059. }
  22060. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  22061. {
  22062. owner->componentMovedOrResized();
  22063. }
  22064. void componentPeerChanged()
  22065. {
  22066. owner->componentPeerChanged();
  22067. }
  22068. void componentVisibilityChanged (Component&)
  22069. {
  22070. owner->componentVisibilityChanged();
  22071. }
  22072. private:
  22073. AudioUnitPluginWindow* const owner;
  22074. };
  22075. CompMovementWatcher* movementWatcher;
  22076. };
  22077. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  22078. {
  22079. AudioUnitPluginWindow* w = new AudioUnitPluginWindow (*this);
  22080. if (! w->isValid())
  22081. deleteAndZero (w);
  22082. return w;
  22083. }
  22084. const String AudioUnitPluginInstance::getCategory() const
  22085. {
  22086. const char* result = 0;
  22087. switch (componentDesc.componentType)
  22088. {
  22089. case kAudioUnitType_Effect:
  22090. case kAudioUnitType_MusicEffect:
  22091. result = "Effect";
  22092. break;
  22093. case kAudioUnitType_MusicDevice:
  22094. result = "Synth";
  22095. break;
  22096. case kAudioUnitType_Generator:
  22097. result = "Generator";
  22098. break;
  22099. case kAudioUnitType_Panner:
  22100. result = "Panner";
  22101. break;
  22102. default:
  22103. break;
  22104. }
  22105. return result;
  22106. }
  22107. int AudioUnitPluginInstance::getNumParameters()
  22108. {
  22109. return parameterIds.size();
  22110. }
  22111. float AudioUnitPluginInstance::getParameter (int index)
  22112. {
  22113. const ScopedLock sl (lock);
  22114. Float32 value = 0.0f;
  22115. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  22116. {
  22117. AudioUnitGetParameter (audioUnit,
  22118. (UInt32) parameterIds.getUnchecked (index),
  22119. kAudioUnitScope_Global, 0,
  22120. &value);
  22121. }
  22122. return value;
  22123. }
  22124. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  22125. {
  22126. const ScopedLock sl (lock);
  22127. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  22128. {
  22129. AudioUnitSetParameter (audioUnit,
  22130. (UInt32) parameterIds.getUnchecked (index),
  22131. kAudioUnitScope_Global, 0,
  22132. newValue, 0);
  22133. }
  22134. }
  22135. const String AudioUnitPluginInstance::getParameterName (int index)
  22136. {
  22137. AudioUnitParameterInfo info;
  22138. zerostruct (info);
  22139. UInt32 sz = sizeof (info);
  22140. String name;
  22141. if (AudioUnitGetProperty (audioUnit,
  22142. kAudioUnitProperty_ParameterInfo,
  22143. kAudioUnitScope_Global,
  22144. parameterIds [index], &info, &sz) == noErr)
  22145. {
  22146. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  22147. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  22148. else
  22149. name = String (info.name, sizeof (info.name));
  22150. }
  22151. return name;
  22152. }
  22153. const String AudioUnitPluginInstance::getParameterText (int index)
  22154. {
  22155. return String (getParameter (index));
  22156. }
  22157. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  22158. {
  22159. AudioUnitParameterInfo info;
  22160. UInt32 sz = sizeof (info);
  22161. if (AudioUnitGetProperty (audioUnit,
  22162. kAudioUnitProperty_ParameterInfo,
  22163. kAudioUnitScope_Global,
  22164. parameterIds [index], &info, &sz) == noErr)
  22165. {
  22166. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  22167. }
  22168. return true;
  22169. }
  22170. int AudioUnitPluginInstance::getNumPrograms()
  22171. {
  22172. CFArrayRef presets;
  22173. UInt32 sz = sizeof (CFArrayRef);
  22174. int num = 0;
  22175. if (AudioUnitGetProperty (audioUnit,
  22176. kAudioUnitProperty_FactoryPresets,
  22177. kAudioUnitScope_Global,
  22178. 0, &presets, &sz) == noErr)
  22179. {
  22180. num = (int) CFArrayGetCount (presets);
  22181. CFRelease (presets);
  22182. }
  22183. return num;
  22184. }
  22185. int AudioUnitPluginInstance::getCurrentProgram()
  22186. {
  22187. AUPreset current;
  22188. current.presetNumber = 0;
  22189. UInt32 sz = sizeof (AUPreset);
  22190. AudioUnitGetProperty (audioUnit,
  22191. kAudioUnitProperty_FactoryPresets,
  22192. kAudioUnitScope_Global,
  22193. 0, &current, &sz);
  22194. return current.presetNumber;
  22195. }
  22196. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  22197. {
  22198. AUPreset current;
  22199. current.presetNumber = newIndex;
  22200. current.presetName = 0;
  22201. AudioUnitSetProperty (audioUnit,
  22202. kAudioUnitProperty_FactoryPresets,
  22203. kAudioUnitScope_Global,
  22204. 0, &current, sizeof (AUPreset));
  22205. }
  22206. const String AudioUnitPluginInstance::getProgramName (int index)
  22207. {
  22208. String s;
  22209. CFArrayRef presets;
  22210. UInt32 sz = sizeof (CFArrayRef);
  22211. if (AudioUnitGetProperty (audioUnit,
  22212. kAudioUnitProperty_FactoryPresets,
  22213. kAudioUnitScope_Global,
  22214. 0, &presets, &sz) == noErr)
  22215. {
  22216. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  22217. {
  22218. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  22219. if (p != 0 && p->presetNumber == index)
  22220. {
  22221. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  22222. break;
  22223. }
  22224. }
  22225. CFRelease (presets);
  22226. }
  22227. return s;
  22228. }
  22229. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  22230. {
  22231. jassertfalse // xxx not implemented!
  22232. }
  22233. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  22234. {
  22235. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  22236. return T("Input ") + String (index + 1);
  22237. return String::empty;
  22238. }
  22239. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  22240. {
  22241. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  22242. return false;
  22243. return true;
  22244. }
  22245. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  22246. {
  22247. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  22248. return T("Output ") + String (index + 1);
  22249. return String::empty;
  22250. }
  22251. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  22252. {
  22253. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  22254. return false;
  22255. return true;
  22256. }
  22257. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  22258. {
  22259. getCurrentProgramStateInformation (destData);
  22260. }
  22261. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  22262. {
  22263. CFPropertyListRef propertyList = 0;
  22264. UInt32 sz = sizeof (CFPropertyListRef);
  22265. if (AudioUnitGetProperty (audioUnit,
  22266. kAudioUnitProperty_ClassInfo,
  22267. kAudioUnitScope_Global,
  22268. 0, &propertyList, &sz) == noErr)
  22269. {
  22270. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  22271. CFWriteStreamOpen (stream);
  22272. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  22273. CFWriteStreamClose (stream);
  22274. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  22275. destData.setSize (bytesWritten);
  22276. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  22277. CFRelease (data);
  22278. CFRelease (stream);
  22279. CFRelease (propertyList);
  22280. }
  22281. }
  22282. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  22283. {
  22284. setCurrentProgramStateInformation (data, sizeInBytes);
  22285. }
  22286. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  22287. {
  22288. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  22289. (const UInt8*) data,
  22290. sizeInBytes,
  22291. kCFAllocatorNull);
  22292. CFReadStreamOpen (stream);
  22293. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  22294. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  22295. stream,
  22296. 0,
  22297. kCFPropertyListImmutable,
  22298. &format,
  22299. 0);
  22300. CFRelease (stream);
  22301. if (propertyList != 0)
  22302. AudioUnitSetProperty (audioUnit,
  22303. kAudioUnitProperty_ClassInfo,
  22304. kAudioUnitScope_Global,
  22305. 0, &propertyList, sizeof (propertyList));
  22306. }
  22307. AudioUnitPluginFormat::AudioUnitPluginFormat()
  22308. {
  22309. }
  22310. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  22311. {
  22312. }
  22313. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  22314. const File& file)
  22315. {
  22316. if (! fileMightContainThisPluginType (file))
  22317. return;
  22318. PluginDescription desc;
  22319. desc.file = file;
  22320. desc.uid = 0;
  22321. AudioUnitPluginInstance* instance = dynamic_cast <AudioUnitPluginInstance*> (createInstanceFromDescription (desc));
  22322. if (instance == 0)
  22323. return;
  22324. try
  22325. {
  22326. instance->fillInPluginDescription (desc);
  22327. results.add (new PluginDescription (desc));
  22328. }
  22329. catch (...)
  22330. {
  22331. // crashed while loading...
  22332. }
  22333. deleteAndZero (instance);
  22334. }
  22335. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  22336. {
  22337. AudioUnitPluginInstance* result = 0;
  22338. if (fileMightContainThisPluginType (desc.file))
  22339. {
  22340. result = new AudioUnitPluginInstance (desc.file);
  22341. if (result->audioUnit != 0)
  22342. {
  22343. result->initialise();
  22344. }
  22345. else
  22346. {
  22347. deleteAndZero (result);
  22348. }
  22349. }
  22350. return result;
  22351. }
  22352. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const File& f)
  22353. {
  22354. return f.hasFileExtension (T(".component"))
  22355. && f.isDirectory();
  22356. }
  22357. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  22358. {
  22359. return FileSearchPath ("~/Library/Audio/Plug-Ins/Components;/Library/Audio/Plug-Ins/Components");
  22360. }
  22361. #endif
  22362. END_JUCE_NAMESPACE
  22363. #undef log
  22364. #endif
  22365. /********* End of inlined file: juce_AudioUnitPluginFormat.cpp *********/
  22366. /********* Start of inlined file: juce_VSTPluginFormat.cpp *********/
  22367. #if JUCE_PLUGINHOST_VST
  22368. #ifdef _WIN32
  22369. #undef _WIN32_WINNT
  22370. #define _WIN32_WINNT 0x500
  22371. #undef STRICT
  22372. #define STRICT
  22373. #include <windows.h>
  22374. #include <float.h>
  22375. #pragma warning (disable : 4312)
  22376. #elif defined (LINUX)
  22377. #include <float.h>
  22378. #include <sys/time.h>
  22379. #include <X11/Xlib.h>
  22380. #include <X11/Xutil.h>
  22381. #include <X11/Xatom.h>
  22382. #undef Font
  22383. #undef KeyPress
  22384. #undef Drawable
  22385. #undef Time
  22386. #else
  22387. #include <Carbon/Carbon.h>
  22388. #endif
  22389. BEGIN_JUCE_NAMESPACE
  22390. #undef PRAGMA_ALIGN_SUPPORTED
  22391. #define VST_FORCE_DEPRECATED 0
  22392. #ifdef _MSC_VER
  22393. #pragma warning (push)
  22394. #pragma warning (disable: 4996)
  22395. #endif
  22396. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  22397. your include path if you want to add VST support.
  22398. If you're not interested in VSTs, you can disable them by changing the
  22399. JUCE_PLUGINHOST_VST flag in juce_Config.h
  22400. */
  22401. #include "pluginterfaces/vst2.x/aeffectx.h"
  22402. #ifdef _MSC_VER
  22403. #pragma warning (pop)
  22404. #endif
  22405. #if JUCE_LINUX
  22406. #define Font JUCE_NAMESPACE::Font
  22407. #define KeyPress JUCE_NAMESPACE::KeyPress
  22408. #define Drawable JUCE_NAMESPACE::Drawable
  22409. #define Time JUCE_NAMESPACE::Time
  22410. #endif
  22411. #if ! JUCE_WIN32
  22412. #define _fpreset()
  22413. #define _clearfp()
  22414. #endif
  22415. extern void juce_callAnyTimersSynchronously();
  22416. const int fxbVersionNum = 1;
  22417. struct fxProgram
  22418. {
  22419. long chunkMagic; // 'CcnK'
  22420. long byteSize; // of this chunk, excl. magic + byteSize
  22421. long fxMagic; // 'FxCk'
  22422. long version;
  22423. long fxID; // fx unique id
  22424. long fxVersion;
  22425. long numParams;
  22426. char prgName[28];
  22427. float params[1]; // variable no. of parameters
  22428. };
  22429. struct fxSet
  22430. {
  22431. long chunkMagic; // 'CcnK'
  22432. long byteSize; // of this chunk, excl. magic + byteSize
  22433. long fxMagic; // 'FxBk'
  22434. long version;
  22435. long fxID; // fx unique id
  22436. long fxVersion;
  22437. long numPrograms;
  22438. char future[128];
  22439. fxProgram programs[1]; // variable no. of programs
  22440. };
  22441. struct fxChunkSet
  22442. {
  22443. long chunkMagic; // 'CcnK'
  22444. long byteSize; // of this chunk, excl. magic + byteSize
  22445. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  22446. long version;
  22447. long fxID; // fx unique id
  22448. long fxVersion;
  22449. long numPrograms;
  22450. char future[128];
  22451. long chunkSize;
  22452. char chunk[8]; // variable
  22453. };
  22454. struct fxProgramSet
  22455. {
  22456. long chunkMagic; // 'CcnK'
  22457. long byteSize; // of this chunk, excl. magic + byteSize
  22458. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  22459. long version;
  22460. long fxID; // fx unique id
  22461. long fxVersion;
  22462. long numPrograms;
  22463. char name[28];
  22464. long chunkSize;
  22465. char chunk[8]; // variable
  22466. };
  22467. #ifdef JUCE_LITTLE_ENDIAN
  22468. static long vst_swap (const long x) throw() { return (long) swapByteOrder ((uint32) x); }
  22469. static float vst_swapFloat (const float x) throw()
  22470. {
  22471. union { uint32 asInt; float asFloat; } n;
  22472. n.asFloat = x;
  22473. n.asInt = swapByteOrder (n.asInt);
  22474. return n.asFloat;
  22475. }
  22476. #else
  22477. #define vst_swap(x) (x)
  22478. #define vst_swapFloat(x) (x)
  22479. #endif
  22480. typedef AEffect* (*MainCall) (audioMasterCallback);
  22481. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  22482. static int shellUIDToCreate = 0;
  22483. static int insideVSTCallback = 0;
  22484. class VSTPluginWindow;
  22485. // Change this to disable logging of various VST activities
  22486. #ifndef VST_LOGGING
  22487. #define VST_LOGGING 1
  22488. #endif
  22489. #if VST_LOGGING
  22490. #define log(a) Logger::writeToLog(a);
  22491. #else
  22492. #define log(a)
  22493. #endif
  22494. #if JUCE_MAC
  22495. extern bool juce_isHIViewCreatedByJuce (HIViewRef view);
  22496. extern bool juce_isWindowCreatedByJuce (WindowRef window);
  22497. #if JUCE_PPC
  22498. static void* NewCFMFromMachO (void* const machofp) throw()
  22499. {
  22500. void* result = juce_malloc (8);
  22501. ((void**) result)[0] = machofp;
  22502. ((void**) result)[1] = result;
  22503. return result;
  22504. }
  22505. #endif
  22506. #endif
  22507. #if JUCE_LINUX
  22508. extern Display* display;
  22509. extern XContext improbableNumber;
  22510. typedef void (*EventProcPtr) (XEvent* ev);
  22511. static bool xErrorTriggered;
  22512. static int temporaryErrorHandler (Display*, XErrorEvent*)
  22513. {
  22514. xErrorTriggered = true;
  22515. return 0;
  22516. }
  22517. static int getPropertyFromXWindow (Window handle, Atom atom)
  22518. {
  22519. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  22520. xErrorTriggered = false;
  22521. int userSize;
  22522. unsigned long bytes, userCount;
  22523. unsigned char* data;
  22524. Atom userType;
  22525. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  22526. &userType, &userSize, &userCount, &bytes, &data);
  22527. XSetErrorHandler (oldErrorHandler);
  22528. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  22529. : 0;
  22530. }
  22531. static Window getChildWindow (Window windowToCheck)
  22532. {
  22533. Window rootWindow, parentWindow;
  22534. Window* childWindows;
  22535. unsigned int numChildren;
  22536. XQueryTree (display,
  22537. windowToCheck,
  22538. &rootWindow,
  22539. &parentWindow,
  22540. &childWindows,
  22541. &numChildren);
  22542. if (numChildren > 0)
  22543. return childWindows [0];
  22544. return 0;
  22545. }
  22546. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  22547. {
  22548. if (e.mods.isLeftButtonDown())
  22549. {
  22550. ev.xbutton.button = Button1;
  22551. ev.xbutton.state |= Button1Mask;
  22552. }
  22553. else if (e.mods.isRightButtonDown())
  22554. {
  22555. ev.xbutton.button = Button3;
  22556. ev.xbutton.state |= Button3Mask;
  22557. }
  22558. else if (e.mods.isMiddleButtonDown())
  22559. {
  22560. ev.xbutton.button = Button2;
  22561. ev.xbutton.state |= Button2Mask;
  22562. }
  22563. }
  22564. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  22565. {
  22566. if (e.mods.isLeftButtonDown())
  22567. ev.xmotion.state |= Button1Mask;
  22568. else if (e.mods.isRightButtonDown())
  22569. ev.xmotion.state |= Button3Mask;
  22570. else if (e.mods.isMiddleButtonDown())
  22571. ev.xmotion.state |= Button2Mask;
  22572. }
  22573. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  22574. {
  22575. if (e.mods.isLeftButtonDown())
  22576. ev.xcrossing.state |= Button1Mask;
  22577. else if (e.mods.isRightButtonDown())
  22578. ev.xcrossing.state |= Button3Mask;
  22579. else if (e.mods.isMiddleButtonDown())
  22580. ev.xcrossing.state |= Button2Mask;
  22581. }
  22582. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  22583. {
  22584. if (increment < 0)
  22585. {
  22586. ev.xbutton.button = Button5;
  22587. ev.xbutton.state |= Button5Mask;
  22588. }
  22589. else if (increment > 0)
  22590. {
  22591. ev.xbutton.button = Button4;
  22592. ev.xbutton.state |= Button4Mask;
  22593. }
  22594. }
  22595. #endif
  22596. static VoidArray activeModules;
  22597. class ModuleHandle : public ReferenceCountedObject
  22598. {
  22599. public:
  22600. File file;
  22601. MainCall moduleMain;
  22602. String pluginName;
  22603. static ModuleHandle* findOrCreateModule (const File& file)
  22604. {
  22605. for (int i = activeModules.size(); --i >= 0;)
  22606. {
  22607. ModuleHandle* const module = (ModuleHandle*) activeModules.getUnchecked(i);
  22608. if (module->file == file)
  22609. return module;
  22610. }
  22611. _fpreset(); // (doesn't do any harm)
  22612. ++insideVSTCallback;
  22613. shellUIDToCreate = 0;
  22614. log ("Attempting to load VST: " + file.getFullPathName());
  22615. ModuleHandle* m = new ModuleHandle (file);
  22616. if (! m->open())
  22617. deleteAndZero (m);
  22618. --insideVSTCallback;
  22619. _fpreset(); // (doesn't do any harm)
  22620. return m;
  22621. }
  22622. ModuleHandle (const File& file_)
  22623. : file (file_),
  22624. moduleMain (0),
  22625. #if JUCE_WIN32 || JUCE_LINUX
  22626. hModule (0)
  22627. #elif JUCE_MAC
  22628. fragId (0),
  22629. resHandle (0),
  22630. bundleRef (0),
  22631. resFileId (0)
  22632. #endif
  22633. {
  22634. activeModules.add (this);
  22635. #if JUCE_WIN32 || JUCE_LINUX
  22636. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  22637. #elif JUCE_MAC
  22638. PlatformUtilities::makeFSSpecFromPath (&parentDirFSSpec, file_.getParentDirectory().getFullPathName());
  22639. #endif
  22640. }
  22641. ~ModuleHandle()
  22642. {
  22643. activeModules.removeValue (this);
  22644. close();
  22645. }
  22646. juce_UseDebuggingNewOperator
  22647. #if JUCE_WIN32 || JUCE_LINUX
  22648. void* hModule;
  22649. String fullParentDirectoryPathName;
  22650. bool open()
  22651. {
  22652. #if JUCE_WIN32
  22653. static bool timePeriodSet = false;
  22654. if (! timePeriodSet)
  22655. {
  22656. timePeriodSet = true;
  22657. timeBeginPeriod (2);
  22658. }
  22659. #endif
  22660. pluginName = file.getFileNameWithoutExtension();
  22661. hModule = Process::loadDynamicLibrary (file.getFullPathName());
  22662. moduleMain = (MainCall) Process::getProcedureEntryPoint (hModule, "VSTPluginMain");
  22663. if (moduleMain == 0)
  22664. moduleMain = (MainCall) Process::getProcedureEntryPoint (hModule, "main");
  22665. return moduleMain != 0;
  22666. }
  22667. void close()
  22668. {
  22669. _fpreset(); // (doesn't do any harm)
  22670. Process::freeDynamicLibrary (hModule);
  22671. }
  22672. void closeEffect (AEffect* eff)
  22673. {
  22674. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  22675. }
  22676. #else
  22677. CFragConnectionID fragId;
  22678. Handle resHandle;
  22679. CFBundleRef bundleRef;
  22680. FSSpec parentDirFSSpec;
  22681. short resFileId;
  22682. bool open()
  22683. {
  22684. bool ok = false;
  22685. const String filename (file.getFullPathName());
  22686. if (file.hasFileExtension (T(".vst")))
  22687. {
  22688. const char* const utf8 = filename.toUTF8();
  22689. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  22690. strlen (utf8), file.isDirectory());
  22691. if (url != 0)
  22692. {
  22693. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  22694. CFRelease (url);
  22695. if (bundleRef != 0)
  22696. {
  22697. if (CFBundleLoadExecutable (bundleRef))
  22698. {
  22699. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  22700. if (moduleMain == 0)
  22701. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  22702. if (moduleMain != 0)
  22703. {
  22704. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  22705. if (name != 0)
  22706. {
  22707. if (CFGetTypeID (name) == CFStringGetTypeID())
  22708. {
  22709. char buffer[1024];
  22710. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  22711. pluginName = buffer;
  22712. }
  22713. }
  22714. if (pluginName.isEmpty())
  22715. pluginName = file.getFileNameWithoutExtension();
  22716. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  22717. ok = true;
  22718. }
  22719. }
  22720. if (! ok)
  22721. {
  22722. CFBundleUnloadExecutable (bundleRef);
  22723. CFRelease (bundleRef);
  22724. bundleRef = 0;
  22725. }
  22726. }
  22727. }
  22728. }
  22729. #if JUCE_PPC
  22730. else
  22731. {
  22732. FSRef fn;
  22733. if (FSPathMakeRef ((UInt8*) (const char*) filename, &fn, 0) == noErr)
  22734. {
  22735. resFileId = FSOpenResFile (&fn, fsRdPerm);
  22736. if (resFileId != -1)
  22737. {
  22738. const int numEffs = Count1Resources ('aEff');
  22739. for (int i = 0; i < numEffs; ++i)
  22740. {
  22741. resHandle = Get1IndResource ('aEff', i + 1);
  22742. if (resHandle != 0)
  22743. {
  22744. OSType type;
  22745. Str255 name;
  22746. SInt16 id;
  22747. GetResInfo (resHandle, &id, &type, name);
  22748. pluginName = String ((const char*) name + 1, name[0]);
  22749. DetachResource (resHandle);
  22750. HLock (resHandle);
  22751. Ptr ptr;
  22752. Str255 errorText;
  22753. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  22754. name, kPrivateCFragCopy,
  22755. &fragId, &ptr, errorText);
  22756. if (err == noErr)
  22757. {
  22758. moduleMain = (MainCall) newMachOFromCFM (ptr);
  22759. ok = true;
  22760. }
  22761. else
  22762. {
  22763. HUnlock (resHandle);
  22764. }
  22765. break;
  22766. }
  22767. }
  22768. if (! ok)
  22769. CloseResFile (resFileId);
  22770. }
  22771. }
  22772. }
  22773. #endif
  22774. return ok;
  22775. }
  22776. void close()
  22777. {
  22778. #if JUCE_PPC
  22779. if (fragId != 0)
  22780. {
  22781. if (moduleMain != 0)
  22782. disposeMachOFromCFM ((void*) moduleMain);
  22783. CloseConnection (&fragId);
  22784. HUnlock (resHandle);
  22785. if (resFileId != 0)
  22786. CloseResFile (resFileId);
  22787. }
  22788. else
  22789. #endif
  22790. if (bundleRef != 0)
  22791. {
  22792. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  22793. if (CFGetRetainCount (bundleRef) == 1)
  22794. CFBundleUnloadExecutable (bundleRef);
  22795. if (CFGetRetainCount (bundleRef) > 0)
  22796. CFRelease (bundleRef);
  22797. }
  22798. }
  22799. void closeEffect (AEffect* eff)
  22800. {
  22801. #if JUCE_PPC
  22802. if (fragId != 0)
  22803. {
  22804. VoidArray thingsToDelete;
  22805. thingsToDelete.add ((void*) eff->dispatcher);
  22806. thingsToDelete.add ((void*) eff->process);
  22807. thingsToDelete.add ((void*) eff->setParameter);
  22808. thingsToDelete.add ((void*) eff->getParameter);
  22809. thingsToDelete.add ((void*) eff->processReplacing);
  22810. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  22811. for (int i = thingsToDelete.size(); --i >= 0;)
  22812. disposeMachOFromCFM (thingsToDelete[i]);
  22813. }
  22814. else
  22815. #endif
  22816. {
  22817. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  22818. }
  22819. }
  22820. #if JUCE_PPC
  22821. static void* newMachOFromCFM (void* cfmfp)
  22822. {
  22823. if (cfmfp == 0)
  22824. return 0;
  22825. UInt32* const mfp = (UInt32*) juce_malloc (sizeof (UInt32) * 6);
  22826. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  22827. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  22828. mfp[2] = 0x800c0000;
  22829. mfp[3] = 0x804c0004;
  22830. mfp[4] = 0x7c0903a6;
  22831. mfp[5] = 0x4e800420;
  22832. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  22833. return mfp;
  22834. }
  22835. static void disposeMachOFromCFM (void* ptr)
  22836. {
  22837. juce_free (ptr);
  22838. }
  22839. void coerceAEffectFunctionCalls (AEffect* eff)
  22840. {
  22841. if (fragId != 0)
  22842. {
  22843. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  22844. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  22845. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  22846. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  22847. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  22848. }
  22849. }
  22850. #endif
  22851. #endif
  22852. };
  22853. /**
  22854. An instance of a plugin, created by a VSTPluginFormat.
  22855. */
  22856. class VSTPluginInstance : public AudioPluginInstance,
  22857. private Timer,
  22858. private AsyncUpdater
  22859. {
  22860. public:
  22861. ~VSTPluginInstance();
  22862. // AudioPluginInstance methods:
  22863. void fillInPluginDescription (PluginDescription& desc) const
  22864. {
  22865. desc.name = name;
  22866. desc.file = module->file;
  22867. desc.uid = getUID();
  22868. desc.lastFileModTime = desc.file.getLastModificationTime();
  22869. desc.pluginFormatName = "VST";
  22870. desc.category = getCategory();
  22871. {
  22872. char buffer [kVstMaxVendorStrLen + 8];
  22873. zerostruct (buffer);
  22874. dispatch (effGetVendorString, 0, 0, buffer, 0);
  22875. desc.manufacturerName = buffer;
  22876. }
  22877. desc.version = getVersion();
  22878. desc.numInputChannels = getNumInputChannels();
  22879. desc.numOutputChannels = getNumOutputChannels();
  22880. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  22881. }
  22882. const String getName() const { return name; }
  22883. int getUID() const throw();
  22884. bool acceptsMidi() const { return wantsMidiMessages; }
  22885. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  22886. // AudioProcessor methods:
  22887. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  22888. void releaseResources();
  22889. void processBlock (AudioSampleBuffer& buffer,
  22890. MidiBuffer& midiMessages);
  22891. AudioProcessorEditor* createEditor();
  22892. const String getInputChannelName (const int index) const;
  22893. bool isInputChannelStereoPair (int index) const;
  22894. const String getOutputChannelName (const int index) const;
  22895. bool isOutputChannelStereoPair (int index) const;
  22896. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  22897. float getParameter (int index);
  22898. void setParameter (int index, float newValue);
  22899. const String getParameterName (int index);
  22900. const String getParameterText (int index);
  22901. bool isParameterAutomatable (int index) const;
  22902. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  22903. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  22904. void setCurrentProgram (int index);
  22905. const String getProgramName (int index);
  22906. void changeProgramName (int index, const String& newName);
  22907. void getStateInformation (MemoryBlock& destData);
  22908. void getCurrentProgramStateInformation (MemoryBlock& destData);
  22909. void setStateInformation (const void* data, int sizeInBytes);
  22910. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  22911. void timerCallback();
  22912. void handleAsyncUpdate();
  22913. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  22914. juce_UseDebuggingNewOperator
  22915. private:
  22916. friend class VSTPluginWindow;
  22917. friend class VSTPluginFormat;
  22918. AEffect* effect;
  22919. String name;
  22920. CriticalSection lock;
  22921. bool wantsMidiMessages, initialised, isPowerOn;
  22922. mutable StringArray programNames;
  22923. AudioSampleBuffer tempBuffer;
  22924. CriticalSection midiInLock;
  22925. MidiBuffer incomingMidi;
  22926. void* midiEventsToSend;
  22927. int numAllocatedMidiEvents;
  22928. VstTimeInfo vstHostTime;
  22929. float** channels;
  22930. ReferenceCountedObjectPtr <ModuleHandle> module;
  22931. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  22932. bool restoreProgramSettings (const fxProgram* const prog);
  22933. const String getCurrentProgramName();
  22934. void setParamsInProgramBlock (fxProgram* const prog) throw();
  22935. void updateStoredProgramNames();
  22936. void initialise();
  22937. void ensureMidiEventSize (int numEventsNeeded);
  22938. void freeMidiEvents();
  22939. void handleMidiFromPlugin (const VstEvents* const events);
  22940. void createTempParameterStore (MemoryBlock& dest);
  22941. void restoreFromTempParameterStore (const MemoryBlock& mb);
  22942. const String getParameterLabel (int index) const;
  22943. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  22944. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  22945. void setChunkData (const char* data, int size, bool isPreset);
  22946. bool loadFromFXBFile (const void* data, int numBytes);
  22947. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  22948. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  22949. const String getVersion() const throw();
  22950. const String getCategory() const throw();
  22951. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  22952. void setPower (const bool on);
  22953. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  22954. };
  22955. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  22956. : effect (0),
  22957. wantsMidiMessages (false),
  22958. initialised (false),
  22959. isPowerOn (false),
  22960. numAllocatedMidiEvents (0),
  22961. midiEventsToSend (0),
  22962. tempBuffer (1, 1),
  22963. channels (0),
  22964. module (module_)
  22965. {
  22966. try
  22967. {
  22968. _fpreset();
  22969. ++insideVSTCallback;
  22970. name = module->pluginName;
  22971. log (T("Creating VST instance: ") + name);
  22972. #if JUCE_MAC
  22973. if (module->resFileId != 0)
  22974. UseResFile (module->resFileId);
  22975. #if JUCE_PPC
  22976. if (module->fragId != 0)
  22977. {
  22978. static void* audioMasterCoerced = 0;
  22979. if (audioMasterCoerced == 0)
  22980. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  22981. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  22982. }
  22983. else
  22984. #endif
  22985. #endif
  22986. {
  22987. effect = module->moduleMain (&audioMaster);
  22988. }
  22989. --insideVSTCallback;
  22990. if (effect != 0 && effect->magic == kEffectMagic)
  22991. {
  22992. #if JUCE_PPC
  22993. module->coerceAEffectFunctionCalls (effect);
  22994. #endif
  22995. jassert (effect->resvd2 == 0);
  22996. jassert (effect->object != 0);
  22997. _fpreset(); // some dodgy plugs fuck around with this
  22998. }
  22999. else
  23000. {
  23001. effect = 0;
  23002. }
  23003. }
  23004. catch (...)
  23005. {
  23006. --insideVSTCallback;
  23007. }
  23008. }
  23009. VSTPluginInstance::~VSTPluginInstance()
  23010. {
  23011. {
  23012. const ScopedLock sl (lock);
  23013. jassert (insideVSTCallback == 0);
  23014. if (effect != 0 && effect->magic == kEffectMagic)
  23015. {
  23016. try
  23017. {
  23018. #if JUCE_MAC
  23019. if (module->resFileId != 0)
  23020. UseResFile (module->resFileId);
  23021. #endif
  23022. // Must delete any editors before deleting the plugin instance!
  23023. jassert (getActiveEditor() == 0);
  23024. _fpreset(); // some dodgy plugs fuck around with this
  23025. module->closeEffect (effect);
  23026. }
  23027. catch (...)
  23028. {}
  23029. }
  23030. module = 0;
  23031. effect = 0;
  23032. }
  23033. freeMidiEvents();
  23034. juce_free (channels);
  23035. channels = 0;
  23036. }
  23037. void VSTPluginInstance::initialise()
  23038. {
  23039. if (initialised || effect == 0)
  23040. return;
  23041. log (T("Initialising VST: ") + module->pluginName);
  23042. initialised = true;
  23043. dispatch (effIdentify, 0, 0, 0, 0);
  23044. // this code would ask the plugin for its name, but so few plugins
  23045. // actually bother implementing this correctly, that it's better to
  23046. // just ignore it and use the file name instead.
  23047. /* {
  23048. char buffer [256];
  23049. zerostruct (buffer);
  23050. dispatch (effGetEffectName, 0, 0, buffer, 0);
  23051. name = String (buffer).trim();
  23052. if (name.isEmpty())
  23053. name = module->pluginName;
  23054. }
  23055. */
  23056. if (getSampleRate() > 0)
  23057. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  23058. if (getBlockSize() > 0)
  23059. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  23060. dispatch (effOpen, 0, 0, 0, 0);
  23061. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  23062. getSampleRate(), getBlockSize());
  23063. if (getNumPrograms() > 1)
  23064. setCurrentProgram (0);
  23065. else
  23066. dispatch (effSetProgram, 0, 0, 0, 0);
  23067. int i;
  23068. for (i = effect->numInputs; --i >= 0;)
  23069. dispatch (effConnectInput, i, 1, 0, 0);
  23070. for (i = effect->numOutputs; --i >= 0;)
  23071. dispatch (effConnectOutput, i, 1, 0, 0);
  23072. updateStoredProgramNames();
  23073. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  23074. setLatencySamples (effect->initialDelay);
  23075. }
  23076. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  23077. int samplesPerBlockExpected)
  23078. {
  23079. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  23080. sampleRate_, samplesPerBlockExpected);
  23081. setLatencySamples (effect->initialDelay);
  23082. juce_free (channels);
  23083. channels = (float**) juce_calloc (sizeof (float*) * jmax (16, getNumOutputChannels() + 2, getNumInputChannels() + 2));
  23084. vstHostTime.tempo = 120.0;
  23085. vstHostTime.timeSigNumerator = 4;
  23086. vstHostTime.timeSigDenominator = 4;
  23087. vstHostTime.sampleRate = sampleRate_;
  23088. vstHostTime.samplePos = 0;
  23089. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  23090. initialise();
  23091. if (initialised)
  23092. {
  23093. wantsMidiMessages = wantsMidiMessages
  23094. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  23095. if (wantsMidiMessages)
  23096. ensureMidiEventSize (256);
  23097. else
  23098. freeMidiEvents();
  23099. incomingMidi.clear();
  23100. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  23101. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  23102. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  23103. if (! isPowerOn)
  23104. setPower (true);
  23105. // dodgy hack to force some plugins to initialise the sample rate..
  23106. if ((! hasEditor()) && getNumParameters() > 0)
  23107. {
  23108. const float old = getParameter (0);
  23109. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  23110. setParameter (0, old);
  23111. }
  23112. dispatch (effStartProcess, 0, 0, 0, 0);
  23113. }
  23114. }
  23115. void VSTPluginInstance::releaseResources()
  23116. {
  23117. if (initialised)
  23118. {
  23119. dispatch (effStopProcess, 0, 0, 0, 0);
  23120. setPower (false);
  23121. }
  23122. tempBuffer.setSize (1, 1);
  23123. incomingMidi.clear();
  23124. freeMidiEvents();
  23125. juce_free (channels);
  23126. channels = 0;
  23127. }
  23128. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  23129. MidiBuffer& midiMessages)
  23130. {
  23131. const int numSamples = buffer.getNumSamples();
  23132. if (initialised)
  23133. {
  23134. #if JUCE_WIN32
  23135. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  23136. #elif JUCE_LINUX
  23137. timeval micro;
  23138. gettimeofday (&micro, 0);
  23139. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  23140. #elif JUCE_MAC
  23141. UnsignedWide micro;
  23142. Microseconds (&micro);
  23143. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  23144. #endif
  23145. if (wantsMidiMessages)
  23146. {
  23147. MidiBuffer::Iterator iter (midiMessages);
  23148. int eventIndex = 0;
  23149. const uint8* midiData;
  23150. int numBytesOfMidiData, samplePosition;
  23151. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  23152. {
  23153. if (numBytesOfMidiData < 4)
  23154. {
  23155. ensureMidiEventSize (eventIndex);
  23156. VstMidiEvent* const e
  23157. = (VstMidiEvent*) ((VstEvents*) midiEventsToSend)->events [eventIndex++];
  23158. // check that some plugin hasn't messed up our objects
  23159. jassert (e->type == kVstMidiType);
  23160. jassert (e->byteSize == 24);
  23161. e->deltaFrames = jlimit (0, numSamples - 1, samplePosition);
  23162. e->noteLength = 0;
  23163. e->noteOffset = 0;
  23164. e->midiData[0] = midiData[0];
  23165. e->midiData[1] = midiData[1];
  23166. e->midiData[2] = midiData[2];
  23167. e->detune = 0;
  23168. e->noteOffVelocity = 0;
  23169. }
  23170. }
  23171. if (midiEventsToSend == 0)
  23172. ensureMidiEventSize (1);
  23173. ((VstEvents*) midiEventsToSend)->numEvents = eventIndex;
  23174. try
  23175. {
  23176. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend, 0);
  23177. }
  23178. catch (...)
  23179. {}
  23180. }
  23181. int i;
  23182. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  23183. for (i = 0; i < maxChans; ++i)
  23184. channels[i] = buffer.getSampleData (i);
  23185. channels [maxChans] = 0;
  23186. _clearfp();
  23187. if ((effect->flags & effFlagsCanReplacing) != 0)
  23188. {
  23189. try
  23190. {
  23191. effect->processReplacing (effect, channels, channels, numSamples);
  23192. }
  23193. catch (...)
  23194. {}
  23195. }
  23196. else
  23197. {
  23198. tempBuffer.setSize (effect->numOutputs, numSamples);
  23199. tempBuffer.clear();
  23200. float* outs [64];
  23201. for (i = effect->numOutputs; --i >= 0;)
  23202. outs[i] = tempBuffer.getSampleData (i);
  23203. outs [effect->numOutputs] = 0;
  23204. try
  23205. {
  23206. effect->process (effect, channels, outs, numSamples);
  23207. }
  23208. catch (...)
  23209. {}
  23210. for (i = effect->numOutputs; --i >= 0;)
  23211. buffer.copyFrom (i, 0, outs[i], numSamples);
  23212. }
  23213. }
  23214. else
  23215. {
  23216. // Not initialised, so just bypass..
  23217. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  23218. buffer.clear (i, 0, buffer.getNumSamples());
  23219. }
  23220. {
  23221. // copy any incoming midi..
  23222. const ScopedLock sl (midiInLock);
  23223. midiMessages = incomingMidi;
  23224. incomingMidi.clear();
  23225. }
  23226. }
  23227. void VSTPluginInstance::ensureMidiEventSize (int numEventsNeeded)
  23228. {
  23229. if (numEventsNeeded > numAllocatedMidiEvents)
  23230. {
  23231. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  23232. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  23233. if (midiEventsToSend == 0)
  23234. midiEventsToSend = juce_calloc (size);
  23235. else
  23236. midiEventsToSend = juce_realloc (midiEventsToSend, size);
  23237. for (int i = numAllocatedMidiEvents; i < numEventsNeeded; ++i)
  23238. {
  23239. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (sizeof (VstMidiEvent));
  23240. e->type = kVstMidiType;
  23241. e->byteSize = 24;
  23242. ((VstEvents*) midiEventsToSend)->events[i] = (VstEvent*) e;
  23243. }
  23244. numAllocatedMidiEvents = numEventsNeeded;
  23245. }
  23246. }
  23247. void VSTPluginInstance::freeMidiEvents()
  23248. {
  23249. if (midiEventsToSend != 0)
  23250. {
  23251. for (int i = numAllocatedMidiEvents; --i >= 0;)
  23252. juce_free (((VstEvents*) midiEventsToSend)->events[i]);
  23253. juce_free (midiEventsToSend);
  23254. midiEventsToSend = 0;
  23255. numAllocatedMidiEvents = 0;
  23256. }
  23257. }
  23258. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  23259. {
  23260. if (events != 0)
  23261. {
  23262. const ScopedLock sl (midiInLock);
  23263. for (int i = 0; i < events->numEvents; ++i)
  23264. {
  23265. const VstEvent* const e = events->events[i];
  23266. if (e->type == kVstMidiType)
  23267. {
  23268. incomingMidi.addEvent ((const uint8*) ((const VstMidiEvent*) e)->midiData,
  23269. 3, e->deltaFrames);
  23270. }
  23271. }
  23272. }
  23273. }
  23274. static Array <VSTPluginWindow*> activeVSTWindows;
  23275. class VSTPluginWindow : public AudioProcessorEditor,
  23276. public Timer
  23277. {
  23278. public:
  23279. VSTPluginWindow (VSTPluginInstance& plugin_)
  23280. : AudioProcessorEditor (&plugin_),
  23281. plugin (plugin_),
  23282. isOpen (false),
  23283. wasShowing (false),
  23284. pluginRefusesToResize (false),
  23285. pluginWantsKeys (false),
  23286. alreadyInside (false),
  23287. recursiveResize (false)
  23288. {
  23289. #if JUCE_WIN32
  23290. sizeCheckCount = 0;
  23291. pluginHWND = 0;
  23292. #elif JUCE_LINUX
  23293. pluginWindow = None;
  23294. pluginProc = None;
  23295. #else
  23296. pluginViewRef = 0;
  23297. #endif
  23298. movementWatcher = new CompMovementWatcher (this);
  23299. activeVSTWindows.add (this);
  23300. setSize (1, 1);
  23301. setOpaque (true);
  23302. setVisible (true);
  23303. }
  23304. ~VSTPluginWindow()
  23305. {
  23306. deleteAndZero (movementWatcher);
  23307. closePluginWindow();
  23308. activeVSTWindows.removeValue (this);
  23309. plugin.editorBeingDeleted (this);
  23310. }
  23311. void componentMovedOrResized()
  23312. {
  23313. if (recursiveResize)
  23314. return;
  23315. Component* const topComp = getTopLevelComponent();
  23316. if (topComp->getPeer() != 0)
  23317. {
  23318. int x = 0, y = 0;
  23319. relativePositionToOtherComponent (topComp, x, y);
  23320. recursiveResize = true;
  23321. #if JUCE_MAC
  23322. if (pluginViewRef != 0)
  23323. {
  23324. HIRect r;
  23325. r.origin.x = (float) x;
  23326. r.origin.y = (float) y;
  23327. r.size.width = (float) getWidth();
  23328. r.size.height = (float) getHeight();
  23329. HIViewSetFrame (pluginViewRef, &r);
  23330. }
  23331. else if (pluginWindowRef != 0)
  23332. {
  23333. Rect r;
  23334. r.left = getScreenX();
  23335. r.top = getScreenY();
  23336. r.right = r.left + getWidth();
  23337. r.bottom = r.top + getHeight();
  23338. WindowGroupRef group = GetWindowGroup (pluginWindowRef);
  23339. WindowGroupAttributes atts;
  23340. GetWindowGroupAttributes (group, &atts);
  23341. ChangeWindowGroupAttributes (group, 0, kWindowGroupAttrMoveTogether);
  23342. SetWindowBounds (pluginWindowRef, kWindowContentRgn, &r);
  23343. if ((atts & kWindowGroupAttrMoveTogether) != 0)
  23344. ChangeWindowGroupAttributes (group, kWindowGroupAttrMoveTogether, 0);
  23345. }
  23346. else
  23347. {
  23348. repaint();
  23349. }
  23350. #elif JUCE_WIN32
  23351. if (pluginHWND != 0)
  23352. MoveWindow (pluginHWND, x, y, getWidth(), getHeight(), TRUE);
  23353. #elif JUCE_LINUX
  23354. if (pluginWindow != 0)
  23355. {
  23356. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  23357. XMoveWindow (display, pluginWindow, x, y);
  23358. XMapRaised (display, pluginWindow);
  23359. }
  23360. #endif
  23361. recursiveResize = false;
  23362. }
  23363. }
  23364. void componentVisibilityChanged()
  23365. {
  23366. const bool isShowingNow = isShowing();
  23367. if (wasShowing != isShowingNow)
  23368. {
  23369. wasShowing = isShowingNow;
  23370. if (isShowingNow)
  23371. openPluginWindow();
  23372. else
  23373. closePluginWindow();
  23374. }
  23375. componentMovedOrResized();
  23376. }
  23377. void componentPeerChanged()
  23378. {
  23379. closePluginWindow();
  23380. openPluginWindow();
  23381. }
  23382. bool keyStateChanged()
  23383. {
  23384. return pluginWantsKeys;
  23385. }
  23386. bool keyPressed (const KeyPress&)
  23387. {
  23388. return pluginWantsKeys;
  23389. }
  23390. void paint (Graphics& g)
  23391. {
  23392. if (isOpen)
  23393. {
  23394. ComponentPeer* const peer = getPeer();
  23395. if (peer != 0)
  23396. {
  23397. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  23398. getScreenY() - peer->getScreenY(),
  23399. getWidth(), getHeight());
  23400. #if JUCE_MAC
  23401. if (pluginViewRef == 0)
  23402. {
  23403. ERect r;
  23404. r.left = getScreenX() - peer->getScreenX();
  23405. r.right = r.left + getWidth();
  23406. r.top = getScreenY() - peer->getScreenY();
  23407. r.bottom = r.top + getHeight();
  23408. dispatch (effEditDraw, 0, 0, &r, 0);
  23409. }
  23410. #elif JUCE_LINUX
  23411. if (pluginWindow != 0)
  23412. {
  23413. const Rectangle clip (g.getClipBounds());
  23414. XEvent ev;
  23415. zerostruct (ev);
  23416. ev.xexpose.type = Expose;
  23417. ev.xexpose.display = display;
  23418. ev.xexpose.window = pluginWindow;
  23419. ev.xexpose.x = clip.getX();
  23420. ev.xexpose.y = clip.getY();
  23421. ev.xexpose.width = clip.getWidth();
  23422. ev.xexpose.height = clip.getHeight();
  23423. sendEventToChild (&ev);
  23424. }
  23425. #endif
  23426. }
  23427. }
  23428. else
  23429. {
  23430. g.fillAll (Colours::black);
  23431. }
  23432. }
  23433. void timerCallback()
  23434. {
  23435. #if JUCE_WIN32
  23436. if (--sizeCheckCount <= 0)
  23437. {
  23438. sizeCheckCount = 10;
  23439. checkPluginWindowSize();
  23440. }
  23441. #endif
  23442. try
  23443. {
  23444. static bool reentrant = false;
  23445. if (! reentrant)
  23446. {
  23447. reentrant = true;
  23448. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  23449. reentrant = false;
  23450. }
  23451. }
  23452. catch (...)
  23453. {}
  23454. }
  23455. void mouseDown (const MouseEvent& e)
  23456. {
  23457. #if JUCE_MAC
  23458. if (! alreadyInside)
  23459. {
  23460. alreadyInside = true;
  23461. toFront (true);
  23462. dispatch (effEditMouse, e.x, e.y, 0, 0);
  23463. alreadyInside = false;
  23464. }
  23465. else
  23466. {
  23467. PostEvent (::mouseDown, 0);
  23468. }
  23469. #elif JUCE_LINUX
  23470. if (pluginWindow == 0)
  23471. return;
  23472. toFront (true);
  23473. XEvent ev;
  23474. zerostruct (ev);
  23475. ev.xbutton.display = display;
  23476. ev.xbutton.type = ButtonPress;
  23477. ev.xbutton.window = pluginWindow;
  23478. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  23479. ev.xbutton.time = CurrentTime;
  23480. ev.xbutton.x = e.x;
  23481. ev.xbutton.y = e.y;
  23482. ev.xbutton.x_root = e.getScreenX();
  23483. ev.xbutton.y_root = e.getScreenY();
  23484. translateJuceToXButtonModifiers (e, ev);
  23485. sendEventToChild (&ev);
  23486. #else
  23487. (void) e;
  23488. toFront (true);
  23489. #endif
  23490. }
  23491. void broughtToFront()
  23492. {
  23493. activeVSTWindows.removeValue (this);
  23494. activeVSTWindows.add (this);
  23495. #if JUCE_MAC
  23496. dispatch (effEditTop, 0, 0, 0, 0);
  23497. #endif
  23498. }
  23499. juce_UseDebuggingNewOperator
  23500. private:
  23501. VSTPluginInstance& plugin;
  23502. bool isOpen, wasShowing, recursiveResize;
  23503. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  23504. #if JUCE_WIN32
  23505. HWND pluginHWND;
  23506. void* originalWndProc;
  23507. int sizeCheckCount;
  23508. #elif JUCE_MAC
  23509. HIViewRef pluginViewRef;
  23510. WindowRef pluginWindowRef;
  23511. #elif JUCE_LINUX
  23512. Window pluginWindow;
  23513. EventProcPtr pluginProc;
  23514. #endif
  23515. void openPluginWindow()
  23516. {
  23517. if (isOpen || getWindowHandle() == 0)
  23518. return;
  23519. log (T("Opening VST UI: ") + plugin.name);
  23520. isOpen = true;
  23521. ERect* rect = 0;
  23522. dispatch (effEditGetRect, 0, 0, &rect, 0);
  23523. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  23524. // do this before and after like in the steinberg example
  23525. dispatch (effEditGetRect, 0, 0, &rect, 0);
  23526. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  23527. // Install keyboard hooks
  23528. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  23529. #if JUCE_WIN32
  23530. originalWndProc = 0;
  23531. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  23532. if (pluginHWND == 0)
  23533. {
  23534. isOpen = false;
  23535. setSize (300, 150);
  23536. return;
  23537. }
  23538. #pragma warning (push)
  23539. #pragma warning (disable: 4244)
  23540. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  23541. if (! pluginWantsKeys)
  23542. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) vstHookWndProc);
  23543. #pragma warning (pop)
  23544. int w, h;
  23545. RECT r;
  23546. GetWindowRect (pluginHWND, &r);
  23547. w = r.right - r.left;
  23548. h = r.bottom - r.top;
  23549. if (rect != 0)
  23550. {
  23551. const int rw = rect->right - rect->left;
  23552. const int rh = rect->bottom - rect->top;
  23553. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  23554. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  23555. {
  23556. // very dodgy logic to decide which size is right.
  23557. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  23558. {
  23559. SetWindowPos (pluginHWND, 0,
  23560. 0, 0, rw, rh,
  23561. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  23562. GetWindowRect (pluginHWND, &r);
  23563. w = r.right - r.left;
  23564. h = r.bottom - r.top;
  23565. pluginRefusesToResize = (w != rw) || (h != rh);
  23566. w = rw;
  23567. h = rh;
  23568. }
  23569. }
  23570. }
  23571. #elif JUCE_MAC
  23572. HIViewRef root = HIViewGetRoot ((WindowRef) getWindowHandle());
  23573. HIViewFindByID (root, kHIViewWindowContentID, &root);
  23574. pluginViewRef = HIViewGetFirstSubview (root);
  23575. while (pluginViewRef != 0 && juce_isHIViewCreatedByJuce (pluginViewRef))
  23576. pluginViewRef = HIViewGetNextView (pluginViewRef);
  23577. pluginWindowRef = 0;
  23578. if (pluginViewRef == 0)
  23579. {
  23580. WindowGroupRef ourGroup = GetWindowGroup ((WindowRef) getWindowHandle());
  23581. //DebugPrintWindowGroup (ourGroup);
  23582. //DebugPrintAllWindowGroups();
  23583. GetIndexedWindow (ourGroup, 1,
  23584. kWindowGroupContentsVisible,
  23585. &pluginWindowRef);
  23586. if (pluginWindowRef == (WindowRef) getWindowHandle()
  23587. || juce_isWindowCreatedByJuce (pluginWindowRef))
  23588. pluginWindowRef = 0;
  23589. }
  23590. int w = 250, h = 150;
  23591. if (rect != 0)
  23592. {
  23593. w = rect->right - rect->left;
  23594. h = rect->bottom - rect->top;
  23595. if (w == 0 || h == 0)
  23596. {
  23597. w = 250;
  23598. h = 150;
  23599. }
  23600. }
  23601. #elif JUCE_LINUX
  23602. pluginWindow = getChildWindow ((Window) getWindowHandle());
  23603. if (pluginWindow != 0)
  23604. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  23605. XInternAtom (display, "_XEventProc", False));
  23606. int w = 250, h = 150;
  23607. if (rect != 0)
  23608. {
  23609. w = rect->right - rect->left;
  23610. h = rect->bottom - rect->top;
  23611. if (w == 0 || h == 0)
  23612. {
  23613. w = 250;
  23614. h = 150;
  23615. }
  23616. }
  23617. if (pluginWindow != 0)
  23618. XMapRaised (display, pluginWindow);
  23619. #endif
  23620. // double-check it's not too tiny
  23621. w = jmax (w, 32);
  23622. h = jmax (h, 32);
  23623. setSize (w, h);
  23624. #if JUCE_WIN32
  23625. checkPluginWindowSize();
  23626. #endif
  23627. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  23628. repaint();
  23629. }
  23630. void closePluginWindow()
  23631. {
  23632. if (isOpen)
  23633. {
  23634. log (T("Closing VST UI: ") + plugin.getName());
  23635. isOpen = false;
  23636. dispatch (effEditClose, 0, 0, 0, 0);
  23637. #if JUCE_WIN32
  23638. #pragma warning (push)
  23639. #pragma warning (disable: 4244)
  23640. if (pluginHWND != 0 && IsWindow (pluginHWND))
  23641. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) originalWndProc);
  23642. #pragma warning (pop)
  23643. stopTimer();
  23644. if (pluginHWND != 0 && IsWindow (pluginHWND))
  23645. DestroyWindow (pluginHWND);
  23646. pluginHWND = 0;
  23647. #elif JUCE_MAC
  23648. dispatch (effEditSleep, 0, 0, 0, 0);
  23649. pluginViewRef = 0;
  23650. stopTimer();
  23651. #elif JUCE_LINUX
  23652. stopTimer();
  23653. pluginWindow = 0;
  23654. pluginProc = 0;
  23655. #endif
  23656. }
  23657. }
  23658. #if JUCE_WIN32
  23659. void checkPluginWindowSize() throw()
  23660. {
  23661. RECT r;
  23662. GetWindowRect (pluginHWND, &r);
  23663. const int w = r.right - r.left;
  23664. const int h = r.bottom - r.top;
  23665. if (isShowing() && w > 0 && h > 0
  23666. && (w != getWidth() || h != getHeight())
  23667. && ! pluginRefusesToResize)
  23668. {
  23669. setSize (w, h);
  23670. sizeCheckCount = 0;
  23671. }
  23672. }
  23673. #endif
  23674. class CompMovementWatcher : public ComponentMovementWatcher
  23675. {
  23676. public:
  23677. CompMovementWatcher (VSTPluginWindow* const owner_)
  23678. : ComponentMovementWatcher (owner_),
  23679. owner (owner_)
  23680. {
  23681. }
  23682. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  23683. {
  23684. owner->componentMovedOrResized();
  23685. }
  23686. void componentPeerChanged()
  23687. {
  23688. owner->componentPeerChanged();
  23689. }
  23690. void componentVisibilityChanged (Component&)
  23691. {
  23692. owner->componentVisibilityChanged();
  23693. }
  23694. private:
  23695. VSTPluginWindow* const owner;
  23696. };
  23697. CompMovementWatcher* movementWatcher;
  23698. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  23699. {
  23700. return plugin.dispatch (opcode, index, value, ptr, opt);
  23701. }
  23702. // hooks to get keyboard events from VST windows..
  23703. #if JUCE_WIN32
  23704. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  23705. {
  23706. for (int i = activeVSTWindows.size(); --i >= 0;)
  23707. {
  23708. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  23709. if (w->pluginHWND == hW)
  23710. {
  23711. if (message == WM_CHAR
  23712. || message == WM_KEYDOWN
  23713. || message == WM_SYSKEYDOWN
  23714. || message == WM_KEYUP
  23715. || message == WM_SYSKEYUP
  23716. || message == WM_APPCOMMAND)
  23717. {
  23718. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  23719. message, wParam, lParam);
  23720. }
  23721. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  23722. (HWND) w->pluginHWND,
  23723. message,
  23724. wParam,
  23725. lParam);
  23726. }
  23727. }
  23728. return DefWindowProc (hW, message, wParam, lParam);
  23729. }
  23730. #endif
  23731. #if JUCE_LINUX
  23732. // overload mouse/keyboard events to forward them to the plugin's inner window..
  23733. void sendEventToChild (XEvent* event)
  23734. {
  23735. if (pluginProc != 0)
  23736. {
  23737. // if the plugin publishes an event procedure, pass the event directly..
  23738. pluginProc (event);
  23739. }
  23740. else if (pluginWindow != 0)
  23741. {
  23742. // if the plugin has a window, then send the event to the window so that
  23743. // its message thread will pick it up..
  23744. XSendEvent (display, pluginWindow, False, 0L, event);
  23745. XFlush (display);
  23746. }
  23747. }
  23748. void mouseEnter (const MouseEvent& e)
  23749. {
  23750. if (pluginWindow != 0)
  23751. {
  23752. XEvent ev;
  23753. zerostruct (ev);
  23754. ev.xcrossing.display = display;
  23755. ev.xcrossing.type = EnterNotify;
  23756. ev.xcrossing.window = pluginWindow;
  23757. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  23758. ev.xcrossing.time = CurrentTime;
  23759. ev.xcrossing.x = e.x;
  23760. ev.xcrossing.y = e.y;
  23761. ev.xcrossing.x_root = e.getScreenX();
  23762. ev.xcrossing.y_root = e.getScreenY();
  23763. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  23764. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  23765. translateJuceToXCrossingModifiers (e, ev);
  23766. sendEventToChild (&ev);
  23767. }
  23768. }
  23769. void mouseExit (const MouseEvent& e)
  23770. {
  23771. if (pluginWindow != 0)
  23772. {
  23773. XEvent ev;
  23774. zerostruct (ev);
  23775. ev.xcrossing.display = display;
  23776. ev.xcrossing.type = LeaveNotify;
  23777. ev.xcrossing.window = pluginWindow;
  23778. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  23779. ev.xcrossing.time = CurrentTime;
  23780. ev.xcrossing.x = e.x;
  23781. ev.xcrossing.y = e.y;
  23782. ev.xcrossing.x_root = e.getScreenX();
  23783. ev.xcrossing.y_root = e.getScreenY();
  23784. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  23785. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  23786. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  23787. translateJuceToXCrossingModifiers (e, ev);
  23788. sendEventToChild (&ev);
  23789. }
  23790. }
  23791. void mouseMove (const MouseEvent& e)
  23792. {
  23793. if (pluginWindow != 0)
  23794. {
  23795. XEvent ev;
  23796. zerostruct (ev);
  23797. ev.xmotion.display = display;
  23798. ev.xmotion.type = MotionNotify;
  23799. ev.xmotion.window = pluginWindow;
  23800. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  23801. ev.xmotion.time = CurrentTime;
  23802. ev.xmotion.is_hint = NotifyNormal;
  23803. ev.xmotion.x = e.x;
  23804. ev.xmotion.y = e.y;
  23805. ev.xmotion.x_root = e.getScreenX();
  23806. ev.xmotion.y_root = e.getScreenY();
  23807. sendEventToChild (&ev);
  23808. }
  23809. }
  23810. void mouseDrag (const MouseEvent& e)
  23811. {
  23812. if (pluginWindow != 0)
  23813. {
  23814. XEvent ev;
  23815. zerostruct (ev);
  23816. ev.xmotion.display = display;
  23817. ev.xmotion.type = MotionNotify;
  23818. ev.xmotion.window = pluginWindow;
  23819. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  23820. ev.xmotion.time = CurrentTime;
  23821. ev.xmotion.x = e.x ;
  23822. ev.xmotion.y = e.y;
  23823. ev.xmotion.x_root = e.getScreenX();
  23824. ev.xmotion.y_root = e.getScreenY();
  23825. ev.xmotion.is_hint = NotifyNormal;
  23826. translateJuceToXMotionModifiers (e, ev);
  23827. sendEventToChild (&ev);
  23828. }
  23829. }
  23830. void mouseUp (const MouseEvent& e)
  23831. {
  23832. if (pluginWindow != 0)
  23833. {
  23834. XEvent ev;
  23835. zerostruct (ev);
  23836. ev.xbutton.display = display;
  23837. ev.xbutton.type = ButtonRelease;
  23838. ev.xbutton.window = pluginWindow;
  23839. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  23840. ev.xbutton.time = CurrentTime;
  23841. ev.xbutton.x = e.x;
  23842. ev.xbutton.y = e.y;
  23843. ev.xbutton.x_root = e.getScreenX();
  23844. ev.xbutton.y_root = e.getScreenY();
  23845. translateJuceToXButtonModifiers (e, ev);
  23846. sendEventToChild (&ev);
  23847. }
  23848. }
  23849. void mouseWheelMove (const MouseEvent& e,
  23850. float incrementX,
  23851. float incrementY)
  23852. {
  23853. if (pluginWindow != 0)
  23854. {
  23855. XEvent ev;
  23856. zerostruct (ev);
  23857. ev.xbutton.display = display;
  23858. ev.xbutton.type = ButtonPress;
  23859. ev.xbutton.window = pluginWindow;
  23860. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  23861. ev.xbutton.time = CurrentTime;
  23862. ev.xbutton.x = e.x;
  23863. ev.xbutton.y = e.y;
  23864. ev.xbutton.x_root = e.getScreenX();
  23865. ev.xbutton.y_root = e.getScreenY();
  23866. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  23867. sendEventToChild (&ev);
  23868. // TODO - put a usleep here ?
  23869. ev.xbutton.type = ButtonRelease;
  23870. sendEventToChild (&ev);
  23871. }
  23872. }
  23873. #endif
  23874. };
  23875. AudioProcessorEditor* VSTPluginInstance::createEditor()
  23876. {
  23877. if (hasEditor())
  23878. return new VSTPluginWindow (*this);
  23879. return 0;
  23880. }
  23881. void VSTPluginInstance::handleAsyncUpdate()
  23882. {
  23883. // indicates that something about the plugin has changed..
  23884. updateHostDisplay();
  23885. }
  23886. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  23887. {
  23888. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  23889. {
  23890. changeProgramName (getCurrentProgram(), prog->prgName);
  23891. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  23892. setParameter (i, vst_swapFloat (prog->params[i]));
  23893. return true;
  23894. }
  23895. return false;
  23896. }
  23897. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  23898. const int dataSize)
  23899. {
  23900. if (dataSize < 28)
  23901. return false;
  23902. const fxSet* const set = (const fxSet*) data;
  23903. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  23904. || vst_swap (set->version) > fxbVersionNum)
  23905. return false;
  23906. if (vst_swap (set->fxMagic) == 'FxBk')
  23907. {
  23908. // bank of programs
  23909. if (vst_swap (set->numPrograms) >= 0)
  23910. {
  23911. const int oldProg = getCurrentProgram();
  23912. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  23913. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  23914. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  23915. {
  23916. if (i != oldProg)
  23917. {
  23918. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  23919. if (((const char*) prog) - ((const char*) set) >= dataSize)
  23920. return false;
  23921. if (vst_swap (set->numPrograms) > 0)
  23922. setCurrentProgram (i);
  23923. if (! restoreProgramSettings (prog))
  23924. return false;
  23925. }
  23926. }
  23927. if (vst_swap (set->numPrograms) > 0)
  23928. setCurrentProgram (oldProg);
  23929. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  23930. if (((const char*) prog) - ((const char*) set) >= dataSize)
  23931. return false;
  23932. if (! restoreProgramSettings (prog))
  23933. return false;
  23934. }
  23935. }
  23936. else if (vst_swap (set->fxMagic) == 'FxCk')
  23937. {
  23938. // single program
  23939. const fxProgram* const prog = (const fxProgram*) data;
  23940. if (vst_swap (prog->chunkMagic) != 'CcnK')
  23941. return false;
  23942. changeProgramName (getCurrentProgram(), prog->prgName);
  23943. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  23944. setParameter (i, vst_swapFloat (prog->params[i]));
  23945. }
  23946. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  23947. {
  23948. // non-preset chunk
  23949. const fxChunkSet* const cset = (const fxChunkSet*) data;
  23950. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  23951. return false;
  23952. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  23953. }
  23954. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  23955. {
  23956. // preset chunk
  23957. const fxProgramSet* const cset = (const fxProgramSet*) data;
  23958. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  23959. return false;
  23960. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  23961. changeProgramName (getCurrentProgram(), cset->name);
  23962. }
  23963. else
  23964. {
  23965. return false;
  23966. }
  23967. return true;
  23968. }
  23969. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  23970. {
  23971. const int numParams = getNumParameters();
  23972. prog->chunkMagic = vst_swap ('CcnK');
  23973. prog->byteSize = 0;
  23974. prog->fxMagic = vst_swap ('FxCk');
  23975. prog->version = vst_swap (fxbVersionNum);
  23976. prog->fxID = vst_swap (getUID());
  23977. prog->fxVersion = vst_swap (getVersionNumber());
  23978. prog->numParams = vst_swap (numParams);
  23979. getCurrentProgramName().copyToBuffer (prog->prgName, sizeof (prog->prgName) - 1);
  23980. for (int i = 0; i < numParams; ++i)
  23981. prog->params[i] = vst_swapFloat (getParameter (i));
  23982. }
  23983. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  23984. {
  23985. const int numPrograms = getNumPrograms();
  23986. const int numParams = getNumParameters();
  23987. if (usesChunks())
  23988. {
  23989. if (isFXB)
  23990. {
  23991. MemoryBlock chunk;
  23992. getChunkData (chunk, false, maxSizeMB);
  23993. const int totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  23994. dest.setSize (totalLen, true);
  23995. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  23996. set->chunkMagic = vst_swap ('CcnK');
  23997. set->byteSize = 0;
  23998. set->fxMagic = vst_swap ('FBCh');
  23999. set->version = vst_swap (fxbVersionNum);
  24000. set->fxID = vst_swap (getUID());
  24001. set->fxVersion = vst_swap (getVersionNumber());
  24002. set->numPrograms = vst_swap (numPrograms);
  24003. set->chunkSize = vst_swap (chunk.getSize());
  24004. chunk.copyTo (set->chunk, 0, chunk.getSize());
  24005. }
  24006. else
  24007. {
  24008. MemoryBlock chunk;
  24009. getChunkData (chunk, true, maxSizeMB);
  24010. const int totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  24011. dest.setSize (totalLen, true);
  24012. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  24013. set->chunkMagic = vst_swap ('CcnK');
  24014. set->byteSize = 0;
  24015. set->fxMagic = vst_swap ('FPCh');
  24016. set->version = vst_swap (fxbVersionNum);
  24017. set->fxID = vst_swap (getUID());
  24018. set->fxVersion = vst_swap (getVersionNumber());
  24019. set->numPrograms = vst_swap (numPrograms);
  24020. set->chunkSize = vst_swap (chunk.getSize());
  24021. getCurrentProgramName().copyToBuffer (set->name, sizeof (set->name) - 1);
  24022. chunk.copyTo (set->chunk, 0, chunk.getSize());
  24023. }
  24024. }
  24025. else
  24026. {
  24027. if (isFXB)
  24028. {
  24029. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  24030. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  24031. dest.setSize (len, true);
  24032. fxSet* const set = (fxSet*) dest.getData();
  24033. set->chunkMagic = vst_swap ('CcnK');
  24034. set->byteSize = 0;
  24035. set->fxMagic = vst_swap ('FxBk');
  24036. set->version = vst_swap (fxbVersionNum);
  24037. set->fxID = vst_swap (getUID());
  24038. set->fxVersion = vst_swap (getVersionNumber());
  24039. set->numPrograms = vst_swap (numPrograms);
  24040. const int oldProgram = getCurrentProgram();
  24041. MemoryBlock oldSettings;
  24042. createTempParameterStore (oldSettings);
  24043. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  24044. for (int i = 0; i < numPrograms; ++i)
  24045. {
  24046. if (i != oldProgram)
  24047. {
  24048. setCurrentProgram (i);
  24049. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  24050. }
  24051. }
  24052. setCurrentProgram (oldProgram);
  24053. restoreFromTempParameterStore (oldSettings);
  24054. }
  24055. else
  24056. {
  24057. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  24058. dest.setSize (totalLen, true);
  24059. setParamsInProgramBlock ((fxProgram*) dest.getData());
  24060. }
  24061. }
  24062. return true;
  24063. }
  24064. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  24065. {
  24066. if (usesChunks())
  24067. {
  24068. void* data = 0;
  24069. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  24070. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  24071. {
  24072. mb.setSize (bytes);
  24073. mb.copyFrom (data, 0, bytes);
  24074. }
  24075. }
  24076. }
  24077. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  24078. {
  24079. if (size > 0 && usesChunks())
  24080. {
  24081. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  24082. if (! isPreset)
  24083. updateStoredProgramNames();
  24084. }
  24085. }
  24086. void VSTPluginInstance::timerCallback()
  24087. {
  24088. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  24089. stopTimer();
  24090. }
  24091. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  24092. {
  24093. const ScopedLock sl (lock);
  24094. ++insideVSTCallback;
  24095. int result = 0;
  24096. try
  24097. {
  24098. if (effect != 0)
  24099. {
  24100. #if JUCE_MAC
  24101. if (module->resFileId != 0)
  24102. UseResFile (module->resFileId);
  24103. CGrafPtr oldPort;
  24104. if (getActiveEditor() != 0)
  24105. {
  24106. int x = 0, y = 0;
  24107. getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), x, y);
  24108. GetPort (&oldPort);
  24109. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  24110. SetOrigin (-x, -y);
  24111. }
  24112. #endif
  24113. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  24114. #if JUCE_MAC
  24115. if (getActiveEditor() != 0)
  24116. SetPort (oldPort);
  24117. module->resFileId = CurResFile();
  24118. #endif
  24119. --insideVSTCallback;
  24120. return result;
  24121. }
  24122. }
  24123. catch (...)
  24124. {
  24125. //char s[512];
  24126. //sprintf (s, "dispatcher (%d, %d, %d, %x, %f)", opcode, index, value, (int)ptr, opt);
  24127. }
  24128. --insideVSTCallback;
  24129. return result;
  24130. }
  24131. // handles non plugin-specific callbacks..
  24132. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  24133. {
  24134. (void) index;
  24135. (void) value;
  24136. (void) opt;
  24137. switch (opcode)
  24138. {
  24139. case audioMasterCanDo:
  24140. {
  24141. static const char* canDos[] = { "supplyIdle",
  24142. "sendVstEvents",
  24143. "sendVstMidiEvent",
  24144. "sendVstTimeInfo",
  24145. "receiveVstEvents",
  24146. "receiveVstMidiEvent",
  24147. "supportShell",
  24148. "shellCategory" };
  24149. for (int i = 0; i < numElementsInArray (canDos); ++i)
  24150. if (strcmp (canDos[i], (const char*) ptr) == 0)
  24151. return 1;
  24152. return 0;
  24153. }
  24154. case audioMasterVersion:
  24155. return 0x2400;
  24156. case audioMasterCurrentId:
  24157. return shellUIDToCreate;
  24158. case audioMasterGetNumAutomatableParameters:
  24159. return 0;
  24160. case audioMasterGetAutomationState:
  24161. return 1;
  24162. case audioMasterGetVendorVersion:
  24163. return 0x0101;
  24164. case audioMasterGetVendorString:
  24165. case audioMasterGetProductString:
  24166. {
  24167. String hostName ("Juce VST Host");
  24168. if (JUCEApplication::getInstance() != 0)
  24169. hostName = JUCEApplication::getInstance()->getApplicationName();
  24170. hostName.copyToBuffer ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  24171. }
  24172. break;
  24173. case audioMasterGetSampleRate:
  24174. return 44100;
  24175. case audioMasterGetBlockSize:
  24176. return 512;
  24177. case audioMasterSetOutputSampleRate:
  24178. return 0;
  24179. default:
  24180. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  24181. break;
  24182. }
  24183. return 0;
  24184. }
  24185. // handles callbacks for a specific plugin
  24186. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  24187. {
  24188. switch (opcode)
  24189. {
  24190. case audioMasterAutomate:
  24191. sendParamChangeMessageToListeners (index, opt);
  24192. break;
  24193. case audioMasterProcessEvents:
  24194. handleMidiFromPlugin ((const VstEvents*) ptr);
  24195. break;
  24196. case audioMasterGetTime:
  24197. #ifdef _MSC_VER
  24198. #pragma warning (push)
  24199. #pragma warning (disable: 4311)
  24200. #endif
  24201. return (VstIntPtr) &vstHostTime;
  24202. #ifdef _MSC_VER
  24203. #pragma warning (pop)
  24204. #endif
  24205. break;
  24206. case audioMasterIdle:
  24207. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  24208. {
  24209. ++insideVSTCallback;
  24210. #if JUCE_MAC
  24211. if (getActiveEditor() != 0)
  24212. dispatch (effEditIdle, 0, 0, 0, 0);
  24213. #endif
  24214. const MessageManagerLock mml;
  24215. juce_callAnyTimersSynchronously();
  24216. handleUpdateNowIfNeeded();
  24217. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  24218. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  24219. --insideVSTCallback;
  24220. }
  24221. break;
  24222. case audioMasterUpdateDisplay:
  24223. triggerAsyncUpdate();
  24224. break;
  24225. case audioMasterTempoAt:
  24226. // returns (10000 * bpm)
  24227. break;
  24228. case audioMasterNeedIdle:
  24229. startTimer (50);
  24230. break;
  24231. case audioMasterSizeWindow:
  24232. if (getActiveEditor() != 0)
  24233. getActiveEditor()->setSize (index, value);
  24234. return 1;
  24235. case audioMasterGetSampleRate:
  24236. return (VstIntPtr) getSampleRate();
  24237. case audioMasterGetBlockSize:
  24238. return (VstIntPtr) getBlockSize();
  24239. case audioMasterWantMidi:
  24240. wantsMidiMessages = true;
  24241. break;
  24242. case audioMasterGetDirectory:
  24243. #if JUCE_MAC
  24244. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  24245. #else
  24246. return (VstIntPtr) (pointer_sized_uint) (const char*) module->fullParentDirectoryPathName;
  24247. #endif
  24248. case audioMasterGetAutomationState:
  24249. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  24250. break;
  24251. // none of these are handled (yet)..
  24252. case audioMasterBeginEdit:
  24253. case audioMasterEndEdit:
  24254. case audioMasterSetTime:
  24255. case audioMasterPinConnected:
  24256. case audioMasterGetParameterQuantization:
  24257. case audioMasterIOChanged:
  24258. case audioMasterGetInputLatency:
  24259. case audioMasterGetOutputLatency:
  24260. case audioMasterGetPreviousPlug:
  24261. case audioMasterGetNextPlug:
  24262. case audioMasterWillReplaceOrAccumulate:
  24263. case audioMasterGetCurrentProcessLevel:
  24264. case audioMasterOfflineStart:
  24265. case audioMasterOfflineRead:
  24266. case audioMasterOfflineWrite:
  24267. case audioMasterOfflineGetCurrentPass:
  24268. case audioMasterOfflineGetCurrentMetaPass:
  24269. case audioMasterVendorSpecific:
  24270. case audioMasterSetIcon:
  24271. case audioMasterGetLanguage:
  24272. case audioMasterOpenWindow:
  24273. case audioMasterCloseWindow:
  24274. break;
  24275. default:
  24276. return handleGeneralCallback (opcode, index, value, ptr, opt);
  24277. }
  24278. return 0;
  24279. }
  24280. // entry point for all callbacks from the plugin
  24281. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  24282. {
  24283. try
  24284. {
  24285. if (effect != 0 && effect->resvd2 != 0)
  24286. {
  24287. return ((VSTPluginInstance*)(effect->resvd2))
  24288. ->handleCallback (opcode, index, value, ptr, opt);
  24289. }
  24290. return handleGeneralCallback (opcode, index, value, ptr, opt);
  24291. }
  24292. catch (...)
  24293. {
  24294. return 0;
  24295. }
  24296. }
  24297. const String VSTPluginInstance::getVersion() const throw()
  24298. {
  24299. int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  24300. String s;
  24301. if (v != 0)
  24302. {
  24303. int versionBits[4];
  24304. int n = 0;
  24305. while (v != 0)
  24306. {
  24307. versionBits [n++] = (v & 0xff);
  24308. v >>= 8;
  24309. }
  24310. s << 'V';
  24311. while (n > 0)
  24312. {
  24313. s << versionBits [--n];
  24314. if (n > 0)
  24315. s << '.';
  24316. }
  24317. }
  24318. return s;
  24319. }
  24320. int VSTPluginInstance::getUID() const throw()
  24321. {
  24322. int uid = effect != 0 ? effect->uniqueID : 0;
  24323. if (uid == 0)
  24324. uid = module->file.hashCode();
  24325. return uid;
  24326. }
  24327. const String VSTPluginInstance::getCategory() const throw()
  24328. {
  24329. const char* result = 0;
  24330. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  24331. {
  24332. case kPlugCategEffect:
  24333. result = "Effect";
  24334. break;
  24335. case kPlugCategSynth:
  24336. result = "Synth";
  24337. break;
  24338. case kPlugCategAnalysis:
  24339. result = "Anaylsis";
  24340. break;
  24341. case kPlugCategMastering:
  24342. result = "Mastering";
  24343. break;
  24344. case kPlugCategSpacializer:
  24345. result = "Spacial";
  24346. break;
  24347. case kPlugCategRoomFx:
  24348. result = "Reverb";
  24349. break;
  24350. case kPlugSurroundFx:
  24351. result = "Surround";
  24352. break;
  24353. case kPlugCategRestoration:
  24354. result = "Restoration";
  24355. break;
  24356. case kPlugCategGenerator:
  24357. result = "Tone generation";
  24358. break;
  24359. default:
  24360. break;
  24361. }
  24362. return result;
  24363. }
  24364. float VSTPluginInstance::getParameter (int index)
  24365. {
  24366. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  24367. {
  24368. try
  24369. {
  24370. const ScopedLock sl (lock);
  24371. return effect->getParameter (effect, index);
  24372. }
  24373. catch (...)
  24374. {
  24375. }
  24376. }
  24377. return 0.0f;
  24378. }
  24379. void VSTPluginInstance::setParameter (int index, float newValue)
  24380. {
  24381. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  24382. {
  24383. try
  24384. {
  24385. const ScopedLock sl (lock);
  24386. if (effect->getParameter (effect, index) != newValue)
  24387. effect->setParameter (effect, index, newValue);
  24388. }
  24389. catch (...)
  24390. {
  24391. }
  24392. }
  24393. }
  24394. const String VSTPluginInstance::getParameterName (int index)
  24395. {
  24396. if (effect != 0)
  24397. {
  24398. jassert (index >= 0 && index < effect->numParams);
  24399. char nm [256];
  24400. zerostruct (nm);
  24401. dispatch (effGetParamName, index, 0, nm, 0);
  24402. return String (nm).trim();
  24403. }
  24404. return String::empty;
  24405. }
  24406. const String VSTPluginInstance::getParameterLabel (int index) const
  24407. {
  24408. if (effect != 0)
  24409. {
  24410. jassert (index >= 0 && index < effect->numParams);
  24411. char nm [256];
  24412. zerostruct (nm);
  24413. dispatch (effGetParamLabel, index, 0, nm, 0);
  24414. return String (nm).trim();
  24415. }
  24416. return String::empty;
  24417. }
  24418. const String VSTPluginInstance::getParameterText (int index)
  24419. {
  24420. if (effect != 0)
  24421. {
  24422. jassert (index >= 0 && index < effect->numParams);
  24423. char nm [256];
  24424. zerostruct (nm);
  24425. dispatch (effGetParamDisplay, index, 0, nm, 0);
  24426. return String (nm).trim();
  24427. }
  24428. return String::empty;
  24429. }
  24430. bool VSTPluginInstance::isParameterAutomatable (int index) const
  24431. {
  24432. if (effect != 0)
  24433. {
  24434. jassert (index >= 0 && index < effect->numParams);
  24435. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  24436. }
  24437. return false;
  24438. }
  24439. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  24440. {
  24441. dest.setSize (64 + 4 * getNumParameters());
  24442. dest.fillWith (0);
  24443. getCurrentProgramName().copyToBuffer ((char*) dest.getData(), 63);
  24444. float* const p = (float*) (((char*) dest.getData()) + 64);
  24445. for (int i = 0; i < getNumParameters(); ++i)
  24446. p[i] = getParameter(i);
  24447. }
  24448. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  24449. {
  24450. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  24451. float* p = (float*) (((char*) m.getData()) + 64);
  24452. for (int i = 0; i < getNumParameters(); ++i)
  24453. setParameter (i, p[i]);
  24454. }
  24455. void VSTPluginInstance::setCurrentProgram (int newIndex)
  24456. {
  24457. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  24458. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  24459. }
  24460. const String VSTPluginInstance::getProgramName (int index)
  24461. {
  24462. if (index == getCurrentProgram())
  24463. {
  24464. return getCurrentProgramName();
  24465. }
  24466. else if (effect != 0)
  24467. {
  24468. char nm [256];
  24469. zerostruct (nm);
  24470. if (dispatch (effGetProgramNameIndexed,
  24471. jlimit (0, getNumPrograms(), index),
  24472. -1, nm, 0) != 0)
  24473. {
  24474. return String (nm).trim();
  24475. }
  24476. }
  24477. return programNames [index];
  24478. }
  24479. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  24480. {
  24481. if (index == getCurrentProgram())
  24482. {
  24483. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  24484. dispatch (effSetProgramName, 0, 0, (void*) (const char*) newName.substring (0, 24), 0.0f);
  24485. }
  24486. else
  24487. {
  24488. jassertfalse // xxx not implemented!
  24489. }
  24490. }
  24491. void VSTPluginInstance::updateStoredProgramNames()
  24492. {
  24493. if (effect != 0 && getNumPrograms() > 0)
  24494. {
  24495. char nm [256];
  24496. zerostruct (nm);
  24497. // only do this if the plugin can't use indexed names..
  24498. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  24499. {
  24500. const int oldProgram = getCurrentProgram();
  24501. MemoryBlock oldSettings;
  24502. createTempParameterStore (oldSettings);
  24503. for (int i = 0; i < getNumPrograms(); ++i)
  24504. {
  24505. setCurrentProgram (i);
  24506. getCurrentProgramName(); // (this updates the list)
  24507. }
  24508. setCurrentProgram (oldProgram);
  24509. restoreFromTempParameterStore (oldSettings);
  24510. }
  24511. }
  24512. }
  24513. const String VSTPluginInstance::getCurrentProgramName()
  24514. {
  24515. if (effect != 0)
  24516. {
  24517. char nm [256];
  24518. zerostruct (nm);
  24519. dispatch (effGetProgramName, 0, 0, nm, 0);
  24520. const int index = getCurrentProgram();
  24521. if (programNames[index].isEmpty())
  24522. {
  24523. while (programNames.size() < index)
  24524. programNames.add (String::empty);
  24525. programNames.set (index, String (nm).trim());
  24526. }
  24527. return String (nm).trim();
  24528. }
  24529. return String::empty;
  24530. }
  24531. const String VSTPluginInstance::getInputChannelName (const int index) const
  24532. {
  24533. if (index >= 0 && index < getNumInputChannels())
  24534. {
  24535. VstPinProperties pinProps;
  24536. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  24537. return String (pinProps.label, sizeof (pinProps.label));
  24538. }
  24539. return String::empty;
  24540. }
  24541. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  24542. {
  24543. if (index < 0 || index >= getNumInputChannels())
  24544. return false;
  24545. VstPinProperties pinProps;
  24546. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  24547. return (pinProps.flags & kVstPinIsStereo) != 0;
  24548. return true;
  24549. }
  24550. const String VSTPluginInstance::getOutputChannelName (const int index) const
  24551. {
  24552. if (index >= 0 && index < getNumOutputChannels())
  24553. {
  24554. VstPinProperties pinProps;
  24555. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  24556. return String (pinProps.label, sizeof (pinProps.label));
  24557. }
  24558. return String::empty;
  24559. }
  24560. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  24561. {
  24562. if (index < 0 || index >= getNumOutputChannels())
  24563. return false;
  24564. VstPinProperties pinProps;
  24565. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  24566. return (pinProps.flags & kVstPinIsStereo) != 0;
  24567. return true;
  24568. }
  24569. void VSTPluginInstance::setPower (const bool on)
  24570. {
  24571. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  24572. isPowerOn = on;
  24573. }
  24574. const int defaultMaxSizeMB = 64;
  24575. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  24576. {
  24577. saveToFXBFile (destData, true, defaultMaxSizeMB);
  24578. }
  24579. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  24580. {
  24581. saveToFXBFile (destData, false, defaultMaxSizeMB);
  24582. }
  24583. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  24584. {
  24585. loadFromFXBFile (data, sizeInBytes);
  24586. }
  24587. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  24588. {
  24589. loadFromFXBFile (data, sizeInBytes);
  24590. }
  24591. VSTPluginFormat::VSTPluginFormat()
  24592. {
  24593. }
  24594. VSTPluginFormat::~VSTPluginFormat()
  24595. {
  24596. }
  24597. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  24598. const File& file)
  24599. {
  24600. if (! fileMightContainThisPluginType (file))
  24601. return;
  24602. PluginDescription desc;
  24603. desc.file = file;
  24604. desc.uid = 0;
  24605. VSTPluginInstance* instance = dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc));
  24606. if (instance == 0)
  24607. return;
  24608. try
  24609. {
  24610. #if JUCE_MAC
  24611. if (instance->module->resFileId != 0)
  24612. UseResFile (instance->module->resFileId);
  24613. #endif
  24614. instance->fillInPluginDescription (desc);
  24615. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  24616. if (category != kPlugCategShell)
  24617. {
  24618. // Normal plugin...
  24619. results.add (new PluginDescription (desc));
  24620. ++insideVSTCallback;
  24621. instance->dispatch (effOpen, 0, 0, 0, 0);
  24622. --insideVSTCallback;
  24623. }
  24624. else
  24625. {
  24626. // It's a shell plugin, so iterate all the subtypes...
  24627. char shellEffectName [64];
  24628. for (;;)
  24629. {
  24630. zerostruct (shellEffectName);
  24631. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  24632. if (uid == 0)
  24633. {
  24634. break;
  24635. }
  24636. else
  24637. {
  24638. desc.uid = uid;
  24639. desc.name = shellEffectName;
  24640. bool alreadyThere = false;
  24641. for (int i = results.size(); --i >= 0;)
  24642. {
  24643. PluginDescription* const d = results.getUnchecked(i);
  24644. if (d->isDuplicateOf (desc))
  24645. {
  24646. alreadyThere = true;
  24647. break;
  24648. }
  24649. }
  24650. if (! alreadyThere)
  24651. results.add (new PluginDescription (desc));
  24652. }
  24653. }
  24654. }
  24655. }
  24656. catch (...)
  24657. {
  24658. // crashed while loading...
  24659. }
  24660. deleteAndZero (instance);
  24661. }
  24662. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  24663. {
  24664. VSTPluginInstance* result = 0;
  24665. if (fileMightContainThisPluginType (desc.file))
  24666. {
  24667. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  24668. desc.file.getParentDirectory().setAsCurrentWorkingDirectory();
  24669. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (desc.file));
  24670. if (module != 0)
  24671. {
  24672. shellUIDToCreate = desc.uid;
  24673. result = new VSTPluginInstance (module);
  24674. if (result->effect != 0)
  24675. {
  24676. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) result;
  24677. result->initialise();
  24678. }
  24679. else
  24680. {
  24681. deleteAndZero (result);
  24682. }
  24683. }
  24684. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  24685. }
  24686. return result;
  24687. }
  24688. bool VSTPluginFormat::fileMightContainThisPluginType (const File& f)
  24689. {
  24690. #if JUCE_MAC
  24691. if (f.isDirectory() && f.hasFileExtension (T(".vst")))
  24692. return true;
  24693. #if JUCE_PPC
  24694. FSRef fileRef;
  24695. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  24696. {
  24697. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  24698. if (resFileId != -1)
  24699. {
  24700. const int numEffects = Count1Resources ('aEff');
  24701. CloseResFile (resFileId);
  24702. if (numEffects > 0)
  24703. return true;
  24704. }
  24705. }
  24706. #endif
  24707. return false;
  24708. #elif JUCE_WIN32
  24709. return f.existsAsFile()
  24710. && f.hasFileExtension (T(".dll"));
  24711. #elif JUCE_LINUX
  24712. return f.existsAsFile()
  24713. && f.hasFileExtension (T(".so"));
  24714. #endif
  24715. }
  24716. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  24717. {
  24718. #if JUCE_MAC
  24719. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  24720. #elif JUCE_WIN32
  24721. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  24722. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  24723. #elif JUCE_LINUX
  24724. return FileSearchPath ("/usr/lib/vst");
  24725. #endif
  24726. }
  24727. END_JUCE_NAMESPACE
  24728. #undef log
  24729. #endif
  24730. /********* End of inlined file: juce_VSTPluginFormat.cpp *********/
  24731. /********* Start of inlined file: juce_AudioProcessor.cpp *********/
  24732. BEGIN_JUCE_NAMESPACE
  24733. AudioProcessor::AudioProcessor()
  24734. : playHead (0),
  24735. activeEditor (0),
  24736. sampleRate (0),
  24737. blockSize (0),
  24738. numInputChannels (0),
  24739. numOutputChannels (0),
  24740. latencySamples (0),
  24741. suspended (false),
  24742. nonRealtime (false)
  24743. {
  24744. }
  24745. AudioProcessor::~AudioProcessor()
  24746. {
  24747. // ooh, nasty - the editor should have been deleted before the filter
  24748. // that it refers to is deleted..
  24749. jassert (activeEditor == 0);
  24750. #ifdef JUCE_DEBUG
  24751. // This will fail if you've called beginParameterChangeGesture() for one
  24752. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  24753. jassert (changingParams.countNumberOfSetBits() == 0);
  24754. #endif
  24755. }
  24756. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  24757. {
  24758. playHead = newPlayHead;
  24759. }
  24760. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  24761. {
  24762. const ScopedLock sl (listenerLock);
  24763. listeners.addIfNotAlreadyThere (newListener);
  24764. }
  24765. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  24766. {
  24767. const ScopedLock sl (listenerLock);
  24768. listeners.removeValue (listenerToRemove);
  24769. }
  24770. void AudioProcessor::setPlayConfigDetails (const int numIns,
  24771. const int numOuts,
  24772. const double sampleRate_,
  24773. const int blockSize_) throw()
  24774. {
  24775. numInputChannels = numIns;
  24776. numOutputChannels = numOuts;
  24777. sampleRate = sampleRate_;
  24778. blockSize = blockSize_;
  24779. }
  24780. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  24781. {
  24782. nonRealtime = nonRealtime_;
  24783. }
  24784. void AudioProcessor::setLatencySamples (const int newLatency)
  24785. {
  24786. if (latencySamples != newLatency)
  24787. {
  24788. latencySamples = newLatency;
  24789. updateHostDisplay();
  24790. }
  24791. }
  24792. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  24793. const float newValue)
  24794. {
  24795. setParameter (parameterIndex, newValue);
  24796. sendParamChangeMessageToListeners (parameterIndex, newValue);
  24797. }
  24798. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  24799. {
  24800. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  24801. for (int i = listeners.size(); --i >= 0;)
  24802. {
  24803. listenerLock.enter();
  24804. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24805. listenerLock.exit();
  24806. if (l != 0)
  24807. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  24808. }
  24809. }
  24810. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  24811. {
  24812. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  24813. #ifdef JUCE_DEBUG
  24814. // This means you've called beginParameterChangeGesture twice in succession without a matching
  24815. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  24816. jassert (! changingParams [parameterIndex]);
  24817. changingParams.setBit (parameterIndex);
  24818. #endif
  24819. for (int i = listeners.size(); --i >= 0;)
  24820. {
  24821. listenerLock.enter();
  24822. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24823. listenerLock.exit();
  24824. if (l != 0)
  24825. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  24826. }
  24827. }
  24828. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  24829. {
  24830. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  24831. #ifdef JUCE_DEBUG
  24832. // This means you've called endParameterChangeGesture without having previously called
  24833. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  24834. // calls matched correctly.
  24835. jassert (changingParams [parameterIndex]);
  24836. changingParams.clearBit (parameterIndex);
  24837. #endif
  24838. for (int i = listeners.size(); --i >= 0;)
  24839. {
  24840. listenerLock.enter();
  24841. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24842. listenerLock.exit();
  24843. if (l != 0)
  24844. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  24845. }
  24846. }
  24847. void AudioProcessor::updateHostDisplay()
  24848. {
  24849. for (int i = listeners.size(); --i >= 0;)
  24850. {
  24851. listenerLock.enter();
  24852. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24853. listenerLock.exit();
  24854. if (l != 0)
  24855. l->audioProcessorChanged (this);
  24856. }
  24857. }
  24858. bool AudioProcessor::isParameterAutomatable (int /*index*/) const
  24859. {
  24860. return true;
  24861. }
  24862. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  24863. {
  24864. const ScopedLock sl (callbackLock);
  24865. suspended = shouldBeSuspended;
  24866. }
  24867. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  24868. {
  24869. const ScopedLock sl (callbackLock);
  24870. jassert (activeEditor == editor);
  24871. if (activeEditor == editor)
  24872. activeEditor = 0;
  24873. }
  24874. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  24875. {
  24876. if (activeEditor != 0)
  24877. return activeEditor;
  24878. AudioProcessorEditor* const ed = createEditor();
  24879. if (ed != 0)
  24880. {
  24881. // you must give your editor comp a size before returning it..
  24882. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  24883. const ScopedLock sl (callbackLock);
  24884. activeEditor = ed;
  24885. }
  24886. return ed;
  24887. }
  24888. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  24889. {
  24890. getStateInformation (destData);
  24891. }
  24892. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  24893. {
  24894. setStateInformation (data, sizeInBytes);
  24895. }
  24896. // magic number to identify memory blocks that we've stored as XML
  24897. const uint32 magicXmlNumber = 0x21324356;
  24898. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  24899. JUCE_NAMESPACE::MemoryBlock& destData)
  24900. {
  24901. const String xmlString (xml.createDocument (String::empty, true, false));
  24902. const int stringLength = xmlString.length();
  24903. destData.setSize (stringLength + 10);
  24904. char* const d = (char*) destData.getData();
  24905. *(uint32*) d = swapIfBigEndian ((const uint32) magicXmlNumber);
  24906. *(uint32*) (d + 4) = swapIfBigEndian ((const uint32) stringLength);
  24907. xmlString.copyToBuffer (d + 8, stringLength);
  24908. }
  24909. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  24910. const int sizeInBytes)
  24911. {
  24912. if (sizeInBytes > 8
  24913. && littleEndianInt ((const char*) data) == magicXmlNumber)
  24914. {
  24915. const uint32 stringLength = littleEndianInt (((const char*) data) + 4);
  24916. if (stringLength > 0)
  24917. {
  24918. XmlDocument doc (String (((const char*) data) + 8,
  24919. jmin ((sizeInBytes - 8), stringLength)));
  24920. return doc.getDocumentElement();
  24921. }
  24922. }
  24923. return 0;
  24924. }
  24925. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  24926. {
  24927. }
  24928. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  24929. {
  24930. }
  24931. END_JUCE_NAMESPACE
  24932. /********* End of inlined file: juce_AudioProcessor.cpp *********/
  24933. /********* Start of inlined file: juce_AudioProcessorEditor.cpp *********/
  24934. BEGIN_JUCE_NAMESPACE
  24935. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  24936. : owner (owner_)
  24937. {
  24938. // the filter must be valid..
  24939. jassert (owner != 0);
  24940. }
  24941. AudioProcessorEditor::~AudioProcessorEditor()
  24942. {
  24943. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  24944. // filter for some reason..
  24945. jassert (owner->getActiveEditor() != this);
  24946. }
  24947. END_JUCE_NAMESPACE
  24948. /********* End of inlined file: juce_AudioProcessorEditor.cpp *********/
  24949. /********* Start of inlined file: juce_AudioProcessorGraph.cpp *********/
  24950. BEGIN_JUCE_NAMESPACE
  24951. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  24952. AudioProcessorGraph::Node::Node (const uint32 id_,
  24953. AudioProcessor* const processor_) throw()
  24954. : id (id_),
  24955. processor (processor_),
  24956. isPrepared (false)
  24957. {
  24958. jassert (processor_ != 0);
  24959. }
  24960. AudioProcessorGraph::Node::~Node()
  24961. {
  24962. delete processor;
  24963. }
  24964. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  24965. AudioProcessorGraph* const graph)
  24966. {
  24967. if (! isPrepared)
  24968. {
  24969. isPrepared = true;
  24970. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  24971. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  24972. if (ioProc != 0)
  24973. ioProc->setParentGraph (graph);
  24974. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  24975. processor->getNumOutputChannels(),
  24976. sampleRate, blockSize);
  24977. processor->prepareToPlay (sampleRate, blockSize);
  24978. }
  24979. }
  24980. void AudioProcessorGraph::Node::unprepare()
  24981. {
  24982. if (isPrepared)
  24983. {
  24984. isPrepared = false;
  24985. processor->releaseResources();
  24986. }
  24987. }
  24988. AudioProcessorGraph::AudioProcessorGraph()
  24989. : lastNodeId (0),
  24990. renderingBuffers (1, 1),
  24991. currentAudioOutputBuffer (1, 1)
  24992. {
  24993. }
  24994. AudioProcessorGraph::~AudioProcessorGraph()
  24995. {
  24996. clearRenderingSequence();
  24997. clear();
  24998. }
  24999. const String AudioProcessorGraph::getName() const
  25000. {
  25001. return "Audio Graph";
  25002. }
  25003. void AudioProcessorGraph::clear()
  25004. {
  25005. nodes.clear();
  25006. connections.clear();
  25007. triggerAsyncUpdate();
  25008. }
  25009. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const throw()
  25010. {
  25011. for (int i = nodes.size(); --i >= 0;)
  25012. if (nodes.getUnchecked(i)->id == nodeId)
  25013. return nodes.getUnchecked(i);
  25014. return 0;
  25015. }
  25016. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  25017. uint32 nodeId)
  25018. {
  25019. if (newProcessor == 0)
  25020. {
  25021. jassertfalse
  25022. return 0;
  25023. }
  25024. if (nodeId == 0)
  25025. {
  25026. nodeId = ++lastNodeId;
  25027. }
  25028. else
  25029. {
  25030. // you can't add a node with an id that already exists in the graph..
  25031. jassert (getNodeForId (nodeId) == 0);
  25032. removeNode (nodeId);
  25033. }
  25034. lastNodeId = nodeId;
  25035. Node* const n = new Node (nodeId, newProcessor);
  25036. nodes.add (n);
  25037. triggerAsyncUpdate();
  25038. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  25039. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  25040. if (ioProc != 0)
  25041. ioProc->setParentGraph (this);
  25042. return n;
  25043. }
  25044. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  25045. {
  25046. disconnectNode (nodeId);
  25047. for (int i = nodes.size(); --i >= 0;)
  25048. {
  25049. if (nodes.getUnchecked(i)->id == nodeId)
  25050. {
  25051. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  25052. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  25053. if (ioProc != 0)
  25054. ioProc->setParentGraph (0);
  25055. nodes.remove (i);
  25056. triggerAsyncUpdate();
  25057. return true;
  25058. }
  25059. }
  25060. return false;
  25061. }
  25062. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  25063. const int sourceChannelIndex,
  25064. const uint32 destNodeId,
  25065. const int destChannelIndex) const throw()
  25066. {
  25067. for (int i = connections.size(); --i >= 0;)
  25068. {
  25069. const Connection* const c = connections.getUnchecked(i);
  25070. if (c->sourceNodeId == sourceNodeId
  25071. && c->destNodeId == destNodeId
  25072. && c->sourceChannelIndex == sourceChannelIndex
  25073. && c->destChannelIndex == destChannelIndex)
  25074. {
  25075. return c;
  25076. }
  25077. }
  25078. return 0;
  25079. }
  25080. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  25081. const uint32 possibleDestNodeId) const throw()
  25082. {
  25083. for (int i = connections.size(); --i >= 0;)
  25084. {
  25085. const Connection* const c = connections.getUnchecked(i);
  25086. if (c->sourceNodeId == possibleSourceNodeId
  25087. && c->destNodeId == possibleDestNodeId)
  25088. {
  25089. return true;
  25090. }
  25091. }
  25092. return false;
  25093. }
  25094. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  25095. const int sourceChannelIndex,
  25096. const uint32 destNodeId,
  25097. const int destChannelIndex) const throw()
  25098. {
  25099. if (sourceChannelIndex < 0
  25100. || destChannelIndex < 0
  25101. || sourceNodeId == destNodeId
  25102. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  25103. return false;
  25104. const Node* const source = getNodeForId (sourceNodeId);
  25105. if (source == 0
  25106. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  25107. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  25108. return false;
  25109. const Node* const dest = getNodeForId (destNodeId);
  25110. if (dest == 0
  25111. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  25112. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  25113. return false;
  25114. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  25115. destNodeId, destChannelIndex) == 0;
  25116. }
  25117. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  25118. const int sourceChannelIndex,
  25119. const uint32 destNodeId,
  25120. const int destChannelIndex)
  25121. {
  25122. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  25123. return false;
  25124. Connection* const c = new Connection();
  25125. c->sourceNodeId = sourceNodeId;
  25126. c->sourceChannelIndex = sourceChannelIndex;
  25127. c->destNodeId = destNodeId;
  25128. c->destChannelIndex = destChannelIndex;
  25129. connections.add (c);
  25130. triggerAsyncUpdate();
  25131. return true;
  25132. }
  25133. void AudioProcessorGraph::removeConnection (const int index)
  25134. {
  25135. connections.remove (index);
  25136. triggerAsyncUpdate();
  25137. }
  25138. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  25139. const uint32 destNodeId, const int destChannelIndex)
  25140. {
  25141. bool doneAnything = false;
  25142. for (int i = connections.size(); --i >= 0;)
  25143. {
  25144. const Connection* const c = connections.getUnchecked(i);
  25145. if (c->sourceNodeId == sourceNodeId
  25146. && c->destNodeId == destNodeId
  25147. && c->sourceChannelIndex == sourceChannelIndex
  25148. && c->destChannelIndex == destChannelIndex)
  25149. {
  25150. removeConnection (i);
  25151. doneAnything = true;
  25152. triggerAsyncUpdate();
  25153. }
  25154. }
  25155. return doneAnything;
  25156. }
  25157. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  25158. {
  25159. bool doneAnything = false;
  25160. for (int i = connections.size(); --i >= 0;)
  25161. {
  25162. const Connection* const c = connections.getUnchecked(i);
  25163. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  25164. {
  25165. removeConnection (i);
  25166. doneAnything = true;
  25167. triggerAsyncUpdate();
  25168. }
  25169. }
  25170. return doneAnything;
  25171. }
  25172. bool AudioProcessorGraph::removeIllegalConnections()
  25173. {
  25174. bool doneAnything = false;
  25175. for (int i = connections.size(); --i >= 0;)
  25176. {
  25177. const Connection* const c = connections.getUnchecked(i);
  25178. const Node* const source = getNodeForId (c->sourceNodeId);
  25179. const Node* const dest = getNodeForId (c->destNodeId);
  25180. if (source == 0 || dest == 0
  25181. || (c->sourceChannelIndex != midiChannelIndex
  25182. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  25183. || (c->sourceChannelIndex == midiChannelIndex
  25184. && ! source->processor->producesMidi())
  25185. || (c->destChannelIndex != midiChannelIndex
  25186. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  25187. || (c->destChannelIndex == midiChannelIndex
  25188. && ! dest->processor->acceptsMidi()))
  25189. {
  25190. removeConnection (i);
  25191. doneAnything = true;
  25192. triggerAsyncUpdate();
  25193. }
  25194. }
  25195. return doneAnything;
  25196. }
  25197. namespace GraphRenderingOps
  25198. {
  25199. class AudioGraphRenderingOp
  25200. {
  25201. public:
  25202. AudioGraphRenderingOp() throw() {}
  25203. virtual ~AudioGraphRenderingOp() throw() {}
  25204. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  25205. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  25206. const int numSamples) throw() = 0;
  25207. juce_UseDebuggingNewOperator
  25208. };
  25209. class ClearChannelOp : public AudioGraphRenderingOp
  25210. {
  25211. public:
  25212. ClearChannelOp (const int channelNum_) throw()
  25213. : channelNum (channelNum_)
  25214. {}
  25215. ~ClearChannelOp() throw() {}
  25216. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  25217. {
  25218. sharedBufferChans.clear (channelNum, 0, numSamples);
  25219. }
  25220. private:
  25221. const int channelNum;
  25222. ClearChannelOp (const ClearChannelOp&);
  25223. const ClearChannelOp& operator= (const ClearChannelOp&);
  25224. };
  25225. class CopyChannelOp : public AudioGraphRenderingOp
  25226. {
  25227. public:
  25228. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  25229. : srcChannelNum (srcChannelNum_),
  25230. dstChannelNum (dstChannelNum_)
  25231. {}
  25232. ~CopyChannelOp() throw() {}
  25233. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  25234. {
  25235. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  25236. }
  25237. private:
  25238. const int srcChannelNum, dstChannelNum;
  25239. CopyChannelOp (const CopyChannelOp&);
  25240. const CopyChannelOp& operator= (const CopyChannelOp&);
  25241. };
  25242. class AddChannelOp : public AudioGraphRenderingOp
  25243. {
  25244. public:
  25245. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  25246. : srcChannelNum (srcChannelNum_),
  25247. dstChannelNum (dstChannelNum_)
  25248. {}
  25249. ~AddChannelOp() throw() {}
  25250. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  25251. {
  25252. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  25253. }
  25254. private:
  25255. const int srcChannelNum, dstChannelNum;
  25256. AddChannelOp (const AddChannelOp&);
  25257. const AddChannelOp& operator= (const AddChannelOp&);
  25258. };
  25259. class ClearMidiBufferOp : public AudioGraphRenderingOp
  25260. {
  25261. public:
  25262. ClearMidiBufferOp (const int bufferNum_) throw()
  25263. : bufferNum (bufferNum_)
  25264. {}
  25265. ~ClearMidiBufferOp() throw() {}
  25266. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  25267. {
  25268. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  25269. }
  25270. private:
  25271. const int bufferNum;
  25272. ClearMidiBufferOp (const ClearMidiBufferOp&);
  25273. const ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  25274. };
  25275. class CopyMidiBufferOp : public AudioGraphRenderingOp
  25276. {
  25277. public:
  25278. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  25279. : srcBufferNum (srcBufferNum_),
  25280. dstBufferNum (dstBufferNum_)
  25281. {}
  25282. ~CopyMidiBufferOp() throw() {}
  25283. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  25284. {
  25285. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  25286. }
  25287. private:
  25288. const int srcBufferNum, dstBufferNum;
  25289. CopyMidiBufferOp (const CopyMidiBufferOp&);
  25290. const CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  25291. };
  25292. class AddMidiBufferOp : public AudioGraphRenderingOp
  25293. {
  25294. public:
  25295. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  25296. : srcBufferNum (srcBufferNum_),
  25297. dstBufferNum (dstBufferNum_)
  25298. {}
  25299. ~AddMidiBufferOp() throw() {}
  25300. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  25301. {
  25302. sharedMidiBuffers.getUnchecked (dstBufferNum)
  25303. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  25304. }
  25305. private:
  25306. const int srcBufferNum, dstBufferNum;
  25307. AddMidiBufferOp (const AddMidiBufferOp&);
  25308. const AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  25309. };
  25310. class ProcessBufferOp : public AudioGraphRenderingOp
  25311. {
  25312. public:
  25313. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  25314. const Array <int>& audioChannelsToUse_,
  25315. const int totalChans_,
  25316. const int midiBufferToUse_) throw()
  25317. : node (node_),
  25318. processor (node_->processor),
  25319. audioChannelsToUse (audioChannelsToUse_),
  25320. totalChans (totalChans_),
  25321. midiBufferToUse (midiBufferToUse_)
  25322. {
  25323. channels = (float**) juce_calloc (sizeof (float*) * totalChans_);
  25324. }
  25325. ~ProcessBufferOp() throw()
  25326. {
  25327. juce_free (channels);
  25328. }
  25329. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  25330. {
  25331. for (int i = totalChans; --i >= 0;)
  25332. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  25333. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  25334. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  25335. }
  25336. const AudioProcessorGraph::Node::Ptr node;
  25337. AudioProcessor* const processor;
  25338. private:
  25339. Array <int> audioChannelsToUse;
  25340. float** channels;
  25341. int totalChans;
  25342. int midiBufferToUse;
  25343. ProcessBufferOp (const ProcessBufferOp&);
  25344. const ProcessBufferOp& operator= (const ProcessBufferOp&);
  25345. };
  25346. /** Used to calculate the correct sequence of rendering ops needed, based on
  25347. the best re-use of shared buffers at each stage.
  25348. */
  25349. class RenderingOpSequenceCalculator
  25350. {
  25351. public:
  25352. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  25353. const VoidArray& orderedNodes_,
  25354. VoidArray& renderingOps)
  25355. : graph (graph_),
  25356. orderedNodes (orderedNodes_)
  25357. {
  25358. nodeIds.add (-2); // first buffer is read-only zeros
  25359. channels.add (0);
  25360. midiNodeIds.add (-2);
  25361. for (int i = 0; i < orderedNodes.size(); ++i)
  25362. {
  25363. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  25364. renderingOps, i);
  25365. markAnyUnusedBuffersAsFree (i);
  25366. }
  25367. }
  25368. int getNumBuffersNeeded() const throw() { return nodeIds.size(); }
  25369. int getNumMidiBuffersNeeded() const throw() { return midiNodeIds.size(); }
  25370. juce_UseDebuggingNewOperator
  25371. private:
  25372. AudioProcessorGraph& graph;
  25373. const VoidArray& orderedNodes;
  25374. Array <int> nodeIds, channels, midiNodeIds;
  25375. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  25376. VoidArray& renderingOps,
  25377. const int ourRenderingIndex)
  25378. {
  25379. const int numIns = node->processor->getNumInputChannels();
  25380. const int numOuts = node->processor->getNumOutputChannels();
  25381. const int totalChans = jmax (numIns, numOuts);
  25382. Array <int> audioChannelsToUse;
  25383. int midiBufferToUse = -1;
  25384. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  25385. {
  25386. // get a list of all the inputs to this node
  25387. Array <int> sourceNodes, sourceOutputChans;
  25388. for (int i = graph.getNumConnections(); --i >= 0;)
  25389. {
  25390. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  25391. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  25392. {
  25393. sourceNodes.add (c->sourceNodeId);
  25394. sourceOutputChans.add (c->sourceChannelIndex);
  25395. }
  25396. }
  25397. int bufIndex = -1;
  25398. if (sourceNodes.size() == 0)
  25399. {
  25400. // unconnected input channel
  25401. if (inputChan >= numOuts)
  25402. {
  25403. bufIndex = getReadOnlyEmptyBuffer();
  25404. jassert (bufIndex >= 0);
  25405. }
  25406. else
  25407. {
  25408. bufIndex = getFreeBuffer (false);
  25409. renderingOps.add (new ClearChannelOp (bufIndex));
  25410. }
  25411. }
  25412. else if (sourceNodes.size() == 1)
  25413. {
  25414. // channel with a straightforward single input..
  25415. const int srcNode = sourceNodes.getUnchecked(0);
  25416. const int srcChan = sourceOutputChans.getUnchecked(0);
  25417. bufIndex = getBufferContaining (srcNode, srcChan);
  25418. if (bufIndex < 0)
  25419. {
  25420. // if not found, this is probably a feedback loop
  25421. bufIndex = getReadOnlyEmptyBuffer();
  25422. jassert (bufIndex >= 0);
  25423. }
  25424. if (inputChan < numOuts
  25425. && isBufferNeededLater (ourRenderingIndex,
  25426. inputChan,
  25427. srcNode, srcChan))
  25428. {
  25429. // can't mess up this channel because it's needed later by another node, so we
  25430. // need to use a copy of it..
  25431. const int newFreeBuffer = getFreeBuffer (false);
  25432. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  25433. bufIndex = newFreeBuffer;
  25434. }
  25435. }
  25436. else
  25437. {
  25438. // channel with a mix of several inputs..
  25439. // try to find a re-usable channel from our inputs..
  25440. int reusableInputIndex = -1;
  25441. for (int i = 0; i < sourceNodes.size(); ++i)
  25442. {
  25443. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  25444. sourceOutputChans.getUnchecked(i));
  25445. if (sourceBufIndex >= 0
  25446. && ! isBufferNeededLater (ourRenderingIndex,
  25447. inputChan,
  25448. sourceNodes.getUnchecked(i),
  25449. sourceOutputChans.getUnchecked(i)))
  25450. {
  25451. // we've found one of our input chans that can be re-used..
  25452. reusableInputIndex = i;
  25453. bufIndex = sourceBufIndex;
  25454. break;
  25455. }
  25456. }
  25457. if (reusableInputIndex < 0)
  25458. {
  25459. // can't re-use any of our input chans, so get a new one and copy everything into it..
  25460. bufIndex = getFreeBuffer (false);
  25461. jassert (bufIndex != 0);
  25462. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  25463. sourceOutputChans.getUnchecked (0));
  25464. if (srcIndex < 0)
  25465. {
  25466. // if not found, this is probably a feedback loop
  25467. renderingOps.add (new ClearChannelOp (bufIndex));
  25468. }
  25469. else
  25470. {
  25471. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  25472. }
  25473. reusableInputIndex = 0;
  25474. }
  25475. for (int j = 0; j < sourceNodes.size(); ++j)
  25476. {
  25477. if (j != reusableInputIndex)
  25478. {
  25479. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  25480. sourceOutputChans.getUnchecked(j));
  25481. if (srcIndex >= 0)
  25482. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  25483. }
  25484. }
  25485. }
  25486. jassert (bufIndex >= 0);
  25487. audioChannelsToUse.add (bufIndex);
  25488. if (inputChan < numOuts)
  25489. markBufferAsContaining (bufIndex, node->id, inputChan);
  25490. }
  25491. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  25492. {
  25493. const int bufIndex = getFreeBuffer (false);
  25494. jassert (bufIndex != 0);
  25495. audioChannelsToUse.add (bufIndex);
  25496. markBufferAsContaining (bufIndex, node->id, outputChan);
  25497. }
  25498. // Now the same thing for midi..
  25499. Array <int> midiSourceNodes;
  25500. for (int i = graph.getNumConnections(); --i >= 0;)
  25501. {
  25502. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  25503. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  25504. midiSourceNodes.add (c->sourceNodeId);
  25505. }
  25506. if (midiSourceNodes.size() == 0)
  25507. {
  25508. // No midi inputs..
  25509. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  25510. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  25511. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  25512. }
  25513. else if (midiSourceNodes.size() == 1)
  25514. {
  25515. // One midi input..
  25516. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  25517. AudioProcessorGraph::midiChannelIndex);
  25518. if (midiBufferToUse >= 0)
  25519. {
  25520. if (isBufferNeededLater (ourRenderingIndex,
  25521. AudioProcessorGraph::midiChannelIndex,
  25522. midiSourceNodes.getUnchecked(0),
  25523. AudioProcessorGraph::midiChannelIndex))
  25524. {
  25525. // can't mess up this channel because it's needed later by another node, so we
  25526. // need to use a copy of it..
  25527. const int newFreeBuffer = getFreeBuffer (true);
  25528. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  25529. midiBufferToUse = newFreeBuffer;
  25530. }
  25531. }
  25532. else
  25533. {
  25534. // probably a feedback loop, so just use an empty one..
  25535. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  25536. }
  25537. }
  25538. else
  25539. {
  25540. // More than one midi input being mixed..
  25541. int reusableInputIndex = -1;
  25542. for (int i = 0; i < midiSourceNodes.size(); ++i)
  25543. {
  25544. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  25545. AudioProcessorGraph::midiChannelIndex);
  25546. if (sourceBufIndex >= 0
  25547. && ! isBufferNeededLater (ourRenderingIndex,
  25548. AudioProcessorGraph::midiChannelIndex,
  25549. midiSourceNodes.getUnchecked(i),
  25550. AudioProcessorGraph::midiChannelIndex))
  25551. {
  25552. // we've found one of our input buffers that can be re-used..
  25553. reusableInputIndex = i;
  25554. midiBufferToUse = sourceBufIndex;
  25555. break;
  25556. }
  25557. }
  25558. if (reusableInputIndex < 0)
  25559. {
  25560. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  25561. midiBufferToUse = getFreeBuffer (true);
  25562. jassert (midiBufferToUse >= 0);
  25563. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  25564. AudioProcessorGraph::midiChannelIndex);
  25565. if (srcIndex >= 0)
  25566. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  25567. else
  25568. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  25569. reusableInputIndex = 0;
  25570. }
  25571. for (int j = 0; j < midiSourceNodes.size(); ++j)
  25572. {
  25573. if (j != reusableInputIndex)
  25574. {
  25575. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  25576. AudioProcessorGraph::midiChannelIndex);
  25577. if (srcIndex >= 0)
  25578. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  25579. }
  25580. }
  25581. }
  25582. if (node->processor->producesMidi())
  25583. markBufferAsContaining (midiBufferToUse, node->id,
  25584. AudioProcessorGraph::midiChannelIndex);
  25585. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  25586. totalChans, midiBufferToUse));
  25587. }
  25588. int getFreeBuffer (const bool forMidi)
  25589. {
  25590. if (forMidi)
  25591. {
  25592. for (int i = 1; i < midiNodeIds.size(); ++i)
  25593. if (midiNodeIds.getUnchecked(i) < 0)
  25594. return i;
  25595. midiNodeIds.add (-1);
  25596. return midiNodeIds.size() - 1;
  25597. }
  25598. else
  25599. {
  25600. for (int i = 1; i < nodeIds.size(); ++i)
  25601. if (nodeIds.getUnchecked(i) < 0)
  25602. return i;
  25603. nodeIds.add (-1);
  25604. channels.add (0);
  25605. return nodeIds.size() - 1;
  25606. }
  25607. }
  25608. int getReadOnlyEmptyBuffer() const throw()
  25609. {
  25610. return 0;
  25611. }
  25612. int getBufferContaining (const int nodeId, const int outputChannel) const throw()
  25613. {
  25614. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  25615. {
  25616. for (int i = midiNodeIds.size(); --i >= 0;)
  25617. if (midiNodeIds.getUnchecked(i) == nodeId)
  25618. return i;
  25619. }
  25620. else
  25621. {
  25622. for (int i = nodeIds.size(); --i >= 0;)
  25623. if (nodeIds.getUnchecked(i) == nodeId
  25624. && channels.getUnchecked(i) == outputChannel)
  25625. return i;
  25626. }
  25627. return -1;
  25628. }
  25629. void markAnyUnusedBuffersAsFree (const int stepIndex)
  25630. {
  25631. int i;
  25632. for (i = 0; i < nodeIds.size(); ++i)
  25633. {
  25634. if (nodeIds.getUnchecked(i) >= 0
  25635. && ! isBufferNeededLater (stepIndex, -1,
  25636. nodeIds.getUnchecked(i),
  25637. channels.getUnchecked(i)))
  25638. {
  25639. nodeIds.set (i, -1);
  25640. }
  25641. }
  25642. for (i = 0; i < midiNodeIds.size(); ++i)
  25643. {
  25644. if (midiNodeIds.getUnchecked(i) >= 0
  25645. && ! isBufferNeededLater (stepIndex, -1,
  25646. midiNodeIds.getUnchecked(i),
  25647. AudioProcessorGraph::midiChannelIndex))
  25648. {
  25649. midiNodeIds.set (i, -1);
  25650. }
  25651. }
  25652. }
  25653. bool isBufferNeededLater (int stepIndexToSearchFrom,
  25654. int inputChannelOfIndexToIgnore,
  25655. const int nodeId,
  25656. const int outputChanIndex) const throw()
  25657. {
  25658. while (stepIndexToSearchFrom < orderedNodes.size())
  25659. {
  25660. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  25661. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  25662. {
  25663. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  25664. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  25665. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  25666. return true;
  25667. }
  25668. else
  25669. {
  25670. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  25671. if (i != inputChannelOfIndexToIgnore
  25672. && graph.getConnectionBetween (nodeId, outputChanIndex,
  25673. node->id, i) != 0)
  25674. return true;
  25675. }
  25676. inputChannelOfIndexToIgnore = -1;
  25677. ++stepIndexToSearchFrom;
  25678. }
  25679. return false;
  25680. }
  25681. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  25682. {
  25683. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  25684. {
  25685. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  25686. midiNodeIds.set (bufferNum, nodeId);
  25687. }
  25688. else
  25689. {
  25690. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  25691. nodeIds.set (bufferNum, nodeId);
  25692. channels.set (bufferNum, outputIndex);
  25693. }
  25694. }
  25695. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  25696. const RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  25697. };
  25698. }
  25699. void AudioProcessorGraph::clearRenderingSequence()
  25700. {
  25701. const ScopedLock sl (renderLock);
  25702. for (int i = renderingOps.size(); --i >= 0;)
  25703. {
  25704. GraphRenderingOps::AudioGraphRenderingOp* const r
  25705. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  25706. renderingOps.remove (i);
  25707. delete r;
  25708. }
  25709. }
  25710. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  25711. const uint32 possibleDestinationId,
  25712. const int recursionCheck) const throw()
  25713. {
  25714. if (recursionCheck > 0)
  25715. {
  25716. for (int i = connections.size(); --i >= 0;)
  25717. {
  25718. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  25719. if (c->destNodeId == possibleDestinationId
  25720. && (c->sourceNodeId == possibleInputId
  25721. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  25722. return true;
  25723. }
  25724. }
  25725. return false;
  25726. }
  25727. void AudioProcessorGraph::buildRenderingSequence()
  25728. {
  25729. VoidArray newRenderingOps;
  25730. int numRenderingBuffersNeeded = 2;
  25731. int numMidiBuffersNeeded = 1;
  25732. {
  25733. MessageManagerLock mml;
  25734. VoidArray orderedNodes;
  25735. int i;
  25736. for (i = 0; i < nodes.size(); ++i)
  25737. {
  25738. Node* const node = nodes.getUnchecked(i);
  25739. node->prepare (getSampleRate(), getBlockSize(), this);
  25740. int j = 0;
  25741. for (; j < orderedNodes.size(); ++j)
  25742. if (isAnInputTo (node->id,
  25743. ((Node*) orderedNodes.getUnchecked (j))->id,
  25744. nodes.size() + 1))
  25745. break;
  25746. orderedNodes.insert (j, node);
  25747. }
  25748. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  25749. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  25750. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  25751. }
  25752. VoidArray oldRenderingOps (renderingOps);
  25753. {
  25754. // swap over to the new rendering sequence..
  25755. const ScopedLock sl (renderLock);
  25756. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  25757. renderingBuffers.clear();
  25758. for (int i = midiBuffers.size(); --i >= 0;)
  25759. midiBuffers.getUnchecked(i)->clear();
  25760. while (midiBuffers.size() < numMidiBuffersNeeded)
  25761. midiBuffers.add (new MidiBuffer());
  25762. renderingOps = newRenderingOps;
  25763. }
  25764. for (int i = oldRenderingOps.size(); --i >= 0;)
  25765. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  25766. }
  25767. void AudioProcessorGraph::handleAsyncUpdate()
  25768. {
  25769. buildRenderingSequence();
  25770. }
  25771. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  25772. {
  25773. currentAudioInputBuffer = 0;
  25774. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  25775. currentMidiInputBuffer = 0;
  25776. currentMidiOutputBuffer.clear();
  25777. clearRenderingSequence();
  25778. buildRenderingSequence();
  25779. }
  25780. void AudioProcessorGraph::releaseResources()
  25781. {
  25782. for (int i = 0; i < nodes.size(); ++i)
  25783. nodes.getUnchecked(i)->unprepare();
  25784. renderingBuffers.setSize (1, 1);
  25785. midiBuffers.clear();
  25786. currentAudioInputBuffer = 0;
  25787. currentAudioOutputBuffer.setSize (1, 1);
  25788. currentMidiInputBuffer = 0;
  25789. currentMidiOutputBuffer.clear();
  25790. }
  25791. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  25792. {
  25793. const int numSamples = buffer.getNumSamples();
  25794. const ScopedLock sl (renderLock);
  25795. currentAudioInputBuffer = &buffer;
  25796. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  25797. currentAudioOutputBuffer.clear();
  25798. currentMidiInputBuffer = &midiMessages;
  25799. currentMidiOutputBuffer.clear();
  25800. int i;
  25801. for (i = 0; i < renderingOps.size(); ++i)
  25802. {
  25803. GraphRenderingOps::AudioGraphRenderingOp* const op
  25804. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  25805. op->perform (renderingBuffers, midiBuffers, numSamples);
  25806. }
  25807. for (i = 0; i < buffer.getNumChannels(); ++i)
  25808. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  25809. }
  25810. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  25811. {
  25812. return "Input " + String (channelIndex + 1);
  25813. }
  25814. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  25815. {
  25816. return "Output " + String (channelIndex + 1);
  25817. }
  25818. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  25819. {
  25820. return true;
  25821. }
  25822. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  25823. {
  25824. return true;
  25825. }
  25826. bool AudioProcessorGraph::acceptsMidi() const
  25827. {
  25828. return true;
  25829. }
  25830. bool AudioProcessorGraph::producesMidi() const
  25831. {
  25832. return true;
  25833. }
  25834. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  25835. {
  25836. }
  25837. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  25838. {
  25839. }
  25840. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  25841. : type (type_),
  25842. graph (0)
  25843. {
  25844. }
  25845. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  25846. {
  25847. }
  25848. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  25849. {
  25850. switch (type)
  25851. {
  25852. case audioOutputNode:
  25853. return "Audio Output";
  25854. case audioInputNode:
  25855. return "Audio Input";
  25856. case midiOutputNode:
  25857. return "Midi Output";
  25858. case midiInputNode:
  25859. return "Midi Input";
  25860. default:
  25861. break;
  25862. }
  25863. return String::empty;
  25864. }
  25865. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  25866. {
  25867. d.name = getName();
  25868. d.uid = d.name.hashCode();
  25869. d.category = "I/O devices";
  25870. d.pluginFormatName = "Internal";
  25871. d.manufacturerName = "Raw Material Software";
  25872. d.version = "1.0";
  25873. d.isInstrument = false;
  25874. d.numInputChannels = getNumInputChannels();
  25875. if (type == audioOutputNode && graph != 0)
  25876. d.numInputChannels = graph->getNumInputChannels();
  25877. d.numOutputChannels = getNumOutputChannels();
  25878. if (type == audioInputNode && graph != 0)
  25879. d.numOutputChannels = graph->getNumOutputChannels();
  25880. }
  25881. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  25882. {
  25883. jassert (graph != 0);
  25884. }
  25885. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  25886. {
  25887. }
  25888. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  25889. MidiBuffer& midiMessages)
  25890. {
  25891. jassert (graph != 0);
  25892. switch (type)
  25893. {
  25894. case audioOutputNode:
  25895. {
  25896. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  25897. buffer.getNumChannels()); --i >= 0;)
  25898. {
  25899. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  25900. }
  25901. break;
  25902. }
  25903. case audioInputNode:
  25904. {
  25905. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  25906. buffer.getNumChannels()); --i >= 0;)
  25907. {
  25908. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  25909. }
  25910. break;
  25911. }
  25912. case midiOutputNode:
  25913. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  25914. break;
  25915. case midiInputNode:
  25916. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  25917. break;
  25918. default:
  25919. break;
  25920. }
  25921. }
  25922. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  25923. {
  25924. return type == midiOutputNode;
  25925. }
  25926. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  25927. {
  25928. return type == midiInputNode;
  25929. }
  25930. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  25931. {
  25932. switch (type)
  25933. {
  25934. case audioOutputNode:
  25935. return "Output " + String (channelIndex + 1);
  25936. case midiOutputNode:
  25937. return "Midi Output";
  25938. default:
  25939. break;
  25940. }
  25941. return String::empty;
  25942. }
  25943. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  25944. {
  25945. switch (type)
  25946. {
  25947. case audioInputNode:
  25948. return "Input " + String (channelIndex + 1);
  25949. case midiInputNode:
  25950. return "Midi Input";
  25951. default:
  25952. break;
  25953. }
  25954. return String::empty;
  25955. }
  25956. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  25957. {
  25958. return type == audioInputNode || type == audioOutputNode;
  25959. }
  25960. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  25961. {
  25962. return isInputChannelStereoPair (index);
  25963. }
  25964. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const throw()
  25965. {
  25966. return type == audioInputNode || type == midiInputNode;
  25967. }
  25968. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const throw()
  25969. {
  25970. return type == audioOutputNode || type == midiOutputNode;
  25971. }
  25972. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  25973. {
  25974. return 0;
  25975. }
  25976. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  25977. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  25978. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  25979. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  25980. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  25981. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  25982. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  25983. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  25984. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  25985. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  25986. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  25987. {
  25988. }
  25989. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  25990. {
  25991. }
  25992. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph) throw()
  25993. {
  25994. graph = newGraph;
  25995. if (graph != 0)
  25996. {
  25997. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  25998. type == audioInputNode ? graph->getNumInputChannels() : 0,
  25999. getSampleRate(),
  26000. getBlockSize());
  26001. updateHostDisplay();
  26002. }
  26003. }
  26004. END_JUCE_NAMESPACE
  26005. /********* End of inlined file: juce_AudioProcessorGraph.cpp *********/
  26006. /********* Start of inlined file: juce_AudioProcessorPlayer.cpp *********/
  26007. BEGIN_JUCE_NAMESPACE
  26008. AudioProcessorPlayer::AudioProcessorPlayer()
  26009. : processor (0),
  26010. sampleRate (0),
  26011. blockSize (0),
  26012. isPrepared (false),
  26013. numInputChans (0),
  26014. numOutputChans (0),
  26015. tempBuffer (1, 1)
  26016. {
  26017. }
  26018. AudioProcessorPlayer::~AudioProcessorPlayer()
  26019. {
  26020. setProcessor (0);
  26021. }
  26022. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  26023. {
  26024. if (processor != processorToPlay)
  26025. {
  26026. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  26027. {
  26028. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  26029. sampleRate, blockSize);
  26030. processorToPlay->prepareToPlay (sampleRate, blockSize);
  26031. }
  26032. lock.enter();
  26033. AudioProcessor* const oldOne = isPrepared ? processor : 0;
  26034. processor = processorToPlay;
  26035. isPrepared = true;
  26036. lock.exit();
  26037. if (oldOne != 0)
  26038. oldOne->releaseResources();
  26039. }
  26040. }
  26041. void AudioProcessorPlayer::audioDeviceIOCallback (const float** inputChannelData,
  26042. int numInputChannels,
  26043. float** outputChannelData,
  26044. int numOutputChannels,
  26045. int numSamples)
  26046. {
  26047. // these should have been prepared by audioDeviceAboutToStart()...
  26048. jassert (sampleRate > 0 && blockSize > 0);
  26049. incomingMidi.clear();
  26050. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  26051. int i, totalNumChans = 0;
  26052. if (numInputChannels > numOutputChannels)
  26053. {
  26054. // if there aren't enough output channels for the number of
  26055. // inputs, we need to create some temporary extra ones (can't
  26056. // use the input data in case it gets written to)
  26057. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  26058. false, false, true);
  26059. for (i = 0; i < numOutputChannels; ++i)
  26060. {
  26061. channels[totalNumChans] = outputChannelData[i];
  26062. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  26063. ++totalNumChans;
  26064. }
  26065. for (i = numOutputChannels; i < numInputChannels; ++i)
  26066. {
  26067. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  26068. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  26069. ++totalNumChans;
  26070. }
  26071. }
  26072. else
  26073. {
  26074. for (i = 0; i < numInputChannels; ++i)
  26075. {
  26076. channels[totalNumChans] = outputChannelData[i];
  26077. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  26078. ++totalNumChans;
  26079. }
  26080. for (i = numInputChannels; i < numOutputChannels; ++i)
  26081. {
  26082. channels[totalNumChans] = outputChannelData[i];
  26083. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  26084. ++totalNumChans;
  26085. }
  26086. }
  26087. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  26088. const ScopedLock sl (lock);
  26089. if (processor != 0)
  26090. processor->processBlock (buffer, incomingMidi);
  26091. }
  26092. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  26093. {
  26094. const ScopedLock sl (lock);
  26095. sampleRate = device->getCurrentSampleRate();
  26096. blockSize = device->getCurrentBufferSizeSamples();
  26097. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  26098. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  26099. messageCollector.reset (sampleRate);
  26100. zeromem (channels, sizeof (channels));
  26101. if (processor != 0)
  26102. {
  26103. if (isPrepared)
  26104. processor->releaseResources();
  26105. AudioProcessor* const oldProcessor = processor;
  26106. setProcessor (0);
  26107. setProcessor (oldProcessor);
  26108. }
  26109. }
  26110. void AudioProcessorPlayer::audioDeviceStopped()
  26111. {
  26112. const ScopedLock sl (lock);
  26113. if (processor != 0 && isPrepared)
  26114. processor->releaseResources();
  26115. sampleRate = 0.0;
  26116. blockSize = 0;
  26117. isPrepared = false;
  26118. tempBuffer.setSize (1, 1);
  26119. }
  26120. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  26121. {
  26122. messageCollector.addMessageToQueue (message);
  26123. }
  26124. END_JUCE_NAMESPACE
  26125. /********* End of inlined file: juce_AudioProcessorPlayer.cpp *********/
  26126. /********* Start of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  26127. BEGIN_JUCE_NAMESPACE
  26128. class ProcessorParameterPropertyComp : public PropertyComponent,
  26129. public AudioProcessorListener,
  26130. public AsyncUpdater
  26131. {
  26132. public:
  26133. ProcessorParameterPropertyComp (const String& name,
  26134. AudioProcessor* const owner_,
  26135. const int index_)
  26136. : PropertyComponent (name),
  26137. owner (owner_),
  26138. index (index_)
  26139. {
  26140. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  26141. owner_->addListener (this);
  26142. }
  26143. ~ProcessorParameterPropertyComp()
  26144. {
  26145. owner->removeListener (this);
  26146. deleteAllChildren();
  26147. }
  26148. void refresh()
  26149. {
  26150. slider->setValue (owner->getParameter (index), false);
  26151. }
  26152. void audioProcessorChanged (AudioProcessor*) {}
  26153. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  26154. {
  26155. if (parameterIndex == index)
  26156. triggerAsyncUpdate();
  26157. }
  26158. void handleAsyncUpdate()
  26159. {
  26160. refresh();
  26161. }
  26162. juce_UseDebuggingNewOperator
  26163. private:
  26164. AudioProcessor* const owner;
  26165. const int index;
  26166. Slider* slider;
  26167. class ParamSlider : public Slider
  26168. {
  26169. public:
  26170. ParamSlider (AudioProcessor* const owner_, const int index_)
  26171. : Slider (String::empty),
  26172. owner (owner_),
  26173. index (index_)
  26174. {
  26175. setRange (0.0, 1.0, 0.0);
  26176. setSliderStyle (Slider::LinearBar);
  26177. setTextBoxIsEditable (false);
  26178. setScrollWheelEnabled (false);
  26179. }
  26180. ~ParamSlider()
  26181. {
  26182. }
  26183. void valueChanged()
  26184. {
  26185. const float newVal = (float) getValue();
  26186. if (owner->getParameter (index) != newVal)
  26187. owner->setParameter (index, newVal);
  26188. }
  26189. const String getTextFromValue (double /*value*/)
  26190. {
  26191. return owner->getParameterText (index);
  26192. }
  26193. juce_UseDebuggingNewOperator
  26194. private:
  26195. AudioProcessor* const owner;
  26196. const int index;
  26197. };
  26198. };
  26199. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner)
  26200. : AudioProcessorEditor (owner)
  26201. {
  26202. setOpaque (true);
  26203. addAndMakeVisible (panel = new PropertyPanel());
  26204. Array <PropertyComponent*> params;
  26205. const int numParams = owner->getNumParameters();
  26206. int totalHeight = 0;
  26207. for (int i = 0; i < numParams; ++i)
  26208. {
  26209. String name (owner->getParameterName (i));
  26210. if (name.trim().isEmpty())
  26211. name = "Unnamed";
  26212. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner, i);
  26213. params.add (pc);
  26214. totalHeight += pc->getPreferredHeight();
  26215. }
  26216. panel->addProperties (params);
  26217. setSize (400, jlimit (25, 400, totalHeight));
  26218. }
  26219. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  26220. {
  26221. deleteAllChildren();
  26222. }
  26223. void GenericAudioProcessorEditor::paint (Graphics& g)
  26224. {
  26225. g.fillAll (Colours::white);
  26226. }
  26227. void GenericAudioProcessorEditor::resized()
  26228. {
  26229. panel->setSize (getWidth(), getHeight());
  26230. }
  26231. END_JUCE_NAMESPACE
  26232. /********* End of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  26233. /********* Start of inlined file: juce_Sampler.cpp *********/
  26234. BEGIN_JUCE_NAMESPACE
  26235. SamplerSound::SamplerSound (const String& name_,
  26236. AudioFormatReader& source,
  26237. const BitArray& midiNotes_,
  26238. const int midiNoteForNormalPitch,
  26239. const double attackTimeSecs,
  26240. const double releaseTimeSecs,
  26241. const double maxSampleLengthSeconds)
  26242. : name (name_),
  26243. midiNotes (midiNotes_),
  26244. midiRootNote (midiNoteForNormalPitch)
  26245. {
  26246. sourceSampleRate = source.sampleRate;
  26247. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  26248. {
  26249. data = 0;
  26250. length = 0;
  26251. attackSamples = 0;
  26252. releaseSamples = 0;
  26253. }
  26254. else
  26255. {
  26256. length = jmin ((int) source.lengthInSamples,
  26257. (int) (maxSampleLengthSeconds * sourceSampleRate));
  26258. data = new AudioSampleBuffer (jmin (2, source.numChannels), length + 4);
  26259. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  26260. attackSamples = roundDoubleToInt (attackTimeSecs * sourceSampleRate);
  26261. releaseSamples = roundDoubleToInt (releaseTimeSecs * sourceSampleRate);
  26262. }
  26263. }
  26264. SamplerSound::~SamplerSound()
  26265. {
  26266. delete data;
  26267. data = 0;
  26268. }
  26269. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  26270. {
  26271. return midiNotes [midiNoteNumber];
  26272. }
  26273. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  26274. {
  26275. return true;
  26276. }
  26277. SamplerVoice::SamplerVoice()
  26278. : pitchRatio (0.0),
  26279. sourceSamplePosition (0.0),
  26280. lgain (0.0f),
  26281. rgain (0.0f),
  26282. isInAttack (false),
  26283. isInRelease (false)
  26284. {
  26285. }
  26286. SamplerVoice::~SamplerVoice()
  26287. {
  26288. }
  26289. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  26290. {
  26291. return dynamic_cast <const SamplerSound*> (sound) != 0;
  26292. }
  26293. void SamplerVoice::startNote (const int midiNoteNumber,
  26294. const float velocity,
  26295. SynthesiserSound* s,
  26296. const int /*currentPitchWheelPosition*/)
  26297. {
  26298. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  26299. jassert (sound != 0); // this object can only play SamplerSounds!
  26300. if (sound != 0)
  26301. {
  26302. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  26303. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  26304. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  26305. sourceSamplePosition = 0.0;
  26306. lgain = velocity;
  26307. rgain = velocity;
  26308. isInAttack = (sound->attackSamples > 0);
  26309. isInRelease = false;
  26310. if (isInAttack)
  26311. {
  26312. attackReleaseLevel = 0.0f;
  26313. attackDelta = (float) (pitchRatio / sound->attackSamples);
  26314. }
  26315. else
  26316. {
  26317. attackReleaseLevel = 1.0f;
  26318. attackDelta = 0.0f;
  26319. }
  26320. if (sound->releaseSamples > 0)
  26321. {
  26322. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  26323. }
  26324. else
  26325. {
  26326. releaseDelta = 0.0f;
  26327. }
  26328. }
  26329. }
  26330. void SamplerVoice::stopNote (const bool allowTailOff)
  26331. {
  26332. if (allowTailOff)
  26333. {
  26334. isInAttack = false;
  26335. isInRelease = true;
  26336. }
  26337. else
  26338. {
  26339. clearCurrentNote();
  26340. }
  26341. }
  26342. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  26343. {
  26344. }
  26345. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  26346. const int /*newValue*/)
  26347. {
  26348. }
  26349. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  26350. {
  26351. const SamplerSound* const playingSound = (SamplerSound*) (SynthesiserSound*) getCurrentlyPlayingSound();
  26352. if (playingSound != 0)
  26353. {
  26354. const float* const inL = playingSound->data->getSampleData (0, 0);
  26355. const float* const inR = playingSound->data->getNumChannels() > 1
  26356. ? playingSound->data->getSampleData (1, 0) : 0;
  26357. float* outL = outputBuffer.getSampleData (0, startSample);
  26358. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  26359. while (--numSamples >= 0)
  26360. {
  26361. const int pos = (int) sourceSamplePosition;
  26362. const float alpha = (float) (sourceSamplePosition - pos);
  26363. const float invAlpha = 1.0f - alpha;
  26364. // just using a very simple linear interpolation here..
  26365. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  26366. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  26367. : l;
  26368. l *= lgain;
  26369. r *= rgain;
  26370. if (isInAttack)
  26371. {
  26372. l *= attackReleaseLevel;
  26373. r *= attackReleaseLevel;
  26374. attackReleaseLevel += attackDelta;
  26375. if (attackReleaseLevel >= 1.0f)
  26376. {
  26377. attackReleaseLevel = 1.0f;
  26378. isInAttack = false;
  26379. }
  26380. }
  26381. else if (isInRelease)
  26382. {
  26383. l *= attackReleaseLevel;
  26384. r *= attackReleaseLevel;
  26385. attackReleaseLevel += releaseDelta;
  26386. if (attackReleaseLevel <= 0.0f)
  26387. {
  26388. stopNote (false);
  26389. break;
  26390. }
  26391. }
  26392. if (outR != 0)
  26393. {
  26394. *outL++ += l;
  26395. *outR++ += r;
  26396. }
  26397. else
  26398. {
  26399. *outL++ += (l + r) * 0.5f;
  26400. }
  26401. sourceSamplePosition += pitchRatio;
  26402. if (sourceSamplePosition > playingSound->length)
  26403. {
  26404. stopNote (false);
  26405. break;
  26406. }
  26407. }
  26408. }
  26409. }
  26410. END_JUCE_NAMESPACE
  26411. /********* End of inlined file: juce_Sampler.cpp *********/
  26412. /********* Start of inlined file: juce_Synthesiser.cpp *********/
  26413. BEGIN_JUCE_NAMESPACE
  26414. SynthesiserSound::SynthesiserSound()
  26415. {
  26416. }
  26417. SynthesiserSound::~SynthesiserSound()
  26418. {
  26419. }
  26420. SynthesiserVoice::SynthesiserVoice()
  26421. : currentSampleRate (44100.0),
  26422. currentlyPlayingNote (-1),
  26423. noteOnTime (0),
  26424. currentlyPlayingSound (0)
  26425. {
  26426. }
  26427. SynthesiserVoice::~SynthesiserVoice()
  26428. {
  26429. }
  26430. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  26431. {
  26432. return currentlyPlayingSound != 0
  26433. && currentlyPlayingSound->appliesToChannel (midiChannel);
  26434. }
  26435. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  26436. {
  26437. currentSampleRate = newRate;
  26438. }
  26439. void SynthesiserVoice::clearCurrentNote()
  26440. {
  26441. currentlyPlayingNote = -1;
  26442. currentlyPlayingSound = 0;
  26443. }
  26444. Synthesiser::Synthesiser()
  26445. : voices (2),
  26446. sounds (2),
  26447. sampleRate (0),
  26448. lastNoteOnCounter (0),
  26449. shouldStealNotes (true)
  26450. {
  26451. zeromem (lastPitchWheelValues, sizeof (lastPitchWheelValues));
  26452. }
  26453. Synthesiser::~Synthesiser()
  26454. {
  26455. }
  26456. SynthesiserVoice* Synthesiser::getVoice (const int index) const throw()
  26457. {
  26458. const ScopedLock sl (lock);
  26459. return voices [index];
  26460. }
  26461. void Synthesiser::clearVoices()
  26462. {
  26463. const ScopedLock sl (lock);
  26464. voices.clear();
  26465. }
  26466. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  26467. {
  26468. const ScopedLock sl (lock);
  26469. voices.add (newVoice);
  26470. }
  26471. void Synthesiser::removeVoice (const int index)
  26472. {
  26473. const ScopedLock sl (lock);
  26474. voices.remove (index);
  26475. }
  26476. void Synthesiser::clearSounds()
  26477. {
  26478. const ScopedLock sl (lock);
  26479. sounds.clear();
  26480. }
  26481. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  26482. {
  26483. const ScopedLock sl (lock);
  26484. sounds.add (newSound);
  26485. }
  26486. void Synthesiser::removeSound (const int index)
  26487. {
  26488. const ScopedLock sl (lock);
  26489. sounds.remove (index);
  26490. }
  26491. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  26492. {
  26493. shouldStealNotes = shouldStealNotes_;
  26494. }
  26495. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  26496. {
  26497. if (sampleRate != newRate)
  26498. {
  26499. const ScopedLock sl (lock);
  26500. allNotesOff (0, false);
  26501. sampleRate = newRate;
  26502. for (int i = voices.size(); --i >= 0;)
  26503. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  26504. }
  26505. }
  26506. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  26507. const MidiBuffer& midiData,
  26508. int startSample,
  26509. int numSamples)
  26510. {
  26511. // must set the sample rate before using this!
  26512. jassert (sampleRate != 0);
  26513. const ScopedLock sl (lock);
  26514. MidiBuffer::Iterator midiIterator (midiData);
  26515. midiIterator.setNextSamplePosition (startSample);
  26516. MidiMessage m (0xf4, 0.0);
  26517. while (numSamples > 0)
  26518. {
  26519. int midiEventPos;
  26520. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  26521. && midiEventPos < startSample + numSamples;
  26522. const int numThisTime = useEvent ? midiEventPos - startSample
  26523. : numSamples;
  26524. if (numThisTime > 0)
  26525. {
  26526. for (int i = voices.size(); --i >= 0;)
  26527. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  26528. }
  26529. if (useEvent)
  26530. {
  26531. if (m.isNoteOn())
  26532. {
  26533. const int channel = m.getChannel();
  26534. noteOn (channel,
  26535. m.getNoteNumber(),
  26536. m.getFloatVelocity());
  26537. }
  26538. else if (m.isNoteOff())
  26539. {
  26540. noteOff (m.getChannel(),
  26541. m.getNoteNumber(),
  26542. true);
  26543. }
  26544. else if (m.isAllNotesOff() || m.isAllSoundOff())
  26545. {
  26546. allNotesOff (m.getChannel(), true);
  26547. }
  26548. else if (m.isPitchWheel())
  26549. {
  26550. const int channel = m.getChannel();
  26551. const int wheelPos = m.getPitchWheelValue();
  26552. lastPitchWheelValues [channel - 1] = wheelPos;
  26553. handlePitchWheel (channel, wheelPos);
  26554. }
  26555. else if (m.isController())
  26556. {
  26557. handleController (m.getChannel(),
  26558. m.getControllerNumber(),
  26559. m.getControllerValue());
  26560. }
  26561. }
  26562. startSample += numThisTime;
  26563. numSamples -= numThisTime;
  26564. }
  26565. }
  26566. void Synthesiser::noteOn (const int midiChannel,
  26567. const int midiNoteNumber,
  26568. const float velocity)
  26569. {
  26570. const ScopedLock sl (lock);
  26571. for (int i = sounds.size(); --i >= 0;)
  26572. {
  26573. SynthesiserSound* const sound = sounds.getUnchecked(i);
  26574. if (sound->appliesToNote (midiNoteNumber)
  26575. && sound->appliesToChannel (midiChannel))
  26576. {
  26577. startVoice (findFreeVoice (sound, shouldStealNotes),
  26578. sound, midiChannel, midiNoteNumber, velocity);
  26579. }
  26580. }
  26581. }
  26582. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  26583. SynthesiserSound* const sound,
  26584. const int midiChannel,
  26585. const int midiNoteNumber,
  26586. const float velocity)
  26587. {
  26588. if (voice != 0 && sound != 0)
  26589. {
  26590. if (voice->currentlyPlayingSound != 0)
  26591. voice->stopNote (false);
  26592. voice->startNote (midiNoteNumber,
  26593. velocity,
  26594. sound,
  26595. lastPitchWheelValues [midiChannel - 1]);
  26596. voice->currentlyPlayingNote = midiNoteNumber;
  26597. voice->noteOnTime = ++lastNoteOnCounter;
  26598. voice->currentlyPlayingSound = sound;
  26599. }
  26600. }
  26601. void Synthesiser::noteOff (const int midiChannel,
  26602. const int midiNoteNumber,
  26603. const bool allowTailOff)
  26604. {
  26605. const ScopedLock sl (lock);
  26606. for (int i = voices.size(); --i >= 0;)
  26607. {
  26608. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26609. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  26610. {
  26611. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  26612. if (sound != 0
  26613. && sound->appliesToNote (midiNoteNumber)
  26614. && sound->appliesToChannel (midiChannel))
  26615. {
  26616. voice->stopNote (allowTailOff);
  26617. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  26618. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  26619. }
  26620. }
  26621. }
  26622. }
  26623. void Synthesiser::allNotesOff (const int midiChannel,
  26624. const bool allowTailOff)
  26625. {
  26626. const ScopedLock sl (lock);
  26627. for (int i = voices.size(); --i >= 0;)
  26628. {
  26629. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26630. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  26631. voice->stopNote (allowTailOff);
  26632. }
  26633. }
  26634. void Synthesiser::handlePitchWheel (const int midiChannel,
  26635. const int wheelValue)
  26636. {
  26637. const ScopedLock sl (lock);
  26638. for (int i = voices.size(); --i >= 0;)
  26639. {
  26640. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26641. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  26642. {
  26643. voice->pitchWheelMoved (wheelValue);
  26644. }
  26645. }
  26646. }
  26647. void Synthesiser::handleController (const int midiChannel,
  26648. const int controllerNumber,
  26649. const int controllerValue)
  26650. {
  26651. const ScopedLock sl (lock);
  26652. for (int i = voices.size(); --i >= 0;)
  26653. {
  26654. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26655. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  26656. voice->controllerMoved (controllerNumber, controllerValue);
  26657. }
  26658. }
  26659. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  26660. const bool stealIfNoneAvailable) const
  26661. {
  26662. const ScopedLock sl (lock);
  26663. for (int i = voices.size(); --i >= 0;)
  26664. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  26665. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  26666. return voices.getUnchecked (i);
  26667. if (stealIfNoneAvailable)
  26668. {
  26669. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  26670. SynthesiserVoice* oldest = 0;
  26671. for (int i = voices.size(); --i >= 0;)
  26672. {
  26673. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26674. if (voice->canPlaySound (soundToPlay)
  26675. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  26676. oldest = voice;
  26677. }
  26678. jassert (oldest != 0);
  26679. return oldest;
  26680. }
  26681. return 0;
  26682. }
  26683. END_JUCE_NAMESPACE
  26684. /********* End of inlined file: juce_Synthesiser.cpp *********/
  26685. /********* Start of inlined file: juce_FileBasedDocument.cpp *********/
  26686. BEGIN_JUCE_NAMESPACE
  26687. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  26688. const String& fileWildcard_,
  26689. const String& openFileDialogTitle_,
  26690. const String& saveFileDialogTitle_)
  26691. : changedSinceSave (false),
  26692. fileExtension (fileExtension_),
  26693. fileWildcard (fileWildcard_),
  26694. openFileDialogTitle (openFileDialogTitle_),
  26695. saveFileDialogTitle (saveFileDialogTitle_)
  26696. {
  26697. }
  26698. FileBasedDocument::~FileBasedDocument()
  26699. {
  26700. }
  26701. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  26702. {
  26703. changedSinceSave = hasChanged;
  26704. }
  26705. void FileBasedDocument::changed()
  26706. {
  26707. changedSinceSave = true;
  26708. sendChangeMessage (this);
  26709. }
  26710. void FileBasedDocument::setFile (const File& newFile)
  26711. {
  26712. if (documentFile != newFile)
  26713. {
  26714. documentFile = newFile;
  26715. changedSinceSave = true;
  26716. }
  26717. }
  26718. bool FileBasedDocument::loadFrom (const File& newFile,
  26719. const bool showMessageOnFailure)
  26720. {
  26721. MouseCursor::showWaitCursor();
  26722. const File oldFile (documentFile);
  26723. documentFile = newFile;
  26724. String error;
  26725. if (newFile.existsAsFile())
  26726. {
  26727. error = loadDocument (newFile);
  26728. if (error.isEmpty())
  26729. {
  26730. setChangedFlag (false);
  26731. MouseCursor::hideWaitCursor();
  26732. setLastDocumentOpened (newFile);
  26733. return true;
  26734. }
  26735. }
  26736. else
  26737. {
  26738. error = "The file doesn't exist";
  26739. }
  26740. documentFile = oldFile;
  26741. MouseCursor::hideWaitCursor();
  26742. if (showMessageOnFailure)
  26743. {
  26744. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  26745. TRANS("Failed to open file..."),
  26746. TRANS("There was an error while trying to load the file:\n\n")
  26747. + newFile.getFullPathName()
  26748. + T("\n\n")
  26749. + error);
  26750. }
  26751. return false;
  26752. }
  26753. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  26754. {
  26755. FileChooser fc (openFileDialogTitle,
  26756. getLastDocumentOpened(),
  26757. fileWildcard);
  26758. if (fc.browseForFileToOpen())
  26759. return loadFrom (fc.getResult(), showMessageOnFailure);
  26760. return false;
  26761. }
  26762. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  26763. const bool showMessageOnFailure)
  26764. {
  26765. return saveAs (documentFile,
  26766. false,
  26767. askUserForFileIfNotSpecified,
  26768. showMessageOnFailure);
  26769. }
  26770. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  26771. const bool warnAboutOverwritingExistingFiles,
  26772. const bool askUserForFileIfNotSpecified,
  26773. const bool showMessageOnFailure)
  26774. {
  26775. if (newFile == File::nonexistent)
  26776. {
  26777. if (askUserForFileIfNotSpecified)
  26778. {
  26779. return saveAsInteractive (true);
  26780. }
  26781. else
  26782. {
  26783. // can't save to an unspecified file
  26784. jassertfalse
  26785. return failedToWriteToFile;
  26786. }
  26787. }
  26788. if (warnAboutOverwritingExistingFiles && newFile.exists())
  26789. {
  26790. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  26791. TRANS("File already exists"),
  26792. TRANS("There's already a file called:\n\n")
  26793. + newFile.getFullPathName()
  26794. + TRANS("\n\nAre you sure you want to overwrite it?"),
  26795. TRANS("overwrite"),
  26796. TRANS("cancel")))
  26797. {
  26798. return userCancelledSave;
  26799. }
  26800. }
  26801. MouseCursor::showWaitCursor();
  26802. const File oldFile (documentFile);
  26803. documentFile = newFile;
  26804. String error (saveDocument (newFile));
  26805. if (error.isEmpty())
  26806. {
  26807. setChangedFlag (false);
  26808. MouseCursor::hideWaitCursor();
  26809. return savedOk;
  26810. }
  26811. documentFile = oldFile;
  26812. MouseCursor::hideWaitCursor();
  26813. if (showMessageOnFailure)
  26814. {
  26815. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  26816. TRANS("Error writing to file..."),
  26817. TRANS("An error occurred while trying to save \"")
  26818. + getDocumentTitle()
  26819. + TRANS("\" to the file:\n\n")
  26820. + newFile.getFullPathName()
  26821. + T("\n\n")
  26822. + error);
  26823. }
  26824. return failedToWriteToFile;
  26825. }
  26826. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  26827. {
  26828. if (! hasChangedSinceSaved())
  26829. return savedOk;
  26830. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  26831. TRANS("Closing document..."),
  26832. TRANS("Do you want to save the changes to \"")
  26833. + getDocumentTitle() + T("\"?"),
  26834. TRANS("save"),
  26835. TRANS("discard changes"),
  26836. TRANS("cancel"));
  26837. if (r == 1)
  26838. {
  26839. // save changes
  26840. return save (true, true);
  26841. }
  26842. else if (r == 2)
  26843. {
  26844. // discard changes
  26845. return savedOk;
  26846. }
  26847. return userCancelledSave;
  26848. }
  26849. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  26850. {
  26851. File f;
  26852. if (documentFile.existsAsFile())
  26853. f = documentFile;
  26854. else
  26855. f = getLastDocumentOpened();
  26856. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  26857. if (legalFilename.isEmpty())
  26858. legalFilename = "unnamed";
  26859. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  26860. f = f.getSiblingFile (legalFilename);
  26861. else
  26862. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  26863. f = f.withFileExtension (fileExtension)
  26864. .getNonexistentSibling (true);
  26865. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  26866. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  26867. {
  26868. setLastDocumentOpened (fc.getResult());
  26869. File chosen (fc.getResult());
  26870. if (chosen.getFileExtension().isEmpty())
  26871. chosen = chosen.withFileExtension (fileExtension);
  26872. return saveAs (chosen, false, false, true);
  26873. }
  26874. return userCancelledSave;
  26875. }
  26876. END_JUCE_NAMESPACE
  26877. /********* End of inlined file: juce_FileBasedDocument.cpp *********/
  26878. /********* Start of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  26879. BEGIN_JUCE_NAMESPACE
  26880. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  26881. : maxNumberOfItems (10)
  26882. {
  26883. }
  26884. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  26885. {
  26886. }
  26887. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  26888. {
  26889. maxNumberOfItems = jmax (1, newMaxNumber);
  26890. while (getNumFiles() > maxNumberOfItems)
  26891. files.remove (getNumFiles() - 1);
  26892. }
  26893. int RecentlyOpenedFilesList::getNumFiles() const
  26894. {
  26895. return files.size();
  26896. }
  26897. const File RecentlyOpenedFilesList::getFile (const int index) const
  26898. {
  26899. return File (files [index]);
  26900. }
  26901. void RecentlyOpenedFilesList::clear()
  26902. {
  26903. files.clear();
  26904. }
  26905. void RecentlyOpenedFilesList::addFile (const File& file)
  26906. {
  26907. const String path (file.getFullPathName());
  26908. files.removeString (path, true);
  26909. files.insert (0, path);
  26910. setMaxNumberOfItems (maxNumberOfItems);
  26911. }
  26912. void RecentlyOpenedFilesList::removeNonExistentFiles()
  26913. {
  26914. for (int i = getNumFiles(); --i >= 0;)
  26915. if (! getFile(i).exists())
  26916. files.remove (i);
  26917. }
  26918. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  26919. const int baseItemId,
  26920. const bool showFullPaths,
  26921. const bool dontAddNonExistentFiles,
  26922. const File** filesToAvoid)
  26923. {
  26924. int num = 0;
  26925. for (int i = 0; i < getNumFiles(); ++i)
  26926. {
  26927. const File f (getFile(i));
  26928. if ((! dontAddNonExistentFiles) || f.exists())
  26929. {
  26930. bool needsAvoiding = false;
  26931. if (filesToAvoid != 0)
  26932. {
  26933. const File** files = filesToAvoid;
  26934. while (*files != 0)
  26935. {
  26936. if (f == **files)
  26937. {
  26938. needsAvoiding = true;
  26939. break;
  26940. }
  26941. ++files;
  26942. }
  26943. }
  26944. if (! needsAvoiding)
  26945. {
  26946. menuToAddTo.addItem (baseItemId + i,
  26947. showFullPaths ? f.getFullPathName()
  26948. : f.getFileName());
  26949. ++num;
  26950. }
  26951. }
  26952. }
  26953. return num;
  26954. }
  26955. const String RecentlyOpenedFilesList::toString() const
  26956. {
  26957. return files.joinIntoString (T("\n"));
  26958. }
  26959. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  26960. {
  26961. clear();
  26962. files.addLines (stringifiedVersion);
  26963. setMaxNumberOfItems (maxNumberOfItems);
  26964. }
  26965. END_JUCE_NAMESPACE
  26966. /********* End of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  26967. /********* Start of inlined file: juce_UndoManager.cpp *********/
  26968. BEGIN_JUCE_NAMESPACE
  26969. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  26970. const int minimumTransactions)
  26971. : totalUnitsStored (0),
  26972. nextIndex (0),
  26973. newTransaction (true),
  26974. reentrancyCheck (false)
  26975. {
  26976. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  26977. minimumTransactions);
  26978. }
  26979. UndoManager::~UndoManager()
  26980. {
  26981. clearUndoHistory();
  26982. }
  26983. void UndoManager::clearUndoHistory()
  26984. {
  26985. transactions.clear();
  26986. transactionNames.clear();
  26987. totalUnitsStored = 0;
  26988. nextIndex = 0;
  26989. sendChangeMessage (this);
  26990. }
  26991. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  26992. {
  26993. return totalUnitsStored;
  26994. }
  26995. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  26996. const int minimumTransactions)
  26997. {
  26998. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  26999. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  27000. }
  27001. bool UndoManager::perform (UndoableAction* const command, const String& actionName)
  27002. {
  27003. if (command != 0)
  27004. {
  27005. if (actionName.isNotEmpty())
  27006. currentTransactionName = actionName;
  27007. if (reentrancyCheck)
  27008. {
  27009. jassertfalse // don't call perform() recursively from the UndoableAction::perform() or
  27010. // undo() methods, or else these actions won't actually get done.
  27011. return false;
  27012. }
  27013. else
  27014. {
  27015. bool success = false;
  27016. JUCE_TRY
  27017. {
  27018. success = command->perform();
  27019. }
  27020. JUCE_CATCH_EXCEPTION
  27021. jassert (success);
  27022. if (success)
  27023. {
  27024. if (nextIndex > 0 && ! newTransaction)
  27025. {
  27026. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  27027. jassert (commandSet != 0);
  27028. if (commandSet == 0)
  27029. return false;
  27030. commandSet->add (command);
  27031. }
  27032. else
  27033. {
  27034. OwnedArray<UndoableAction>* commandSet = new OwnedArray<UndoableAction>();
  27035. commandSet->add (command);
  27036. transactions.insert (nextIndex, commandSet);
  27037. transactionNames.insert (nextIndex, currentTransactionName);
  27038. ++nextIndex;
  27039. }
  27040. totalUnitsStored += command->getSizeInUnits();
  27041. newTransaction = false;
  27042. }
  27043. while (nextIndex < transactions.size())
  27044. {
  27045. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  27046. for (int i = lastSet->size(); --i >= 0;)
  27047. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  27048. transactions.removeLast();
  27049. transactionNames.remove (transactionNames.size() - 1);
  27050. }
  27051. while (nextIndex > 0
  27052. && totalUnitsStored > maxNumUnitsToKeep
  27053. && transactions.size() > minimumTransactionsToKeep)
  27054. {
  27055. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  27056. for (int i = firstSet->size(); --i >= 0;)
  27057. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  27058. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  27059. transactions.remove (0);
  27060. transactionNames.remove (0);
  27061. --nextIndex;
  27062. }
  27063. sendChangeMessage (this);
  27064. return success;
  27065. }
  27066. }
  27067. return false;
  27068. }
  27069. void UndoManager::beginNewTransaction (const String& actionName)
  27070. {
  27071. newTransaction = true;
  27072. currentTransactionName = actionName;
  27073. }
  27074. void UndoManager::setCurrentTransactionName (const String& newName)
  27075. {
  27076. currentTransactionName = newName;
  27077. }
  27078. bool UndoManager::canUndo() const
  27079. {
  27080. return nextIndex > 0;
  27081. }
  27082. bool UndoManager::canRedo() const
  27083. {
  27084. return nextIndex < transactions.size();
  27085. }
  27086. const String UndoManager::getUndoDescription() const
  27087. {
  27088. return transactionNames [nextIndex - 1];
  27089. }
  27090. const String UndoManager::getRedoDescription() const
  27091. {
  27092. return transactionNames [nextIndex];
  27093. }
  27094. bool UndoManager::undo()
  27095. {
  27096. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  27097. if (commandSet == 0)
  27098. return false;
  27099. reentrancyCheck = true;
  27100. bool failed = false;
  27101. for (int i = commandSet->size(); --i >= 0;)
  27102. {
  27103. if (! commandSet->getUnchecked(i)->undo())
  27104. {
  27105. jassertfalse
  27106. failed = true;
  27107. break;
  27108. }
  27109. }
  27110. reentrancyCheck = false;
  27111. if (failed)
  27112. {
  27113. clearUndoHistory();
  27114. }
  27115. else
  27116. {
  27117. --nextIndex;
  27118. }
  27119. beginNewTransaction();
  27120. sendChangeMessage (this);
  27121. return true;
  27122. }
  27123. bool UndoManager::redo()
  27124. {
  27125. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  27126. if (commandSet == 0)
  27127. return false;
  27128. reentrancyCheck = true;
  27129. bool failed = false;
  27130. for (int i = 0; i < commandSet->size(); ++i)
  27131. {
  27132. if (! commandSet->getUnchecked(i)->perform())
  27133. {
  27134. jassertfalse
  27135. failed = true;
  27136. break;
  27137. }
  27138. }
  27139. reentrancyCheck = false;
  27140. if (failed)
  27141. {
  27142. clearUndoHistory();
  27143. }
  27144. else
  27145. {
  27146. ++nextIndex;
  27147. }
  27148. beginNewTransaction();
  27149. sendChangeMessage (this);
  27150. return true;
  27151. }
  27152. bool UndoManager::undoCurrentTransactionOnly()
  27153. {
  27154. return newTransaction ? false
  27155. : undo();
  27156. }
  27157. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  27158. {
  27159. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  27160. if (commandSet != 0 && ! newTransaction)
  27161. {
  27162. for (int i = 0; i < commandSet->size(); ++i)
  27163. actionsFound.add (commandSet->getUnchecked(i));
  27164. }
  27165. }
  27166. END_JUCE_NAMESPACE
  27167. /********* End of inlined file: juce_UndoManager.cpp *********/
  27168. /********* Start of inlined file: juce_ActionBroadcaster.cpp *********/
  27169. BEGIN_JUCE_NAMESPACE
  27170. ActionBroadcaster::ActionBroadcaster() throw()
  27171. {
  27172. // are you trying to create this object before or after juce has been intialised??
  27173. jassert (MessageManager::instance != 0);
  27174. }
  27175. ActionBroadcaster::~ActionBroadcaster()
  27176. {
  27177. // all event-based objects must be deleted BEFORE juce is shut down!
  27178. jassert (MessageManager::instance != 0);
  27179. }
  27180. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  27181. {
  27182. actionListenerList.addActionListener (listener);
  27183. }
  27184. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  27185. {
  27186. jassert (actionListenerList.isValidMessageListener());
  27187. if (actionListenerList.isValidMessageListener())
  27188. actionListenerList.removeActionListener (listener);
  27189. }
  27190. void ActionBroadcaster::removeAllActionListeners()
  27191. {
  27192. actionListenerList.removeAllActionListeners();
  27193. }
  27194. void ActionBroadcaster::sendActionMessage (const String& message) const
  27195. {
  27196. actionListenerList.sendActionMessage (message);
  27197. }
  27198. END_JUCE_NAMESPACE
  27199. /********* End of inlined file: juce_ActionBroadcaster.cpp *********/
  27200. /********* Start of inlined file: juce_ActionListenerList.cpp *********/
  27201. BEGIN_JUCE_NAMESPACE
  27202. // special message of our own with a string in it
  27203. class ActionMessage : public Message
  27204. {
  27205. public:
  27206. const String message;
  27207. ActionMessage (const String& messageText,
  27208. void* const listener_) throw()
  27209. : message (messageText)
  27210. {
  27211. pointerParameter = listener_;
  27212. }
  27213. ~ActionMessage() throw()
  27214. {
  27215. }
  27216. private:
  27217. ActionMessage (const ActionMessage&);
  27218. const ActionMessage& operator= (const ActionMessage&);
  27219. };
  27220. ActionListenerList::ActionListenerList() throw()
  27221. {
  27222. }
  27223. ActionListenerList::~ActionListenerList() throw()
  27224. {
  27225. }
  27226. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  27227. {
  27228. const ScopedLock sl (actionListenerLock_);
  27229. jassert (listener != 0);
  27230. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  27231. if (listener != 0)
  27232. actionListeners_.add (listener);
  27233. }
  27234. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  27235. {
  27236. const ScopedLock sl (actionListenerLock_);
  27237. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  27238. actionListeners_.removeValue (listener);
  27239. }
  27240. void ActionListenerList::removeAllActionListeners() throw()
  27241. {
  27242. const ScopedLock sl (actionListenerLock_);
  27243. actionListeners_.clear();
  27244. }
  27245. void ActionListenerList::sendActionMessage (const String& message) const
  27246. {
  27247. const ScopedLock sl (actionListenerLock_);
  27248. for (int i = actionListeners_.size(); --i >= 0;)
  27249. {
  27250. postMessage (new ActionMessage (message,
  27251. (ActionListener*) actionListeners_.getUnchecked(i)));
  27252. }
  27253. }
  27254. void ActionListenerList::handleMessage (const Message& message)
  27255. {
  27256. const ActionMessage& am = (const ActionMessage&) message;
  27257. if (actionListeners_.contains (am.pointerParameter))
  27258. ((ActionListener*) am.pointerParameter)->actionListenerCallback (am.message);
  27259. }
  27260. END_JUCE_NAMESPACE
  27261. /********* End of inlined file: juce_ActionListenerList.cpp *********/
  27262. /********* Start of inlined file: juce_AsyncUpdater.cpp *********/
  27263. BEGIN_JUCE_NAMESPACE
  27264. AsyncUpdater::AsyncUpdater() throw()
  27265. : asyncMessagePending (false)
  27266. {
  27267. internalAsyncHandler.owner = this;
  27268. }
  27269. AsyncUpdater::~AsyncUpdater()
  27270. {
  27271. }
  27272. void AsyncUpdater::triggerAsyncUpdate() throw()
  27273. {
  27274. if (! asyncMessagePending)
  27275. {
  27276. asyncMessagePending = true;
  27277. internalAsyncHandler.postMessage (new Message());
  27278. }
  27279. }
  27280. void AsyncUpdater::cancelPendingUpdate() throw()
  27281. {
  27282. asyncMessagePending = false;
  27283. }
  27284. void AsyncUpdater::handleUpdateNowIfNeeded()
  27285. {
  27286. if (asyncMessagePending)
  27287. {
  27288. asyncMessagePending = false;
  27289. handleAsyncUpdate();
  27290. }
  27291. }
  27292. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  27293. {
  27294. owner->handleUpdateNowIfNeeded();
  27295. }
  27296. END_JUCE_NAMESPACE
  27297. /********* End of inlined file: juce_AsyncUpdater.cpp *********/
  27298. /********* Start of inlined file: juce_ChangeBroadcaster.cpp *********/
  27299. BEGIN_JUCE_NAMESPACE
  27300. ChangeBroadcaster::ChangeBroadcaster() throw()
  27301. {
  27302. // are you trying to create this object before or after juce has been intialised??
  27303. jassert (MessageManager::instance != 0);
  27304. }
  27305. ChangeBroadcaster::~ChangeBroadcaster()
  27306. {
  27307. // all event-based objects must be deleted BEFORE juce is shut down!
  27308. jassert (MessageManager::instance != 0);
  27309. }
  27310. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  27311. {
  27312. changeListenerList.addChangeListener (listener);
  27313. }
  27314. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  27315. {
  27316. jassert (changeListenerList.isValidMessageListener());
  27317. if (changeListenerList.isValidMessageListener())
  27318. changeListenerList.removeChangeListener (listener);
  27319. }
  27320. void ChangeBroadcaster::removeAllChangeListeners() throw()
  27321. {
  27322. changeListenerList.removeAllChangeListeners();
  27323. }
  27324. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  27325. {
  27326. changeListenerList.sendChangeMessage (objectThatHasChanged);
  27327. }
  27328. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  27329. {
  27330. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  27331. }
  27332. void ChangeBroadcaster::dispatchPendingMessages()
  27333. {
  27334. changeListenerList.dispatchPendingMessages();
  27335. }
  27336. END_JUCE_NAMESPACE
  27337. /********* End of inlined file: juce_ChangeBroadcaster.cpp *********/
  27338. /********* Start of inlined file: juce_ChangeListenerList.cpp *********/
  27339. BEGIN_JUCE_NAMESPACE
  27340. ChangeListenerList::ChangeListenerList() throw()
  27341. : lastChangedObject (0),
  27342. messagePending (false)
  27343. {
  27344. }
  27345. ChangeListenerList::~ChangeListenerList() throw()
  27346. {
  27347. }
  27348. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  27349. {
  27350. const ScopedLock sl (lock);
  27351. jassert (listener != 0);
  27352. if (listener != 0)
  27353. listeners.add (listener);
  27354. }
  27355. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  27356. {
  27357. const ScopedLock sl (lock);
  27358. listeners.removeValue (listener);
  27359. }
  27360. void ChangeListenerList::removeAllChangeListeners() throw()
  27361. {
  27362. const ScopedLock sl (lock);
  27363. listeners.clear();
  27364. }
  27365. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  27366. {
  27367. const ScopedLock sl (lock);
  27368. if ((! messagePending) && (listeners.size() > 0))
  27369. {
  27370. lastChangedObject = objectThatHasChanged;
  27371. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  27372. messagePending = true;
  27373. }
  27374. }
  27375. void ChangeListenerList::handleMessage (const Message& message)
  27376. {
  27377. sendSynchronousChangeMessage (message.pointerParameter);
  27378. }
  27379. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  27380. {
  27381. const ScopedLock sl (lock);
  27382. messagePending = false;
  27383. for (int i = listeners.size(); --i >= 0;)
  27384. {
  27385. ChangeListener* const l = (ChangeListener*) listeners.getUnchecked (i);
  27386. {
  27387. const ScopedUnlock tempUnlocker (lock);
  27388. l->changeListenerCallback (objectThatHasChanged);
  27389. }
  27390. i = jmin (i, listeners.size());
  27391. }
  27392. }
  27393. void ChangeListenerList::dispatchPendingMessages()
  27394. {
  27395. if (messagePending)
  27396. sendSynchronousChangeMessage (lastChangedObject);
  27397. }
  27398. END_JUCE_NAMESPACE
  27399. /********* End of inlined file: juce_ChangeListenerList.cpp *********/
  27400. /********* Start of inlined file: juce_InterprocessConnection.cpp *********/
  27401. BEGIN_JUCE_NAMESPACE
  27402. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  27403. const uint32 magicMessageHeaderNumber)
  27404. : Thread ("Juce IPC connection"),
  27405. socket (0),
  27406. pipe (0),
  27407. callbackConnectionState (false),
  27408. useMessageThread (callbacksOnMessageThread),
  27409. magicMessageHeader (magicMessageHeaderNumber),
  27410. pipeReceiveMessageTimeout (-1)
  27411. {
  27412. }
  27413. InterprocessConnection::~InterprocessConnection()
  27414. {
  27415. callbackConnectionState = false;
  27416. disconnect();
  27417. }
  27418. bool InterprocessConnection::connectToSocket (const String& hostName,
  27419. const int portNumber,
  27420. const int timeOutMillisecs)
  27421. {
  27422. disconnect();
  27423. const ScopedLock sl (pipeAndSocketLock);
  27424. socket = new StreamingSocket();
  27425. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  27426. {
  27427. connectionMadeInt();
  27428. startThread();
  27429. return true;
  27430. }
  27431. else
  27432. {
  27433. deleteAndZero (socket);
  27434. return false;
  27435. }
  27436. }
  27437. bool InterprocessConnection::connectToPipe (const String& pipeName,
  27438. const int pipeReceiveMessageTimeoutMs)
  27439. {
  27440. disconnect();
  27441. NamedPipe* const newPipe = new NamedPipe();
  27442. if (newPipe->openExisting (pipeName))
  27443. {
  27444. const ScopedLock sl (pipeAndSocketLock);
  27445. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  27446. initialiseWithPipe (newPipe);
  27447. return true;
  27448. }
  27449. else
  27450. {
  27451. delete newPipe;
  27452. return false;
  27453. }
  27454. }
  27455. bool InterprocessConnection::createPipe (const String& pipeName,
  27456. const int pipeReceiveMessageTimeoutMs)
  27457. {
  27458. disconnect();
  27459. NamedPipe* const newPipe = new NamedPipe();
  27460. if (newPipe->createNewPipe (pipeName))
  27461. {
  27462. const ScopedLock sl (pipeAndSocketLock);
  27463. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  27464. initialiseWithPipe (newPipe);
  27465. return true;
  27466. }
  27467. else
  27468. {
  27469. delete newPipe;
  27470. return false;
  27471. }
  27472. }
  27473. void InterprocessConnection::disconnect()
  27474. {
  27475. if (socket != 0)
  27476. socket->close();
  27477. if (pipe != 0)
  27478. {
  27479. pipe->cancelPendingReads();
  27480. pipe->close();
  27481. }
  27482. stopThread (4000);
  27483. {
  27484. const ScopedLock sl (pipeAndSocketLock);
  27485. deleteAndZero (socket);
  27486. deleteAndZero (pipe);
  27487. }
  27488. connectionLostInt();
  27489. }
  27490. bool InterprocessConnection::isConnected() const
  27491. {
  27492. const ScopedLock sl (pipeAndSocketLock);
  27493. return ((socket != 0 && socket->isConnected())
  27494. || (pipe != 0 && pipe->isOpen()))
  27495. && isThreadRunning();
  27496. }
  27497. const String InterprocessConnection::getConnectedHostName() const
  27498. {
  27499. if (pipe != 0)
  27500. {
  27501. return "localhost";
  27502. }
  27503. else if (socket != 0)
  27504. {
  27505. if (! socket->isLocal())
  27506. return socket->getHostName();
  27507. return "localhost";
  27508. }
  27509. return String::empty;
  27510. }
  27511. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  27512. {
  27513. uint32 messageHeader[2];
  27514. messageHeader [0] = swapIfBigEndian (magicMessageHeader);
  27515. messageHeader [1] = swapIfBigEndian ((uint32) message.getSize());
  27516. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  27517. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  27518. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  27519. int bytesWritten = 0;
  27520. const ScopedLock sl (pipeAndSocketLock);
  27521. if (socket != 0)
  27522. {
  27523. bytesWritten = socket->write (messageData.getData(), messageData.getSize());
  27524. }
  27525. else if (pipe != 0)
  27526. {
  27527. bytesWritten = pipe->write (messageData.getData(), messageData.getSize());
  27528. }
  27529. if (bytesWritten < 0)
  27530. {
  27531. // error..
  27532. return false;
  27533. }
  27534. return (bytesWritten == messageData.getSize());
  27535. }
  27536. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  27537. {
  27538. jassert (socket == 0);
  27539. socket = socket_;
  27540. connectionMadeInt();
  27541. startThread();
  27542. }
  27543. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  27544. {
  27545. jassert (pipe == 0);
  27546. pipe = pipe_;
  27547. connectionMadeInt();
  27548. startThread();
  27549. }
  27550. const int messageMagicNumber = 0xb734128b;
  27551. void InterprocessConnection::handleMessage (const Message& message)
  27552. {
  27553. if (message.intParameter1 == messageMagicNumber)
  27554. {
  27555. switch (message.intParameter2)
  27556. {
  27557. case 0:
  27558. {
  27559. MemoryBlock* const data = (MemoryBlock*) message.pointerParameter;
  27560. messageReceived (*data);
  27561. delete data;
  27562. break;
  27563. }
  27564. case 1:
  27565. connectionMade();
  27566. break;
  27567. case 2:
  27568. connectionLost();
  27569. break;
  27570. }
  27571. }
  27572. }
  27573. void InterprocessConnection::connectionMadeInt()
  27574. {
  27575. if (! callbackConnectionState)
  27576. {
  27577. callbackConnectionState = true;
  27578. if (useMessageThread)
  27579. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  27580. else
  27581. connectionMade();
  27582. }
  27583. }
  27584. void InterprocessConnection::connectionLostInt()
  27585. {
  27586. if (callbackConnectionState)
  27587. {
  27588. callbackConnectionState = false;
  27589. if (useMessageThread)
  27590. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  27591. else
  27592. connectionLost();
  27593. }
  27594. }
  27595. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  27596. {
  27597. jassert (callbackConnectionState);
  27598. if (useMessageThread)
  27599. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  27600. else
  27601. messageReceived (data);
  27602. }
  27603. bool InterprocessConnection::readNextMessageInt()
  27604. {
  27605. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  27606. uint32 messageHeader[2];
  27607. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader))
  27608. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  27609. if (bytes == sizeof (messageHeader)
  27610. && swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  27611. {
  27612. const int bytesInMessage = (int) swapIfBigEndian (messageHeader[1]);
  27613. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  27614. {
  27615. MemoryBlock messageData (bytesInMessage, true);
  27616. int bytesRead = 0;
  27617. while (bytesRead < bytesInMessage)
  27618. {
  27619. if (threadShouldExit())
  27620. return false;
  27621. const int numThisTime = jmin (bytesInMessage, 65536);
  27622. const int bytesIn = (socket != 0) ? socket->read (((char*) messageData.getData()) + bytesRead, numThisTime)
  27623. : pipe->read (((char*) messageData.getData()) + bytesRead, numThisTime,
  27624. pipeReceiveMessageTimeout);
  27625. if (bytesIn <= 0)
  27626. break;
  27627. bytesRead += bytesIn;
  27628. }
  27629. if (bytesRead >= 0)
  27630. deliverDataInt (messageData);
  27631. }
  27632. }
  27633. else if (bytes < 0)
  27634. {
  27635. {
  27636. const ScopedLock sl (pipeAndSocketLock);
  27637. deleteAndZero (socket);
  27638. }
  27639. connectionLostInt();
  27640. return false;
  27641. }
  27642. return true;
  27643. }
  27644. void InterprocessConnection::run()
  27645. {
  27646. while (! threadShouldExit())
  27647. {
  27648. if (socket != 0)
  27649. {
  27650. const int ready = socket->waitUntilReady (true, 0);
  27651. if (ready < 0)
  27652. {
  27653. {
  27654. const ScopedLock sl (pipeAndSocketLock);
  27655. deleteAndZero (socket);
  27656. }
  27657. connectionLostInt();
  27658. break;
  27659. }
  27660. else if (ready > 0)
  27661. {
  27662. if (! readNextMessageInt())
  27663. break;
  27664. }
  27665. else
  27666. {
  27667. Thread::sleep (2);
  27668. }
  27669. }
  27670. else if (pipe != 0)
  27671. {
  27672. if (! pipe->isOpen())
  27673. {
  27674. {
  27675. const ScopedLock sl (pipeAndSocketLock);
  27676. deleteAndZero (pipe);
  27677. }
  27678. connectionLostInt();
  27679. break;
  27680. }
  27681. else
  27682. {
  27683. if (! readNextMessageInt())
  27684. break;
  27685. }
  27686. }
  27687. else
  27688. {
  27689. break;
  27690. }
  27691. }
  27692. }
  27693. END_JUCE_NAMESPACE
  27694. /********* End of inlined file: juce_InterprocessConnection.cpp *********/
  27695. /********* Start of inlined file: juce_InterprocessConnectionServer.cpp *********/
  27696. BEGIN_JUCE_NAMESPACE
  27697. InterprocessConnectionServer::InterprocessConnectionServer()
  27698. : Thread ("Juce IPC server"),
  27699. socket (0)
  27700. {
  27701. }
  27702. InterprocessConnectionServer::~InterprocessConnectionServer()
  27703. {
  27704. stop();
  27705. }
  27706. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  27707. {
  27708. stop();
  27709. socket = new StreamingSocket();
  27710. if (socket->createListener (portNumber))
  27711. {
  27712. startThread();
  27713. return true;
  27714. }
  27715. deleteAndZero (socket);
  27716. return false;
  27717. }
  27718. void InterprocessConnectionServer::stop()
  27719. {
  27720. signalThreadShouldExit();
  27721. if (socket != 0)
  27722. socket->close();
  27723. stopThread (4000);
  27724. deleteAndZero (socket);
  27725. }
  27726. void InterprocessConnectionServer::run()
  27727. {
  27728. while ((! threadShouldExit()) && socket != 0)
  27729. {
  27730. StreamingSocket* const clientSocket = socket->waitForNextConnection();
  27731. if (clientSocket != 0)
  27732. {
  27733. InterprocessConnection* newConnection = createConnectionObject();
  27734. if (newConnection != 0)
  27735. {
  27736. newConnection->initialiseWithSocket (clientSocket);
  27737. }
  27738. else
  27739. {
  27740. delete clientSocket;
  27741. }
  27742. }
  27743. }
  27744. }
  27745. END_JUCE_NAMESPACE
  27746. /********* End of inlined file: juce_InterprocessConnectionServer.cpp *********/
  27747. /********* Start of inlined file: juce_Message.cpp *********/
  27748. BEGIN_JUCE_NAMESPACE
  27749. Message::Message() throw()
  27750. {
  27751. }
  27752. Message::~Message() throw()
  27753. {
  27754. }
  27755. Message::Message (const int intParameter1_,
  27756. const int intParameter2_,
  27757. const int intParameter3_,
  27758. void* const pointerParameter_) throw()
  27759. : intParameter1 (intParameter1_),
  27760. intParameter2 (intParameter2_),
  27761. intParameter3 (intParameter3_),
  27762. pointerParameter (pointerParameter_)
  27763. {
  27764. }
  27765. END_JUCE_NAMESPACE
  27766. /********* End of inlined file: juce_Message.cpp *********/
  27767. /********* Start of inlined file: juce_MessageListener.cpp *********/
  27768. BEGIN_JUCE_NAMESPACE
  27769. MessageListener::MessageListener() throw()
  27770. {
  27771. // are you trying to create a messagelistener before or after juce has been intialised??
  27772. jassert (MessageManager::instance != 0);
  27773. if (MessageManager::instance != 0)
  27774. MessageManager::instance->messageListeners.add (this);
  27775. }
  27776. MessageListener::~MessageListener()
  27777. {
  27778. if (MessageManager::instance != 0)
  27779. MessageManager::instance->messageListeners.removeValue (this);
  27780. }
  27781. void MessageListener::postMessage (Message* const message) const throw()
  27782. {
  27783. message->messageRecipient = const_cast <MessageListener*> (this);
  27784. if (MessageManager::instance == 0)
  27785. MessageManager::getInstance();
  27786. MessageManager::instance->postMessageToQueue (message);
  27787. }
  27788. bool MessageListener::isValidMessageListener() const throw()
  27789. {
  27790. return (MessageManager::instance != 0)
  27791. && MessageManager::instance->messageListeners.contains (this);
  27792. }
  27793. END_JUCE_NAMESPACE
  27794. /********* End of inlined file: juce_MessageListener.cpp *********/
  27795. /********* Start of inlined file: juce_MessageManager.cpp *********/
  27796. BEGIN_JUCE_NAMESPACE
  27797. // platform-specific functions..
  27798. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  27799. bool juce_postMessageToSystemQueue (void* message);
  27800. MessageManager* MessageManager::instance = 0;
  27801. static const int quitMessageId = 0xfffff321;
  27802. MessageManager::MessageManager() throw()
  27803. : broadcastListeners (0),
  27804. quitMessagePosted (false),
  27805. quitMessageReceived (false),
  27806. useMaximumForceWhenQuitting (true),
  27807. messageCounter (0),
  27808. lastMessageCounter (-1),
  27809. isInMessageDispatcher (0),
  27810. needToGetRidOfWaitCursor (false),
  27811. timeBeforeWaitCursor (0),
  27812. lastActivityCheckOkTime (0)
  27813. {
  27814. currentLockingThreadId = messageThreadId = Thread::getCurrentThreadId();
  27815. }
  27816. MessageManager::~MessageManager() throw()
  27817. {
  27818. jassert (instance == this);
  27819. instance = 0;
  27820. deleteAndZero (broadcastListeners);
  27821. doPlatformSpecificShutdown();
  27822. }
  27823. MessageManager* MessageManager::getInstance() throw()
  27824. {
  27825. if (instance == 0)
  27826. {
  27827. instance = new MessageManager();
  27828. doPlatformSpecificInitialisation();
  27829. instance->setTimeBeforeShowingWaitCursor (500);
  27830. }
  27831. return instance;
  27832. }
  27833. void MessageManager::postMessageToQueue (Message* const message)
  27834. {
  27835. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  27836. delete message;
  27837. }
  27838. // not for public use..
  27839. void MessageManager::deliverMessage (void* message)
  27840. {
  27841. const MessageManagerLock lock;
  27842. Message* const m = (Message*) message;
  27843. MessageListener* const recipient = m->messageRecipient;
  27844. if (messageListeners.contains (recipient))
  27845. {
  27846. JUCE_TRY
  27847. {
  27848. recipient->handleMessage (*m);
  27849. }
  27850. JUCE_CATCH_EXCEPTION
  27851. if (needToGetRidOfWaitCursor)
  27852. {
  27853. needToGetRidOfWaitCursor = false;
  27854. MouseCursor::hideWaitCursor();
  27855. }
  27856. ++messageCounter;
  27857. }
  27858. else if (recipient == 0 && m->intParameter1 == quitMessageId)
  27859. {
  27860. quitMessageReceived = true;
  27861. useMaximumForceWhenQuitting = (m->intParameter2 != 0);
  27862. }
  27863. delete m;
  27864. }
  27865. bool MessageManager::dispatchNextMessage (const bool returnImmediatelyIfNoMessages,
  27866. bool* const wasAMessageDispatched)
  27867. {
  27868. if (quitMessageReceived)
  27869. {
  27870. if (wasAMessageDispatched != 0)
  27871. *wasAMessageDispatched = false;
  27872. return false;
  27873. }
  27874. ++isInMessageDispatcher;
  27875. bool result = false;
  27876. JUCE_TRY
  27877. {
  27878. result = juce_dispatchNextMessageOnSystemQueue (returnImmediatelyIfNoMessages);
  27879. if (wasAMessageDispatched != 0)
  27880. *wasAMessageDispatched = result;
  27881. if (instance == 0)
  27882. return false;
  27883. }
  27884. JUCE_CATCH_EXCEPTION
  27885. --isInMessageDispatcher;
  27886. ++messageCounter;
  27887. return result || ! returnImmediatelyIfNoMessages;
  27888. }
  27889. void MessageManager::dispatchPendingMessages (int maxNumberOfMessagesToDispatch)
  27890. {
  27891. jassert (isThisTheMessageThread()); // must only be called by the message thread
  27892. while (--maxNumberOfMessagesToDispatch >= 0 && ! quitMessageReceived)
  27893. {
  27894. ++isInMessageDispatcher;
  27895. bool carryOn = false;
  27896. JUCE_TRY
  27897. {
  27898. carryOn = juce_dispatchNextMessageOnSystemQueue (true);
  27899. }
  27900. JUCE_CATCH_EXCEPTION
  27901. --isInMessageDispatcher;
  27902. ++messageCounter;
  27903. if (! carryOn)
  27904. break;
  27905. }
  27906. }
  27907. bool MessageManager::runDispatchLoop()
  27908. {
  27909. jassert (isThisTheMessageThread()); // must only be called by the message thread
  27910. while (dispatchNextMessage())
  27911. {
  27912. }
  27913. return useMaximumForceWhenQuitting;
  27914. }
  27915. void MessageManager::postQuitMessage (const bool useMaximumForce)
  27916. {
  27917. Message* const m = new Message (quitMessageId, (useMaximumForce) ? 1 : 0, 0, 0);
  27918. m->messageRecipient = 0;
  27919. postMessageToQueue (m);
  27920. quitMessagePosted = true;
  27921. }
  27922. bool MessageManager::hasQuitMessageBeenPosted() const throw()
  27923. {
  27924. return quitMessagePosted;
  27925. }
  27926. void MessageManager::deliverBroadcastMessage (const String& value)
  27927. {
  27928. if (broadcastListeners != 0)
  27929. broadcastListeners->sendActionMessage (value);
  27930. }
  27931. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  27932. {
  27933. if (broadcastListeners == 0)
  27934. broadcastListeners = new ActionListenerList();
  27935. broadcastListeners->addActionListener (listener);
  27936. }
  27937. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  27938. {
  27939. if (broadcastListeners != 0)
  27940. broadcastListeners->removeActionListener (listener);
  27941. }
  27942. // This gets called occasionally by the timer thread (to save using an extra thread
  27943. // for it).
  27944. void MessageManager::inactivityCheckCallback() throw()
  27945. {
  27946. if (instance != 0)
  27947. instance->inactivityCheckCallbackInt();
  27948. }
  27949. void MessageManager::inactivityCheckCallbackInt() throw()
  27950. {
  27951. const unsigned int now = Time::getApproximateMillisecondCounter();
  27952. if (isInMessageDispatcher > 0
  27953. && lastMessageCounter == messageCounter
  27954. && timeBeforeWaitCursor > 0
  27955. && lastActivityCheckOkTime > 0
  27956. && ! ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  27957. {
  27958. if (now >= lastActivityCheckOkTime + timeBeforeWaitCursor
  27959. && ! needToGetRidOfWaitCursor)
  27960. {
  27961. // been in the same message call too long..
  27962. MouseCursor::showWaitCursor();
  27963. needToGetRidOfWaitCursor = true;
  27964. }
  27965. }
  27966. else
  27967. {
  27968. lastActivityCheckOkTime = now;
  27969. lastMessageCounter = messageCounter;
  27970. }
  27971. }
  27972. void MessageManager::delayWaitCursor() throw()
  27973. {
  27974. if (instance != 0)
  27975. {
  27976. instance->messageCounter++;
  27977. if (instance->needToGetRidOfWaitCursor)
  27978. {
  27979. instance->needToGetRidOfWaitCursor = false;
  27980. MouseCursor::hideWaitCursor();
  27981. }
  27982. }
  27983. }
  27984. void MessageManager::setTimeBeforeShowingWaitCursor (const int millisecs) throw()
  27985. {
  27986. // if this is a bit too small you'll get a lot of unwanted hourglass cursors..
  27987. jassert (millisecs <= 0 || millisecs > 200);
  27988. timeBeforeWaitCursor = millisecs;
  27989. if (millisecs > 0)
  27990. startTimer (millisecs / 2); // (see timerCallback() for explanation of this)
  27991. else
  27992. stopTimer();
  27993. }
  27994. void MessageManager::timerCallback()
  27995. {
  27996. // dummy callback - the message manager is just a Timer to ensure that there are always
  27997. // some events coming in - otherwise it'll show the egg-timer/beachball-of-death.
  27998. ++messageCounter;
  27999. }
  28000. int MessageManager::getTimeBeforeShowingWaitCursor() const throw()
  28001. {
  28002. return timeBeforeWaitCursor;
  28003. }
  28004. bool MessageManager::isThisTheMessageThread() const throw()
  28005. {
  28006. return Thread::getCurrentThreadId() == messageThreadId;
  28007. }
  28008. void MessageManager::setCurrentMessageThread (const int threadId) throw()
  28009. {
  28010. messageThreadId = threadId;
  28011. }
  28012. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  28013. {
  28014. return Thread::getCurrentThreadId() == currentLockingThreadId;
  28015. }
  28016. MessageManagerLock::MessageManagerLock() throw()
  28017. : locked (false)
  28018. {
  28019. if (MessageManager::instance != 0)
  28020. {
  28021. MessageManager::instance->messageDispatchLock.enter();
  28022. lastLockingThreadId = MessageManager::instance->currentLockingThreadId;
  28023. MessageManager::instance->currentLockingThreadId = Thread::getCurrentThreadId();
  28024. locked = true;
  28025. }
  28026. }
  28027. MessageManagerLock::MessageManagerLock (Thread* const thread) throw()
  28028. : locked (false)
  28029. {
  28030. jassert (thread != 0); // This will only work if you give it a valid thread!
  28031. if (MessageManager::instance != 0)
  28032. {
  28033. for (;;)
  28034. {
  28035. if (MessageManager::instance->messageDispatchLock.tryEnter())
  28036. {
  28037. locked = true;
  28038. lastLockingThreadId = MessageManager::instance->currentLockingThreadId;
  28039. MessageManager::instance->currentLockingThreadId = Thread::getCurrentThreadId();
  28040. break;
  28041. }
  28042. if (thread != 0 && thread->threadShouldExit())
  28043. break;
  28044. Thread::sleep (1);
  28045. }
  28046. }
  28047. }
  28048. MessageManagerLock::~MessageManagerLock() throw()
  28049. {
  28050. if (locked && MessageManager::instance != 0)
  28051. {
  28052. MessageManager::instance->currentLockingThreadId = lastLockingThreadId;
  28053. MessageManager::instance->messageDispatchLock.exit();
  28054. }
  28055. }
  28056. END_JUCE_NAMESPACE
  28057. /********* End of inlined file: juce_MessageManager.cpp *********/
  28058. /********* Start of inlined file: juce_MultiTimer.cpp *********/
  28059. BEGIN_JUCE_NAMESPACE
  28060. class InternalMultiTimerCallback : public Timer
  28061. {
  28062. public:
  28063. InternalMultiTimerCallback (const int timerId_, MultiTimer& owner_)
  28064. : timerId (timerId_),
  28065. owner (owner_)
  28066. {
  28067. }
  28068. ~InternalMultiTimerCallback()
  28069. {
  28070. }
  28071. void timerCallback()
  28072. {
  28073. owner.timerCallback (timerId);
  28074. }
  28075. const int timerId;
  28076. private:
  28077. MultiTimer& owner;
  28078. };
  28079. MultiTimer::MultiTimer() throw()
  28080. {
  28081. }
  28082. MultiTimer::MultiTimer (const MultiTimer&) throw()
  28083. {
  28084. }
  28085. MultiTimer::~MultiTimer()
  28086. {
  28087. const ScopedLock sl (timerListLock);
  28088. for (int i = timers.size(); --i >= 0;)
  28089. delete (InternalMultiTimerCallback*) timers.getUnchecked(i);
  28090. timers.clear();
  28091. }
  28092. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  28093. {
  28094. const ScopedLock sl (timerListLock);
  28095. for (int i = timers.size(); --i >= 0;)
  28096. {
  28097. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  28098. if (t->timerId == timerId)
  28099. {
  28100. t->startTimer (intervalInMilliseconds);
  28101. return;
  28102. }
  28103. }
  28104. InternalMultiTimerCallback* const newTimer = new InternalMultiTimerCallback (timerId, *this);
  28105. timers.add (newTimer);
  28106. newTimer->startTimer (intervalInMilliseconds);
  28107. }
  28108. void MultiTimer::stopTimer (const int timerId) throw()
  28109. {
  28110. const ScopedLock sl (timerListLock);
  28111. for (int i = timers.size(); --i >= 0;)
  28112. {
  28113. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  28114. if (t->timerId == timerId)
  28115. t->stopTimer();
  28116. }
  28117. }
  28118. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  28119. {
  28120. const ScopedLock sl (timerListLock);
  28121. for (int i = timers.size(); --i >= 0;)
  28122. {
  28123. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  28124. if (t->timerId == timerId)
  28125. return t->isTimerRunning();
  28126. }
  28127. return false;
  28128. }
  28129. int MultiTimer::getTimerInterval (const int timerId) const throw()
  28130. {
  28131. const ScopedLock sl (timerListLock);
  28132. for (int i = timers.size(); --i >= 0;)
  28133. {
  28134. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  28135. if (t->timerId == timerId)
  28136. return t->getTimerInterval();
  28137. }
  28138. return 0;
  28139. }
  28140. END_JUCE_NAMESPACE
  28141. /********* End of inlined file: juce_MultiTimer.cpp *********/
  28142. /********* Start of inlined file: juce_Timer.cpp *********/
  28143. BEGIN_JUCE_NAMESPACE
  28144. class InternalTimerThread : private Thread,
  28145. private MessageListener,
  28146. private DeletedAtShutdown,
  28147. private AsyncUpdater
  28148. {
  28149. private:
  28150. friend class Timer;
  28151. static InternalTimerThread* instance;
  28152. static CriticalSection lock;
  28153. Timer* volatile firstTimer;
  28154. bool volatile callbackNeeded;
  28155. InternalTimerThread (const InternalTimerThread&);
  28156. const InternalTimerThread& operator= (const InternalTimerThread&);
  28157. void addTimer (Timer* const t) throw()
  28158. {
  28159. #ifdef JUCE_DEBUG
  28160. Timer* tt = firstTimer;
  28161. while (tt != 0)
  28162. {
  28163. // trying to add a timer that's already here - shouldn't get to this point,
  28164. // so if you get this assertion, let me know!
  28165. jassert (tt != t);
  28166. tt = tt->next;
  28167. }
  28168. jassert (t->previous == 0 && t->next == 0);
  28169. #endif
  28170. Timer* i = firstTimer;
  28171. if (i == 0 || i->countdownMs > t->countdownMs)
  28172. {
  28173. t->next = firstTimer;
  28174. firstTimer = t;
  28175. }
  28176. else
  28177. {
  28178. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  28179. i = i->next;
  28180. jassert (i != 0);
  28181. t->next = i->next;
  28182. t->previous = i;
  28183. i->next = t;
  28184. }
  28185. if (t->next != 0)
  28186. t->next->previous = t;
  28187. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  28188. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  28189. notify();
  28190. }
  28191. void removeTimer (Timer* const t) throw()
  28192. {
  28193. #ifdef JUCE_DEBUG
  28194. Timer* tt = firstTimer;
  28195. bool found = false;
  28196. while (tt != 0)
  28197. {
  28198. if (tt == t)
  28199. {
  28200. found = true;
  28201. break;
  28202. }
  28203. tt = tt->next;
  28204. }
  28205. // trying to remove a timer that's not here - shouldn't get to this point,
  28206. // so if you get this assertion, let me know!
  28207. jassert (found);
  28208. #endif
  28209. if (t->previous != 0)
  28210. {
  28211. jassert (firstTimer != t);
  28212. t->previous->next = t->next;
  28213. }
  28214. else
  28215. {
  28216. jassert (firstTimer == t);
  28217. firstTimer = t->next;
  28218. }
  28219. if (t->next != 0)
  28220. t->next->previous = t->previous;
  28221. t->next = 0;
  28222. t->previous = 0;
  28223. }
  28224. void decrementAllCounters (const int numMillisecs) const
  28225. {
  28226. Timer* t = firstTimer;
  28227. while (t != 0)
  28228. {
  28229. t->countdownMs -= numMillisecs;
  28230. t = t->next;
  28231. }
  28232. }
  28233. void handleAsyncUpdate()
  28234. {
  28235. startThread (7);
  28236. }
  28237. public:
  28238. InternalTimerThread()
  28239. : Thread ("Juce Timer"),
  28240. firstTimer (0),
  28241. callbackNeeded (false)
  28242. {
  28243. triggerAsyncUpdate();
  28244. }
  28245. ~InternalTimerThread() throw()
  28246. {
  28247. stopThread (4000);
  28248. jassert (instance == this || instance == 0);
  28249. if (instance == this)
  28250. instance = 0;
  28251. }
  28252. void run()
  28253. {
  28254. uint32 lastTime = Time::getMillisecondCounter();
  28255. uint32 lastMessageManagerCallback = lastTime;
  28256. while (! threadShouldExit())
  28257. {
  28258. uint32 now = Time::getMillisecondCounter();
  28259. if (now <= lastTime)
  28260. {
  28261. wait (2);
  28262. continue;
  28263. }
  28264. const int elapsed = now - lastTime;
  28265. lastTime = now;
  28266. lock.enter();
  28267. decrementAllCounters (elapsed);
  28268. const int timeUntilFirstTimer = (firstTimer != 0) ? firstTimer->countdownMs
  28269. : 1000;
  28270. lock.exit();
  28271. if (timeUntilFirstTimer <= 0)
  28272. {
  28273. callbackNeeded = true;
  28274. postMessage (new Message());
  28275. // sometimes, our message could get discarded by the OS (particularly when running as an RTAS when the app has a modal loop),
  28276. // so this is how long to wait before assuming the message has been lost and trying again.
  28277. const uint32 messageDeliveryTimeout = now + 2000;
  28278. while (callbackNeeded)
  28279. {
  28280. wait (4);
  28281. if (threadShouldExit())
  28282. return;
  28283. now = Time::getMillisecondCounter();
  28284. if (now > lastMessageManagerCallback + 200)
  28285. {
  28286. lastMessageManagerCallback = now;
  28287. MessageManager::inactivityCheckCallback();
  28288. }
  28289. if (now > messageDeliveryTimeout)
  28290. break;
  28291. }
  28292. }
  28293. else
  28294. {
  28295. // don't wait for too long because running this loop also helps keep the
  28296. // Time::getApproximateMillisecondTimer value stay up-to-date
  28297. wait (jlimit (1, 50, timeUntilFirstTimer));
  28298. }
  28299. if (now > lastMessageManagerCallback + 200)
  28300. {
  28301. lastMessageManagerCallback = now;
  28302. MessageManager::inactivityCheckCallback();
  28303. }
  28304. }
  28305. }
  28306. void handleMessage (const Message&)
  28307. {
  28308. const ScopedLock sl (lock);
  28309. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  28310. {
  28311. Timer* const t = firstTimer;
  28312. t->countdownMs = t->periodMs;
  28313. removeTimer (t);
  28314. addTimer (t);
  28315. const ScopedUnlock ul (lock);
  28316. callbackNeeded = false;
  28317. JUCE_TRY
  28318. {
  28319. t->timerCallback();
  28320. }
  28321. JUCE_CATCH_EXCEPTION
  28322. }
  28323. callbackNeeded = false;
  28324. }
  28325. static void callAnyTimersSynchronously()
  28326. {
  28327. if (InternalTimerThread::instance != 0)
  28328. {
  28329. const Message m;
  28330. InternalTimerThread::instance->handleMessage (m);
  28331. }
  28332. }
  28333. static inline void add (Timer* const tim) throw()
  28334. {
  28335. if (instance == 0)
  28336. instance = new InternalTimerThread();
  28337. instance->addTimer (tim);
  28338. }
  28339. static inline void remove (Timer* const tim) throw()
  28340. {
  28341. if (instance != 0)
  28342. instance->removeTimer (tim);
  28343. }
  28344. static inline void resetCounter (Timer* const tim,
  28345. const int newCounter) throw()
  28346. {
  28347. if (instance != 0)
  28348. {
  28349. tim->countdownMs = newCounter;
  28350. tim->periodMs = newCounter;
  28351. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  28352. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  28353. {
  28354. instance->removeTimer (tim);
  28355. instance->addTimer (tim);
  28356. }
  28357. }
  28358. }
  28359. };
  28360. InternalTimerThread* InternalTimerThread::instance = 0;
  28361. CriticalSection InternalTimerThread::lock;
  28362. void juce_callAnyTimersSynchronously()
  28363. {
  28364. InternalTimerThread::callAnyTimersSynchronously();
  28365. }
  28366. #ifdef JUCE_DEBUG
  28367. static SortedSet <Timer*> activeTimers;
  28368. #endif
  28369. Timer::Timer() throw()
  28370. : countdownMs (0),
  28371. periodMs (0),
  28372. previous (0),
  28373. next (0)
  28374. {
  28375. #ifdef JUCE_DEBUG
  28376. activeTimers.add (this);
  28377. #endif
  28378. }
  28379. Timer::Timer (const Timer&) throw()
  28380. : countdownMs (0),
  28381. periodMs (0),
  28382. previous (0),
  28383. next (0)
  28384. {
  28385. #ifdef JUCE_DEBUG
  28386. activeTimers.add (this);
  28387. #endif
  28388. }
  28389. Timer::~Timer()
  28390. {
  28391. stopTimer();
  28392. #ifdef JUCE_DEBUG
  28393. activeTimers.removeValue (this);
  28394. #endif
  28395. }
  28396. void Timer::startTimer (const int interval) throw()
  28397. {
  28398. const ScopedLock sl (InternalTimerThread::lock);
  28399. #ifdef JUCE_DEBUG
  28400. // this isn't a valid object! Your timer might be a dangling pointer or something..
  28401. jassert (activeTimers.contains (this));
  28402. #endif
  28403. if (periodMs == 0)
  28404. {
  28405. countdownMs = interval;
  28406. periodMs = jmax (1, interval);
  28407. InternalTimerThread::add (this);
  28408. }
  28409. else
  28410. {
  28411. InternalTimerThread::resetCounter (this, interval);
  28412. }
  28413. }
  28414. void Timer::stopTimer() throw()
  28415. {
  28416. const ScopedLock sl (InternalTimerThread::lock);
  28417. #ifdef JUCE_DEBUG
  28418. // this isn't a valid object! Your timer might be a dangling pointer or something..
  28419. jassert (activeTimers.contains (this));
  28420. #endif
  28421. if (periodMs > 0)
  28422. {
  28423. InternalTimerThread::remove (this);
  28424. periodMs = 0;
  28425. }
  28426. }
  28427. END_JUCE_NAMESPACE
  28428. /********* End of inlined file: juce_Timer.cpp *********/
  28429. /********* Start of inlined file: juce_Component.cpp *********/
  28430. BEGIN_JUCE_NAMESPACE
  28431. Component* Component::componentUnderMouse = 0;
  28432. Component* Component::currentlyFocusedComponent = 0;
  28433. static Array <Component*> modalComponentStack (4), modalComponentReturnValueKeys (4);
  28434. static Array <int> modalReturnValues (4);
  28435. static const int customCommandMessage = 0x7fff0001;
  28436. static const int exitModalStateMessage = 0x7fff0002;
  28437. // these are also used by ComponentPeer
  28438. int64 juce_recentMouseDownTimes [4] = { 0, 0, 0, 0 };
  28439. int juce_recentMouseDownX [4] = { 0, 0, 0, 0 };
  28440. int juce_recentMouseDownY [4] = { 0, 0, 0, 0 };
  28441. Component* juce_recentMouseDownComponent [4] = { 0, 0, 0, 0 };
  28442. int juce_LastMousePosX = 0;
  28443. int juce_LastMousePosY = 0;
  28444. int juce_MouseClickCounter = 0;
  28445. bool juce_MouseHasMovedSignificantlySincePressed = false;
  28446. static int countMouseClicks() throw()
  28447. {
  28448. int numClicks = 0;
  28449. if (juce_recentMouseDownTimes[0] != 0)
  28450. {
  28451. if (! juce_MouseHasMovedSignificantlySincePressed)
  28452. ++numClicks;
  28453. for (int i = 1; i < numElementsInArray (juce_recentMouseDownTimes); ++i)
  28454. {
  28455. if (juce_recentMouseDownTimes[0] - juce_recentMouseDownTimes [i]
  28456. < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  28457. && abs (juce_recentMouseDownX[0] - juce_recentMouseDownX[i]) < 8
  28458. && abs (juce_recentMouseDownY[0] - juce_recentMouseDownY[i]) < 8
  28459. && juce_recentMouseDownComponent[0] == juce_recentMouseDownComponent [i])
  28460. {
  28461. ++numClicks;
  28462. }
  28463. else
  28464. {
  28465. break;
  28466. }
  28467. }
  28468. }
  28469. return numClicks;
  28470. }
  28471. static int unboundedMouseOffsetX = 0;
  28472. static int unboundedMouseOffsetY = 0;
  28473. static bool isUnboundedMouseModeOn = false;
  28474. static bool isCursorVisibleUntilOffscreen;
  28475. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  28476. static uint32 nextComponentUID = 0;
  28477. Component::Component() throw()
  28478. : parentComponent_ (0),
  28479. componentUID (++nextComponentUID),
  28480. numDeepMouseListeners (0),
  28481. childComponentList_ (16),
  28482. lookAndFeel_ (0),
  28483. effect_ (0),
  28484. bufferedImage_ (0),
  28485. mouseListeners_ (0),
  28486. keyListeners_ (0),
  28487. componentListeners_ (0),
  28488. propertySet_ (0),
  28489. componentFlags_ (0)
  28490. {
  28491. }
  28492. Component::Component (const String& name) throw()
  28493. : componentName_ (name),
  28494. parentComponent_ (0),
  28495. componentUID (++nextComponentUID),
  28496. numDeepMouseListeners (0),
  28497. childComponentList_ (16),
  28498. lookAndFeel_ (0),
  28499. effect_ (0),
  28500. bufferedImage_ (0),
  28501. mouseListeners_ (0),
  28502. keyListeners_ (0),
  28503. componentListeners_ (0),
  28504. propertySet_ (0),
  28505. componentFlags_ (0)
  28506. {
  28507. }
  28508. Component::~Component()
  28509. {
  28510. if (parentComponent_ != 0)
  28511. {
  28512. parentComponent_->removeChildComponent (this);
  28513. }
  28514. else if ((currentlyFocusedComponent == this)
  28515. || isParentOf (currentlyFocusedComponent))
  28516. {
  28517. giveAwayFocus();
  28518. }
  28519. if (componentUnderMouse == this)
  28520. componentUnderMouse = 0;
  28521. if (flags.hasHeavyweightPeerFlag)
  28522. removeFromDesktop();
  28523. modalComponentStack.removeValue (this);
  28524. for (int i = childComponentList_.size(); --i >= 0;)
  28525. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  28526. delete bufferedImage_;
  28527. delete mouseListeners_;
  28528. delete keyListeners_;
  28529. delete componentListeners_;
  28530. delete propertySet_;
  28531. }
  28532. void Component::setName (const String& name)
  28533. {
  28534. // if component methods are being called from threads other than the message
  28535. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28536. checkMessageManagerIsLocked
  28537. if (componentName_ != name)
  28538. {
  28539. componentName_ = name;
  28540. if (flags.hasHeavyweightPeerFlag)
  28541. {
  28542. ComponentPeer* const peer = getPeer();
  28543. jassert (peer != 0);
  28544. if (peer != 0)
  28545. peer->setTitle (name);
  28546. }
  28547. if (componentListeners_ != 0)
  28548. {
  28549. const ComponentDeletionWatcher deletionChecker (this);
  28550. for (int i = componentListeners_->size(); --i >= 0;)
  28551. {
  28552. ((ComponentListener*) componentListeners_->getUnchecked (i))
  28553. ->componentNameChanged (*this);
  28554. if (deletionChecker.hasBeenDeleted())
  28555. return;
  28556. i = jmin (i, componentListeners_->size());
  28557. }
  28558. }
  28559. }
  28560. }
  28561. void Component::setVisible (bool shouldBeVisible)
  28562. {
  28563. if (flags.visibleFlag != shouldBeVisible)
  28564. {
  28565. // if component methods are being called from threads other than the message
  28566. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28567. checkMessageManagerIsLocked
  28568. const ComponentDeletionWatcher deletionChecker (this);
  28569. flags.visibleFlag = shouldBeVisible;
  28570. internalRepaint (0, 0, getWidth(), getHeight());
  28571. sendFakeMouseMove();
  28572. if (! shouldBeVisible)
  28573. {
  28574. if (currentlyFocusedComponent == this
  28575. || isParentOf (currentlyFocusedComponent))
  28576. {
  28577. if (parentComponent_ != 0)
  28578. parentComponent_->grabKeyboardFocus();
  28579. else
  28580. giveAwayFocus();
  28581. }
  28582. }
  28583. sendVisibilityChangeMessage();
  28584. if ((! deletionChecker.hasBeenDeleted()) && flags.hasHeavyweightPeerFlag)
  28585. {
  28586. ComponentPeer* const peer = getPeer();
  28587. jassert (peer != 0);
  28588. if (peer != 0)
  28589. {
  28590. peer->setVisible (shouldBeVisible);
  28591. internalHierarchyChanged();
  28592. }
  28593. }
  28594. }
  28595. }
  28596. void Component::visibilityChanged()
  28597. {
  28598. }
  28599. void Component::sendVisibilityChangeMessage()
  28600. {
  28601. const ComponentDeletionWatcher deletionChecker (this);
  28602. visibilityChanged();
  28603. if ((! deletionChecker.hasBeenDeleted()) && componentListeners_ != 0)
  28604. {
  28605. for (int i = componentListeners_->size(); --i >= 0;)
  28606. {
  28607. ((ComponentListener*) componentListeners_->getUnchecked (i))
  28608. ->componentVisibilityChanged (*this);
  28609. if (deletionChecker.hasBeenDeleted())
  28610. return;
  28611. i = jmin (i, componentListeners_->size());
  28612. }
  28613. }
  28614. }
  28615. bool Component::isShowing() const throw()
  28616. {
  28617. if (flags.visibleFlag)
  28618. {
  28619. if (parentComponent_ != 0)
  28620. {
  28621. return parentComponent_->isShowing();
  28622. }
  28623. else
  28624. {
  28625. const ComponentPeer* const peer = getPeer();
  28626. return peer != 0 && ! peer->isMinimised();
  28627. }
  28628. }
  28629. return false;
  28630. }
  28631. class FadeOutProxyComponent : public Component,
  28632. public Timer
  28633. {
  28634. public:
  28635. FadeOutProxyComponent (Component* comp,
  28636. const int fadeLengthMs,
  28637. const int deltaXToMove,
  28638. const int deltaYToMove,
  28639. const float scaleFactorAtEnd)
  28640. : lastTime (0),
  28641. alpha (1.0f),
  28642. scale (1.0f)
  28643. {
  28644. image = comp->createComponentSnapshot (Rectangle (0, 0, comp->getWidth(), comp->getHeight()));
  28645. setBounds (comp->getBounds());
  28646. comp->getParentComponent()->addAndMakeVisible (this);
  28647. toBehind (comp);
  28648. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  28649. centreX = comp->getX() + comp->getWidth() * 0.5f;
  28650. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  28651. centreY = comp->getY() + comp->getHeight() * 0.5f;
  28652. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  28653. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  28654. setInterceptsMouseClicks (false, false);
  28655. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  28656. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  28657. }
  28658. ~FadeOutProxyComponent()
  28659. {
  28660. delete image;
  28661. }
  28662. void paint (Graphics& g)
  28663. {
  28664. g.setOpacity (alpha);
  28665. g.drawImage (image,
  28666. 0, 0, getWidth(), getHeight(),
  28667. 0, 0, image->getWidth(), image->getHeight());
  28668. }
  28669. void timerCallback()
  28670. {
  28671. const uint32 now = Time::getMillisecondCounter();
  28672. if (lastTime == 0)
  28673. lastTime = now;
  28674. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  28675. lastTime = now;
  28676. alpha += alphaChangePerMs * msPassed;
  28677. if (alpha > 0)
  28678. {
  28679. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  28680. {
  28681. centreX += xChangePerMs * msPassed;
  28682. centreY += yChangePerMs * msPassed;
  28683. scale += scaleChangePerMs * msPassed;
  28684. const int w = roundFloatToInt (image->getWidth() * scale);
  28685. const int h = roundFloatToInt (image->getHeight() * scale);
  28686. setBounds (roundFloatToInt (centreX) - w / 2,
  28687. roundFloatToInt (centreY) - h / 2,
  28688. w, h);
  28689. }
  28690. repaint();
  28691. }
  28692. else
  28693. {
  28694. delete this;
  28695. }
  28696. }
  28697. juce_UseDebuggingNewOperator
  28698. private:
  28699. Image* image;
  28700. uint32 lastTime;
  28701. float alpha, alphaChangePerMs;
  28702. float centreX, xChangePerMs;
  28703. float centreY, yChangePerMs;
  28704. float scale, scaleChangePerMs;
  28705. FadeOutProxyComponent (const FadeOutProxyComponent&);
  28706. const FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  28707. };
  28708. void Component::fadeOutComponent (const int millisecondsToFade,
  28709. const int deltaXToMove,
  28710. const int deltaYToMove,
  28711. const float scaleFactorAtEnd)
  28712. {
  28713. //xxx won't work for comps without parents
  28714. if (isShowing() && millisecondsToFade > 0)
  28715. new FadeOutProxyComponent (this, millisecondsToFade,
  28716. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  28717. setVisible (false);
  28718. }
  28719. bool Component::isValidComponent() const throw()
  28720. {
  28721. return (this != 0) && isValidMessageListener();
  28722. }
  28723. void* Component::getWindowHandle() const throw()
  28724. {
  28725. const ComponentPeer* const peer = getPeer();
  28726. if (peer != 0)
  28727. return peer->getNativeHandle();
  28728. return 0;
  28729. }
  28730. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  28731. {
  28732. // if component methods are being called from threads other than the message
  28733. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28734. checkMessageManagerIsLocked
  28735. if (! isOpaque())
  28736. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  28737. int currentStyleFlags = 0;
  28738. // don't use getPeer(), so that we only get the peer that's specifically
  28739. // for this comp, and not for one of its parents.
  28740. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  28741. if (peer != 0)
  28742. currentStyleFlags = peer->getStyleFlags();
  28743. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  28744. {
  28745. const ComponentDeletionWatcher deletionChecker (this);
  28746. #if JUCE_LINUX
  28747. // it's wise to give the component a non-zero size before
  28748. // putting it on the desktop, as X windows get confused by this, and
  28749. // a (1, 1) minimum size is enforced here.
  28750. setSize (jmax (1, getWidth()),
  28751. jmax (1, getHeight()));
  28752. #endif
  28753. int x = 0, y = 0;
  28754. relativePositionToGlobal (x, y);
  28755. bool wasFullscreen = false;
  28756. bool wasMinimised = false;
  28757. ComponentBoundsConstrainer* currentConstainer = 0;
  28758. Rectangle oldNonFullScreenBounds;
  28759. if (peer != 0)
  28760. {
  28761. wasFullscreen = peer->isFullScreen();
  28762. wasMinimised = peer->isMinimised();
  28763. currentConstainer = peer->getConstrainer();
  28764. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  28765. removeFromDesktop();
  28766. }
  28767. if (parentComponent_ != 0)
  28768. parentComponent_->removeChildComponent (this);
  28769. if (! deletionChecker.hasBeenDeleted())
  28770. {
  28771. flags.hasHeavyweightPeerFlag = true;
  28772. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  28773. Desktop::getInstance().addDesktopComponent (this);
  28774. bounds_.setPosition (x, y);
  28775. peer->setBounds (x, y, getWidth(), getHeight(), false);
  28776. peer->setVisible (isVisible());
  28777. if (wasFullscreen)
  28778. {
  28779. peer->setFullScreen (true);
  28780. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  28781. }
  28782. if (wasMinimised)
  28783. peer->setMinimised (true);
  28784. if (isAlwaysOnTop())
  28785. peer->setAlwaysOnTop (true);
  28786. peer->setConstrainer (currentConstainer);
  28787. repaint();
  28788. }
  28789. internalHierarchyChanged();
  28790. }
  28791. }
  28792. void Component::removeFromDesktop()
  28793. {
  28794. // if component methods are being called from threads other than the message
  28795. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28796. checkMessageManagerIsLocked
  28797. if (flags.hasHeavyweightPeerFlag)
  28798. {
  28799. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  28800. flags.hasHeavyweightPeerFlag = false;
  28801. jassert (peer != 0);
  28802. delete peer;
  28803. Desktop::getInstance().removeDesktopComponent (this);
  28804. }
  28805. }
  28806. bool Component::isOnDesktop() const throw()
  28807. {
  28808. return flags.hasHeavyweightPeerFlag;
  28809. }
  28810. void Component::userTriedToCloseWindow()
  28811. {
  28812. /* This means that the user's trying to get rid of your window with the 'close window' system
  28813. menu option (on windows) or possibly the task manager - you should really handle this
  28814. and delete or hide your component in an appropriate way.
  28815. If you want to ignore the event and don't want to trigger this assertion, just override
  28816. this method and do nothing.
  28817. */
  28818. jassertfalse
  28819. }
  28820. void Component::minimisationStateChanged (bool)
  28821. {
  28822. }
  28823. void Component::setOpaque (const bool shouldBeOpaque) throw()
  28824. {
  28825. if (shouldBeOpaque != flags.opaqueFlag)
  28826. {
  28827. flags.opaqueFlag = shouldBeOpaque;
  28828. if (flags.hasHeavyweightPeerFlag)
  28829. {
  28830. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  28831. if (peer != 0)
  28832. {
  28833. // to make it recreate the heavyweight window
  28834. addToDesktop (peer->getStyleFlags());
  28835. }
  28836. }
  28837. repaint();
  28838. }
  28839. }
  28840. bool Component::isOpaque() const throw()
  28841. {
  28842. return flags.opaqueFlag;
  28843. }
  28844. void Component::setBufferedToImage (const bool shouldBeBuffered) throw()
  28845. {
  28846. if (shouldBeBuffered != flags.bufferToImageFlag)
  28847. {
  28848. deleteAndZero (bufferedImage_);
  28849. flags.bufferToImageFlag = shouldBeBuffered;
  28850. }
  28851. }
  28852. void Component::toFront (const bool setAsForeground)
  28853. {
  28854. // if component methods are being called from threads other than the message
  28855. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28856. checkMessageManagerIsLocked
  28857. if (flags.hasHeavyweightPeerFlag)
  28858. {
  28859. ComponentPeer* const peer = getPeer();
  28860. if (peer != 0)
  28861. {
  28862. peer->toFront (setAsForeground);
  28863. if (setAsForeground && ! hasKeyboardFocus (true))
  28864. grabKeyboardFocus();
  28865. }
  28866. }
  28867. else if (parentComponent_ != 0)
  28868. {
  28869. if (parentComponent_->childComponentList_.getLast() != this)
  28870. {
  28871. const int index = parentComponent_->childComponentList_.indexOf (this);
  28872. if (index >= 0)
  28873. {
  28874. int insertIndex = -1;
  28875. if (! flags.alwaysOnTopFlag)
  28876. {
  28877. insertIndex = parentComponent_->childComponentList_.size() - 1;
  28878. while (insertIndex > 0
  28879. && parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  28880. {
  28881. --insertIndex;
  28882. }
  28883. }
  28884. if (index != insertIndex)
  28885. {
  28886. parentComponent_->childComponentList_.move (index, insertIndex);
  28887. sendFakeMouseMove();
  28888. repaintParent();
  28889. }
  28890. }
  28891. }
  28892. if (setAsForeground)
  28893. {
  28894. internalBroughtToFront();
  28895. grabKeyboardFocus();
  28896. }
  28897. }
  28898. }
  28899. void Component::toBehind (Component* const other)
  28900. {
  28901. if (other != 0)
  28902. {
  28903. // the two components must belong to the same parent..
  28904. jassert (parentComponent_ == other->parentComponent_);
  28905. if (parentComponent_ != 0)
  28906. {
  28907. const int index = parentComponent_->childComponentList_.indexOf (this);
  28908. int otherIndex = parentComponent_->childComponentList_.indexOf (other);
  28909. if (index >= 0
  28910. && otherIndex >= 0
  28911. && index != otherIndex - 1
  28912. && other != this)
  28913. {
  28914. if (index < otherIndex)
  28915. --otherIndex;
  28916. parentComponent_->childComponentList_.move (index, otherIndex);
  28917. sendFakeMouseMove();
  28918. repaintParent();
  28919. }
  28920. }
  28921. else if (isOnDesktop())
  28922. {
  28923. jassert (other->isOnDesktop());
  28924. if (other->isOnDesktop())
  28925. {
  28926. ComponentPeer* const us = getPeer();
  28927. ComponentPeer* const them = other->getPeer();
  28928. jassert (us != 0 && them != 0);
  28929. if (us != 0 && them != 0)
  28930. us->toBehind (them);
  28931. }
  28932. }
  28933. }
  28934. }
  28935. void Component::toBack()
  28936. {
  28937. if (isOnDesktop())
  28938. {
  28939. jassertfalse //xxx need to add this to native window
  28940. }
  28941. else if (parentComponent_ != 0
  28942. && parentComponent_->childComponentList_.getFirst() != this)
  28943. {
  28944. const int index = parentComponent_->childComponentList_.indexOf (this);
  28945. if (index > 0)
  28946. {
  28947. int insertIndex = 0;
  28948. if (flags.alwaysOnTopFlag)
  28949. {
  28950. while (insertIndex < parentComponent_->childComponentList_.size()
  28951. && ! parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  28952. {
  28953. ++insertIndex;
  28954. }
  28955. }
  28956. if (index != insertIndex)
  28957. {
  28958. parentComponent_->childComponentList_.move (index, insertIndex);
  28959. sendFakeMouseMove();
  28960. repaintParent();
  28961. }
  28962. }
  28963. }
  28964. }
  28965. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  28966. {
  28967. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  28968. {
  28969. flags.alwaysOnTopFlag = shouldStayOnTop;
  28970. if (isOnDesktop())
  28971. {
  28972. ComponentPeer* const peer = getPeer();
  28973. jassert (peer != 0);
  28974. if (peer != 0)
  28975. {
  28976. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  28977. {
  28978. // some kinds of peer can't change their always-on-top status, so
  28979. // for these, we'll need to create a new window
  28980. const int oldFlags = peer->getStyleFlags();
  28981. removeFromDesktop();
  28982. addToDesktop (oldFlags);
  28983. }
  28984. }
  28985. }
  28986. if (shouldStayOnTop)
  28987. toFront (false);
  28988. internalHierarchyChanged();
  28989. }
  28990. }
  28991. bool Component::isAlwaysOnTop() const throw()
  28992. {
  28993. return flags.alwaysOnTopFlag;
  28994. }
  28995. int Component::proportionOfWidth (const float proportion) const throw()
  28996. {
  28997. return roundDoubleToInt (proportion * bounds_.getWidth());
  28998. }
  28999. int Component::proportionOfHeight (const float proportion) const throw()
  29000. {
  29001. return roundDoubleToInt (proportion * bounds_.getHeight());
  29002. }
  29003. int Component::getParentWidth() const throw()
  29004. {
  29005. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  29006. : getParentMonitorArea().getWidth();
  29007. }
  29008. int Component::getParentHeight() const throw()
  29009. {
  29010. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  29011. : getParentMonitorArea().getHeight();
  29012. }
  29013. int Component::getScreenX() const throw()
  29014. {
  29015. return (parentComponent_ != 0) ? parentComponent_->getScreenX() + getX()
  29016. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenX()
  29017. : getX());
  29018. }
  29019. int Component::getScreenY() const throw()
  29020. {
  29021. return (parentComponent_ != 0) ? parentComponent_->getScreenY() + getY()
  29022. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenY()
  29023. : getY());
  29024. }
  29025. void Component::relativePositionToGlobal (int& x, int& y) const throw()
  29026. {
  29027. const Component* c = this;
  29028. do
  29029. {
  29030. if (c->flags.hasHeavyweightPeerFlag)
  29031. {
  29032. c->getPeer()->relativePositionToGlobal (x, y);
  29033. break;
  29034. }
  29035. x += c->getX();
  29036. y += c->getY();
  29037. c = c->parentComponent_;
  29038. }
  29039. while (c != 0);
  29040. }
  29041. void Component::globalPositionToRelative (int& x, int& y) const throw()
  29042. {
  29043. if (flags.hasHeavyweightPeerFlag)
  29044. {
  29045. getPeer()->globalPositionToRelative (x, y);
  29046. }
  29047. else
  29048. {
  29049. if (parentComponent_ != 0)
  29050. parentComponent_->globalPositionToRelative (x, y);
  29051. x -= getX();
  29052. y -= getY();
  29053. }
  29054. }
  29055. void Component::relativePositionToOtherComponent (const Component* const targetComponent, int& x, int& y) const throw()
  29056. {
  29057. if (targetComponent != 0)
  29058. {
  29059. const Component* c = this;
  29060. do
  29061. {
  29062. if (c == targetComponent)
  29063. return;
  29064. if (c->flags.hasHeavyweightPeerFlag)
  29065. {
  29066. c->getPeer()->relativePositionToGlobal (x, y);
  29067. break;
  29068. }
  29069. x += c->getX();
  29070. y += c->getY();
  29071. c = c->parentComponent_;
  29072. }
  29073. while (c != 0);
  29074. targetComponent->globalPositionToRelative (x, y);
  29075. }
  29076. }
  29077. void Component::setBounds (int x, int y, int w, int h)
  29078. {
  29079. // if component methods are being called from threads other than the message
  29080. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29081. checkMessageManagerIsLocked
  29082. if (w < 0) w = 0;
  29083. if (h < 0) h = 0;
  29084. const bool wasResized = (getWidth() != w || getHeight() != h);
  29085. const bool wasMoved = (getX() != x || getY() != y);
  29086. #ifdef JUCE_DEBUG
  29087. // It's a very bad idea to try to resize a window during its paint() method!
  29088. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  29089. #endif
  29090. if (wasMoved || wasResized)
  29091. {
  29092. if (flags.visibleFlag)
  29093. {
  29094. // send a fake mouse move to trigger enter/exit messages if needed..
  29095. sendFakeMouseMove();
  29096. if (! flags.hasHeavyweightPeerFlag)
  29097. repaintParent();
  29098. }
  29099. bounds_.setBounds (x, y, w, h);
  29100. if (wasResized)
  29101. repaint();
  29102. else if (! flags.hasHeavyweightPeerFlag)
  29103. repaintParent();
  29104. if (flags.hasHeavyweightPeerFlag)
  29105. {
  29106. ComponentPeer* const peer = getPeer();
  29107. if (peer != 0)
  29108. {
  29109. if (wasMoved && wasResized)
  29110. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  29111. else if (wasMoved)
  29112. peer->setPosition (getX(), getY());
  29113. else if (wasResized)
  29114. peer->setSize (getWidth(), getHeight());
  29115. }
  29116. }
  29117. sendMovedResizedMessages (wasMoved, wasResized);
  29118. }
  29119. }
  29120. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  29121. {
  29122. JUCE_TRY
  29123. {
  29124. if (wasMoved)
  29125. moved();
  29126. if (wasResized)
  29127. {
  29128. resized();
  29129. for (int i = childComponentList_.size(); --i >= 0;)
  29130. {
  29131. childComponentList_.getUnchecked(i)->parentSizeChanged();
  29132. i = jmin (i, childComponentList_.size());
  29133. }
  29134. }
  29135. if (parentComponent_ != 0)
  29136. parentComponent_->childBoundsChanged (this);
  29137. if (componentListeners_ != 0)
  29138. {
  29139. const ComponentDeletionWatcher deletionChecker (this);
  29140. for (int i = componentListeners_->size(); --i >= 0;)
  29141. {
  29142. ((ComponentListener*) componentListeners_->getUnchecked (i))
  29143. ->componentMovedOrResized (*this, wasMoved, wasResized);
  29144. if (deletionChecker.hasBeenDeleted())
  29145. return;
  29146. i = jmin (i, componentListeners_->size());
  29147. }
  29148. }
  29149. }
  29150. JUCE_CATCH_EXCEPTION
  29151. }
  29152. void Component::setSize (const int w, const int h)
  29153. {
  29154. setBounds (getX(), getY(), w, h);
  29155. }
  29156. void Component::setTopLeftPosition (const int x, const int y)
  29157. {
  29158. setBounds (x, y, getWidth(), getHeight());
  29159. }
  29160. void Component::setTopRightPosition (const int x, const int y)
  29161. {
  29162. setTopLeftPosition (x - getWidth(), y);
  29163. }
  29164. void Component::setBounds (const Rectangle& r)
  29165. {
  29166. setBounds (r.getX(),
  29167. r.getY(),
  29168. r.getWidth(),
  29169. r.getHeight());
  29170. }
  29171. void Component::setBoundsRelative (const float x, const float y,
  29172. const float w, const float h)
  29173. {
  29174. const int pw = getParentWidth();
  29175. const int ph = getParentHeight();
  29176. setBounds (roundFloatToInt (x * pw),
  29177. roundFloatToInt (y * ph),
  29178. roundFloatToInt (w * pw),
  29179. roundFloatToInt (h * ph));
  29180. }
  29181. void Component::setCentrePosition (const int x, const int y)
  29182. {
  29183. setTopLeftPosition (x - getWidth() / 2,
  29184. y - getHeight() / 2);
  29185. }
  29186. void Component::setCentreRelative (const float x, const float y)
  29187. {
  29188. setCentrePosition (roundFloatToInt (getParentWidth() * x),
  29189. roundFloatToInt (getParentHeight() * y));
  29190. }
  29191. void Component::centreWithSize (const int width, const int height)
  29192. {
  29193. setBounds ((getParentWidth() - width) / 2,
  29194. (getParentHeight() - height) / 2,
  29195. width,
  29196. height);
  29197. }
  29198. void Component::setBoundsInset (const BorderSize& borders)
  29199. {
  29200. setBounds (borders.getLeft(),
  29201. borders.getTop(),
  29202. getParentWidth() - (borders.getLeftAndRight()),
  29203. getParentHeight() - (borders.getTopAndBottom()));
  29204. }
  29205. void Component::setBoundsToFit (int x, int y, int width, int height,
  29206. const Justification& justification,
  29207. const bool onlyReduceInSize)
  29208. {
  29209. // it's no good calling this method unless both the component and
  29210. // target rectangle have a finite size.
  29211. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  29212. if (getWidth() > 0 && getHeight() > 0
  29213. && width > 0 && height > 0)
  29214. {
  29215. int newW, newH;
  29216. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  29217. {
  29218. newW = getWidth();
  29219. newH = getHeight();
  29220. }
  29221. else
  29222. {
  29223. const double imageRatio = getHeight() / (double) getWidth();
  29224. const double targetRatio = height / (double) width;
  29225. if (imageRatio <= targetRatio)
  29226. {
  29227. newW = width;
  29228. newH = jmin (height, roundDoubleToInt (newW * imageRatio));
  29229. }
  29230. else
  29231. {
  29232. newH = height;
  29233. newW = jmin (width, roundDoubleToInt (newH / imageRatio));
  29234. }
  29235. }
  29236. if (newW > 0 && newH > 0)
  29237. {
  29238. int newX, newY;
  29239. justification.applyToRectangle (newX, newY, newW, newH,
  29240. x, y, width, height);
  29241. setBounds (newX, newY, newW, newH);
  29242. }
  29243. }
  29244. }
  29245. bool Component::hitTest (int x, int y)
  29246. {
  29247. if (! flags.ignoresMouseClicksFlag)
  29248. return true;
  29249. if (flags.allowChildMouseClicksFlag)
  29250. {
  29251. for (int i = getNumChildComponents(); --i >= 0;)
  29252. {
  29253. Component* const c = getChildComponent (i);
  29254. if (c->isVisible()
  29255. && c->bounds_.contains (x, y)
  29256. && c->hitTest (x - c->getX(),
  29257. y - c->getY()))
  29258. {
  29259. return true;
  29260. }
  29261. }
  29262. }
  29263. return false;
  29264. }
  29265. void Component::setInterceptsMouseClicks (const bool allowClicks,
  29266. const bool allowClicksOnChildComponents) throw()
  29267. {
  29268. flags.ignoresMouseClicksFlag = ! allowClicks;
  29269. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  29270. }
  29271. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  29272. bool& allowsClicksOnChildComponents) const throw()
  29273. {
  29274. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  29275. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  29276. }
  29277. bool Component::contains (const int x, const int y)
  29278. {
  29279. if (((unsigned int) x) < (unsigned int) getWidth()
  29280. && ((unsigned int) y) < (unsigned int) getHeight()
  29281. && hitTest (x, y))
  29282. {
  29283. if (parentComponent_ != 0)
  29284. {
  29285. return parentComponent_->contains (x + getX(),
  29286. y + getY());
  29287. }
  29288. else if (flags.hasHeavyweightPeerFlag)
  29289. {
  29290. const ComponentPeer* const peer = getPeer();
  29291. if (peer != 0)
  29292. return peer->contains (x, y, true);
  29293. }
  29294. }
  29295. return false;
  29296. }
  29297. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  29298. {
  29299. if (! contains (x, y))
  29300. return false;
  29301. Component* p = this;
  29302. while (p->parentComponent_ != 0)
  29303. {
  29304. x += p->getX();
  29305. y += p->getY();
  29306. p = p->parentComponent_;
  29307. }
  29308. const Component* const c = p->getComponentAt (x, y);
  29309. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  29310. }
  29311. Component* Component::getComponentAt (const int x, const int y)
  29312. {
  29313. if (flags.visibleFlag
  29314. && ((unsigned int) x) < (unsigned int) getWidth()
  29315. && ((unsigned int) y) < (unsigned int) getHeight()
  29316. && hitTest (x, y))
  29317. {
  29318. for (int i = childComponentList_.size(); --i >= 0;)
  29319. {
  29320. Component* const child = childComponentList_.getUnchecked(i);
  29321. Component* const c = child->getComponentAt (x - child->getX(),
  29322. y - child->getY());
  29323. if (c != 0)
  29324. return c;
  29325. }
  29326. return this;
  29327. }
  29328. return 0;
  29329. }
  29330. void Component::addChildComponent (Component* const child, int zOrder)
  29331. {
  29332. // if component methods are being called from threads other than the message
  29333. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29334. checkMessageManagerIsLocked
  29335. if (child != 0 && child->parentComponent_ != this)
  29336. {
  29337. if (child->parentComponent_ != 0)
  29338. child->parentComponent_->removeChildComponent (child);
  29339. else
  29340. child->removeFromDesktop();
  29341. child->parentComponent_ = this;
  29342. if (child->isVisible())
  29343. child->repaintParent();
  29344. if (! child->isAlwaysOnTop())
  29345. {
  29346. if (zOrder < 0 || zOrder > childComponentList_.size())
  29347. zOrder = childComponentList_.size();
  29348. while (zOrder > 0)
  29349. {
  29350. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  29351. break;
  29352. --zOrder;
  29353. }
  29354. }
  29355. childComponentList_.insert (zOrder, child);
  29356. child->internalHierarchyChanged();
  29357. internalChildrenChanged();
  29358. }
  29359. }
  29360. void Component::addAndMakeVisible (Component* const child, int zOrder)
  29361. {
  29362. if (child != 0)
  29363. {
  29364. child->setVisible (true);
  29365. addChildComponent (child, zOrder);
  29366. }
  29367. }
  29368. void Component::removeChildComponent (Component* const child)
  29369. {
  29370. removeChildComponent (childComponentList_.indexOf (child));
  29371. }
  29372. Component* Component::removeChildComponent (const int index)
  29373. {
  29374. // if component methods are being called from threads other than the message
  29375. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29376. checkMessageManagerIsLocked
  29377. Component* const child = childComponentList_ [index];
  29378. if (child != 0)
  29379. {
  29380. sendFakeMouseMove();
  29381. child->repaintParent();
  29382. childComponentList_.remove (index);
  29383. child->parentComponent_ = 0;
  29384. JUCE_TRY
  29385. {
  29386. if ((currentlyFocusedComponent == child)
  29387. || child->isParentOf (currentlyFocusedComponent))
  29388. {
  29389. // get rid first to force the grabKeyboardFocus to change to us.
  29390. giveAwayFocus();
  29391. grabKeyboardFocus();
  29392. }
  29393. }
  29394. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  29395. catch (const std::exception& e)
  29396. {
  29397. currentlyFocusedComponent = 0;
  29398. Desktop::getInstance().triggerFocusCallback();
  29399. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  29400. }
  29401. catch (...)
  29402. {
  29403. currentlyFocusedComponent = 0;
  29404. Desktop::getInstance().triggerFocusCallback();
  29405. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  29406. }
  29407. #endif
  29408. child->internalHierarchyChanged();
  29409. internalChildrenChanged();
  29410. }
  29411. return child;
  29412. }
  29413. void Component::removeAllChildren()
  29414. {
  29415. for (int i = childComponentList_.size(); --i >= 0;)
  29416. removeChildComponent (i);
  29417. }
  29418. void Component::deleteAllChildren()
  29419. {
  29420. for (int i = childComponentList_.size(); --i >= 0;)
  29421. delete (removeChildComponent (i));
  29422. }
  29423. int Component::getNumChildComponents() const throw()
  29424. {
  29425. return childComponentList_.size();
  29426. }
  29427. Component* Component::getChildComponent (const int index) const throw()
  29428. {
  29429. return childComponentList_ [index];
  29430. }
  29431. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  29432. {
  29433. return childComponentList_.indexOf (const_cast <Component*> (child));
  29434. }
  29435. Component* Component::getTopLevelComponent() const throw()
  29436. {
  29437. const Component* comp = this;
  29438. while (comp->parentComponent_ != 0)
  29439. comp = comp->parentComponent_;
  29440. return (Component*) comp;
  29441. }
  29442. bool Component::isParentOf (const Component* possibleChild) const throw()
  29443. {
  29444. while (possibleChild->isValidComponent())
  29445. {
  29446. possibleChild = possibleChild->parentComponent_;
  29447. if (possibleChild == this)
  29448. return true;
  29449. }
  29450. return false;
  29451. }
  29452. void Component::parentHierarchyChanged()
  29453. {
  29454. }
  29455. void Component::childrenChanged()
  29456. {
  29457. }
  29458. void Component::internalChildrenChanged()
  29459. {
  29460. const ComponentDeletionWatcher deletionChecker (this);
  29461. const bool hasListeners = componentListeners_ != 0;
  29462. childrenChanged();
  29463. if (hasListeners)
  29464. {
  29465. if (deletionChecker.hasBeenDeleted())
  29466. return;
  29467. for (int i = componentListeners_->size(); --i >= 0;)
  29468. {
  29469. ((ComponentListener*) componentListeners_->getUnchecked (i))
  29470. ->componentChildrenChanged (*this);
  29471. if (deletionChecker.hasBeenDeleted())
  29472. return;
  29473. i = jmin (i, componentListeners_->size());
  29474. }
  29475. }
  29476. }
  29477. void Component::internalHierarchyChanged()
  29478. {
  29479. parentHierarchyChanged();
  29480. const ComponentDeletionWatcher deletionChecker (this);
  29481. if (componentListeners_ != 0)
  29482. {
  29483. for (int i = componentListeners_->size(); --i >= 0;)
  29484. {
  29485. ((ComponentListener*) componentListeners_->getUnchecked (i))
  29486. ->componentParentHierarchyChanged (*this);
  29487. if (deletionChecker.hasBeenDeleted())
  29488. return;
  29489. i = jmin (i, componentListeners_->size());
  29490. }
  29491. }
  29492. for (int i = childComponentList_.size(); --i >= 0;)
  29493. {
  29494. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  29495. // you really shouldn't delete the parent component during a callback telling you
  29496. // that it's changed..
  29497. jassert (! deletionChecker.hasBeenDeleted());
  29498. if (deletionChecker.hasBeenDeleted())
  29499. return;
  29500. i = jmin (i, childComponentList_.size());
  29501. }
  29502. }
  29503. void* Component::runModalLoopCallback (void* userData)
  29504. {
  29505. return (void*) (pointer_sized_int) ((Component*) userData)->runModalLoop();
  29506. }
  29507. int Component::runModalLoop()
  29508. {
  29509. if (! MessageManager::getInstance()->isThisTheMessageThread())
  29510. {
  29511. // use a callback so this can be called from non-gui threads
  29512. return (int) (pointer_sized_int)
  29513. MessageManager::getInstance()
  29514. ->callFunctionOnMessageThread (&runModalLoopCallback, (void*) this);
  29515. }
  29516. Component* const prevFocused = getCurrentlyFocusedComponent();
  29517. ComponentDeletionWatcher* deletionChecker = 0;
  29518. if (prevFocused != 0)
  29519. deletionChecker = new ComponentDeletionWatcher (prevFocused);
  29520. if (! isCurrentlyModal())
  29521. enterModalState();
  29522. JUCE_TRY
  29523. {
  29524. while (flags.currentlyModalFlag && flags.visibleFlag)
  29525. {
  29526. if (! MessageManager::getInstance()->dispatchNextMessage())
  29527. break;
  29528. // check whether this component was deleted during the last message
  29529. if (! isValidMessageListener())
  29530. break;
  29531. }
  29532. }
  29533. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  29534. catch (const std::exception& e)
  29535. {
  29536. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  29537. return 0;
  29538. }
  29539. catch (...)
  29540. {
  29541. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  29542. return 0;
  29543. }
  29544. #endif
  29545. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  29546. int returnValue = 0;
  29547. if (modalIndex >= 0)
  29548. {
  29549. modalComponentReturnValueKeys.remove (modalIndex);
  29550. returnValue = modalReturnValues.remove (modalIndex);
  29551. }
  29552. modalComponentStack.removeValue (this);
  29553. if (deletionChecker != 0)
  29554. {
  29555. if (! deletionChecker->hasBeenDeleted())
  29556. prevFocused->grabKeyboardFocus();
  29557. delete deletionChecker;
  29558. }
  29559. return returnValue;
  29560. }
  29561. void Component::enterModalState (const bool takeKeyboardFocus)
  29562. {
  29563. // if component methods are being called from threads other than the message
  29564. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29565. checkMessageManagerIsLocked
  29566. // Check for an attempt to make a component modal when it already is!
  29567. // This can cause nasty problems..
  29568. jassert (! flags.currentlyModalFlag);
  29569. if (! isCurrentlyModal())
  29570. {
  29571. modalComponentStack.add (this);
  29572. modalComponentReturnValueKeys.add (this);
  29573. modalReturnValues.add (0);
  29574. flags.currentlyModalFlag = true;
  29575. setVisible (true);
  29576. if (takeKeyboardFocus)
  29577. grabKeyboardFocus();
  29578. }
  29579. }
  29580. void Component::exitModalState (const int returnValue)
  29581. {
  29582. if (isCurrentlyModal())
  29583. {
  29584. if (MessageManager::getInstance()->isThisTheMessageThread())
  29585. {
  29586. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  29587. if (modalIndex >= 0)
  29588. {
  29589. modalReturnValues.set (modalIndex, returnValue);
  29590. }
  29591. else
  29592. {
  29593. modalComponentReturnValueKeys.add (this);
  29594. modalReturnValues.add (returnValue);
  29595. }
  29596. modalComponentStack.removeValue (this);
  29597. flags.currentlyModalFlag = false;
  29598. }
  29599. else
  29600. {
  29601. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  29602. }
  29603. }
  29604. }
  29605. bool Component::isCurrentlyModal() const throw()
  29606. {
  29607. return flags.currentlyModalFlag
  29608. && getCurrentlyModalComponent() == this;
  29609. }
  29610. bool Component::isCurrentlyBlockedByAnotherModalComponent() const throw()
  29611. {
  29612. Component* const mc = getCurrentlyModalComponent();
  29613. return mc != 0
  29614. && mc != this
  29615. && (! mc->isParentOf (this))
  29616. && ! mc->canModalEventBeSentToComponent (this);
  29617. }
  29618. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent() throw()
  29619. {
  29620. Component* const c = (Component*) modalComponentStack.getLast();
  29621. return c->isValidComponent() ? c : 0;
  29622. }
  29623. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  29624. {
  29625. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  29626. }
  29627. bool Component::isBroughtToFrontOnMouseClick() const throw()
  29628. {
  29629. return flags.bringToFrontOnClickFlag;
  29630. }
  29631. void Component::setMouseCursor (const MouseCursor& cursor) throw()
  29632. {
  29633. cursor_ = cursor;
  29634. if (flags.visibleFlag)
  29635. {
  29636. int mx, my;
  29637. getMouseXYRelative (mx, my);
  29638. if (flags.draggingFlag || reallyContains (mx, my, false))
  29639. {
  29640. internalUpdateMouseCursor (false);
  29641. }
  29642. }
  29643. }
  29644. const MouseCursor Component::getMouseCursor()
  29645. {
  29646. return cursor_;
  29647. }
  29648. void Component::updateMouseCursor() const throw()
  29649. {
  29650. sendFakeMouseMove();
  29651. }
  29652. void Component::internalUpdateMouseCursor (const bool forcedUpdate) throw()
  29653. {
  29654. ComponentPeer* const peer = getPeer();
  29655. if (peer != 0)
  29656. {
  29657. MouseCursor mc (getMouseCursor());
  29658. if (isUnboundedMouseModeOn && (unboundedMouseOffsetX != 0
  29659. || unboundedMouseOffsetY != 0
  29660. || ! isCursorVisibleUntilOffscreen))
  29661. {
  29662. mc = MouseCursor::NoCursor;
  29663. }
  29664. static void* currentCursorHandle = 0;
  29665. if (forcedUpdate || mc.getHandle() != currentCursorHandle)
  29666. {
  29667. currentCursorHandle = mc.getHandle();
  29668. mc.showInWindow (peer);
  29669. }
  29670. }
  29671. }
  29672. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  29673. {
  29674. flags.repaintOnMouseActivityFlag = shouldRepaint;
  29675. }
  29676. void Component::repaintParent() throw()
  29677. {
  29678. if (flags.visibleFlag)
  29679. internalRepaint (0, 0, getWidth(), getHeight());
  29680. }
  29681. void Component::repaint() throw()
  29682. {
  29683. repaint (0, 0, getWidth(), getHeight());
  29684. }
  29685. void Component::repaint (const int x, const int y,
  29686. const int w, const int h) throw()
  29687. {
  29688. deleteAndZero (bufferedImage_);
  29689. if (flags.visibleFlag)
  29690. internalRepaint (x, y, w, h);
  29691. }
  29692. void Component::internalRepaint (int x, int y, int w, int h)
  29693. {
  29694. // if component methods are being called from threads other than the message
  29695. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29696. checkMessageManagerIsLocked
  29697. if (x < 0)
  29698. {
  29699. w += x;
  29700. x = 0;
  29701. }
  29702. if (x + w > getWidth())
  29703. w = getWidth() - x;
  29704. if (w > 0)
  29705. {
  29706. if (y < 0)
  29707. {
  29708. h += y;
  29709. y = 0;
  29710. }
  29711. if (y + h > getHeight())
  29712. h = getHeight() - y;
  29713. if (h > 0)
  29714. {
  29715. if (parentComponent_ != 0)
  29716. {
  29717. x += getX();
  29718. y += getY();
  29719. if (parentComponent_->flags.visibleFlag)
  29720. parentComponent_->internalRepaint (x, y, w, h);
  29721. }
  29722. else if (flags.hasHeavyweightPeerFlag)
  29723. {
  29724. ComponentPeer* const peer = getPeer();
  29725. if (peer != 0)
  29726. peer->repaint (x, y, w, h);
  29727. }
  29728. }
  29729. }
  29730. }
  29731. void Component::paintEntireComponent (Graphics& originalContext)
  29732. {
  29733. jassert (! originalContext.isClipEmpty());
  29734. #ifdef JUCE_DEBUG
  29735. flags.isInsidePaintCall = true;
  29736. #endif
  29737. Graphics* g = &originalContext;
  29738. Image* effectImage = 0;
  29739. if (effect_ != 0)
  29740. {
  29741. effectImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  29742. getWidth(), getHeight(),
  29743. ! flags.opaqueFlag);
  29744. g = new Graphics (*effectImage);
  29745. }
  29746. g->saveState();
  29747. clipObscuredRegions (*g, g->getClipBounds(), 0, 0);
  29748. if (! g->isClipEmpty())
  29749. {
  29750. if (bufferedImage_ != 0)
  29751. {
  29752. g->setColour (Colours::black);
  29753. g->drawImageAt (bufferedImage_, 0, 0);
  29754. }
  29755. else
  29756. {
  29757. if (flags.bufferToImageFlag)
  29758. {
  29759. if (bufferedImage_ == 0)
  29760. {
  29761. bufferedImage_ = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  29762. getWidth(), getHeight(), ! flags.opaqueFlag);
  29763. Graphics imG (*bufferedImage_);
  29764. paint (imG);
  29765. }
  29766. g->setColour (Colours::black);
  29767. g->drawImageAt (bufferedImage_, 0, 0);
  29768. }
  29769. else
  29770. {
  29771. paint (*g);
  29772. g->resetToDefaultState();
  29773. }
  29774. }
  29775. }
  29776. g->restoreState();
  29777. for (int i = 0; i < childComponentList_.size(); ++i)
  29778. {
  29779. Component* const child = childComponentList_.getUnchecked (i);
  29780. if (child->isVisible())
  29781. {
  29782. g->saveState();
  29783. if (g->reduceClipRegion (child->getX(), child->getY(),
  29784. child->getWidth(), child->getHeight()))
  29785. {
  29786. for (int j = i + 1; j < childComponentList_.size(); ++j)
  29787. {
  29788. const Component* const sibling = childComponentList_.getUnchecked (j);
  29789. if (sibling->flags.opaqueFlag && sibling->isVisible())
  29790. g->excludeClipRegion (sibling->getX(), sibling->getY(),
  29791. sibling->getWidth(), sibling->getHeight());
  29792. }
  29793. if (! g->isClipEmpty())
  29794. {
  29795. g->setOrigin (child->getX(), child->getY());
  29796. child->paintEntireComponent (*g);
  29797. }
  29798. }
  29799. g->restoreState();
  29800. }
  29801. }
  29802. JUCE_TRY
  29803. {
  29804. g->saveState();
  29805. paintOverChildren (*g);
  29806. g->restoreState();
  29807. }
  29808. JUCE_CATCH_EXCEPTION
  29809. if (effect_ != 0)
  29810. {
  29811. delete g;
  29812. effect_->applyEffect (*effectImage, originalContext);
  29813. delete effectImage;
  29814. }
  29815. #ifdef JUCE_DEBUG
  29816. flags.isInsidePaintCall = false;
  29817. #endif
  29818. }
  29819. Image* Component::createComponentSnapshot (const Rectangle& areaToGrab,
  29820. const bool clipImageToComponentBounds)
  29821. {
  29822. Rectangle r (areaToGrab);
  29823. if (clipImageToComponentBounds)
  29824. r = r.getIntersection (Rectangle (0, 0, getWidth(), getHeight()));
  29825. Image* const componentImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  29826. jmax (1, r.getWidth()),
  29827. jmax (1, r.getHeight()),
  29828. true);
  29829. Graphics imageContext (*componentImage);
  29830. imageContext.setOrigin (-r.getX(),
  29831. -r.getY());
  29832. paintEntireComponent (imageContext);
  29833. return componentImage;
  29834. }
  29835. void Component::setComponentEffect (ImageEffectFilter* const effect)
  29836. {
  29837. if (effect_ != effect)
  29838. {
  29839. effect_ = effect;
  29840. repaint();
  29841. }
  29842. }
  29843. LookAndFeel& Component::getLookAndFeel() const throw()
  29844. {
  29845. const Component* c = this;
  29846. do
  29847. {
  29848. if (c->lookAndFeel_ != 0)
  29849. return *(c->lookAndFeel_);
  29850. c = c->parentComponent_;
  29851. }
  29852. while (c != 0);
  29853. return LookAndFeel::getDefaultLookAndFeel();
  29854. }
  29855. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  29856. {
  29857. if (lookAndFeel_ != newLookAndFeel)
  29858. {
  29859. lookAndFeel_ = newLookAndFeel;
  29860. sendLookAndFeelChange();
  29861. }
  29862. }
  29863. void Component::lookAndFeelChanged()
  29864. {
  29865. }
  29866. void Component::sendLookAndFeelChange()
  29867. {
  29868. repaint();
  29869. lookAndFeelChanged();
  29870. // (it's not a great idea to do anything that would delete this component
  29871. // during the lookAndFeelChanged() callback)
  29872. jassert (isValidComponent());
  29873. const ComponentDeletionWatcher deletionChecker (this);
  29874. for (int i = childComponentList_.size(); --i >= 0;)
  29875. {
  29876. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  29877. if (deletionChecker.hasBeenDeleted())
  29878. return;
  29879. i = jmin (i, childComponentList_.size());
  29880. }
  29881. }
  29882. static const String getColourPropertyName (const int colourId) throw()
  29883. {
  29884. String s;
  29885. s.preallocateStorage (18);
  29886. s << T("jcclr_") << colourId;
  29887. return s;
  29888. }
  29889. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const throw()
  29890. {
  29891. const String customColour (getComponentProperty (getColourPropertyName (colourId),
  29892. inheritFromParent,
  29893. String::empty));
  29894. if (customColour.isNotEmpty())
  29895. return Colour (customColour.getIntValue());
  29896. return getLookAndFeel().findColour (colourId);
  29897. }
  29898. bool Component::isColourSpecified (const int colourId) const throw()
  29899. {
  29900. return getComponentProperty (getColourPropertyName (colourId),
  29901. false,
  29902. String::empty).isNotEmpty();
  29903. }
  29904. void Component::removeColour (const int colourId)
  29905. {
  29906. if (isColourSpecified (colourId))
  29907. {
  29908. removeComponentProperty (getColourPropertyName (colourId));
  29909. colourChanged();
  29910. }
  29911. }
  29912. void Component::setColour (const int colourId, const Colour& colour)
  29913. {
  29914. const String colourName (getColourPropertyName (colourId));
  29915. const String customColour (getComponentProperty (colourName, false, String::empty));
  29916. if (customColour.isEmpty() || Colour (customColour.getIntValue()) != colour)
  29917. {
  29918. setComponentProperty (colourName, colour);
  29919. colourChanged();
  29920. }
  29921. }
  29922. void Component::copyAllExplicitColoursTo (Component& target) const throw()
  29923. {
  29924. if (propertySet_ != 0)
  29925. {
  29926. const StringPairArray& props = propertySet_->getAllProperties();
  29927. const StringArray& keys = props.getAllKeys();
  29928. for (int i = 0; i < keys.size(); ++i)
  29929. {
  29930. if (keys[i].startsWith (T("jcclr_")))
  29931. {
  29932. target.setComponentProperty (keys[i],
  29933. props.getAllValues() [i]);
  29934. }
  29935. }
  29936. target.colourChanged();
  29937. }
  29938. }
  29939. void Component::colourChanged()
  29940. {
  29941. }
  29942. const Rectangle Component::getUnclippedArea() const
  29943. {
  29944. int x = 0, y = 0, w = getWidth(), h = getHeight();
  29945. Component* p = parentComponent_;
  29946. int px = getX();
  29947. int py = getY();
  29948. while (p != 0)
  29949. {
  29950. if (! Rectangle::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  29951. return Rectangle();
  29952. px += p->getX();
  29953. py += p->getY();
  29954. p = p->parentComponent_;
  29955. }
  29956. return Rectangle (x, y, w, h);
  29957. }
  29958. void Component::clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  29959. const int deltaX, const int deltaY) const throw()
  29960. {
  29961. for (int i = childComponentList_.size(); --i >= 0;)
  29962. {
  29963. const Component* const c = childComponentList_.getUnchecked(i);
  29964. if (c->isVisible())
  29965. {
  29966. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  29967. if (! newClip.isEmpty())
  29968. {
  29969. if (c->isOpaque())
  29970. {
  29971. g.excludeClipRegion (deltaX + newClip.getX(),
  29972. deltaY + newClip.getY(),
  29973. newClip.getWidth(),
  29974. newClip.getHeight());
  29975. }
  29976. else
  29977. {
  29978. newClip.translate (-c->getX(), -c->getY());
  29979. c->clipObscuredRegions (g, newClip,
  29980. c->getX() + deltaX,
  29981. c->getY() + deltaY);
  29982. }
  29983. }
  29984. }
  29985. }
  29986. }
  29987. void Component::getVisibleArea (RectangleList& result,
  29988. const bool includeSiblings) const
  29989. {
  29990. result.clear();
  29991. const Rectangle unclipped (getUnclippedArea());
  29992. if (! unclipped.isEmpty())
  29993. {
  29994. result.add (unclipped);
  29995. if (includeSiblings)
  29996. {
  29997. const Component* const c = getTopLevelComponent();
  29998. int x = 0, y = 0;
  29999. c->relativePositionToOtherComponent (this, x, y);
  30000. c->subtractObscuredRegions (result, x, y,
  30001. Rectangle (0, 0, c->getWidth(), c->getHeight()),
  30002. this);
  30003. }
  30004. subtractObscuredRegions (result, 0, 0, unclipped, 0);
  30005. result.consolidate();
  30006. }
  30007. }
  30008. void Component::subtractObscuredRegions (RectangleList& result,
  30009. const int deltaX,
  30010. const int deltaY,
  30011. const Rectangle& clipRect,
  30012. const Component* const compToAvoid) const throw()
  30013. {
  30014. for (int i = childComponentList_.size(); --i >= 0;)
  30015. {
  30016. const Component* const c = childComponentList_.getUnchecked(i);
  30017. if (c != compToAvoid && c->isVisible())
  30018. {
  30019. if (c->isOpaque())
  30020. {
  30021. Rectangle childBounds (c->bounds_.getIntersection (clipRect));
  30022. childBounds.translate (deltaX, deltaY);
  30023. result.subtract (childBounds);
  30024. }
  30025. else
  30026. {
  30027. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  30028. newClip.translate (-c->getX(), -c->getY());
  30029. c->subtractObscuredRegions (result,
  30030. c->getX() + deltaX,
  30031. c->getY() + deltaY,
  30032. newClip,
  30033. compToAvoid);
  30034. }
  30035. }
  30036. }
  30037. }
  30038. void Component::mouseEnter (const MouseEvent&)
  30039. {
  30040. // base class does nothing
  30041. }
  30042. void Component::mouseExit (const MouseEvent&)
  30043. {
  30044. // base class does nothing
  30045. }
  30046. void Component::mouseDown (const MouseEvent&)
  30047. {
  30048. // base class does nothing
  30049. }
  30050. void Component::mouseUp (const MouseEvent&)
  30051. {
  30052. // base class does nothing
  30053. }
  30054. void Component::mouseDrag (const MouseEvent&)
  30055. {
  30056. // base class does nothing
  30057. }
  30058. void Component::mouseMove (const MouseEvent&)
  30059. {
  30060. // base class does nothing
  30061. }
  30062. void Component::mouseDoubleClick (const MouseEvent&)
  30063. {
  30064. // base class does nothing
  30065. }
  30066. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  30067. {
  30068. // the base class just passes this event up to its parent..
  30069. if (parentComponent_ != 0)
  30070. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  30071. wheelIncrementX, wheelIncrementY);
  30072. }
  30073. void Component::resized()
  30074. {
  30075. // base class does nothing
  30076. }
  30077. void Component::moved()
  30078. {
  30079. // base class does nothing
  30080. }
  30081. void Component::childBoundsChanged (Component*)
  30082. {
  30083. // base class does nothing
  30084. }
  30085. void Component::parentSizeChanged()
  30086. {
  30087. // base class does nothing
  30088. }
  30089. void Component::addComponentListener (ComponentListener* const newListener) throw()
  30090. {
  30091. if (componentListeners_ == 0)
  30092. componentListeners_ = new VoidArray (4);
  30093. componentListeners_->addIfNotAlreadyThere (newListener);
  30094. }
  30095. void Component::removeComponentListener (ComponentListener* const listenerToRemove) throw()
  30096. {
  30097. jassert (isValidComponent());
  30098. if (componentListeners_ != 0)
  30099. componentListeners_->removeValue (listenerToRemove);
  30100. }
  30101. void Component::inputAttemptWhenModal()
  30102. {
  30103. getTopLevelComponent()->toFront (true);
  30104. getLookAndFeel().playAlertSound();
  30105. }
  30106. bool Component::canModalEventBeSentToComponent (const Component*)
  30107. {
  30108. return false;
  30109. }
  30110. void Component::internalModalInputAttempt()
  30111. {
  30112. Component* const current = getCurrentlyModalComponent();
  30113. if (current != 0)
  30114. current->inputAttemptWhenModal();
  30115. }
  30116. void Component::paint (Graphics&)
  30117. {
  30118. // all painting is done in the subclasses
  30119. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  30120. }
  30121. void Component::paintOverChildren (Graphics&)
  30122. {
  30123. // all painting is done in the subclasses
  30124. }
  30125. void Component::handleMessage (const Message& message)
  30126. {
  30127. if (message.intParameter1 == exitModalStateMessage)
  30128. {
  30129. exitModalState (message.intParameter2);
  30130. }
  30131. else if (message.intParameter1 == customCommandMessage)
  30132. {
  30133. handleCommandMessage (message.intParameter2);
  30134. }
  30135. }
  30136. void Component::postCommandMessage (const int commandId) throw()
  30137. {
  30138. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  30139. }
  30140. void Component::handleCommandMessage (int)
  30141. {
  30142. // used by subclasses
  30143. }
  30144. void Component::addMouseListener (MouseListener* const newListener,
  30145. const bool wantsEventsForAllNestedChildComponents) throw()
  30146. {
  30147. // if component methods are being called from threads other than the message
  30148. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30149. checkMessageManagerIsLocked
  30150. if (mouseListeners_ == 0)
  30151. mouseListeners_ = new VoidArray (4);
  30152. if (! mouseListeners_->contains (newListener))
  30153. {
  30154. if (wantsEventsForAllNestedChildComponents)
  30155. {
  30156. mouseListeners_->insert (0, newListener);
  30157. ++numDeepMouseListeners;
  30158. }
  30159. else
  30160. {
  30161. mouseListeners_->add (newListener);
  30162. }
  30163. }
  30164. }
  30165. void Component::removeMouseListener (MouseListener* const listenerToRemove) throw()
  30166. {
  30167. // if component methods are being called from threads other than the message
  30168. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30169. checkMessageManagerIsLocked
  30170. if (mouseListeners_ != 0)
  30171. {
  30172. const int index = mouseListeners_->indexOf (listenerToRemove);
  30173. if (index >= 0)
  30174. {
  30175. if (index < numDeepMouseListeners)
  30176. --numDeepMouseListeners;
  30177. mouseListeners_->remove (index);
  30178. }
  30179. }
  30180. }
  30181. void Component::internalMouseEnter (int x, int y, int64 time)
  30182. {
  30183. if (isCurrentlyBlockedByAnotherModalComponent())
  30184. {
  30185. // if something else is modal, always just show a normal mouse cursor
  30186. if (componentUnderMouse == this)
  30187. {
  30188. ComponentPeer* const peer = getPeer();
  30189. if (peer != 0)
  30190. {
  30191. MouseCursor mc (MouseCursor::NormalCursor);
  30192. mc.showInWindow (peer);
  30193. }
  30194. }
  30195. return;
  30196. }
  30197. if (! flags.mouseInsideFlag)
  30198. {
  30199. flags.mouseInsideFlag = true;
  30200. flags.mouseOverFlag = true;
  30201. flags.draggingFlag = false;
  30202. if (isValidComponent())
  30203. {
  30204. const ComponentDeletionWatcher deletionChecker (this);
  30205. if (flags.repaintOnMouseActivityFlag)
  30206. repaint();
  30207. const MouseEvent me (x, y,
  30208. ModifierKeys::getCurrentModifiers(),
  30209. this,
  30210. Time (time),
  30211. x, y,
  30212. Time (time),
  30213. 0, false);
  30214. mouseEnter (me);
  30215. if (deletionChecker.hasBeenDeleted())
  30216. return;
  30217. Desktop::getInstance().resetTimer();
  30218. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30219. {
  30220. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseEnter (me);
  30221. if (deletionChecker.hasBeenDeleted())
  30222. return;
  30223. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30224. }
  30225. if (mouseListeners_ != 0)
  30226. {
  30227. for (int i = mouseListeners_->size(); --i >= 0;)
  30228. {
  30229. ((MouseListener*) mouseListeners_->getUnchecked(i))->mouseEnter (me);
  30230. if (deletionChecker.hasBeenDeleted())
  30231. return;
  30232. i = jmin (i, mouseListeners_->size());
  30233. }
  30234. }
  30235. const Component* p = parentComponent_;
  30236. while (p != 0)
  30237. {
  30238. const ComponentDeletionWatcher parentDeletionChecker (p);
  30239. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30240. {
  30241. ((MouseListener*) (p->mouseListeners_->getUnchecked(i)))->mouseEnter (me);
  30242. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30243. return;
  30244. i = jmin (i, p->numDeepMouseListeners);
  30245. }
  30246. p = p->parentComponent_;
  30247. }
  30248. }
  30249. }
  30250. if (componentUnderMouse == this)
  30251. internalUpdateMouseCursor (true);
  30252. }
  30253. void Component::internalMouseExit (int x, int y, int64 time)
  30254. {
  30255. const ComponentDeletionWatcher deletionChecker (this);
  30256. if (flags.draggingFlag)
  30257. {
  30258. internalMouseUp (ModifierKeys::getCurrentModifiers().getRawFlags(), x, y, time);
  30259. if (deletionChecker.hasBeenDeleted())
  30260. return;
  30261. }
  30262. enableUnboundedMouseMovement (false);
  30263. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  30264. {
  30265. flags.mouseInsideFlag = false;
  30266. flags.mouseOverFlag = false;
  30267. flags.draggingFlag = false;
  30268. if (flags.repaintOnMouseActivityFlag)
  30269. repaint();
  30270. const MouseEvent me (x, y,
  30271. ModifierKeys::getCurrentModifiers(),
  30272. this,
  30273. Time (time),
  30274. x, y,
  30275. Time (time),
  30276. 0, false);
  30277. mouseExit (me);
  30278. if (deletionChecker.hasBeenDeleted())
  30279. return;
  30280. Desktop::getInstance().resetTimer();
  30281. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30282. {
  30283. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseExit (me);
  30284. if (deletionChecker.hasBeenDeleted())
  30285. return;
  30286. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30287. }
  30288. if (mouseListeners_ != 0)
  30289. {
  30290. for (int i = mouseListeners_->size(); --i >= 0;)
  30291. {
  30292. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  30293. if (deletionChecker.hasBeenDeleted())
  30294. return;
  30295. i = jmin (i, mouseListeners_->size());
  30296. }
  30297. }
  30298. const Component* p = parentComponent_;
  30299. while (p != 0)
  30300. {
  30301. const ComponentDeletionWatcher parentDeletionChecker (p);
  30302. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30303. {
  30304. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseExit (me);
  30305. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30306. return;
  30307. i = jmin (i, p->numDeepMouseListeners);
  30308. }
  30309. p = p->parentComponent_;
  30310. }
  30311. }
  30312. }
  30313. class InternalDragRepeater : public Timer
  30314. {
  30315. public:
  30316. InternalDragRepeater()
  30317. {}
  30318. ~InternalDragRepeater()
  30319. {}
  30320. void timerCallback()
  30321. {
  30322. Component* const c = Component::getComponentUnderMouse();
  30323. if (c != 0 && c->isMouseButtonDown())
  30324. {
  30325. int x, y;
  30326. c->getMouseXYRelative (x, y);
  30327. // the offsets have been added on, so must be taken off before calling the
  30328. // drag.. otherwise they'll be added twice
  30329. x -= unboundedMouseOffsetX;
  30330. y -= unboundedMouseOffsetY;
  30331. c->internalMouseDrag (x, y, Time::currentTimeMillis());
  30332. }
  30333. }
  30334. juce_UseDebuggingNewOperator
  30335. };
  30336. static InternalDragRepeater* dragRepeater = 0;
  30337. void Component::beginDragAutoRepeat (const int interval)
  30338. {
  30339. if (interval > 0)
  30340. {
  30341. if (dragRepeater == 0)
  30342. dragRepeater = new InternalDragRepeater();
  30343. if (dragRepeater->getTimerInterval() != interval)
  30344. dragRepeater->startTimer (interval);
  30345. }
  30346. else
  30347. {
  30348. deleteAndZero (dragRepeater);
  30349. }
  30350. }
  30351. void Component::internalMouseDown (const int x, const int y)
  30352. {
  30353. const ComponentDeletionWatcher deletionChecker (this);
  30354. if (isCurrentlyBlockedByAnotherModalComponent())
  30355. {
  30356. internalModalInputAttempt();
  30357. if (deletionChecker.hasBeenDeleted())
  30358. return;
  30359. // If processing the input attempt has exited the modal loop, we'll allow the event
  30360. // to be delivered..
  30361. if (isCurrentlyBlockedByAnotherModalComponent())
  30362. {
  30363. // allow blocked mouse-events to go to global listeners..
  30364. const MouseEvent me (x, y,
  30365. ModifierKeys::getCurrentModifiers(),
  30366. this,
  30367. Time (juce_recentMouseDownTimes[0]),
  30368. x, y,
  30369. Time (juce_recentMouseDownTimes[0]),
  30370. countMouseClicks(),
  30371. false);
  30372. Desktop::getInstance().resetTimer();
  30373. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30374. {
  30375. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  30376. if (deletionChecker.hasBeenDeleted())
  30377. return;
  30378. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30379. }
  30380. return;
  30381. }
  30382. }
  30383. {
  30384. Component* c = this;
  30385. while (c != 0)
  30386. {
  30387. if (c->isBroughtToFrontOnMouseClick())
  30388. {
  30389. c->toFront (true);
  30390. if (deletionChecker.hasBeenDeleted())
  30391. return;
  30392. }
  30393. c = c->parentComponent_;
  30394. }
  30395. }
  30396. if (! flags.dontFocusOnMouseClickFlag)
  30397. grabFocusInternal (focusChangedByMouseClick);
  30398. if (! deletionChecker.hasBeenDeleted())
  30399. {
  30400. flags.draggingFlag = true;
  30401. flags.mouseOverFlag = true;
  30402. if (flags.repaintOnMouseActivityFlag)
  30403. repaint();
  30404. const MouseEvent me (x, y,
  30405. ModifierKeys::getCurrentModifiers(),
  30406. this,
  30407. Time (juce_recentMouseDownTimes[0]),
  30408. x, y,
  30409. Time (juce_recentMouseDownTimes[0]),
  30410. countMouseClicks(),
  30411. false);
  30412. mouseDown (me);
  30413. if (deletionChecker.hasBeenDeleted())
  30414. return;
  30415. Desktop::getInstance().resetTimer();
  30416. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30417. {
  30418. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  30419. if (deletionChecker.hasBeenDeleted())
  30420. return;
  30421. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30422. }
  30423. if (mouseListeners_ != 0)
  30424. {
  30425. for (int i = mouseListeners_->size(); --i >= 0;)
  30426. {
  30427. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  30428. if (deletionChecker.hasBeenDeleted())
  30429. return;
  30430. i = jmin (i, mouseListeners_->size());
  30431. }
  30432. }
  30433. const Component* p = parentComponent_;
  30434. while (p != 0)
  30435. {
  30436. const ComponentDeletionWatcher parentDeletionChecker (p);
  30437. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30438. {
  30439. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDown (me);
  30440. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30441. return;
  30442. i = jmin (i, p->numDeepMouseListeners);
  30443. }
  30444. p = p->parentComponent_;
  30445. }
  30446. }
  30447. }
  30448. void Component::internalMouseUp (const int oldModifiers, int x, int y, const int64 time)
  30449. {
  30450. if (isValidComponent() && flags.draggingFlag)
  30451. {
  30452. flags.draggingFlag = false;
  30453. deleteAndZero (dragRepeater);
  30454. x += unboundedMouseOffsetX;
  30455. y += unboundedMouseOffsetY;
  30456. juce_LastMousePosX = x;
  30457. juce_LastMousePosY = y;
  30458. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  30459. const ComponentDeletionWatcher deletionChecker (this);
  30460. if (flags.repaintOnMouseActivityFlag)
  30461. repaint();
  30462. int mdx = juce_recentMouseDownX[0];
  30463. int mdy = juce_recentMouseDownY[0];
  30464. globalPositionToRelative (mdx, mdy);
  30465. const MouseEvent me (x, y,
  30466. oldModifiers,
  30467. this,
  30468. Time (time),
  30469. mdx, mdy,
  30470. Time (juce_recentMouseDownTimes [0]),
  30471. countMouseClicks(),
  30472. juce_MouseHasMovedSignificantlySincePressed
  30473. || juce_recentMouseDownTimes[0] + 300 < time);
  30474. mouseUp (me);
  30475. if (deletionChecker.hasBeenDeleted())
  30476. return;
  30477. Desktop::getInstance().resetTimer();
  30478. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30479. {
  30480. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseUp (me);
  30481. if (deletionChecker.hasBeenDeleted())
  30482. return;
  30483. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30484. }
  30485. if (mouseListeners_ != 0)
  30486. {
  30487. for (int i = mouseListeners_->size(); --i >= 0;)
  30488. {
  30489. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  30490. if (deletionChecker.hasBeenDeleted())
  30491. return;
  30492. i = jmin (i, mouseListeners_->size());
  30493. }
  30494. }
  30495. {
  30496. const Component* p = parentComponent_;
  30497. while (p != 0)
  30498. {
  30499. const ComponentDeletionWatcher parentDeletionChecker (p);
  30500. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30501. {
  30502. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseUp (me);
  30503. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30504. return;
  30505. i = jmin (i, p->numDeepMouseListeners);
  30506. }
  30507. p = p->parentComponent_;
  30508. }
  30509. }
  30510. // check for double-click
  30511. if (me.getNumberOfClicks() >= 2)
  30512. {
  30513. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  30514. mouseDoubleClick (me);
  30515. int i;
  30516. for (i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30517. {
  30518. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDoubleClick (me);
  30519. if (deletionChecker.hasBeenDeleted())
  30520. return;
  30521. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30522. }
  30523. for (i = numListeners; --i >= 0;)
  30524. {
  30525. if (deletionChecker.hasBeenDeleted() || mouseListeners_ == 0)
  30526. return;
  30527. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  30528. if (ml != 0)
  30529. ml->mouseDoubleClick (me);
  30530. }
  30531. if (deletionChecker.hasBeenDeleted())
  30532. return;
  30533. const Component* p = parentComponent_;
  30534. while (p != 0)
  30535. {
  30536. const ComponentDeletionWatcher parentDeletionChecker (p);
  30537. for (i = p->numDeepMouseListeners; --i >= 0;)
  30538. {
  30539. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDoubleClick (me);
  30540. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30541. return;
  30542. i = jmin (i, p->numDeepMouseListeners);
  30543. }
  30544. p = p->parentComponent_;
  30545. }
  30546. }
  30547. }
  30548. enableUnboundedMouseMovement (false);
  30549. }
  30550. void Component::internalMouseDrag (int x, int y, const int64 time)
  30551. {
  30552. if (isValidComponent() && flags.draggingFlag)
  30553. {
  30554. flags.mouseOverFlag = reallyContains (x, y, false);
  30555. x += unboundedMouseOffsetX;
  30556. y += unboundedMouseOffsetY;
  30557. juce_LastMousePosX = x;
  30558. juce_LastMousePosY = y;
  30559. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  30560. juce_MouseHasMovedSignificantlySincePressed
  30561. = juce_MouseHasMovedSignificantlySincePressed
  30562. || abs (juce_recentMouseDownX[0] - juce_LastMousePosX) >= 4
  30563. || abs (juce_recentMouseDownY[0] - juce_LastMousePosY) >= 4;
  30564. const ComponentDeletionWatcher deletionChecker (this);
  30565. int mdx = juce_recentMouseDownX[0];
  30566. int mdy = juce_recentMouseDownY[0];
  30567. globalPositionToRelative (mdx, mdy);
  30568. const MouseEvent me (x, y,
  30569. ModifierKeys::getCurrentModifiers(),
  30570. this,
  30571. Time (time),
  30572. mdx, mdy,
  30573. Time (juce_recentMouseDownTimes[0]),
  30574. countMouseClicks(),
  30575. juce_MouseHasMovedSignificantlySincePressed
  30576. || juce_recentMouseDownTimes[0] + 300 < time);
  30577. mouseDrag (me);
  30578. if (deletionChecker.hasBeenDeleted())
  30579. return;
  30580. Desktop::getInstance().resetTimer();
  30581. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30582. {
  30583. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDrag (me);
  30584. if (deletionChecker.hasBeenDeleted())
  30585. return;
  30586. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30587. }
  30588. if (mouseListeners_ != 0)
  30589. {
  30590. for (int i = mouseListeners_->size(); --i >= 0;)
  30591. {
  30592. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  30593. if (deletionChecker.hasBeenDeleted())
  30594. return;
  30595. i = jmin (i, mouseListeners_->size());
  30596. }
  30597. }
  30598. const Component* p = parentComponent_;
  30599. while (p != 0)
  30600. {
  30601. const ComponentDeletionWatcher parentDeletionChecker (p);
  30602. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30603. {
  30604. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDrag (me);
  30605. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30606. return;
  30607. i = jmin (i, p->numDeepMouseListeners);
  30608. }
  30609. p = p->parentComponent_;
  30610. }
  30611. if (this == componentUnderMouse)
  30612. {
  30613. if (isUnboundedMouseModeOn)
  30614. {
  30615. Rectangle screenArea (getParentMonitorArea().expanded (-2, -2));
  30616. int mx, my;
  30617. Desktop::getMousePosition (mx, my);
  30618. if (! screenArea.contains (mx, my))
  30619. {
  30620. int deltaX = 0, deltaY = 0;
  30621. if (mx <= screenArea.getX() || mx >= screenArea.getRight())
  30622. deltaX = getScreenX() + getWidth() / 2 - mx;
  30623. if (my <= screenArea.getY() || my >= screenArea.getBottom())
  30624. deltaY = getScreenY() + getHeight() / 2 - my;
  30625. unboundedMouseOffsetX -= deltaX;
  30626. unboundedMouseOffsetY -= deltaY;
  30627. Desktop::setMousePosition (mx + deltaX,
  30628. my + deltaY);
  30629. }
  30630. else if (isCursorVisibleUntilOffscreen
  30631. && (unboundedMouseOffsetX != 0 || unboundedMouseOffsetY != 0)
  30632. && screenArea.contains (mx + unboundedMouseOffsetX,
  30633. my + unboundedMouseOffsetY))
  30634. {
  30635. mx += unboundedMouseOffsetX;
  30636. my += unboundedMouseOffsetY;
  30637. unboundedMouseOffsetX = 0;
  30638. unboundedMouseOffsetY = 0;
  30639. Desktop::setMousePosition (mx, my);
  30640. }
  30641. }
  30642. internalUpdateMouseCursor (false);
  30643. }
  30644. }
  30645. }
  30646. void Component::internalMouseMove (const int x, const int y, const int64 time)
  30647. {
  30648. const ComponentDeletionWatcher deletionChecker (this);
  30649. if (isValidComponent())
  30650. {
  30651. const MouseEvent me (x, y,
  30652. ModifierKeys::getCurrentModifiers(),
  30653. this,
  30654. Time (time),
  30655. x, y,
  30656. Time (time),
  30657. 0, false);
  30658. if (isCurrentlyBlockedByAnotherModalComponent())
  30659. {
  30660. // allow blocked mouse-events to go to global listeners..
  30661. Desktop::getInstance().sendMouseMove();
  30662. }
  30663. else
  30664. {
  30665. if (this == componentUnderMouse)
  30666. internalUpdateMouseCursor (false);
  30667. flags.mouseOverFlag = true;
  30668. mouseMove (me);
  30669. if (deletionChecker.hasBeenDeleted())
  30670. return;
  30671. Desktop::getInstance().resetTimer();
  30672. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30673. {
  30674. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseMove (me);
  30675. if (deletionChecker.hasBeenDeleted())
  30676. return;
  30677. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30678. }
  30679. if (mouseListeners_ != 0)
  30680. {
  30681. for (int i = mouseListeners_->size(); --i >= 0;)
  30682. {
  30683. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  30684. if (deletionChecker.hasBeenDeleted())
  30685. return;
  30686. i = jmin (i, mouseListeners_->size());
  30687. }
  30688. }
  30689. const Component* p = parentComponent_;
  30690. while (p != 0)
  30691. {
  30692. const ComponentDeletionWatcher parentDeletionChecker (p);
  30693. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30694. {
  30695. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseMove (me);
  30696. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30697. return;
  30698. i = jmin (i, p->numDeepMouseListeners);
  30699. }
  30700. p = p->parentComponent_;
  30701. }
  30702. }
  30703. }
  30704. }
  30705. void Component::internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time)
  30706. {
  30707. const ComponentDeletionWatcher deletionChecker (this);
  30708. const float wheelIncrementX = intAmountX * (1.0f / 256.0f);
  30709. const float wheelIncrementY = intAmountY * (1.0f / 256.0f);
  30710. int mx, my;
  30711. getMouseXYRelative (mx, my);
  30712. const MouseEvent me (mx, my,
  30713. ModifierKeys::getCurrentModifiers(),
  30714. this,
  30715. Time (time),
  30716. mx, my,
  30717. Time (time),
  30718. 0, false);
  30719. if (isCurrentlyBlockedByAnotherModalComponent())
  30720. {
  30721. // allow blocked mouse-events to go to global listeners..
  30722. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30723. {
  30724. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30725. if (deletionChecker.hasBeenDeleted())
  30726. return;
  30727. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30728. }
  30729. }
  30730. else
  30731. {
  30732. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30733. if (deletionChecker.hasBeenDeleted())
  30734. return;
  30735. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30736. {
  30737. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30738. if (deletionChecker.hasBeenDeleted())
  30739. return;
  30740. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30741. }
  30742. if (mouseListeners_ != 0)
  30743. {
  30744. for (int i = mouseListeners_->size(); --i >= 0;)
  30745. {
  30746. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30747. if (deletionChecker.hasBeenDeleted())
  30748. return;
  30749. i = jmin (i, mouseListeners_->size());
  30750. }
  30751. }
  30752. const Component* p = parentComponent_;
  30753. while (p != 0)
  30754. {
  30755. const ComponentDeletionWatcher parentDeletionChecker (p);
  30756. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30757. {
  30758. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30759. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30760. return;
  30761. i = jmin (i, p->numDeepMouseListeners);
  30762. }
  30763. p = p->parentComponent_;
  30764. }
  30765. sendFakeMouseMove();
  30766. }
  30767. }
  30768. void Component::sendFakeMouseMove() const
  30769. {
  30770. ComponentPeer* const peer = getPeer();
  30771. if (peer != 0)
  30772. peer->sendFakeMouseMove();
  30773. }
  30774. void Component::broughtToFront()
  30775. {
  30776. }
  30777. void Component::internalBroughtToFront()
  30778. {
  30779. if (isValidComponent())
  30780. {
  30781. if (flags.hasHeavyweightPeerFlag)
  30782. Desktop::getInstance().componentBroughtToFront (this);
  30783. const ComponentDeletionWatcher deletionChecker (this);
  30784. broughtToFront();
  30785. if (deletionChecker.hasBeenDeleted())
  30786. return;
  30787. if (componentListeners_ != 0)
  30788. {
  30789. for (int i = componentListeners_->size(); --i >= 0;)
  30790. {
  30791. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30792. ->componentBroughtToFront (*this);
  30793. if (deletionChecker.hasBeenDeleted())
  30794. return;
  30795. i = jmin (i, componentListeners_->size());
  30796. }
  30797. }
  30798. // when brought to the front and there's a modal component blocking this one,
  30799. // we need to bring the modal one to the front instead..
  30800. Component* const cm = getCurrentlyModalComponent();
  30801. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  30802. {
  30803. cm->getTopLevelComponent()->toFront (false);
  30804. }
  30805. }
  30806. }
  30807. void Component::focusGained (FocusChangeType)
  30808. {
  30809. // base class does nothing
  30810. }
  30811. void Component::internalFocusGain (const FocusChangeType cause)
  30812. {
  30813. const ComponentDeletionWatcher deletionChecker (this);
  30814. focusGained (cause);
  30815. if (! deletionChecker.hasBeenDeleted())
  30816. internalChildFocusChange (cause);
  30817. }
  30818. void Component::focusLost (FocusChangeType)
  30819. {
  30820. // base class does nothing
  30821. }
  30822. void Component::internalFocusLoss (const FocusChangeType cause)
  30823. {
  30824. const ComponentDeletionWatcher deletionChecker (this);
  30825. focusLost (focusChangedDirectly);
  30826. if (! deletionChecker.hasBeenDeleted())
  30827. internalChildFocusChange (cause);
  30828. }
  30829. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  30830. {
  30831. // base class does nothing
  30832. }
  30833. void Component::internalChildFocusChange (FocusChangeType cause)
  30834. {
  30835. const bool childIsNowFocused = hasKeyboardFocus (true);
  30836. if (flags.childCompFocusedFlag != childIsNowFocused)
  30837. {
  30838. flags.childCompFocusedFlag = childIsNowFocused;
  30839. const ComponentDeletionWatcher deletionChecker (this);
  30840. focusOfChildComponentChanged (cause);
  30841. if (deletionChecker.hasBeenDeleted())
  30842. return;
  30843. }
  30844. if (parentComponent_ != 0)
  30845. parentComponent_->internalChildFocusChange (cause);
  30846. }
  30847. bool Component::isEnabled() const throw()
  30848. {
  30849. return (! flags.isDisabledFlag)
  30850. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  30851. }
  30852. void Component::setEnabled (const bool shouldBeEnabled)
  30853. {
  30854. if (flags.isDisabledFlag == shouldBeEnabled)
  30855. {
  30856. flags.isDisabledFlag = ! shouldBeEnabled;
  30857. // if any parent components are disabled, setting our flag won't make a difference,
  30858. // so no need to send a change message
  30859. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  30860. sendEnablementChangeMessage();
  30861. }
  30862. }
  30863. void Component::sendEnablementChangeMessage()
  30864. {
  30865. const ComponentDeletionWatcher deletionChecker (this);
  30866. enablementChanged();
  30867. if (deletionChecker.hasBeenDeleted())
  30868. return;
  30869. for (int i = getNumChildComponents(); --i >= 0;)
  30870. {
  30871. Component* const c = getChildComponent (i);
  30872. if (c != 0)
  30873. {
  30874. c->sendEnablementChangeMessage();
  30875. if (deletionChecker.hasBeenDeleted())
  30876. return;
  30877. }
  30878. }
  30879. }
  30880. void Component::enablementChanged()
  30881. {
  30882. }
  30883. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  30884. {
  30885. flags.wantsFocusFlag = wantsFocus;
  30886. }
  30887. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  30888. {
  30889. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  30890. }
  30891. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  30892. {
  30893. return ! flags.dontFocusOnMouseClickFlag;
  30894. }
  30895. bool Component::getWantsKeyboardFocus() const throw()
  30896. {
  30897. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  30898. }
  30899. void Component::setFocusContainer (const bool isFocusContainer) throw()
  30900. {
  30901. flags.isFocusContainerFlag = isFocusContainer;
  30902. }
  30903. bool Component::isFocusContainer() const throw()
  30904. {
  30905. return flags.isFocusContainerFlag;
  30906. }
  30907. int Component::getExplicitFocusOrder() const throw()
  30908. {
  30909. return getComponentPropertyInt (T("_jexfo"), false, 0);
  30910. }
  30911. void Component::setExplicitFocusOrder (const int newFocusOrderIndex) throw()
  30912. {
  30913. setComponentProperty (T("_jexfo"), newFocusOrderIndex);
  30914. }
  30915. KeyboardFocusTraverser* Component::createFocusTraverser()
  30916. {
  30917. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  30918. return new KeyboardFocusTraverser();
  30919. return parentComponent_->createFocusTraverser();
  30920. }
  30921. void Component::takeKeyboardFocus (const FocusChangeType cause)
  30922. {
  30923. // give the focus to this component
  30924. if (currentlyFocusedComponent != this)
  30925. {
  30926. JUCE_TRY
  30927. {
  30928. // get the focus onto our desktop window
  30929. ComponentPeer* const peer = getPeer();
  30930. if (peer != 0)
  30931. {
  30932. const ComponentDeletionWatcher deletionChecker (this);
  30933. peer->grabFocus();
  30934. if (peer->isFocused() && currentlyFocusedComponent != this)
  30935. {
  30936. Component* const componentLosingFocus = currentlyFocusedComponent;
  30937. currentlyFocusedComponent = this;
  30938. Desktop::getInstance().triggerFocusCallback();
  30939. // call this after setting currentlyFocusedComponent so that the one that's
  30940. // losing it has a chance to see where focus is going
  30941. if (componentLosingFocus->isValidComponent())
  30942. componentLosingFocus->internalFocusLoss (cause);
  30943. if (currentlyFocusedComponent == this)
  30944. {
  30945. focusGained (cause);
  30946. if (! deletionChecker.hasBeenDeleted())
  30947. internalChildFocusChange (cause);
  30948. }
  30949. }
  30950. }
  30951. }
  30952. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  30953. catch (const std::exception& e)
  30954. {
  30955. currentlyFocusedComponent = 0;
  30956. Desktop::getInstance().triggerFocusCallback();
  30957. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  30958. }
  30959. catch (...)
  30960. {
  30961. currentlyFocusedComponent = 0;
  30962. Desktop::getInstance().triggerFocusCallback();
  30963. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  30964. }
  30965. #endif
  30966. }
  30967. }
  30968. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  30969. {
  30970. if (isShowing())
  30971. {
  30972. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  30973. {
  30974. takeKeyboardFocus (cause);
  30975. }
  30976. else
  30977. {
  30978. if (isParentOf (currentlyFocusedComponent)
  30979. && currentlyFocusedComponent->isShowing())
  30980. {
  30981. // do nothing if the focused component is actually a child of ours..
  30982. }
  30983. else
  30984. {
  30985. // find the default child component..
  30986. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  30987. if (traverser != 0)
  30988. {
  30989. Component* const defaultComp = traverser->getDefaultComponent (this);
  30990. delete traverser;
  30991. if (defaultComp != 0)
  30992. {
  30993. defaultComp->grabFocusInternal (cause, false);
  30994. return;
  30995. }
  30996. }
  30997. if (canTryParent && parentComponent_ != 0)
  30998. {
  30999. // if no children want it and we're allowed to try our parent comp,
  31000. // then pass up to parent, which will try our siblings.
  31001. parentComponent_->grabFocusInternal (cause, true);
  31002. }
  31003. }
  31004. }
  31005. }
  31006. }
  31007. void Component::grabKeyboardFocus()
  31008. {
  31009. // if component methods are being called from threads other than the message
  31010. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31011. checkMessageManagerIsLocked
  31012. grabFocusInternal (focusChangedDirectly);
  31013. }
  31014. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  31015. {
  31016. // if component methods are being called from threads other than the message
  31017. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31018. checkMessageManagerIsLocked
  31019. if (parentComponent_ != 0)
  31020. {
  31021. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  31022. if (traverser != 0)
  31023. {
  31024. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  31025. : traverser->getPreviousComponent (this);
  31026. delete traverser;
  31027. if (nextComp != 0)
  31028. {
  31029. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  31030. {
  31031. const ComponentDeletionWatcher deletionChecker (nextComp);
  31032. internalModalInputAttempt();
  31033. if (deletionChecker.hasBeenDeleted()
  31034. || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  31035. return;
  31036. }
  31037. nextComp->grabFocusInternal (focusChangedByTabKey);
  31038. return;
  31039. }
  31040. }
  31041. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  31042. }
  31043. }
  31044. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const throw()
  31045. {
  31046. return (currentlyFocusedComponent == this)
  31047. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  31048. }
  31049. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  31050. {
  31051. return currentlyFocusedComponent;
  31052. }
  31053. void Component::giveAwayFocus()
  31054. {
  31055. // use a copy so we can clear the value before the call
  31056. Component* const componentLosingFocus = currentlyFocusedComponent;
  31057. currentlyFocusedComponent = 0;
  31058. Desktop::getInstance().triggerFocusCallback();
  31059. if (componentLosingFocus->isValidComponent())
  31060. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  31061. }
  31062. bool Component::isMouseOver() const throw()
  31063. {
  31064. return flags.mouseOverFlag;
  31065. }
  31066. bool Component::isMouseButtonDown() const throw()
  31067. {
  31068. return flags.draggingFlag;
  31069. }
  31070. bool Component::isMouseOverOrDragging() const throw()
  31071. {
  31072. return flags.mouseOverFlag || flags.draggingFlag;
  31073. }
  31074. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  31075. {
  31076. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  31077. }
  31078. void Component::getMouseXYRelative (int& mx, int& my) const throw()
  31079. {
  31080. Desktop::getMousePosition (mx, my);
  31081. globalPositionToRelative (mx, my);
  31082. mx += unboundedMouseOffsetX;
  31083. my += unboundedMouseOffsetY;
  31084. }
  31085. void Component::enableUnboundedMouseMovement (bool enable,
  31086. bool keepCursorVisibleUntilOffscreen) throw()
  31087. {
  31088. enable = enable && isMouseButtonDown();
  31089. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  31090. if (enable != isUnboundedMouseModeOn)
  31091. {
  31092. if ((! enable) && ((! isCursorVisibleUntilOffscreen)
  31093. || unboundedMouseOffsetX != 0
  31094. || unboundedMouseOffsetY != 0))
  31095. {
  31096. // when released, return the mouse to within the component's bounds
  31097. int mx, my;
  31098. getMouseXYRelative (mx, my);
  31099. mx = jlimit (0, getWidth(), mx);
  31100. my = jlimit (0, getHeight(), my);
  31101. relativePositionToGlobal (mx, my);
  31102. Desktop::setMousePosition (mx, my);
  31103. }
  31104. isUnboundedMouseModeOn = enable;
  31105. unboundedMouseOffsetX = 0;
  31106. unboundedMouseOffsetY = 0;
  31107. internalUpdateMouseCursor (true);
  31108. }
  31109. }
  31110. Component* JUCE_CALLTYPE Component::getComponentUnderMouse() throw()
  31111. {
  31112. return componentUnderMouse;
  31113. }
  31114. const Rectangle Component::getParentMonitorArea() const throw()
  31115. {
  31116. int centreX = getWidth() / 2;
  31117. int centreY = getHeight() / 2;
  31118. relativePositionToGlobal (centreX, centreY);
  31119. return Desktop::getInstance().getMonitorAreaContaining (centreX, centreY);
  31120. }
  31121. void Component::addKeyListener (KeyListener* const newListener) throw()
  31122. {
  31123. if (keyListeners_ == 0)
  31124. keyListeners_ = new VoidArray (4);
  31125. keyListeners_->addIfNotAlreadyThere (newListener);
  31126. }
  31127. void Component::removeKeyListener (KeyListener* const listenerToRemove) throw()
  31128. {
  31129. if (keyListeners_ != 0)
  31130. keyListeners_->removeValue (listenerToRemove);
  31131. }
  31132. bool Component::keyPressed (const KeyPress&)
  31133. {
  31134. return false;
  31135. }
  31136. bool Component::keyStateChanged()
  31137. {
  31138. return false;
  31139. }
  31140. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  31141. {
  31142. if (parentComponent_ != 0)
  31143. parentComponent_->modifierKeysChanged (modifiers);
  31144. }
  31145. void Component::internalModifierKeysChanged()
  31146. {
  31147. sendFakeMouseMove();
  31148. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  31149. }
  31150. ComponentPeer* Component::getPeer() const throw()
  31151. {
  31152. if (flags.hasHeavyweightPeerFlag)
  31153. return ComponentPeer::getPeerFor (this);
  31154. else if (parentComponent_ != 0)
  31155. return parentComponent_->getPeer();
  31156. else
  31157. return 0;
  31158. }
  31159. const String Component::getComponentProperty (const String& keyName,
  31160. const bool useParentComponentIfNotFound,
  31161. const String& defaultReturnValue) const throw()
  31162. {
  31163. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  31164. return propertySet_->getValue (keyName, defaultReturnValue);
  31165. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  31166. return parentComponent_->getComponentProperty (keyName, true, defaultReturnValue);
  31167. return defaultReturnValue;
  31168. }
  31169. int Component::getComponentPropertyInt (const String& keyName,
  31170. const bool useParentComponentIfNotFound,
  31171. const int defaultReturnValue) const throw()
  31172. {
  31173. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  31174. return propertySet_->getIntValue (keyName, defaultReturnValue);
  31175. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  31176. return parentComponent_->getComponentPropertyInt (keyName, true, defaultReturnValue);
  31177. return defaultReturnValue;
  31178. }
  31179. double Component::getComponentPropertyDouble (const String& keyName,
  31180. const bool useParentComponentIfNotFound,
  31181. const double defaultReturnValue) const throw()
  31182. {
  31183. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  31184. return propertySet_->getDoubleValue (keyName, defaultReturnValue);
  31185. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  31186. return parentComponent_->getComponentPropertyDouble (keyName, true, defaultReturnValue);
  31187. return defaultReturnValue;
  31188. }
  31189. bool Component::getComponentPropertyBool (const String& keyName,
  31190. const bool useParentComponentIfNotFound,
  31191. const bool defaultReturnValue) const throw()
  31192. {
  31193. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  31194. return propertySet_->getBoolValue (keyName, defaultReturnValue);
  31195. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  31196. return parentComponent_->getComponentPropertyBool (keyName, true, defaultReturnValue);
  31197. return defaultReturnValue;
  31198. }
  31199. const Colour Component::getComponentPropertyColour (const String& keyName,
  31200. const bool useParentComponentIfNotFound,
  31201. const Colour& defaultReturnValue) const throw()
  31202. {
  31203. return Colour ((uint32) getComponentPropertyInt (keyName,
  31204. useParentComponentIfNotFound,
  31205. defaultReturnValue.getARGB()));
  31206. }
  31207. void Component::setComponentProperty (const String& keyName, const String& value) throw()
  31208. {
  31209. if (propertySet_ == 0)
  31210. propertySet_ = new PropertySet();
  31211. propertySet_->setValue (keyName, value);
  31212. }
  31213. void Component::setComponentProperty (const String& keyName, const int value) throw()
  31214. {
  31215. if (propertySet_ == 0)
  31216. propertySet_ = new PropertySet();
  31217. propertySet_->setValue (keyName, value);
  31218. }
  31219. void Component::setComponentProperty (const String& keyName, const double value) throw()
  31220. {
  31221. if (propertySet_ == 0)
  31222. propertySet_ = new PropertySet();
  31223. propertySet_->setValue (keyName, value);
  31224. }
  31225. void Component::setComponentProperty (const String& keyName, const bool value) throw()
  31226. {
  31227. if (propertySet_ == 0)
  31228. propertySet_ = new PropertySet();
  31229. propertySet_->setValue (keyName, value);
  31230. }
  31231. void Component::setComponentProperty (const String& keyName, const Colour& colour) throw()
  31232. {
  31233. setComponentProperty (keyName, (int) colour.getARGB());
  31234. }
  31235. void Component::removeComponentProperty (const String& keyName) throw()
  31236. {
  31237. if (propertySet_ != 0)
  31238. propertySet_->removeValue (keyName);
  31239. }
  31240. ComponentDeletionWatcher::ComponentDeletionWatcher (const Component* const componentToWatch_) throw()
  31241. : componentToWatch (componentToWatch_),
  31242. componentUID (componentToWatch_->getComponentUID())
  31243. {
  31244. // not possible to check on an already-deleted object..
  31245. jassert (componentToWatch_->isValidComponent());
  31246. }
  31247. ComponentDeletionWatcher::~ComponentDeletionWatcher() throw() {}
  31248. bool ComponentDeletionWatcher::hasBeenDeleted() const throw()
  31249. {
  31250. return ! (componentToWatch->isValidComponent()
  31251. && componentToWatch->getComponentUID() == componentUID);
  31252. }
  31253. const Component* ComponentDeletionWatcher::getComponent() const throw()
  31254. {
  31255. return hasBeenDeleted() ? 0 : componentToWatch;
  31256. }
  31257. END_JUCE_NAMESPACE
  31258. /********* End of inlined file: juce_Component.cpp *********/
  31259. /********* Start of inlined file: juce_ComponentListener.cpp *********/
  31260. BEGIN_JUCE_NAMESPACE
  31261. void ComponentListener::componentMovedOrResized (Component&, bool, bool)
  31262. {
  31263. }
  31264. void ComponentListener::componentBroughtToFront (Component&)
  31265. {
  31266. }
  31267. void ComponentListener::componentVisibilityChanged (Component&)
  31268. {
  31269. }
  31270. void ComponentListener::componentChildrenChanged (Component&)
  31271. {
  31272. }
  31273. void ComponentListener::componentParentHierarchyChanged (Component&)
  31274. {
  31275. }
  31276. void ComponentListener::componentNameChanged (Component&)
  31277. {
  31278. }
  31279. END_JUCE_NAMESPACE
  31280. /********* End of inlined file: juce_ComponentListener.cpp *********/
  31281. /********* Start of inlined file: juce_Desktop.cpp *********/
  31282. BEGIN_JUCE_NAMESPACE
  31283. extern void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords,
  31284. const bool clipToWorkArea) throw();
  31285. static Desktop* juce_desktopInstance = 0;
  31286. Desktop::Desktop() throw()
  31287. : mouseListeners (2),
  31288. desktopComponents (4),
  31289. monitorCoordsClipped (2),
  31290. monitorCoordsUnclipped (2),
  31291. lastMouseX (0),
  31292. lastMouseY (0)
  31293. {
  31294. refreshMonitorSizes();
  31295. }
  31296. Desktop::~Desktop() throw()
  31297. {
  31298. jassert (juce_desktopInstance == this);
  31299. juce_desktopInstance = 0;
  31300. // doh! If you don't delete all your windows before exiting, you're going to
  31301. // be leaking memory!
  31302. jassert (desktopComponents.size() == 0);
  31303. }
  31304. Desktop& JUCE_CALLTYPE Desktop::getInstance() throw()
  31305. {
  31306. if (juce_desktopInstance == 0)
  31307. juce_desktopInstance = new Desktop();
  31308. return *juce_desktopInstance;
  31309. }
  31310. void Desktop::refreshMonitorSizes() throw()
  31311. {
  31312. const Array <Rectangle> oldClipped (monitorCoordsClipped);
  31313. const Array <Rectangle> oldUnclipped (monitorCoordsUnclipped);
  31314. monitorCoordsClipped.clear();
  31315. monitorCoordsUnclipped.clear();
  31316. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  31317. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  31318. jassert (monitorCoordsClipped.size() > 0
  31319. && monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  31320. if (oldClipped != monitorCoordsClipped
  31321. || oldUnclipped != monitorCoordsUnclipped)
  31322. {
  31323. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  31324. {
  31325. ComponentPeer* const p = ComponentPeer::getPeer (i);
  31326. if (p != 0)
  31327. p->handleScreenSizeChange();
  31328. }
  31329. }
  31330. }
  31331. int Desktop::getNumDisplayMonitors() const throw()
  31332. {
  31333. return monitorCoordsClipped.size();
  31334. }
  31335. const Rectangle Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  31336. {
  31337. return clippedToWorkArea ? monitorCoordsClipped [index]
  31338. : monitorCoordsUnclipped [index];
  31339. }
  31340. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  31341. {
  31342. RectangleList rl;
  31343. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  31344. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  31345. return rl;
  31346. }
  31347. const Rectangle Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  31348. {
  31349. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  31350. }
  31351. const Rectangle Desktop::getMonitorAreaContaining (int cx, int cy, const bool clippedToWorkArea) const throw()
  31352. {
  31353. Rectangle best (getMainMonitorArea (clippedToWorkArea));
  31354. double bestDistance = 1.0e10;
  31355. for (int i = getNumDisplayMonitors(); --i >= 0;)
  31356. {
  31357. const Rectangle rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  31358. if (rect.contains (cx, cy))
  31359. return rect;
  31360. const double distance = juce_hypot ((double) (rect.getCentreX() - cx),
  31361. (double) (rect.getCentreY() - cy));
  31362. if (distance < bestDistance)
  31363. {
  31364. bestDistance = distance;
  31365. best = rect;
  31366. }
  31367. }
  31368. return best;
  31369. }
  31370. int Desktop::getNumComponents() const throw()
  31371. {
  31372. return desktopComponents.size();
  31373. }
  31374. Component* Desktop::getComponent (const int index) const throw()
  31375. {
  31376. return (Component*) desktopComponents [index];
  31377. }
  31378. Component* Desktop::findComponentAt (const int screenX,
  31379. const int screenY) const
  31380. {
  31381. for (int i = desktopComponents.size(); --i >= 0;)
  31382. {
  31383. Component* const c = (Component*) desktopComponents.getUnchecked(i);
  31384. int x = screenX, y = screenY;
  31385. c->globalPositionToRelative (x, y);
  31386. if (c->contains (x, y))
  31387. return c->getComponentAt (x, y);
  31388. }
  31389. return 0;
  31390. }
  31391. void Desktop::addDesktopComponent (Component* const c) throw()
  31392. {
  31393. jassert (c != 0);
  31394. jassert (! desktopComponents.contains (c));
  31395. desktopComponents.addIfNotAlreadyThere (c);
  31396. }
  31397. void Desktop::removeDesktopComponent (Component* const c) throw()
  31398. {
  31399. desktopComponents.removeValue (c);
  31400. }
  31401. void Desktop::componentBroughtToFront (Component* const c) throw()
  31402. {
  31403. const int index = desktopComponents.indexOf (c);
  31404. jassert (index >= 0);
  31405. if (index >= 0)
  31406. desktopComponents.move (index, -1);
  31407. }
  31408. // from Component.cpp
  31409. extern int juce_recentMouseDownX [4];
  31410. extern int juce_recentMouseDownY [4];
  31411. extern int juce_MouseClickCounter;
  31412. void Desktop::getLastMouseDownPosition (int& x, int& y) throw()
  31413. {
  31414. x = juce_recentMouseDownX [0];
  31415. y = juce_recentMouseDownY [0];
  31416. }
  31417. int Desktop::getMouseButtonClickCounter() throw()
  31418. {
  31419. return juce_MouseClickCounter;
  31420. }
  31421. void Desktop::addGlobalMouseListener (MouseListener* const listener) throw()
  31422. {
  31423. jassert (listener != 0);
  31424. if (listener != 0)
  31425. {
  31426. mouseListeners.add (listener);
  31427. resetTimer();
  31428. }
  31429. }
  31430. void Desktop::removeGlobalMouseListener (MouseListener* const listener) throw()
  31431. {
  31432. mouseListeners.removeValue (listener);
  31433. resetTimer();
  31434. }
  31435. void Desktop::addFocusChangeListener (FocusChangeListener* const listener) throw()
  31436. {
  31437. jassert (listener != 0);
  31438. if (listener != 0)
  31439. focusListeners.add (listener);
  31440. }
  31441. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener) throw()
  31442. {
  31443. focusListeners.removeValue (listener);
  31444. }
  31445. void Desktop::triggerFocusCallback() throw()
  31446. {
  31447. triggerAsyncUpdate();
  31448. }
  31449. void Desktop::handleAsyncUpdate()
  31450. {
  31451. for (int i = focusListeners.size(); --i >= 0;)
  31452. {
  31453. ((FocusChangeListener*) focusListeners.getUnchecked (i))->globalFocusChanged (Component::getCurrentlyFocusedComponent());
  31454. i = jmin (i, focusListeners.size());
  31455. }
  31456. }
  31457. void Desktop::timerCallback()
  31458. {
  31459. int x, y;
  31460. getMousePosition (x, y);
  31461. if (lastMouseX != x || lastMouseY != y)
  31462. sendMouseMove();
  31463. }
  31464. void Desktop::sendMouseMove()
  31465. {
  31466. if (mouseListeners.size() > 0)
  31467. {
  31468. startTimer (20);
  31469. int x, y;
  31470. getMousePosition (x, y);
  31471. lastMouseX = x;
  31472. lastMouseY = y;
  31473. Component* const target = findComponentAt (x, y);
  31474. if (target != 0)
  31475. {
  31476. target->globalPositionToRelative (x, y);
  31477. ComponentDeletionWatcher deletionChecker (target);
  31478. const MouseEvent me (x, y,
  31479. ModifierKeys::getCurrentModifiers(),
  31480. target,
  31481. Time::getCurrentTime(),
  31482. x, y,
  31483. Time::getCurrentTime(),
  31484. 0, false);
  31485. for (int i = mouseListeners.size(); --i >= 0;)
  31486. {
  31487. if (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  31488. ((MouseListener*) mouseListeners[i])->mouseDrag (me);
  31489. else
  31490. ((MouseListener*) mouseListeners[i])->mouseMove (me);
  31491. if (deletionChecker.hasBeenDeleted())
  31492. return;
  31493. i = jmin (i, mouseListeners.size());
  31494. }
  31495. }
  31496. }
  31497. }
  31498. void Desktop::resetTimer() throw()
  31499. {
  31500. if (mouseListeners.size() == 0)
  31501. stopTimer();
  31502. else
  31503. startTimer (100);
  31504. getMousePosition (lastMouseX, lastMouseY);
  31505. }
  31506. END_JUCE_NAMESPACE
  31507. /********* End of inlined file: juce_Desktop.cpp *********/
  31508. /********* Start of inlined file: juce_ArrowButton.cpp *********/
  31509. BEGIN_JUCE_NAMESPACE
  31510. ArrowButton::ArrowButton (const String& name,
  31511. float arrowDirectionInRadians,
  31512. const Colour& arrowColour)
  31513. : Button (name),
  31514. colour (arrowColour)
  31515. {
  31516. path.lineTo (0.0f, 1.0f);
  31517. path.lineTo (1.0f, 0.5f);
  31518. path.closeSubPath();
  31519. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  31520. 0.5f, 0.5f));
  31521. setComponentEffect (&shadow);
  31522. buttonStateChanged();
  31523. }
  31524. ArrowButton::~ArrowButton()
  31525. {
  31526. }
  31527. void ArrowButton::paintButton (Graphics& g,
  31528. bool /*isMouseOverButton*/,
  31529. bool /*isButtonDown*/)
  31530. {
  31531. g.setColour (colour);
  31532. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  31533. (float) offset,
  31534. (float) (getWidth() - 3),
  31535. (float) (getHeight() - 3),
  31536. false));
  31537. }
  31538. void ArrowButton::buttonStateChanged()
  31539. {
  31540. offset = (isDown()) ? 1 : 0;
  31541. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  31542. 0.3f, -1, 0);
  31543. }
  31544. END_JUCE_NAMESPACE
  31545. /********* End of inlined file: juce_ArrowButton.cpp *********/
  31546. /********* Start of inlined file: juce_Button.cpp *********/
  31547. BEGIN_JUCE_NAMESPACE
  31548. Button::Button (const String& name)
  31549. : Component (name),
  31550. shortcuts (2),
  31551. keySource (0),
  31552. text (name),
  31553. buttonListeners (2),
  31554. repeatTimer (0),
  31555. buttonPressTime (0),
  31556. lastTimeCallbackTime (0),
  31557. commandManagerToUse (0),
  31558. autoRepeatDelay (-1),
  31559. autoRepeatSpeed (0),
  31560. autoRepeatMinimumDelay (-1),
  31561. radioGroupId (0),
  31562. commandID (0),
  31563. connectedEdgeFlags (0),
  31564. buttonState (buttonNormal),
  31565. isOn (false),
  31566. clickTogglesState (false),
  31567. needsToRelease (false),
  31568. needsRepainting (false),
  31569. isKeyDown (false),
  31570. triggerOnMouseDown (false),
  31571. generateTooltip (false)
  31572. {
  31573. setWantsKeyboardFocus (true);
  31574. }
  31575. Button::~Button()
  31576. {
  31577. if (commandManagerToUse != 0)
  31578. commandManagerToUse->removeListener (this);
  31579. delete repeatTimer;
  31580. clearShortcuts();
  31581. }
  31582. void Button::setButtonText (const String& newText) throw()
  31583. {
  31584. if (text != newText)
  31585. {
  31586. text = newText;
  31587. repaint();
  31588. }
  31589. }
  31590. void Button::setTooltip (const String& newTooltip)
  31591. {
  31592. SettableTooltipClient::setTooltip (newTooltip);
  31593. generateTooltip = false;
  31594. }
  31595. const String Button::getTooltip()
  31596. {
  31597. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  31598. {
  31599. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  31600. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  31601. for (int i = 0; i < keyPresses.size(); ++i)
  31602. {
  31603. const String key (keyPresses.getReference(i).getTextDescription());
  31604. if (key.length() == 1)
  31605. tt << " [shortcut: '" << key << "']";
  31606. else
  31607. tt << " [" << key << ']';
  31608. }
  31609. return tt;
  31610. }
  31611. return SettableTooltipClient::getTooltip();
  31612. }
  31613. void Button::setConnectedEdges (const int connectedEdgeFlags_) throw()
  31614. {
  31615. if (connectedEdgeFlags != connectedEdgeFlags_)
  31616. {
  31617. connectedEdgeFlags = connectedEdgeFlags_;
  31618. repaint();
  31619. }
  31620. }
  31621. void Button::setToggleState (const bool shouldBeOn,
  31622. const bool sendChangeNotification)
  31623. {
  31624. if (shouldBeOn != isOn)
  31625. {
  31626. const ComponentDeletionWatcher deletionWatcher (this);
  31627. isOn = shouldBeOn;
  31628. repaint();
  31629. if (sendChangeNotification)
  31630. sendClickMessage (ModifierKeys());
  31631. if ((! deletionWatcher.hasBeenDeleted()) && isOn)
  31632. turnOffOtherButtonsInGroup (sendChangeNotification);
  31633. }
  31634. }
  31635. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  31636. {
  31637. clickTogglesState = shouldToggle;
  31638. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  31639. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  31640. // it is that this button represents, and the button will update its state to reflect this
  31641. // in the applicationCommandListChanged() method.
  31642. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  31643. }
  31644. bool Button::getClickingTogglesState() const throw()
  31645. {
  31646. return clickTogglesState;
  31647. }
  31648. void Button::setRadioGroupId (const int newGroupId)
  31649. {
  31650. if (radioGroupId != newGroupId)
  31651. {
  31652. radioGroupId = newGroupId;
  31653. if (isOn)
  31654. turnOffOtherButtonsInGroup (true);
  31655. }
  31656. }
  31657. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  31658. {
  31659. Component* const p = getParentComponent();
  31660. if (p != 0 && radioGroupId != 0)
  31661. {
  31662. const ComponentDeletionWatcher deletionWatcher (this);
  31663. for (int i = p->getNumChildComponents(); --i >= 0;)
  31664. {
  31665. Component* const c = p->getChildComponent (i);
  31666. if (c != this)
  31667. {
  31668. Button* const b = dynamic_cast <Button*> (c);
  31669. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  31670. {
  31671. b->setToggleState (false, sendChangeNotification);
  31672. if (deletionWatcher.hasBeenDeleted())
  31673. return;
  31674. }
  31675. }
  31676. }
  31677. }
  31678. }
  31679. void Button::enablementChanged()
  31680. {
  31681. updateState (0);
  31682. repaint();
  31683. }
  31684. Button::ButtonState Button::updateState (const MouseEvent* const e) throw()
  31685. {
  31686. ButtonState state = buttonNormal;
  31687. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  31688. {
  31689. int mx, my;
  31690. if (e == 0)
  31691. {
  31692. getMouseXYRelative (mx, my);
  31693. }
  31694. else
  31695. {
  31696. const MouseEvent e2 (e->getEventRelativeTo (this));
  31697. mx = e2.x;
  31698. my = e2.y;
  31699. }
  31700. const bool over = reallyContains (mx, my, true);
  31701. const bool down = isMouseButtonDown();
  31702. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  31703. state = buttonDown;
  31704. else if (over)
  31705. state = buttonOver;
  31706. }
  31707. setState (state);
  31708. return state;
  31709. }
  31710. void Button::setState (const ButtonState newState)
  31711. {
  31712. if (buttonState != newState)
  31713. {
  31714. buttonState = newState;
  31715. repaint();
  31716. if (buttonState == buttonDown)
  31717. {
  31718. buttonPressTime = Time::getApproximateMillisecondCounter();
  31719. lastTimeCallbackTime = buttonPressTime;
  31720. }
  31721. sendStateMessage();
  31722. }
  31723. }
  31724. bool Button::isDown() const throw()
  31725. {
  31726. return buttonState == buttonDown;
  31727. }
  31728. bool Button::isOver() const throw()
  31729. {
  31730. return buttonState != buttonNormal;
  31731. }
  31732. void Button::buttonStateChanged()
  31733. {
  31734. }
  31735. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  31736. {
  31737. const uint32 now = Time::getApproximateMillisecondCounter();
  31738. return now > buttonPressTime ? now - buttonPressTime : 0;
  31739. }
  31740. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  31741. {
  31742. triggerOnMouseDown = isTriggeredOnMouseDown;
  31743. }
  31744. void Button::clicked()
  31745. {
  31746. }
  31747. void Button::clicked (const ModifierKeys& /*modifiers*/)
  31748. {
  31749. clicked();
  31750. }
  31751. static const int clickMessageId = 0x2f3f4f99;
  31752. void Button::triggerClick()
  31753. {
  31754. postCommandMessage (clickMessageId);
  31755. }
  31756. void Button::internalClickCallback (const ModifierKeys& modifiers)
  31757. {
  31758. if (clickTogglesState)
  31759. setToggleState ((radioGroupId != 0) || ! isOn, false);
  31760. sendClickMessage (modifiers);
  31761. }
  31762. void Button::flashButtonState() throw()
  31763. {
  31764. if (isEnabled())
  31765. {
  31766. needsToRelease = true;
  31767. setState (buttonDown);
  31768. getRepeatTimer().startTimer (100);
  31769. }
  31770. }
  31771. void Button::handleCommandMessage (int commandId)
  31772. {
  31773. if (commandId == clickMessageId)
  31774. {
  31775. if (isEnabled())
  31776. {
  31777. flashButtonState();
  31778. internalClickCallback (ModifierKeys::getCurrentModifiers());
  31779. }
  31780. }
  31781. else
  31782. {
  31783. Component::handleCommandMessage (commandId);
  31784. }
  31785. }
  31786. void Button::addButtonListener (ButtonListener* const newListener) throw()
  31787. {
  31788. jassert (newListener != 0);
  31789. jassert (! buttonListeners.contains (newListener)); // trying to add a listener to the list twice!
  31790. if (newListener != 0)
  31791. buttonListeners.add (newListener);
  31792. }
  31793. void Button::removeButtonListener (ButtonListener* const listener) throw()
  31794. {
  31795. jassert (buttonListeners.contains (listener)); // trying to remove a listener that isn't on the list!
  31796. buttonListeners.removeValue (listener);
  31797. }
  31798. void Button::sendClickMessage (const ModifierKeys& modifiers)
  31799. {
  31800. const ComponentDeletionWatcher cdw (this);
  31801. if (commandManagerToUse != 0 && commandID != 0)
  31802. {
  31803. ApplicationCommandTarget::InvocationInfo info (commandID);
  31804. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  31805. info.originatingComponent = this;
  31806. commandManagerToUse->invoke (info, true);
  31807. }
  31808. clicked (modifiers);
  31809. if (! cdw.hasBeenDeleted())
  31810. {
  31811. for (int i = buttonListeners.size(); --i >= 0;)
  31812. {
  31813. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  31814. if (bl != 0)
  31815. {
  31816. bl->buttonClicked (this);
  31817. if (cdw.hasBeenDeleted())
  31818. return;
  31819. }
  31820. }
  31821. }
  31822. }
  31823. void Button::sendStateMessage()
  31824. {
  31825. const ComponentDeletionWatcher cdw (this);
  31826. buttonStateChanged();
  31827. if (cdw.hasBeenDeleted())
  31828. return;
  31829. for (int i = buttonListeners.size(); --i >= 0;)
  31830. {
  31831. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  31832. if (bl != 0)
  31833. {
  31834. bl->buttonStateChanged (this);
  31835. if (cdw.hasBeenDeleted())
  31836. return;
  31837. }
  31838. }
  31839. }
  31840. void Button::paint (Graphics& g)
  31841. {
  31842. if (needsToRelease && isEnabled())
  31843. {
  31844. needsToRelease = false;
  31845. needsRepainting = true;
  31846. }
  31847. paintButton (g, isOver(), isDown());
  31848. }
  31849. void Button::mouseEnter (const MouseEvent& e)
  31850. {
  31851. updateState (&e);
  31852. }
  31853. void Button::mouseExit (const MouseEvent& e)
  31854. {
  31855. updateState (&e);
  31856. }
  31857. void Button::mouseDown (const MouseEvent& e)
  31858. {
  31859. updateState (&e);
  31860. if (isDown())
  31861. {
  31862. if (autoRepeatDelay >= 0)
  31863. getRepeatTimer().startTimer (autoRepeatDelay);
  31864. if (triggerOnMouseDown)
  31865. internalClickCallback (e.mods);
  31866. }
  31867. }
  31868. void Button::mouseUp (const MouseEvent& e)
  31869. {
  31870. const bool wasDown = isDown();
  31871. updateState (&e);
  31872. if (wasDown && isOver() && ! triggerOnMouseDown)
  31873. internalClickCallback (e.mods);
  31874. }
  31875. void Button::mouseDrag (const MouseEvent& e)
  31876. {
  31877. const ButtonState oldState = buttonState;
  31878. updateState (&e);
  31879. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  31880. getRepeatTimer().startTimer (autoRepeatSpeed);
  31881. }
  31882. void Button::focusGained (FocusChangeType)
  31883. {
  31884. updateState (0);
  31885. repaint();
  31886. }
  31887. void Button::focusLost (FocusChangeType)
  31888. {
  31889. updateState (0);
  31890. repaint();
  31891. }
  31892. void Button::setVisible (bool shouldBeVisible)
  31893. {
  31894. if (shouldBeVisible != isVisible())
  31895. {
  31896. Component::setVisible (shouldBeVisible);
  31897. if (! shouldBeVisible)
  31898. needsToRelease = false;
  31899. updateState (0);
  31900. }
  31901. else
  31902. {
  31903. Component::setVisible (shouldBeVisible);
  31904. }
  31905. }
  31906. void Button::parentHierarchyChanged()
  31907. {
  31908. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  31909. if (newKeySource != keySource)
  31910. {
  31911. if (keySource->isValidComponent())
  31912. keySource->removeKeyListener (this);
  31913. keySource = newKeySource;
  31914. if (keySource->isValidComponent())
  31915. keySource->addKeyListener (this);
  31916. }
  31917. }
  31918. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  31919. const int commandID_,
  31920. const bool generateTooltip_)
  31921. {
  31922. commandID = commandID_;
  31923. generateTooltip = generateTooltip_;
  31924. if (commandManagerToUse != commandManagerToUse_)
  31925. {
  31926. if (commandManagerToUse != 0)
  31927. commandManagerToUse->removeListener (this);
  31928. commandManagerToUse = commandManagerToUse_;
  31929. if (commandManagerToUse != 0)
  31930. commandManagerToUse->addListener (this);
  31931. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  31932. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  31933. // it is that this button represents, and the button will update its state to reflect this
  31934. // in the applicationCommandListChanged() method.
  31935. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  31936. }
  31937. if (commandManagerToUse != 0)
  31938. applicationCommandListChanged();
  31939. else
  31940. setEnabled (true);
  31941. }
  31942. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  31943. {
  31944. if (info.commandID == commandID
  31945. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  31946. {
  31947. flashButtonState();
  31948. }
  31949. }
  31950. void Button::applicationCommandListChanged()
  31951. {
  31952. if (commandManagerToUse != 0)
  31953. {
  31954. ApplicationCommandInfo info (0);
  31955. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  31956. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  31957. if (target != 0)
  31958. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  31959. }
  31960. }
  31961. void Button::addShortcut (const KeyPress& key)
  31962. {
  31963. if (key.isValid())
  31964. {
  31965. jassert (! isRegisteredForShortcut (key)); // already registered!
  31966. shortcuts.add (key);
  31967. parentHierarchyChanged();
  31968. }
  31969. }
  31970. void Button::clearShortcuts()
  31971. {
  31972. shortcuts.clear();
  31973. parentHierarchyChanged();
  31974. }
  31975. bool Button::isShortcutPressed() const throw()
  31976. {
  31977. if (! isCurrentlyBlockedByAnotherModalComponent())
  31978. {
  31979. for (int i = shortcuts.size(); --i >= 0;)
  31980. if (shortcuts.getReference(i).isCurrentlyDown())
  31981. return true;
  31982. }
  31983. return false;
  31984. }
  31985. bool Button::isRegisteredForShortcut (const KeyPress& key) const throw()
  31986. {
  31987. for (int i = shortcuts.size(); --i >= 0;)
  31988. if (key == shortcuts.getReference(i))
  31989. return true;
  31990. return false;
  31991. }
  31992. bool Button::keyStateChanged (Component*)
  31993. {
  31994. if (! isEnabled())
  31995. return false;
  31996. const bool wasDown = isKeyDown;
  31997. isKeyDown = isShortcutPressed();
  31998. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  31999. getRepeatTimer().startTimer (autoRepeatDelay);
  32000. updateState (0);
  32001. if (isEnabled() && wasDown && ! isKeyDown)
  32002. internalClickCallback (ModifierKeys::getCurrentModifiers());
  32003. return isKeyDown || wasDown;
  32004. }
  32005. bool Button::keyPressed (const KeyPress&, Component*)
  32006. {
  32007. // returning true will avoid forwarding events for keys that we're using as shortcuts
  32008. return isShortcutPressed();
  32009. }
  32010. bool Button::keyPressed (const KeyPress& key)
  32011. {
  32012. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  32013. {
  32014. triggerClick();
  32015. return true;
  32016. }
  32017. return false;
  32018. }
  32019. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  32020. const int repeatMillisecs,
  32021. const int minimumDelayInMillisecs) throw()
  32022. {
  32023. autoRepeatDelay = initialDelayMillisecs;
  32024. autoRepeatSpeed = repeatMillisecs;
  32025. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  32026. }
  32027. void Button::repeatTimerCallback() throw()
  32028. {
  32029. if (needsRepainting)
  32030. {
  32031. getRepeatTimer().stopTimer();
  32032. updateState (0);
  32033. needsRepainting = false;
  32034. }
  32035. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  32036. {
  32037. int repeatSpeed = autoRepeatSpeed;
  32038. if (autoRepeatMinimumDelay >= 0)
  32039. {
  32040. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  32041. timeHeldDown *= timeHeldDown;
  32042. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  32043. }
  32044. repeatSpeed = jmax (1, repeatSpeed);
  32045. getRepeatTimer().startTimer (repeatSpeed);
  32046. const uint32 now = Time::getApproximateMillisecondCounter();
  32047. const int numTimesToCallback
  32048. = (now > lastTimeCallbackTime) ? jmax (1, (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  32049. lastTimeCallbackTime = now;
  32050. const ComponentDeletionWatcher cdw (this);
  32051. for (int i = numTimesToCallback; --i >= 0;)
  32052. {
  32053. internalClickCallback (ModifierKeys::getCurrentModifiers());
  32054. if (cdw.hasBeenDeleted() || ! isDown())
  32055. return;
  32056. }
  32057. }
  32058. else if (! needsToRelease)
  32059. {
  32060. getRepeatTimer().stopTimer();
  32061. }
  32062. }
  32063. class InternalButtonRepeatTimer : public Timer
  32064. {
  32065. public:
  32066. InternalButtonRepeatTimer (Button& owner_) throw()
  32067. : owner (owner_)
  32068. {
  32069. }
  32070. ~InternalButtonRepeatTimer()
  32071. {
  32072. }
  32073. void timerCallback()
  32074. {
  32075. owner.repeatTimerCallback();
  32076. }
  32077. private:
  32078. Button& owner;
  32079. InternalButtonRepeatTimer (const InternalButtonRepeatTimer&);
  32080. const InternalButtonRepeatTimer& operator= (const InternalButtonRepeatTimer&);
  32081. };
  32082. Timer& Button::getRepeatTimer() throw()
  32083. {
  32084. if (repeatTimer == 0)
  32085. repeatTimer = new InternalButtonRepeatTimer (*this);
  32086. return *repeatTimer;
  32087. }
  32088. END_JUCE_NAMESPACE
  32089. /********* End of inlined file: juce_Button.cpp *********/
  32090. /********* Start of inlined file: juce_DrawableButton.cpp *********/
  32091. BEGIN_JUCE_NAMESPACE
  32092. DrawableButton::DrawableButton (const String& name,
  32093. const DrawableButton::ButtonStyle buttonStyle)
  32094. : Button (name),
  32095. style (buttonStyle),
  32096. normalImage (0),
  32097. overImage (0),
  32098. downImage (0),
  32099. disabledImage (0),
  32100. normalImageOn (0),
  32101. overImageOn (0),
  32102. downImageOn (0),
  32103. disabledImageOn (0),
  32104. edgeIndent (3)
  32105. {
  32106. if (buttonStyle == ImageOnButtonBackground)
  32107. {
  32108. backgroundOff = Colour (0xffbbbbff);
  32109. backgroundOn = Colour (0xff3333ff);
  32110. }
  32111. else
  32112. {
  32113. backgroundOff = Colours::transparentBlack;
  32114. backgroundOn = Colour (0xaabbbbff);
  32115. }
  32116. }
  32117. DrawableButton::~DrawableButton()
  32118. {
  32119. deleteImages();
  32120. }
  32121. void DrawableButton::deleteImages()
  32122. {
  32123. deleteAndZero (normalImage);
  32124. deleteAndZero (overImage);
  32125. deleteAndZero (downImage);
  32126. deleteAndZero (disabledImage);
  32127. deleteAndZero (normalImageOn);
  32128. deleteAndZero (overImageOn);
  32129. deleteAndZero (downImageOn);
  32130. deleteAndZero (disabledImageOn);
  32131. }
  32132. void DrawableButton::setImages (const Drawable* normal,
  32133. const Drawable* over,
  32134. const Drawable* down,
  32135. const Drawable* disabled,
  32136. const Drawable* normalOn,
  32137. const Drawable* overOn,
  32138. const Drawable* downOn,
  32139. const Drawable* disabledOn)
  32140. {
  32141. deleteImages();
  32142. jassert (normal != 0); // you really need to give it at least a normal image..
  32143. if (normal != 0)
  32144. normalImage = normal->createCopy();
  32145. if (over != 0)
  32146. overImage = over->createCopy();
  32147. if (down != 0)
  32148. downImage = down->createCopy();
  32149. if (disabled != 0)
  32150. disabledImage = disabled->createCopy();
  32151. if (normalOn != 0)
  32152. normalImageOn = normalOn->createCopy();
  32153. if (overOn != 0)
  32154. overImageOn = overOn->createCopy();
  32155. if (downOn != 0)
  32156. downImageOn = downOn->createCopy();
  32157. if (disabledOn != 0)
  32158. disabledImageOn = disabledOn->createCopy();
  32159. repaint();
  32160. }
  32161. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  32162. {
  32163. if (style != newStyle)
  32164. {
  32165. style = newStyle;
  32166. repaint();
  32167. }
  32168. }
  32169. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  32170. const Colour& toggledOnColour)
  32171. {
  32172. if (backgroundOff != toggledOffColour
  32173. || backgroundOn != toggledOnColour)
  32174. {
  32175. backgroundOff = toggledOffColour;
  32176. backgroundOn = toggledOnColour;
  32177. repaint();
  32178. }
  32179. }
  32180. const Colour& DrawableButton::getBackgroundColour() const throw()
  32181. {
  32182. return getToggleState() ? backgroundOn
  32183. : backgroundOff;
  32184. }
  32185. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  32186. {
  32187. edgeIndent = numPixelsIndent;
  32188. repaint();
  32189. }
  32190. void DrawableButton::paintButton (Graphics& g,
  32191. bool isMouseOverButton,
  32192. bool isButtonDown)
  32193. {
  32194. Rectangle imageSpace;
  32195. if (style == ImageOnButtonBackground)
  32196. {
  32197. const int insetX = getWidth() / 4;
  32198. const int insetY = getHeight() / 4;
  32199. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  32200. getLookAndFeel().drawButtonBackground (g, *this,
  32201. getBackgroundColour(),
  32202. isMouseOverButton,
  32203. isButtonDown);
  32204. }
  32205. else
  32206. {
  32207. g.fillAll (getBackgroundColour());
  32208. const int textH = (style == ImageAboveTextLabel)
  32209. ? jmin (16, proportionOfHeight (0.25f))
  32210. : 0;
  32211. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  32212. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  32213. imageSpace.setBounds (indentX, indentY,
  32214. getWidth() - indentX * 2,
  32215. getHeight() - indentY * 2 - textH);
  32216. if (textH > 0)
  32217. {
  32218. g.setFont ((float) textH);
  32219. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  32220. g.drawFittedText (getName(),
  32221. 2, getHeight() - textH - 1,
  32222. getWidth() - 4, textH,
  32223. Justification::centred, 1);
  32224. }
  32225. }
  32226. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  32227. g.setOpacity (1.0f);
  32228. const Drawable* imageToDraw = 0;
  32229. if (isEnabled())
  32230. {
  32231. imageToDraw = getCurrentImage();
  32232. }
  32233. else
  32234. {
  32235. imageToDraw = getToggleState() ? disabledImageOn
  32236. : disabledImage;
  32237. if (imageToDraw == 0)
  32238. {
  32239. g.setOpacity (0.4f);
  32240. imageToDraw = getNormalImage();
  32241. }
  32242. }
  32243. if (imageToDraw != 0)
  32244. {
  32245. if (style == ImageRaw)
  32246. {
  32247. imageToDraw->draw (g);
  32248. }
  32249. else
  32250. {
  32251. imageToDraw->drawWithin (g,
  32252. imageSpace.getX(),
  32253. imageSpace.getY(),
  32254. imageSpace.getWidth(),
  32255. imageSpace.getHeight(),
  32256. RectanglePlacement::centred);
  32257. }
  32258. }
  32259. }
  32260. const Drawable* DrawableButton::getCurrentImage() const throw()
  32261. {
  32262. if (isDown())
  32263. return getDownImage();
  32264. if (isOver())
  32265. return getOverImage();
  32266. return getNormalImage();
  32267. }
  32268. const Drawable* DrawableButton::getNormalImage() const throw()
  32269. {
  32270. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  32271. : normalImage;
  32272. }
  32273. const Drawable* DrawableButton::getOverImage() const throw()
  32274. {
  32275. const Drawable* d = normalImage;
  32276. if (getToggleState())
  32277. {
  32278. if (overImageOn != 0)
  32279. d = overImageOn;
  32280. else if (normalImageOn != 0)
  32281. d = normalImageOn;
  32282. else if (overImage != 0)
  32283. d = overImage;
  32284. }
  32285. else
  32286. {
  32287. if (overImage != 0)
  32288. d = overImage;
  32289. }
  32290. return d;
  32291. }
  32292. const Drawable* DrawableButton::getDownImage() const throw()
  32293. {
  32294. const Drawable* d = normalImage;
  32295. if (getToggleState())
  32296. {
  32297. if (downImageOn != 0)
  32298. d = downImageOn;
  32299. else if (overImageOn != 0)
  32300. d = overImageOn;
  32301. else if (normalImageOn != 0)
  32302. d = normalImageOn;
  32303. else if (downImage != 0)
  32304. d = downImage;
  32305. else
  32306. d = getOverImage();
  32307. }
  32308. else
  32309. {
  32310. if (downImage != 0)
  32311. d = downImage;
  32312. else
  32313. d = getOverImage();
  32314. }
  32315. return d;
  32316. }
  32317. END_JUCE_NAMESPACE
  32318. /********* End of inlined file: juce_DrawableButton.cpp *********/
  32319. /********* Start of inlined file: juce_HyperlinkButton.cpp *********/
  32320. BEGIN_JUCE_NAMESPACE
  32321. HyperlinkButton::HyperlinkButton (const String& linkText,
  32322. const URL& linkURL)
  32323. : Button (linkText),
  32324. url (linkURL),
  32325. font (14.0f, Font::underlined),
  32326. resizeFont (true),
  32327. justification (Justification::centred)
  32328. {
  32329. setMouseCursor (MouseCursor::PointingHandCursor);
  32330. setTooltip (linkURL.toString (false));
  32331. }
  32332. HyperlinkButton::~HyperlinkButton()
  32333. {
  32334. }
  32335. void HyperlinkButton::setFont (const Font& newFont,
  32336. const bool resizeToMatchComponentHeight,
  32337. const Justification& justificationType)
  32338. {
  32339. font = newFont;
  32340. resizeFont = resizeToMatchComponentHeight;
  32341. justification = justificationType;
  32342. repaint();
  32343. }
  32344. void HyperlinkButton::setURL (const URL& newURL) throw()
  32345. {
  32346. url = newURL;
  32347. setTooltip (newURL.toString (false));
  32348. }
  32349. const Font HyperlinkButton::getFontToUse() const
  32350. {
  32351. Font f (font);
  32352. if (resizeFont)
  32353. f.setHeight (getHeight() * 0.7f);
  32354. return f;
  32355. }
  32356. void HyperlinkButton::changeWidthToFitText()
  32357. {
  32358. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  32359. }
  32360. void HyperlinkButton::colourChanged()
  32361. {
  32362. repaint();
  32363. }
  32364. void HyperlinkButton::clicked()
  32365. {
  32366. if (url.isWellFormed())
  32367. url.launchInDefaultBrowser();
  32368. }
  32369. void HyperlinkButton::paintButton (Graphics& g,
  32370. bool isMouseOverButton,
  32371. bool isButtonDown)
  32372. {
  32373. const Colour textColour (findColour (textColourId));
  32374. if (isEnabled())
  32375. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  32376. : textColour);
  32377. else
  32378. g.setColour (textColour.withMultipliedAlpha (0.4f));
  32379. g.setFont (getFontToUse());
  32380. g.drawText (getButtonText(),
  32381. 2, 0, getWidth() - 2, getHeight(),
  32382. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  32383. true);
  32384. }
  32385. END_JUCE_NAMESPACE
  32386. /********* End of inlined file: juce_HyperlinkButton.cpp *********/
  32387. /********* Start of inlined file: juce_ImageButton.cpp *********/
  32388. BEGIN_JUCE_NAMESPACE
  32389. ImageButton::ImageButton (const String& text)
  32390. : Button (text),
  32391. scaleImageToFit (true),
  32392. preserveProportions (true),
  32393. alphaThreshold (0),
  32394. imageX (0),
  32395. imageY (0),
  32396. imageW (0),
  32397. imageH (0),
  32398. normalImage (0),
  32399. overImage (0),
  32400. downImage (0)
  32401. {
  32402. }
  32403. ImageButton::~ImageButton()
  32404. {
  32405. deleteImages();
  32406. }
  32407. void ImageButton::deleteImages()
  32408. {
  32409. if (normalImage != 0)
  32410. {
  32411. if (ImageCache::isImageInCache (normalImage))
  32412. ImageCache::release (normalImage);
  32413. else
  32414. delete normalImage;
  32415. }
  32416. if (overImage != 0)
  32417. {
  32418. if (ImageCache::isImageInCache (overImage))
  32419. ImageCache::release (overImage);
  32420. else
  32421. delete overImage;
  32422. }
  32423. if (downImage != 0)
  32424. {
  32425. if (ImageCache::isImageInCache (downImage))
  32426. ImageCache::release (downImage);
  32427. else
  32428. delete downImage;
  32429. }
  32430. }
  32431. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  32432. const bool rescaleImagesWhenButtonSizeChanges,
  32433. const bool preserveImageProportions,
  32434. Image* const normalImage_,
  32435. const float imageOpacityWhenNormal,
  32436. const Colour& overlayColourWhenNormal,
  32437. Image* const overImage_,
  32438. const float imageOpacityWhenOver,
  32439. const Colour& overlayColourWhenOver,
  32440. Image* const downImage_,
  32441. const float imageOpacityWhenDown,
  32442. const Colour& overlayColourWhenDown,
  32443. const float hitTestAlphaThreshold)
  32444. {
  32445. deleteImages();
  32446. normalImage = normalImage_;
  32447. overImage = overImage_;
  32448. downImage = downImage_;
  32449. if (resizeButtonNowToFitThisImage && normalImage != 0)
  32450. {
  32451. imageW = normalImage->getWidth();
  32452. imageH = normalImage->getHeight();
  32453. setSize (imageW, imageH);
  32454. }
  32455. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  32456. preserveProportions = preserveImageProportions;
  32457. normalOpacity = imageOpacityWhenNormal;
  32458. normalOverlay = overlayColourWhenNormal;
  32459. overOpacity = imageOpacityWhenOver;
  32460. overOverlay = overlayColourWhenOver;
  32461. downOpacity = imageOpacityWhenDown;
  32462. downOverlay = overlayColourWhenDown;
  32463. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundFloatToInt (255.0f * hitTestAlphaThreshold));
  32464. repaint();
  32465. }
  32466. Image* ImageButton::getCurrentImage() const
  32467. {
  32468. if (isDown())
  32469. return getDownImage();
  32470. if (isOver())
  32471. return getOverImage();
  32472. return getNormalImage();
  32473. }
  32474. Image* ImageButton::getNormalImage() const throw()
  32475. {
  32476. return normalImage;
  32477. }
  32478. Image* ImageButton::getOverImage() const throw()
  32479. {
  32480. return (overImage != 0) ? overImage
  32481. : normalImage;
  32482. }
  32483. Image* ImageButton::getDownImage() const throw()
  32484. {
  32485. return (downImage != 0) ? downImage
  32486. : getOverImage();
  32487. }
  32488. void ImageButton::paintButton (Graphics& g,
  32489. bool isMouseOverButton,
  32490. bool isButtonDown)
  32491. {
  32492. if (! isEnabled())
  32493. {
  32494. isMouseOverButton = false;
  32495. isButtonDown = false;
  32496. }
  32497. Image* const im = getCurrentImage();
  32498. if (im != 0)
  32499. {
  32500. const int iw = im->getWidth();
  32501. const int ih = im->getHeight();
  32502. imageW = getWidth();
  32503. imageH = getHeight();
  32504. imageX = (imageW - iw) >> 1;
  32505. imageY = (imageH - ih) >> 1;
  32506. if (scaleImageToFit)
  32507. {
  32508. if (preserveProportions)
  32509. {
  32510. int newW, newH;
  32511. const float imRatio = ih / (float)iw;
  32512. const float destRatio = imageH / (float)imageW;
  32513. if (imRatio > destRatio)
  32514. {
  32515. newW = roundFloatToInt (imageH / imRatio);
  32516. newH = imageH;
  32517. }
  32518. else
  32519. {
  32520. newW = imageW;
  32521. newH = roundFloatToInt (imageW * imRatio);
  32522. }
  32523. imageX = (imageW - newW) / 2;
  32524. imageY = (imageH - newH) / 2;
  32525. imageW = newW;
  32526. imageH = newH;
  32527. }
  32528. else
  32529. {
  32530. imageX = 0;
  32531. imageY = 0;
  32532. }
  32533. }
  32534. const Colour& overlayColour = (isButtonDown) ? downOverlay
  32535. : ((isMouseOverButton) ? overOverlay
  32536. : normalOverlay);
  32537. if (! overlayColour.isOpaque())
  32538. {
  32539. g.setOpacity ((isButtonDown) ? downOpacity
  32540. : ((isMouseOverButton) ? overOpacity
  32541. : normalOpacity));
  32542. if (scaleImageToFit)
  32543. g.drawImage (im, imageX, imageY, imageW, imageH, 0, 0, iw, ih, false);
  32544. else
  32545. g.drawImageAt (im, imageX, imageY, false);
  32546. }
  32547. if (! overlayColour.isTransparent())
  32548. {
  32549. g.setColour (overlayColour);
  32550. if (scaleImageToFit)
  32551. g.drawImage (im, imageX, imageY, imageW, imageH, 0, 0, iw, ih, true);
  32552. else
  32553. g.drawImageAt (im, imageX, imageY, true);
  32554. }
  32555. }
  32556. }
  32557. bool ImageButton::hitTest (int x, int y)
  32558. {
  32559. if (alphaThreshold == 0)
  32560. return true;
  32561. Image* const im = getCurrentImage();
  32562. return im == 0
  32563. || (imageW > 0 && imageH > 0
  32564. && alphaThreshold < im->getPixelAt (((x - imageX) * im->getWidth()) / imageW,
  32565. ((y - imageY) * im->getHeight()) / imageH).getAlpha());
  32566. }
  32567. END_JUCE_NAMESPACE
  32568. /********* End of inlined file: juce_ImageButton.cpp *********/
  32569. /********* Start of inlined file: juce_ShapeButton.cpp *********/
  32570. BEGIN_JUCE_NAMESPACE
  32571. ShapeButton::ShapeButton (const String& text,
  32572. const Colour& normalColour_,
  32573. const Colour& overColour_,
  32574. const Colour& downColour_)
  32575. : Button (text),
  32576. normalColour (normalColour_),
  32577. overColour (overColour_),
  32578. downColour (downColour_),
  32579. maintainShapeProportions (false),
  32580. outlineWidth (0.0f)
  32581. {
  32582. }
  32583. ShapeButton::~ShapeButton()
  32584. {
  32585. }
  32586. void ShapeButton::setColours (const Colour& newNormalColour,
  32587. const Colour& newOverColour,
  32588. const Colour& newDownColour)
  32589. {
  32590. normalColour = newNormalColour;
  32591. overColour = newOverColour;
  32592. downColour = newDownColour;
  32593. }
  32594. void ShapeButton::setOutline (const Colour& newOutlineColour,
  32595. const float newOutlineWidth)
  32596. {
  32597. outlineColour = newOutlineColour;
  32598. outlineWidth = newOutlineWidth;
  32599. }
  32600. void ShapeButton::setShape (const Path& newShape,
  32601. const bool resizeNowToFitThisShape,
  32602. const bool maintainShapeProportions_,
  32603. const bool hasShadow)
  32604. {
  32605. shape = newShape;
  32606. maintainShapeProportions = maintainShapeProportions_;
  32607. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  32608. setComponentEffect ((hasShadow) ? &shadow : 0);
  32609. if (resizeNowToFitThisShape)
  32610. {
  32611. float x, y, w, h;
  32612. shape.getBounds (x, y, w, h);
  32613. shape.applyTransform (AffineTransform::translation (-x, -y));
  32614. if (hasShadow)
  32615. {
  32616. w += 4.0f;
  32617. h += 4.0f;
  32618. shape.applyTransform (AffineTransform::translation (2.0f, 2.0f));
  32619. }
  32620. setSize (1 + (int) (w + outlineWidth),
  32621. 1 + (int) (h + outlineWidth));
  32622. }
  32623. }
  32624. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  32625. {
  32626. if (! isEnabled())
  32627. {
  32628. isMouseOverButton = false;
  32629. isButtonDown = false;
  32630. }
  32631. g.setColour ((isButtonDown) ? downColour
  32632. : (isMouseOverButton) ? overColour
  32633. : normalColour);
  32634. int w = getWidth();
  32635. int h = getHeight();
  32636. if (getComponentEffect() != 0)
  32637. {
  32638. w -= 4;
  32639. h -= 4;
  32640. }
  32641. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  32642. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  32643. w - offset - outlineWidth,
  32644. h - offset - outlineWidth,
  32645. maintainShapeProportions));
  32646. g.fillPath (shape, trans);
  32647. if (outlineWidth > 0.0f)
  32648. {
  32649. g.setColour (outlineColour);
  32650. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  32651. }
  32652. }
  32653. END_JUCE_NAMESPACE
  32654. /********* End of inlined file: juce_ShapeButton.cpp *********/
  32655. /********* Start of inlined file: juce_TextButton.cpp *********/
  32656. BEGIN_JUCE_NAMESPACE
  32657. TextButton::TextButton (const String& name,
  32658. const String& toolTip)
  32659. : Button (name)
  32660. {
  32661. setTooltip (toolTip);
  32662. }
  32663. TextButton::~TextButton()
  32664. {
  32665. }
  32666. void TextButton::paintButton (Graphics& g,
  32667. bool isMouseOverButton,
  32668. bool isButtonDown)
  32669. {
  32670. getLookAndFeel().drawButtonBackground (g, *this,
  32671. findColour (getToggleState() ? buttonOnColourId
  32672. : buttonColourId),
  32673. isMouseOverButton,
  32674. isButtonDown);
  32675. getLookAndFeel().drawButtonText (g, *this,
  32676. isMouseOverButton,
  32677. isButtonDown);
  32678. }
  32679. void TextButton::colourChanged()
  32680. {
  32681. repaint();
  32682. }
  32683. const Font TextButton::getFont()
  32684. {
  32685. return Font (jmin (15.0f, getHeight() * 0.6f));
  32686. }
  32687. void TextButton::changeWidthToFitText (const int newHeight)
  32688. {
  32689. if (newHeight >= 0)
  32690. setSize (jmax (1, getWidth()), newHeight);
  32691. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  32692. getHeight());
  32693. }
  32694. END_JUCE_NAMESPACE
  32695. /********* End of inlined file: juce_TextButton.cpp *********/
  32696. /********* Start of inlined file: juce_ToggleButton.cpp *********/
  32697. BEGIN_JUCE_NAMESPACE
  32698. ToggleButton::ToggleButton (const String& buttonText)
  32699. : Button (buttonText)
  32700. {
  32701. setClickingTogglesState (true);
  32702. }
  32703. ToggleButton::~ToggleButton()
  32704. {
  32705. }
  32706. void ToggleButton::paintButton (Graphics& g,
  32707. bool isMouseOverButton,
  32708. bool isButtonDown)
  32709. {
  32710. getLookAndFeel().drawToggleButton (g, *this,
  32711. isMouseOverButton,
  32712. isButtonDown);
  32713. }
  32714. void ToggleButton::changeWidthToFitText()
  32715. {
  32716. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  32717. }
  32718. void ToggleButton::colourChanged()
  32719. {
  32720. repaint();
  32721. }
  32722. END_JUCE_NAMESPACE
  32723. /********* End of inlined file: juce_ToggleButton.cpp *********/
  32724. /********* Start of inlined file: juce_ToolbarButton.cpp *********/
  32725. BEGIN_JUCE_NAMESPACE
  32726. ToolbarButton::ToolbarButton (const int itemId,
  32727. const String& buttonText,
  32728. Drawable* const normalImage_,
  32729. Drawable* const toggledOnImage_)
  32730. : ToolbarItemComponent (itemId, buttonText, true),
  32731. normalImage (normalImage_),
  32732. toggledOnImage (toggledOnImage_)
  32733. {
  32734. }
  32735. ToolbarButton::~ToolbarButton()
  32736. {
  32737. delete normalImage;
  32738. delete toggledOnImage;
  32739. }
  32740. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  32741. bool /*isToolbarVertical*/,
  32742. int& preferredSize,
  32743. int& minSize, int& maxSize)
  32744. {
  32745. preferredSize = minSize = maxSize = toolbarDepth;
  32746. return true;
  32747. }
  32748. void ToolbarButton::paintButtonArea (Graphics& g,
  32749. int width, int height,
  32750. bool /*isMouseOver*/,
  32751. bool /*isMouseDown*/)
  32752. {
  32753. Drawable* d = normalImage;
  32754. if (getToggleState() && toggledOnImage != 0)
  32755. d = toggledOnImage;
  32756. if (! isEnabled())
  32757. {
  32758. Image im (Image::ARGB, width, height, true);
  32759. Graphics g2 (im);
  32760. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred);
  32761. im.desaturate();
  32762. g.drawImageAt (&im, 0, 0);
  32763. }
  32764. else
  32765. {
  32766. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred);
  32767. }
  32768. }
  32769. void ToolbarButton::contentAreaChanged (const Rectangle&)
  32770. {
  32771. }
  32772. END_JUCE_NAMESPACE
  32773. /********* End of inlined file: juce_ToolbarButton.cpp *********/
  32774. /********* Start of inlined file: juce_ComboBox.cpp *********/
  32775. BEGIN_JUCE_NAMESPACE
  32776. ComboBox::ComboBox (const String& name)
  32777. : Component (name),
  32778. items (4),
  32779. currentIndex (-1),
  32780. isButtonDown (false),
  32781. separatorPending (false),
  32782. menuActive (false),
  32783. listeners (2),
  32784. label (0)
  32785. {
  32786. noChoicesMessage = TRANS("(no choices)");
  32787. setRepaintsOnMouseActivity (true);
  32788. lookAndFeelChanged();
  32789. }
  32790. ComboBox::~ComboBox()
  32791. {
  32792. if (menuActive)
  32793. PopupMenu::dismissAllActiveMenus();
  32794. deleteAllChildren();
  32795. }
  32796. void ComboBox::setEditableText (const bool isEditable)
  32797. {
  32798. label->setEditable (isEditable, isEditable, false);
  32799. setWantsKeyboardFocus (! isEditable);
  32800. resized();
  32801. }
  32802. bool ComboBox::isTextEditable() const throw()
  32803. {
  32804. return label->isEditable();
  32805. }
  32806. void ComboBox::setJustificationType (const Justification& justification) throw()
  32807. {
  32808. label->setJustificationType (justification);
  32809. }
  32810. const Justification ComboBox::getJustificationType() const throw()
  32811. {
  32812. return label->getJustificationType();
  32813. }
  32814. void ComboBox::setTooltip (const String& newTooltip)
  32815. {
  32816. SettableTooltipClient::setTooltip (newTooltip);
  32817. label->setTooltip (newTooltip);
  32818. }
  32819. void ComboBox::addItem (const String& newItemText,
  32820. const int newItemId) throw()
  32821. {
  32822. // you can't add empty strings to the list..
  32823. jassert (newItemText.isNotEmpty());
  32824. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  32825. jassert (newItemId != 0);
  32826. // you shouldn't use duplicate item IDs!
  32827. jassert (getItemForId (newItemId) == 0);
  32828. if (newItemText.isNotEmpty() && newItemId != 0)
  32829. {
  32830. if (separatorPending)
  32831. {
  32832. separatorPending = false;
  32833. ItemInfo* const item = new ItemInfo();
  32834. item->itemId = 0;
  32835. item->isEnabled = false;
  32836. item->isHeading = false;
  32837. items.add (item);
  32838. }
  32839. ItemInfo* const item = new ItemInfo();
  32840. item->name = newItemText;
  32841. item->itemId = newItemId;
  32842. item->isEnabled = true;
  32843. item->isHeading = false;
  32844. items.add (item);
  32845. }
  32846. }
  32847. void ComboBox::addSeparator() throw()
  32848. {
  32849. separatorPending = (items.size() > 0);
  32850. }
  32851. void ComboBox::addSectionHeading (const String& headingName) throw()
  32852. {
  32853. // you can't add empty strings to the list..
  32854. jassert (headingName.isNotEmpty());
  32855. if (headingName.isNotEmpty())
  32856. {
  32857. if (separatorPending)
  32858. {
  32859. separatorPending = false;
  32860. ItemInfo* const item = new ItemInfo();
  32861. item->itemId = 0;
  32862. item->isEnabled = false;
  32863. item->isHeading = false;
  32864. items.add (item);
  32865. }
  32866. ItemInfo* const item = new ItemInfo();
  32867. item->name = headingName;
  32868. item->itemId = 0;
  32869. item->isEnabled = true;
  32870. item->isHeading = true;
  32871. items.add (item);
  32872. }
  32873. }
  32874. void ComboBox::setItemEnabled (const int itemId,
  32875. const bool isEnabled) throw()
  32876. {
  32877. ItemInfo* const item = getItemForId (itemId);
  32878. if (item != 0)
  32879. item->isEnabled = isEnabled;
  32880. }
  32881. void ComboBox::changeItemText (const int itemId,
  32882. const String& newText) throw()
  32883. {
  32884. ItemInfo* const item = getItemForId (itemId);
  32885. jassert (item != 0);
  32886. if (item != 0)
  32887. item->name = newText;
  32888. }
  32889. void ComboBox::clear (const bool dontSendChangeMessage)
  32890. {
  32891. items.clear();
  32892. separatorPending = false;
  32893. if (! label->isEditable())
  32894. setSelectedItemIndex (-1, dontSendChangeMessage);
  32895. }
  32896. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  32897. {
  32898. jassert (itemId != 0);
  32899. if (itemId != 0)
  32900. {
  32901. for (int i = items.size(); --i >= 0;)
  32902. if (items.getUnchecked(i)->itemId == itemId)
  32903. return items.getUnchecked(i);
  32904. }
  32905. return 0;
  32906. }
  32907. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  32908. {
  32909. int n = 0;
  32910. for (int i = 0; i < items.size(); ++i)
  32911. {
  32912. ItemInfo* const item = items.getUnchecked(i);
  32913. if (item->isRealItem())
  32914. {
  32915. if (n++ == index)
  32916. return item;
  32917. }
  32918. }
  32919. return 0;
  32920. }
  32921. int ComboBox::getNumItems() const throw()
  32922. {
  32923. int n = 0;
  32924. for (int i = items.size(); --i >= 0;)
  32925. {
  32926. ItemInfo* const item = items.getUnchecked(i);
  32927. if (item->isRealItem())
  32928. ++n;
  32929. }
  32930. return n;
  32931. }
  32932. const String ComboBox::getItemText (const int index) const throw()
  32933. {
  32934. ItemInfo* const item = getItemForIndex (index);
  32935. if (item != 0)
  32936. return item->name;
  32937. return String::empty;
  32938. }
  32939. int ComboBox::getItemId (const int index) const throw()
  32940. {
  32941. ItemInfo* const item = getItemForIndex (index);
  32942. return (item != 0) ? item->itemId : 0;
  32943. }
  32944. bool ComboBox::ItemInfo::isSeparator() const throw()
  32945. {
  32946. return name.isEmpty();
  32947. }
  32948. bool ComboBox::ItemInfo::isRealItem() const throw()
  32949. {
  32950. return ! (isHeading || name.isEmpty());
  32951. }
  32952. int ComboBox::getSelectedItemIndex() const throw()
  32953. {
  32954. return (currentIndex >= 0 && getText() == getItemText (currentIndex))
  32955. ? currentIndex
  32956. : -1;
  32957. }
  32958. void ComboBox::setSelectedItemIndex (const int index,
  32959. const bool dontSendChangeMessage) throw()
  32960. {
  32961. if (currentIndex != index || label->getText() != getItemText (currentIndex))
  32962. {
  32963. if (((unsigned int) index) < (unsigned int) getNumItems())
  32964. currentIndex = index;
  32965. else
  32966. currentIndex = -1;
  32967. label->setText (getItemText (currentIndex), false);
  32968. if (! dontSendChangeMessage)
  32969. triggerAsyncUpdate();
  32970. }
  32971. }
  32972. void ComboBox::setSelectedId (const int newItemId,
  32973. const bool dontSendChangeMessage) throw()
  32974. {
  32975. for (int i = getNumItems(); --i >= 0;)
  32976. {
  32977. if (getItemId(i) == newItemId)
  32978. {
  32979. setSelectedItemIndex (i, dontSendChangeMessage);
  32980. break;
  32981. }
  32982. }
  32983. }
  32984. int ComboBox::getSelectedId() const throw()
  32985. {
  32986. const ItemInfo* const item = getItemForIndex (currentIndex);
  32987. return (item != 0 && getText() == item->name)
  32988. ? item->itemId
  32989. : 0;
  32990. }
  32991. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  32992. {
  32993. jassert (listener != 0);
  32994. if (listener != 0)
  32995. listeners.add (listener);
  32996. }
  32997. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  32998. {
  32999. listeners.removeValue (listener);
  33000. }
  33001. void ComboBox::handleAsyncUpdate()
  33002. {
  33003. for (int i = listeners.size(); --i >= 0;)
  33004. {
  33005. ((ComboBoxListener*) listeners.getUnchecked (i))->comboBoxChanged (this);
  33006. i = jmin (i, listeners.size());
  33007. }
  33008. }
  33009. const String ComboBox::getText() const throw()
  33010. {
  33011. return label->getText();
  33012. }
  33013. void ComboBox::setText (const String& newText,
  33014. const bool dontSendChangeMessage) throw()
  33015. {
  33016. for (int i = items.size(); --i >= 0;)
  33017. {
  33018. ItemInfo* const item = items.getUnchecked(i);
  33019. if (item->isRealItem()
  33020. && item->name == newText)
  33021. {
  33022. setSelectedId (item->itemId, dontSendChangeMessage);
  33023. return;
  33024. }
  33025. }
  33026. currentIndex = -1;
  33027. if (label->getText() != newText)
  33028. {
  33029. label->setText (newText, false);
  33030. if (! dontSendChangeMessage)
  33031. triggerAsyncUpdate();
  33032. }
  33033. repaint();
  33034. }
  33035. void ComboBox::showEditor()
  33036. {
  33037. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  33038. label->showEditor();
  33039. }
  33040. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  33041. {
  33042. textWhenNothingSelected = newMessage;
  33043. repaint();
  33044. }
  33045. const String ComboBox::getTextWhenNothingSelected() const throw()
  33046. {
  33047. return textWhenNothingSelected;
  33048. }
  33049. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  33050. {
  33051. noChoicesMessage = newMessage;
  33052. }
  33053. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  33054. {
  33055. return noChoicesMessage;
  33056. }
  33057. void ComboBox::paint (Graphics& g)
  33058. {
  33059. getLookAndFeel().drawComboBox (g,
  33060. getWidth(),
  33061. getHeight(),
  33062. isButtonDown,
  33063. label->getRight(),
  33064. 0,
  33065. getWidth() - label->getRight(),
  33066. getHeight(),
  33067. *this);
  33068. if (textWhenNothingSelected.isNotEmpty()
  33069. && label->getText().isEmpty()
  33070. && ! label->isBeingEdited())
  33071. {
  33072. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  33073. g.setFont (label->getFont());
  33074. g.drawFittedText (textWhenNothingSelected,
  33075. label->getX() + 2, label->getY() + 1,
  33076. label->getWidth() - 4, label->getHeight() - 2,
  33077. label->getJustificationType(),
  33078. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  33079. }
  33080. }
  33081. void ComboBox::resized()
  33082. {
  33083. if (getHeight() > 0 && getWidth() > 0)
  33084. getLookAndFeel().positionComboBoxText (*this, *label);
  33085. }
  33086. void ComboBox::enablementChanged()
  33087. {
  33088. repaint();
  33089. }
  33090. void ComboBox::lookAndFeelChanged()
  33091. {
  33092. repaint();
  33093. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  33094. if (label != 0)
  33095. {
  33096. newLabel->setEditable (label->isEditable());
  33097. newLabel->setJustificationType (label->getJustificationType());
  33098. newLabel->setTooltip (label->getTooltip());
  33099. newLabel->setText (label->getText(), false);
  33100. }
  33101. delete label;
  33102. label = newLabel;
  33103. addAndMakeVisible (newLabel);
  33104. newLabel->addListener (this);
  33105. newLabel->addMouseListener (this, false);
  33106. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  33107. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  33108. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  33109. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  33110. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  33111. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  33112. resized();
  33113. }
  33114. void ComboBox::colourChanged()
  33115. {
  33116. lookAndFeelChanged();
  33117. }
  33118. bool ComboBox::keyPressed (const KeyPress& key)
  33119. {
  33120. bool used = false;
  33121. if (key.isKeyCode (KeyPress::upKey)
  33122. || key.isKeyCode (KeyPress::leftKey))
  33123. {
  33124. setSelectedItemIndex (jmax (0, currentIndex - 1));
  33125. used = true;
  33126. }
  33127. else if (key.isKeyCode (KeyPress::downKey)
  33128. || key.isKeyCode (KeyPress::rightKey))
  33129. {
  33130. setSelectedItemIndex (jmin (currentIndex + 1, getNumItems() - 1));
  33131. used = true;
  33132. }
  33133. else if (key.isKeyCode (KeyPress::returnKey))
  33134. {
  33135. showPopup();
  33136. used = true;
  33137. }
  33138. return used;
  33139. }
  33140. bool ComboBox::keyStateChanged()
  33141. {
  33142. // only forward key events that aren't used by this component
  33143. return KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  33144. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  33145. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  33146. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey);
  33147. }
  33148. void ComboBox::focusGained (FocusChangeType)
  33149. {
  33150. repaint();
  33151. }
  33152. void ComboBox::focusLost (FocusChangeType)
  33153. {
  33154. repaint();
  33155. }
  33156. void ComboBox::labelTextChanged (Label*)
  33157. {
  33158. triggerAsyncUpdate();
  33159. }
  33160. void ComboBox::showPopup()
  33161. {
  33162. if (! menuActive)
  33163. {
  33164. const int currentId = getSelectedId();
  33165. ComponentDeletionWatcher deletionWatcher (this);
  33166. PopupMenu menu;
  33167. menu.setLookAndFeel (&getLookAndFeel());
  33168. for (int i = 0; i < items.size(); ++i)
  33169. {
  33170. const ItemInfo* const item = items.getUnchecked(i);
  33171. if (item->isSeparator())
  33172. menu.addSeparator();
  33173. else if (item->isHeading)
  33174. menu.addSectionHeader (item->name);
  33175. else
  33176. menu.addItem (item->itemId, item->name,
  33177. item->isEnabled, item->itemId == currentId);
  33178. }
  33179. if (items.size() == 0)
  33180. menu.addItem (1, noChoicesMessage, false);
  33181. const int itemHeight = jlimit (12, 24, getHeight());
  33182. menuActive = true;
  33183. const int resultId = menu.showAt (this, currentId,
  33184. getWidth(), 1, itemHeight);
  33185. if (deletionWatcher.hasBeenDeleted())
  33186. return;
  33187. menuActive = false;
  33188. if (resultId != 0)
  33189. setSelectedId (resultId);
  33190. }
  33191. }
  33192. void ComboBox::mouseDown (const MouseEvent& e)
  33193. {
  33194. beginDragAutoRepeat (300);
  33195. isButtonDown = isEnabled();
  33196. if (isButtonDown
  33197. && (e.eventComponent == this || ! label->isEditable()))
  33198. {
  33199. showPopup();
  33200. }
  33201. }
  33202. void ComboBox::mouseDrag (const MouseEvent& e)
  33203. {
  33204. beginDragAutoRepeat (50);
  33205. if (isButtonDown && ! e.mouseWasClicked())
  33206. showPopup();
  33207. }
  33208. void ComboBox::mouseUp (const MouseEvent& e2)
  33209. {
  33210. if (isButtonDown)
  33211. {
  33212. isButtonDown = false;
  33213. repaint();
  33214. const MouseEvent e (e2.getEventRelativeTo (this));
  33215. if (reallyContains (e.x, e.y, true)
  33216. && (e2.eventComponent == this || ! label->isEditable()))
  33217. {
  33218. showPopup();
  33219. }
  33220. }
  33221. }
  33222. END_JUCE_NAMESPACE
  33223. /********* End of inlined file: juce_ComboBox.cpp *********/
  33224. /********* Start of inlined file: juce_Label.cpp *********/
  33225. BEGIN_JUCE_NAMESPACE
  33226. Label::Label (const String& componentName,
  33227. const String& labelText)
  33228. : Component (componentName),
  33229. text (labelText),
  33230. font (15.0f),
  33231. justification (Justification::centredLeft),
  33232. editor (0),
  33233. listeners (2),
  33234. ownerComponent (0),
  33235. deletionWatcher (0),
  33236. editSingleClick (false),
  33237. editDoubleClick (false),
  33238. lossOfFocusDiscardsChanges (false)
  33239. {
  33240. setColour (TextEditor::textColourId, Colours::black);
  33241. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  33242. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  33243. }
  33244. Label::~Label()
  33245. {
  33246. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33247. ownerComponent->removeComponentListener (this);
  33248. deleteAndZero (deletionWatcher);
  33249. if (editor != 0)
  33250. delete editor;
  33251. }
  33252. void Label::setText (const String& newText,
  33253. const bool broadcastChangeMessage)
  33254. {
  33255. hideEditor (true);
  33256. if (text != newText)
  33257. {
  33258. text = newText;
  33259. if (broadcastChangeMessage)
  33260. triggerAsyncUpdate();
  33261. repaint();
  33262. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33263. componentMovedOrResized (*ownerComponent, true, true);
  33264. }
  33265. }
  33266. const String Label::getText (const bool returnActiveEditorContents) const throw()
  33267. {
  33268. return (returnActiveEditorContents && isBeingEdited())
  33269. ? editor->getText()
  33270. : text;
  33271. }
  33272. void Label::setFont (const Font& newFont) throw()
  33273. {
  33274. font = newFont;
  33275. repaint();
  33276. }
  33277. const Font& Label::getFont() const throw()
  33278. {
  33279. return font;
  33280. }
  33281. void Label::setEditable (const bool editOnSingleClick,
  33282. const bool editOnDoubleClick,
  33283. const bool lossOfFocusDiscardsChanges_) throw()
  33284. {
  33285. editSingleClick = editOnSingleClick;
  33286. editDoubleClick = editOnDoubleClick;
  33287. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  33288. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  33289. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  33290. }
  33291. void Label::setJustificationType (const Justification& justification_) throw()
  33292. {
  33293. justification = justification_;
  33294. repaint();
  33295. }
  33296. void Label::attachToComponent (Component* owner,
  33297. const bool onLeft)
  33298. {
  33299. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33300. ownerComponent->removeComponentListener (this);
  33301. deleteAndZero (deletionWatcher);
  33302. ownerComponent = owner;
  33303. leftOfOwnerComp = onLeft;
  33304. if (ownerComponent != 0)
  33305. {
  33306. deletionWatcher = new ComponentDeletionWatcher (owner);
  33307. setVisible (owner->isVisible());
  33308. ownerComponent->addComponentListener (this);
  33309. componentParentHierarchyChanged (*ownerComponent);
  33310. componentMovedOrResized (*ownerComponent, true, true);
  33311. }
  33312. }
  33313. void Label::componentMovedOrResized (Component& component,
  33314. bool /*wasMoved*/,
  33315. bool /*wasResized*/)
  33316. {
  33317. if (leftOfOwnerComp)
  33318. {
  33319. setSize (jmin (getFont().getStringWidth (text) + 8, component.getX()),
  33320. component.getHeight());
  33321. setTopRightPosition (component.getX(), component.getY());
  33322. }
  33323. else
  33324. {
  33325. setSize (component.getWidth(),
  33326. 8 + roundFloatToInt (getFont().getHeight()));
  33327. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  33328. }
  33329. }
  33330. void Label::componentParentHierarchyChanged (Component& component)
  33331. {
  33332. if (component.getParentComponent() != 0)
  33333. component.getParentComponent()->addChildComponent (this);
  33334. }
  33335. void Label::componentVisibilityChanged (Component& component)
  33336. {
  33337. setVisible (component.isVisible());
  33338. }
  33339. void Label::textWasEdited()
  33340. {
  33341. }
  33342. void Label::showEditor()
  33343. {
  33344. if (editor == 0)
  33345. {
  33346. addAndMakeVisible (editor = createEditorComponent());
  33347. editor->setText (getText());
  33348. editor->addListener (this);
  33349. editor->grabKeyboardFocus();
  33350. editor->setHighlightedRegion (0, text.length());
  33351. editor->addListener (this);
  33352. resized();
  33353. repaint();
  33354. enterModalState();
  33355. editor->grabKeyboardFocus();
  33356. }
  33357. }
  33358. bool Label::updateFromTextEditorContents()
  33359. {
  33360. jassert (editor != 0);
  33361. const String newText (editor->getText());
  33362. if (text != newText)
  33363. {
  33364. text = newText;
  33365. triggerAsyncUpdate();
  33366. repaint();
  33367. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33368. componentMovedOrResized (*ownerComponent, true, true);
  33369. return true;
  33370. }
  33371. return false;
  33372. }
  33373. void Label::hideEditor (const bool discardCurrentEditorContents)
  33374. {
  33375. if (editor != 0)
  33376. {
  33377. const bool changed = (! discardCurrentEditorContents)
  33378. && updateFromTextEditorContents();
  33379. deleteAndZero (editor);
  33380. repaint();
  33381. if (changed)
  33382. textWasEdited();
  33383. exitModalState (0);
  33384. }
  33385. }
  33386. void Label::inputAttemptWhenModal()
  33387. {
  33388. if (editor != 0)
  33389. {
  33390. if (lossOfFocusDiscardsChanges)
  33391. textEditorEscapeKeyPressed (*editor);
  33392. else
  33393. textEditorReturnKeyPressed (*editor);
  33394. }
  33395. }
  33396. bool Label::isBeingEdited() const throw()
  33397. {
  33398. return editor != 0;
  33399. }
  33400. TextEditor* Label::createEditorComponent()
  33401. {
  33402. TextEditor* const ed = new TextEditor (getName());
  33403. ed->setFont (font);
  33404. // copy these colours from our own settings..
  33405. const int cols[] = { TextEditor::backgroundColourId,
  33406. TextEditor::textColourId,
  33407. TextEditor::highlightColourId,
  33408. TextEditor::highlightedTextColourId,
  33409. TextEditor::caretColourId,
  33410. TextEditor::outlineColourId,
  33411. TextEditor::focusedOutlineColourId,
  33412. TextEditor::shadowColourId };
  33413. for (int i = 0; i < numElementsInArray (cols); ++i)
  33414. ed->setColour (cols[i], findColour (cols[i]));
  33415. return ed;
  33416. }
  33417. void Label::paint (Graphics& g)
  33418. {
  33419. g.fillAll (findColour (backgroundColourId));
  33420. if (editor == 0)
  33421. {
  33422. const float alpha = isEnabled() ? 1.0f : 0.5f;
  33423. g.setColour (findColour (textColourId).withMultipliedAlpha (alpha));
  33424. g.setFont (font);
  33425. g.drawFittedText (text,
  33426. 3, 1, getWidth() - 6, getHeight() - 2,
  33427. justification,
  33428. jmax (1, (int) (getHeight() / font.getHeight())));
  33429. g.setColour (findColour (outlineColourId).withMultipliedAlpha (alpha));
  33430. g.drawRect (0, 0, getWidth(), getHeight());
  33431. }
  33432. else if (isEnabled())
  33433. {
  33434. g.setColour (editor->findColour (TextEditor::backgroundColourId)
  33435. .overlaidWith (findColour (outlineColourId)));
  33436. g.drawRect (0, 0, getWidth(), getHeight());
  33437. }
  33438. }
  33439. void Label::mouseUp (const MouseEvent& e)
  33440. {
  33441. if (editSingleClick
  33442. && e.mouseWasClicked()
  33443. && contains (e.x, e.y)
  33444. && ! e.mods.isPopupMenu())
  33445. {
  33446. showEditor();
  33447. }
  33448. }
  33449. void Label::mouseDoubleClick (const MouseEvent& e)
  33450. {
  33451. if (editDoubleClick && ! e.mods.isPopupMenu())
  33452. showEditor();
  33453. }
  33454. void Label::resized()
  33455. {
  33456. if (editor != 0)
  33457. editor->setBoundsInset (BorderSize (0));
  33458. }
  33459. void Label::focusGained (FocusChangeType cause)
  33460. {
  33461. if (editSingleClick && cause == focusChangedByTabKey)
  33462. showEditor();
  33463. }
  33464. void Label::enablementChanged()
  33465. {
  33466. repaint();
  33467. }
  33468. void Label::colourChanged()
  33469. {
  33470. repaint();
  33471. }
  33472. // We'll use a custom focus traverser here to make sure focus goes from the
  33473. // text editor to another component rather than back to the label itself.
  33474. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  33475. {
  33476. public:
  33477. LabelKeyboardFocusTraverser() {}
  33478. Component* getNextComponent (Component* current)
  33479. {
  33480. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  33481. ? current->getParentComponent() : current);
  33482. }
  33483. Component* getPreviousComponent (Component* current)
  33484. {
  33485. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  33486. ? current->getParentComponent() : current);
  33487. }
  33488. };
  33489. KeyboardFocusTraverser* Label::createFocusTraverser()
  33490. {
  33491. return new LabelKeyboardFocusTraverser();
  33492. }
  33493. void Label::addListener (LabelListener* const listener) throw()
  33494. {
  33495. jassert (listener != 0);
  33496. if (listener != 0)
  33497. listeners.add (listener);
  33498. }
  33499. void Label::removeListener (LabelListener* const listener) throw()
  33500. {
  33501. listeners.removeValue (listener);
  33502. }
  33503. void Label::handleAsyncUpdate()
  33504. {
  33505. for (int i = listeners.size(); --i >= 0;)
  33506. {
  33507. ((LabelListener*) listeners.getUnchecked (i))->labelTextChanged (this);
  33508. i = jmin (i, listeners.size());
  33509. }
  33510. }
  33511. void Label::textEditorTextChanged (TextEditor& ed)
  33512. {
  33513. if (editor != 0)
  33514. {
  33515. jassert (&ed == editor);
  33516. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  33517. {
  33518. if (lossOfFocusDiscardsChanges)
  33519. textEditorEscapeKeyPressed (ed);
  33520. else
  33521. textEditorReturnKeyPressed (ed);
  33522. }
  33523. }
  33524. }
  33525. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  33526. {
  33527. if (editor != 0)
  33528. {
  33529. jassert (&ed == editor);
  33530. (void) ed;
  33531. const bool changed = updateFromTextEditorContents();
  33532. hideEditor (true);
  33533. if (changed)
  33534. textWasEdited();
  33535. }
  33536. }
  33537. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  33538. {
  33539. if (editor != 0)
  33540. {
  33541. jassert (&ed == editor);
  33542. (void) ed;
  33543. editor->setText (text, false);
  33544. hideEditor (true);
  33545. }
  33546. }
  33547. void Label::textEditorFocusLost (TextEditor& ed)
  33548. {
  33549. textEditorTextChanged (ed);
  33550. }
  33551. END_JUCE_NAMESPACE
  33552. /********* End of inlined file: juce_Label.cpp *********/
  33553. /********* Start of inlined file: juce_ListBox.cpp *********/
  33554. BEGIN_JUCE_NAMESPACE
  33555. class ListBoxRowComponent : public Component
  33556. {
  33557. public:
  33558. ListBoxRowComponent (ListBox& owner_)
  33559. : owner (owner_),
  33560. row (-1),
  33561. selected (false),
  33562. isDragging (false)
  33563. {
  33564. }
  33565. ~ListBoxRowComponent()
  33566. {
  33567. deleteAllChildren();
  33568. }
  33569. void paint (Graphics& g)
  33570. {
  33571. if (owner.getModel() != 0)
  33572. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  33573. }
  33574. void update (const int row_, const bool selected_)
  33575. {
  33576. if (row != row_ || selected != selected_)
  33577. {
  33578. repaint();
  33579. row = row_;
  33580. selected = selected_;
  33581. }
  33582. if (owner.getModel() != 0)
  33583. {
  33584. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  33585. if (customComp != 0)
  33586. {
  33587. addAndMakeVisible (customComp);
  33588. customComp->setBounds (0, 0, getWidth(), getHeight());
  33589. for (int i = getNumChildComponents(); --i >= 0;)
  33590. if (getChildComponent (i) != customComp)
  33591. delete getChildComponent (i);
  33592. }
  33593. else
  33594. {
  33595. deleteAllChildren();
  33596. }
  33597. }
  33598. }
  33599. void mouseDown (const MouseEvent& e)
  33600. {
  33601. isDragging = false;
  33602. selectRowOnMouseUp = false;
  33603. if (isEnabled())
  33604. {
  33605. if (! selected)
  33606. {
  33607. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  33608. if (owner.getModel() != 0)
  33609. owner.getModel()->listBoxItemClicked (row, e);
  33610. }
  33611. else
  33612. {
  33613. selectRowOnMouseUp = true;
  33614. }
  33615. }
  33616. }
  33617. void mouseUp (const MouseEvent& e)
  33618. {
  33619. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  33620. {
  33621. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  33622. if (owner.getModel() != 0)
  33623. owner.getModel()->listBoxItemClicked (row, e);
  33624. }
  33625. }
  33626. void mouseDoubleClick (const MouseEvent& e)
  33627. {
  33628. if (owner.getModel() != 0 && isEnabled())
  33629. owner.getModel()->listBoxItemDoubleClicked (row, e);
  33630. }
  33631. void mouseDrag (const MouseEvent& e)
  33632. {
  33633. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  33634. {
  33635. const SparseSet <int> selectedRows (owner.getSelectedRows());
  33636. if (selectedRows.size() > 0)
  33637. {
  33638. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  33639. if (dragDescription.isNotEmpty())
  33640. {
  33641. isDragging = true;
  33642. DragAndDropContainer* const dragContainer
  33643. = DragAndDropContainer::findParentDragContainerFor (this);
  33644. if (dragContainer != 0)
  33645. {
  33646. Image* dragImage = owner.createSnapshotOfSelectedRows();
  33647. dragImage->multiplyAllAlphas (0.6f);
  33648. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  33649. }
  33650. else
  33651. {
  33652. // to be able to do a drag-and-drop operation, the listbox needs to
  33653. // be inside a component which is also a DragAndDropContainer.
  33654. jassertfalse
  33655. }
  33656. }
  33657. }
  33658. }
  33659. }
  33660. void resized()
  33661. {
  33662. if (getNumChildComponents() > 0)
  33663. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  33664. }
  33665. juce_UseDebuggingNewOperator
  33666. bool neededFlag;
  33667. private:
  33668. ListBox& owner;
  33669. int row;
  33670. bool selected, isDragging, selectRowOnMouseUp;
  33671. ListBoxRowComponent (const ListBoxRowComponent&);
  33672. const ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  33673. };
  33674. class ListViewport : public Viewport
  33675. {
  33676. public:
  33677. int firstIndex, firstWholeIndex, lastWholeIndex;
  33678. bool hasUpdated;
  33679. ListViewport (ListBox& owner_)
  33680. : owner (owner_)
  33681. {
  33682. setWantsKeyboardFocus (false);
  33683. setViewedComponent (new Component());
  33684. getViewedComponent()->addMouseListener (this, false);
  33685. getViewedComponent()->setWantsKeyboardFocus (false);
  33686. }
  33687. ~ListViewport()
  33688. {
  33689. getViewedComponent()->removeMouseListener (this);
  33690. getViewedComponent()->deleteAllChildren();
  33691. }
  33692. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  33693. {
  33694. return (ListBoxRowComponent*) getViewedComponent()
  33695. ->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents()));
  33696. }
  33697. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  33698. {
  33699. const int index = getIndexOfChildComponent (rowComponent);
  33700. const int num = getViewedComponent()->getNumChildComponents();
  33701. for (int i = num; --i >= 0;)
  33702. if (((firstIndex + i) % jmax (1, num)) == index)
  33703. return firstIndex + i;
  33704. return -1;
  33705. }
  33706. Component* getComponentForRowIfOnscreen (const int row) const throw()
  33707. {
  33708. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  33709. ? getComponentForRow (row) : 0;
  33710. }
  33711. void visibleAreaChanged (int, int, int, int)
  33712. {
  33713. updateVisibleArea (true);
  33714. if (owner.getModel() != 0)
  33715. owner.getModel()->listWasScrolled();
  33716. }
  33717. void updateVisibleArea (const bool makeSureItUpdatesContent)
  33718. {
  33719. hasUpdated = false;
  33720. const int newX = getViewedComponent()->getX();
  33721. int newY = getViewedComponent()->getY();
  33722. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  33723. const int newH = owner.totalItems * owner.getRowHeight();
  33724. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  33725. newY = getMaximumVisibleHeight() - newH;
  33726. getViewedComponent()->setBounds (newX, newY, newW, newH);
  33727. if (makeSureItUpdatesContent && ! hasUpdated)
  33728. updateContents();
  33729. }
  33730. void updateContents()
  33731. {
  33732. hasUpdated = true;
  33733. const int rowHeight = owner.getRowHeight();
  33734. if (rowHeight > 0)
  33735. {
  33736. const int y = getViewPositionY();
  33737. const int w = getViewedComponent()->getWidth();
  33738. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  33739. while (numNeeded > getViewedComponent()->getNumChildComponents())
  33740. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  33741. jassert (numNeeded >= 0);
  33742. while (numNeeded < getViewedComponent()->getNumChildComponents())
  33743. {
  33744. Component* const rowToRemove
  33745. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  33746. delete rowToRemove;
  33747. }
  33748. firstIndex = y / rowHeight;
  33749. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  33750. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  33751. for (int i = 0; i < numNeeded; ++i)
  33752. {
  33753. const int row = i + firstIndex;
  33754. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  33755. if (rowComp != 0)
  33756. {
  33757. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  33758. rowComp->update (row, owner.isRowSelected (row));
  33759. }
  33760. }
  33761. }
  33762. if (owner.headerComponent != 0)
  33763. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  33764. owner.outlineThickness,
  33765. jmax (owner.getWidth() - owner.outlineThickness * 2,
  33766. getViewedComponent()->getWidth()),
  33767. owner.headerComponent->getHeight());
  33768. }
  33769. void paint (Graphics& g)
  33770. {
  33771. if (isOpaque())
  33772. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  33773. }
  33774. bool keyPressed (const KeyPress& key)
  33775. {
  33776. if (key.isKeyCode (KeyPress::upKey)
  33777. || key.isKeyCode (KeyPress::downKey)
  33778. || key.isKeyCode (KeyPress::pageUpKey)
  33779. || key.isKeyCode (KeyPress::pageDownKey)
  33780. || key.isKeyCode (KeyPress::homeKey)
  33781. || key.isKeyCode (KeyPress::endKey))
  33782. {
  33783. // we want to avoid these keypresses going to the viewport, and instead allow
  33784. // them to pass up to our listbox..
  33785. return false;
  33786. }
  33787. return Viewport::keyPressed (key);
  33788. }
  33789. juce_UseDebuggingNewOperator
  33790. private:
  33791. ListBox& owner;
  33792. ListViewport (const ListViewport&);
  33793. const ListViewport& operator= (const ListViewport&);
  33794. };
  33795. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  33796. : Component (name),
  33797. model (model_),
  33798. headerComponent (0),
  33799. totalItems (0),
  33800. rowHeight (22),
  33801. minimumRowWidth (0),
  33802. outlineThickness (0),
  33803. lastRowSelected (-1),
  33804. mouseMoveSelects (false),
  33805. multipleSelection (false),
  33806. hasDoneInitialUpdate (false)
  33807. {
  33808. addAndMakeVisible (viewport = new ListViewport (*this));
  33809. setWantsKeyboardFocus (true);
  33810. }
  33811. ListBox::~ListBox()
  33812. {
  33813. deleteAllChildren();
  33814. }
  33815. void ListBox::setModel (ListBoxModel* const newModel)
  33816. {
  33817. if (model != newModel)
  33818. {
  33819. model = newModel;
  33820. updateContent();
  33821. }
  33822. }
  33823. void ListBox::setMultipleSelectionEnabled (bool b)
  33824. {
  33825. multipleSelection = b;
  33826. }
  33827. void ListBox::setMouseMoveSelectsRows (bool b)
  33828. {
  33829. mouseMoveSelects = b;
  33830. if (b)
  33831. addMouseListener (this, true);
  33832. }
  33833. void ListBox::paint (Graphics& g)
  33834. {
  33835. if (! hasDoneInitialUpdate)
  33836. updateContent();
  33837. g.fillAll (findColour (backgroundColourId));
  33838. }
  33839. void ListBox::paintOverChildren (Graphics& g)
  33840. {
  33841. if (outlineThickness > 0)
  33842. {
  33843. g.setColour (findColour (outlineColourId));
  33844. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  33845. }
  33846. }
  33847. void ListBox::resized()
  33848. {
  33849. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  33850. outlineThickness,
  33851. outlineThickness,
  33852. outlineThickness));
  33853. viewport->setSingleStepSizes (20, getRowHeight());
  33854. viewport->updateVisibleArea (false);
  33855. }
  33856. void ListBox::visibilityChanged()
  33857. {
  33858. viewport->updateVisibleArea (true);
  33859. }
  33860. Viewport* ListBox::getViewport() const throw()
  33861. {
  33862. return viewport;
  33863. }
  33864. void ListBox::updateContent()
  33865. {
  33866. hasDoneInitialUpdate = true;
  33867. totalItems = (model != 0) ? model->getNumRows() : 0;
  33868. bool selectionChanged = false;
  33869. if (selected [selected.size() - 1] >= totalItems)
  33870. {
  33871. selected.removeRange (totalItems, INT_MAX - totalItems);
  33872. lastRowSelected = getSelectedRow (0);
  33873. selectionChanged = true;
  33874. }
  33875. viewport->updateVisibleArea (isVisible());
  33876. viewport->resized();
  33877. if (selectionChanged && model != 0)
  33878. model->selectedRowsChanged (lastRowSelected);
  33879. }
  33880. void ListBox::selectRow (const int row,
  33881. bool dontScroll,
  33882. bool deselectOthersFirst)
  33883. {
  33884. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  33885. }
  33886. void ListBox::selectRowInternal (const int row,
  33887. bool dontScroll,
  33888. bool deselectOthersFirst,
  33889. bool isMouseClick)
  33890. {
  33891. if (! multipleSelection)
  33892. deselectOthersFirst = true;
  33893. if ((! isRowSelected (row))
  33894. || (deselectOthersFirst && getNumSelectedRows() > 1))
  33895. {
  33896. if (((unsigned int) row) < (unsigned int) totalItems)
  33897. {
  33898. if (deselectOthersFirst)
  33899. selected.clear();
  33900. selected.addRange (row, 1);
  33901. if (getHeight() == 0 || getWidth() == 0)
  33902. dontScroll = true;
  33903. viewport->hasUpdated = false;
  33904. if (row < viewport->firstWholeIndex && ! dontScroll)
  33905. {
  33906. viewport->setViewPosition (viewport->getViewPositionX(),
  33907. row * getRowHeight());
  33908. }
  33909. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  33910. {
  33911. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  33912. if (row >= lastRowSelected + rowsOnScreen
  33913. && rowsOnScreen < totalItems - 1
  33914. && ! isMouseClick)
  33915. {
  33916. viewport->setViewPosition (viewport->getViewPositionX(),
  33917. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  33918. * getRowHeight());
  33919. }
  33920. else
  33921. {
  33922. viewport->setViewPosition (viewport->getViewPositionX(),
  33923. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  33924. }
  33925. }
  33926. if (! viewport->hasUpdated)
  33927. viewport->updateContents();
  33928. lastRowSelected = row;
  33929. model->selectedRowsChanged (row);
  33930. }
  33931. else
  33932. {
  33933. if (deselectOthersFirst)
  33934. deselectAllRows();
  33935. }
  33936. }
  33937. }
  33938. void ListBox::deselectRow (const int row)
  33939. {
  33940. if (selected.contains (row))
  33941. {
  33942. selected.removeRange (row, 1);
  33943. if (row == lastRowSelected)
  33944. lastRowSelected = getSelectedRow (0);
  33945. viewport->updateContents();
  33946. model->selectedRowsChanged (lastRowSelected);
  33947. }
  33948. }
  33949. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  33950. const bool sendNotificationEventToModel)
  33951. {
  33952. selected = setOfRowsToBeSelected;
  33953. selected.removeRange (totalItems, INT_MAX - totalItems);
  33954. if (! isRowSelected (lastRowSelected))
  33955. lastRowSelected = getSelectedRow (0);
  33956. viewport->updateContents();
  33957. if ((model != 0) && sendNotificationEventToModel)
  33958. model->selectedRowsChanged (lastRowSelected);
  33959. }
  33960. const SparseSet<int> ListBox::getSelectedRows() const
  33961. {
  33962. return selected;
  33963. }
  33964. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  33965. {
  33966. if (multipleSelection && (firstRow != lastRow))
  33967. {
  33968. const int numRows = totalItems - 1;
  33969. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  33970. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  33971. selected.addRange (jmin (firstRow, lastRow),
  33972. abs (firstRow - lastRow) + 1);
  33973. selected.removeRange (lastRow, 1);
  33974. }
  33975. selectRowInternal (lastRow, false, false, true);
  33976. }
  33977. void ListBox::flipRowSelection (const int row)
  33978. {
  33979. if (isRowSelected (row))
  33980. deselectRow (row);
  33981. else
  33982. selectRowInternal (row, false, false, true);
  33983. }
  33984. void ListBox::deselectAllRows()
  33985. {
  33986. if (! selected.isEmpty())
  33987. {
  33988. selected.clear();
  33989. lastRowSelected = -1;
  33990. viewport->updateContents();
  33991. if (model != 0)
  33992. model->selectedRowsChanged (lastRowSelected);
  33993. }
  33994. }
  33995. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  33996. const ModifierKeys& mods)
  33997. {
  33998. if (multipleSelection && mods.isCommandDown())
  33999. {
  34000. flipRowSelection (row);
  34001. }
  34002. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  34003. {
  34004. selectRangeOfRows (lastRowSelected, row);
  34005. }
  34006. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  34007. {
  34008. selectRowInternal (row, false, true, true);
  34009. }
  34010. }
  34011. int ListBox::getNumSelectedRows() const
  34012. {
  34013. return selected.size();
  34014. }
  34015. int ListBox::getSelectedRow (const int index) const
  34016. {
  34017. return (((unsigned int) index) < (unsigned int) selected.size())
  34018. ? selected [index] : -1;
  34019. }
  34020. bool ListBox::isRowSelected (const int row) const
  34021. {
  34022. return selected.contains (row);
  34023. }
  34024. int ListBox::getLastRowSelected() const
  34025. {
  34026. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  34027. }
  34028. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  34029. {
  34030. if (((unsigned int) x) < (unsigned int) getWidth())
  34031. {
  34032. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  34033. if (((unsigned int) row) < (unsigned int) totalItems)
  34034. return row;
  34035. }
  34036. return -1;
  34037. }
  34038. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  34039. {
  34040. if (((unsigned int) x) < (unsigned int) getWidth())
  34041. {
  34042. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  34043. return jlimit (0, totalItems, row);
  34044. }
  34045. return -1;
  34046. }
  34047. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  34048. {
  34049. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  34050. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  34051. }
  34052. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  34053. {
  34054. return viewport->getRowNumberOfComponent (rowComponent);
  34055. }
  34056. const Rectangle ListBox::getRowPosition (const int rowNumber,
  34057. const bool relativeToComponentTopLeft) const throw()
  34058. {
  34059. const int rowHeight = getRowHeight();
  34060. int y = viewport->getY() + rowHeight * rowNumber;
  34061. if (relativeToComponentTopLeft)
  34062. y -= viewport->getViewPositionY();
  34063. return Rectangle (viewport->getX(), y,
  34064. viewport->getViewedComponent()->getWidth(), rowHeight);
  34065. }
  34066. void ListBox::setVerticalPosition (const double proportion)
  34067. {
  34068. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  34069. viewport->setViewPosition (viewport->getViewPositionX(),
  34070. jmax (0, roundDoubleToInt (proportion * offscreen)));
  34071. }
  34072. double ListBox::getVerticalPosition() const
  34073. {
  34074. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  34075. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  34076. : 0;
  34077. }
  34078. int ListBox::getVisibleRowWidth() const throw()
  34079. {
  34080. return viewport->getViewWidth();
  34081. }
  34082. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  34083. {
  34084. if (row < viewport->firstWholeIndex)
  34085. {
  34086. viewport->setViewPosition (viewport->getViewPositionX(),
  34087. row * getRowHeight());
  34088. }
  34089. else if (row >= viewport->lastWholeIndex)
  34090. {
  34091. viewport->setViewPosition (viewport->getViewPositionX(),
  34092. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  34093. }
  34094. }
  34095. bool ListBox::keyPressed (const KeyPress& key)
  34096. {
  34097. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  34098. const bool multiple = multipleSelection
  34099. && (lastRowSelected >= 0)
  34100. && (key.getModifiers().isShiftDown()
  34101. || key.getModifiers().isCtrlDown()
  34102. || key.getModifiers().isCommandDown());
  34103. if (key.isKeyCode (KeyPress::upKey))
  34104. {
  34105. if (multiple)
  34106. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  34107. else
  34108. selectRow (jmax (0, lastRowSelected - 1));
  34109. }
  34110. else if (key.isKeyCode (KeyPress::returnKey)
  34111. && isRowSelected (lastRowSelected))
  34112. {
  34113. if (model != 0)
  34114. model->returnKeyPressed (lastRowSelected);
  34115. }
  34116. else if (key.isKeyCode (KeyPress::pageUpKey))
  34117. {
  34118. if (multiple)
  34119. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  34120. else
  34121. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  34122. }
  34123. else if (key.isKeyCode (KeyPress::pageDownKey))
  34124. {
  34125. if (multiple)
  34126. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  34127. else
  34128. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  34129. }
  34130. else if (key.isKeyCode (KeyPress::homeKey))
  34131. {
  34132. if (multiple && key.getModifiers().isShiftDown())
  34133. selectRangeOfRows (lastRowSelected, 0);
  34134. else
  34135. selectRow (0);
  34136. }
  34137. else if (key.isKeyCode (KeyPress::endKey))
  34138. {
  34139. if (multiple && key.getModifiers().isShiftDown())
  34140. selectRangeOfRows (lastRowSelected, totalItems - 1);
  34141. else
  34142. selectRow (totalItems - 1);
  34143. }
  34144. else if (key.isKeyCode (KeyPress::downKey))
  34145. {
  34146. if (multiple)
  34147. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  34148. else
  34149. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  34150. }
  34151. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  34152. && isRowSelected (lastRowSelected))
  34153. {
  34154. if (model != 0)
  34155. model->deleteKeyPressed (lastRowSelected);
  34156. }
  34157. else if (multiple && key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  34158. {
  34159. selectRangeOfRows (0, INT_MAX);
  34160. }
  34161. else
  34162. {
  34163. return false;
  34164. }
  34165. return true;
  34166. }
  34167. bool ListBox::keyStateChanged()
  34168. {
  34169. return KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  34170. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  34171. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  34172. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  34173. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  34174. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  34175. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey);
  34176. }
  34177. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  34178. {
  34179. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  34180. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  34181. }
  34182. void ListBox::mouseMove (const MouseEvent& e)
  34183. {
  34184. if (mouseMoveSelects)
  34185. {
  34186. const MouseEvent e2 (e.getEventRelativeTo (this));
  34187. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  34188. lastMouseX = e2.x;
  34189. lastMouseY = e2.y;
  34190. }
  34191. }
  34192. void ListBox::mouseExit (const MouseEvent& e)
  34193. {
  34194. mouseMove (e);
  34195. }
  34196. void ListBox::mouseUp (const MouseEvent& e)
  34197. {
  34198. if (e.mouseWasClicked() && model != 0)
  34199. model->backgroundClicked();
  34200. }
  34201. void ListBox::setRowHeight (const int newHeight)
  34202. {
  34203. rowHeight = jmax (1, newHeight);
  34204. viewport->setSingleStepSizes (20, rowHeight);
  34205. updateContent();
  34206. }
  34207. int ListBox::getNumRowsOnScreen() const throw()
  34208. {
  34209. return viewport->getMaximumVisibleHeight() / rowHeight;
  34210. }
  34211. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  34212. {
  34213. minimumRowWidth = newMinimumWidth;
  34214. updateContent();
  34215. }
  34216. int ListBox::getVisibleContentWidth() const throw()
  34217. {
  34218. return viewport->getMaximumVisibleWidth();
  34219. }
  34220. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  34221. {
  34222. return viewport->getVerticalScrollBar();
  34223. }
  34224. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  34225. {
  34226. return viewport->getHorizontalScrollBar();
  34227. }
  34228. void ListBox::colourChanged()
  34229. {
  34230. setOpaque (findColour (backgroundColourId).isOpaque());
  34231. viewport->setOpaque (isOpaque());
  34232. repaint();
  34233. }
  34234. void ListBox::setOutlineThickness (const int outlineThickness_)
  34235. {
  34236. outlineThickness = outlineThickness_;
  34237. resized();
  34238. }
  34239. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  34240. {
  34241. if (headerComponent != newHeaderComponent)
  34242. {
  34243. if (headerComponent != 0)
  34244. delete headerComponent;
  34245. headerComponent = newHeaderComponent;
  34246. addAndMakeVisible (newHeaderComponent);
  34247. ListBox::resized();
  34248. }
  34249. }
  34250. void ListBox::repaintRow (const int rowNumber) throw()
  34251. {
  34252. const Rectangle r (getRowPosition (rowNumber, true));
  34253. repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  34254. }
  34255. Image* ListBox::createSnapshotOfSelectedRows()
  34256. {
  34257. Image* snapshot = new Image (Image::ARGB, getWidth(), getHeight(), true);
  34258. Graphics g (*snapshot);
  34259. const int firstRow = getRowContainingPosition (0, 0);
  34260. for (int i = getNumRowsOnScreen() + 2; --i >= 0;)
  34261. {
  34262. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  34263. if (rowComp != 0 && isRowSelected (firstRow + i))
  34264. {
  34265. g.saveState();
  34266. int x = 0, y = 0;
  34267. rowComp->relativePositionToOtherComponent (this, x, y);
  34268. g.setOrigin (x, y);
  34269. g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight());
  34270. rowComp->paintEntireComponent (g);
  34271. g.restoreState();
  34272. }
  34273. }
  34274. return snapshot;
  34275. }
  34276. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  34277. {
  34278. (void) existingComponentToUpdate;
  34279. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  34280. return 0;
  34281. }
  34282. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  34283. {
  34284. }
  34285. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  34286. {
  34287. }
  34288. void ListBoxModel::backgroundClicked()
  34289. {
  34290. }
  34291. void ListBoxModel::selectedRowsChanged (int)
  34292. {
  34293. }
  34294. void ListBoxModel::deleteKeyPressed (int)
  34295. {
  34296. }
  34297. void ListBoxModel::returnKeyPressed (int)
  34298. {
  34299. }
  34300. void ListBoxModel::listWasScrolled()
  34301. {
  34302. }
  34303. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  34304. {
  34305. return String::empty;
  34306. }
  34307. END_JUCE_NAMESPACE
  34308. /********* End of inlined file: juce_ListBox.cpp *********/
  34309. /********* Start of inlined file: juce_ProgressBar.cpp *********/
  34310. BEGIN_JUCE_NAMESPACE
  34311. ProgressBar::ProgressBar (double& progress_)
  34312. : progress (progress_),
  34313. displayPercentage (true)
  34314. {
  34315. currentValue = jlimit (0.0, 1.0, progress);
  34316. }
  34317. ProgressBar::~ProgressBar()
  34318. {
  34319. }
  34320. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  34321. {
  34322. displayPercentage = shouldDisplayPercentage;
  34323. repaint();
  34324. }
  34325. void ProgressBar::setTextToDisplay (const String& text)
  34326. {
  34327. displayPercentage = false;
  34328. displayedMessage = text;
  34329. }
  34330. void ProgressBar::lookAndFeelChanged()
  34331. {
  34332. setOpaque (findColour (backgroundColourId).isOpaque());
  34333. }
  34334. void ProgressBar::colourChanged()
  34335. {
  34336. lookAndFeelChanged();
  34337. }
  34338. void ProgressBar::paint (Graphics& g)
  34339. {
  34340. String text;
  34341. if (displayPercentage)
  34342. {
  34343. if (currentValue >= 0 && currentValue <= 1.0)
  34344. text << roundDoubleToInt (currentValue * 100.0) << T("%");
  34345. }
  34346. else
  34347. {
  34348. text = displayedMessage;
  34349. }
  34350. getLookAndFeel().drawProgressBar (g, *this,
  34351. getWidth(), getHeight(),
  34352. currentValue, text);
  34353. }
  34354. void ProgressBar::visibilityChanged()
  34355. {
  34356. if (isVisible())
  34357. startTimer (30);
  34358. else
  34359. stopTimer();
  34360. }
  34361. void ProgressBar::timerCallback()
  34362. {
  34363. double newProgress = progress;
  34364. if (currentValue != newProgress
  34365. || newProgress < 0 || newProgress >= 1.0
  34366. || currentMessage != displayedMessage)
  34367. {
  34368. if (currentValue < newProgress
  34369. && newProgress >= 0 && newProgress < 1.0
  34370. && currentValue >= 0 && newProgress < 1.0)
  34371. {
  34372. newProgress = jmin (currentValue + 0.02, newProgress);
  34373. }
  34374. currentValue = newProgress;
  34375. currentMessage = displayedMessage;
  34376. repaint();
  34377. }
  34378. }
  34379. END_JUCE_NAMESPACE
  34380. /********* End of inlined file: juce_ProgressBar.cpp *********/
  34381. /********* Start of inlined file: juce_Slider.cpp *********/
  34382. BEGIN_JUCE_NAMESPACE
  34383. class SliderPopupDisplayComponent : public BubbleComponent
  34384. {
  34385. public:
  34386. SliderPopupDisplayComponent (Slider* const owner_)
  34387. : owner (owner_),
  34388. font (15.0f, Font::bold)
  34389. {
  34390. setAlwaysOnTop (true);
  34391. }
  34392. ~SliderPopupDisplayComponent()
  34393. {
  34394. }
  34395. void paintContent (Graphics& g, int w, int h)
  34396. {
  34397. g.setFont (font);
  34398. g.setColour (Colours::black);
  34399. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  34400. }
  34401. void getContentSize (int& w, int& h)
  34402. {
  34403. w = font.getStringWidth (text) + 18;
  34404. h = (int) (font.getHeight() * 1.6f);
  34405. }
  34406. void updatePosition (const String& newText)
  34407. {
  34408. if (text != newText)
  34409. {
  34410. text = newText;
  34411. repaint();
  34412. }
  34413. BubbleComponent::setPosition (owner);
  34414. }
  34415. juce_UseDebuggingNewOperator
  34416. private:
  34417. Slider* owner;
  34418. Font font;
  34419. String text;
  34420. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  34421. const SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  34422. };
  34423. Slider::Slider (const String& name)
  34424. : Component (name),
  34425. listeners (2),
  34426. currentValue (0.0),
  34427. valueMin (0.0),
  34428. valueMax (0.0),
  34429. minimum (0),
  34430. maximum (10),
  34431. interval (0),
  34432. skewFactor (1.0),
  34433. velocityModeSensitivity (1.0),
  34434. velocityModeOffset (0.0),
  34435. velocityModeThreshold (1),
  34436. rotaryStart (float_Pi * 1.2f),
  34437. rotaryEnd (float_Pi * 2.8f),
  34438. numDecimalPlaces (7),
  34439. sliderRegionStart (0),
  34440. sliderRegionSize (1),
  34441. sliderBeingDragged (-1),
  34442. pixelsForFullDragExtent (250),
  34443. style (LinearHorizontal),
  34444. textBoxPos (TextBoxLeft),
  34445. textBoxWidth (80),
  34446. textBoxHeight (20),
  34447. incDecButtonMode (incDecButtonsNotDraggable),
  34448. editableText (true),
  34449. doubleClickToValue (false),
  34450. isVelocityBased (false),
  34451. userKeyOverridesVelocity (true),
  34452. rotaryStop (true),
  34453. incDecButtonsSideBySide (false),
  34454. sendChangeOnlyOnRelease (false),
  34455. popupDisplayEnabled (false),
  34456. menuEnabled (false),
  34457. menuShown (false),
  34458. scrollWheelEnabled (true),
  34459. snapsToMousePos (true),
  34460. valueBox (0),
  34461. incButton (0),
  34462. decButton (0),
  34463. popupDisplay (0),
  34464. parentForPopupDisplay (0)
  34465. {
  34466. setWantsKeyboardFocus (false);
  34467. setRepaintsOnMouseActivity (true);
  34468. lookAndFeelChanged();
  34469. updateText();
  34470. }
  34471. Slider::~Slider()
  34472. {
  34473. deleteAndZero (popupDisplay);
  34474. deleteAllChildren();
  34475. }
  34476. void Slider::handleAsyncUpdate()
  34477. {
  34478. cancelPendingUpdate();
  34479. for (int i = listeners.size(); --i >= 0;)
  34480. {
  34481. ((SliderListener*) listeners.getUnchecked (i))->sliderValueChanged (this);
  34482. i = jmin (i, listeners.size());
  34483. }
  34484. }
  34485. void Slider::sendDragStart()
  34486. {
  34487. startedDragging();
  34488. for (int i = listeners.size(); --i >= 0;)
  34489. {
  34490. ((SliderListener*) listeners.getUnchecked (i))->sliderDragStarted (this);
  34491. i = jmin (i, listeners.size());
  34492. }
  34493. }
  34494. void Slider::sendDragEnd()
  34495. {
  34496. stoppedDragging();
  34497. sliderBeingDragged = -1;
  34498. for (int i = listeners.size(); --i >= 0;)
  34499. {
  34500. ((SliderListener*) listeners.getUnchecked (i))->sliderDragEnded (this);
  34501. i = jmin (i, listeners.size());
  34502. }
  34503. }
  34504. void Slider::addListener (SliderListener* const listener) throw()
  34505. {
  34506. jassert (listener != 0);
  34507. if (listener != 0)
  34508. listeners.add (listener);
  34509. }
  34510. void Slider::removeListener (SliderListener* const listener) throw()
  34511. {
  34512. listeners.removeValue (listener);
  34513. }
  34514. void Slider::setSliderStyle (const SliderStyle newStyle)
  34515. {
  34516. if (style != newStyle)
  34517. {
  34518. style = newStyle;
  34519. repaint();
  34520. lookAndFeelChanged();
  34521. }
  34522. }
  34523. void Slider::setRotaryParameters (const float startAngleRadians,
  34524. const float endAngleRadians,
  34525. const bool stopAtEnd)
  34526. {
  34527. // make sure the values are sensible..
  34528. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  34529. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  34530. jassert (rotaryStart < rotaryEnd);
  34531. rotaryStart = startAngleRadians;
  34532. rotaryEnd = endAngleRadians;
  34533. rotaryStop = stopAtEnd;
  34534. }
  34535. void Slider::setVelocityBasedMode (const bool velBased) throw()
  34536. {
  34537. isVelocityBased = velBased;
  34538. }
  34539. void Slider::setVelocityModeParameters (const double sensitivity,
  34540. const int threshold,
  34541. const double offset,
  34542. const bool userCanPressKeyToSwapMode) throw()
  34543. {
  34544. jassert (threshold >= 0);
  34545. jassert (sensitivity > 0);
  34546. jassert (offset >= 0);
  34547. velocityModeSensitivity = sensitivity;
  34548. velocityModeOffset = offset;
  34549. velocityModeThreshold = threshold;
  34550. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  34551. }
  34552. void Slider::setSkewFactor (const double factor) throw()
  34553. {
  34554. skewFactor = factor;
  34555. }
  34556. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw()
  34557. {
  34558. if (maximum > minimum)
  34559. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  34560. / (maximum - minimum));
  34561. }
  34562. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  34563. {
  34564. jassert (distanceForFullScaleDrag > 0);
  34565. pixelsForFullDragExtent = distanceForFullScaleDrag;
  34566. }
  34567. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  34568. {
  34569. if (incDecButtonMode != mode)
  34570. {
  34571. incDecButtonMode = mode;
  34572. lookAndFeelChanged();
  34573. }
  34574. }
  34575. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  34576. const bool isReadOnly,
  34577. const int textEntryBoxWidth,
  34578. const int textEntryBoxHeight)
  34579. {
  34580. textBoxPos = newPosition;
  34581. editableText = ! isReadOnly;
  34582. textBoxWidth = textEntryBoxWidth;
  34583. textBoxHeight = textEntryBoxHeight;
  34584. repaint();
  34585. lookAndFeelChanged();
  34586. }
  34587. void Slider::setTextBoxIsEditable (const bool shouldBeEditable) throw()
  34588. {
  34589. editableText = shouldBeEditable;
  34590. if (valueBox != 0)
  34591. valueBox->setEditable (shouldBeEditable && isEnabled());
  34592. }
  34593. void Slider::showTextBox()
  34594. {
  34595. jassert (editableText); // this should probably be avoided in read-only sliders.
  34596. if (valueBox != 0)
  34597. valueBox->showEditor();
  34598. }
  34599. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  34600. {
  34601. if (valueBox != 0)
  34602. {
  34603. valueBox->hideEditor (discardCurrentEditorContents);
  34604. if (discardCurrentEditorContents)
  34605. updateText();
  34606. }
  34607. }
  34608. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw()
  34609. {
  34610. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  34611. }
  34612. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw()
  34613. {
  34614. snapsToMousePos = shouldSnapToMouse;
  34615. }
  34616. void Slider::setPopupDisplayEnabled (const bool enabled,
  34617. Component* const parentComponentToUse) throw()
  34618. {
  34619. popupDisplayEnabled = enabled;
  34620. parentForPopupDisplay = parentComponentToUse;
  34621. }
  34622. void Slider::colourChanged()
  34623. {
  34624. lookAndFeelChanged();
  34625. }
  34626. void Slider::lookAndFeelChanged()
  34627. {
  34628. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  34629. : getTextFromValue (currentValue));
  34630. deleteAllChildren();
  34631. valueBox = 0;
  34632. LookAndFeel& lf = getLookAndFeel();
  34633. if (textBoxPos != NoTextBox)
  34634. {
  34635. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  34636. valueBox->setWantsKeyboardFocus (false);
  34637. valueBox->setText (previousTextBoxContent, false);
  34638. valueBox->setEditable (editableText && isEnabled());
  34639. valueBox->addListener (this);
  34640. if (style == LinearBar)
  34641. valueBox->addMouseListener (this, false);
  34642. }
  34643. if (style == IncDecButtons)
  34644. {
  34645. addAndMakeVisible (incButton = lf.createSliderButton (true));
  34646. incButton->addButtonListener (this);
  34647. addAndMakeVisible (decButton = lf.createSliderButton (false));
  34648. decButton->addButtonListener (this);
  34649. if (incDecButtonMode != incDecButtonsNotDraggable)
  34650. {
  34651. incButton->addMouseListener (this, false);
  34652. decButton->addMouseListener (this, false);
  34653. }
  34654. else
  34655. {
  34656. incButton->setRepeatSpeed (300, 100, 20);
  34657. incButton->addMouseListener (decButton, false);
  34658. decButton->setRepeatSpeed (300, 100, 20);
  34659. decButton->addMouseListener (incButton, false);
  34660. }
  34661. }
  34662. setComponentEffect (lf.getSliderEffect());
  34663. resized();
  34664. repaint();
  34665. }
  34666. void Slider::setRange (const double newMin,
  34667. const double newMax,
  34668. const double newInt)
  34669. {
  34670. if (minimum != newMin
  34671. || maximum != newMax
  34672. || interval != newInt)
  34673. {
  34674. minimum = newMin;
  34675. maximum = newMax;
  34676. interval = newInt;
  34677. // figure out the number of DPs needed to display all values at this
  34678. // interval setting.
  34679. numDecimalPlaces = 7;
  34680. if (newInt != 0)
  34681. {
  34682. int v = abs ((int) (newInt * 10000000));
  34683. while ((v % 10) == 0)
  34684. {
  34685. --numDecimalPlaces;
  34686. v /= 10;
  34687. }
  34688. }
  34689. // keep the current values inside the new range..
  34690. if (style != TwoValueHorizontal && style != TwoValueVertical)
  34691. {
  34692. setValue (currentValue, false, false);
  34693. }
  34694. else
  34695. {
  34696. setMinValue (getMinValue(), false, false);
  34697. setMaxValue (getMaxValue(), false, false);
  34698. }
  34699. updateText();
  34700. }
  34701. }
  34702. void Slider::triggerChangeMessage (const bool synchronous)
  34703. {
  34704. if (synchronous)
  34705. handleAsyncUpdate();
  34706. else
  34707. triggerAsyncUpdate();
  34708. valueChanged();
  34709. }
  34710. double Slider::getValue() const throw()
  34711. {
  34712. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  34713. // methods to get the two values.
  34714. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  34715. return currentValue;
  34716. }
  34717. void Slider::setValue (double newValue,
  34718. const bool sendUpdateMessage,
  34719. const bool sendMessageSynchronously)
  34720. {
  34721. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  34722. // methods to set the two values.
  34723. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  34724. newValue = constrainedValue (newValue);
  34725. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  34726. {
  34727. jassert (valueMin <= valueMax);
  34728. newValue = jlimit (valueMin, valueMax, newValue);
  34729. }
  34730. if (currentValue != newValue)
  34731. {
  34732. if (valueBox != 0)
  34733. valueBox->hideEditor (true);
  34734. currentValue = newValue;
  34735. updateText();
  34736. repaint();
  34737. if (popupDisplay != 0)
  34738. {
  34739. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (currentValue));
  34740. popupDisplay->repaint();
  34741. }
  34742. if (sendUpdateMessage)
  34743. triggerChangeMessage (sendMessageSynchronously);
  34744. }
  34745. }
  34746. double Slider::getMinValue() const throw()
  34747. {
  34748. // The minimum value only applies to sliders that are in two- or three-value mode.
  34749. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34750. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34751. return valueMin;
  34752. }
  34753. double Slider::getMaxValue() const throw()
  34754. {
  34755. // The maximum value only applies to sliders that are in two- or three-value mode.
  34756. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34757. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34758. return valueMax;
  34759. }
  34760. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously)
  34761. {
  34762. // The minimum value only applies to sliders that are in two- or three-value mode.
  34763. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34764. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34765. newValue = constrainedValue (newValue);
  34766. if (style == TwoValueHorizontal || style == TwoValueVertical)
  34767. newValue = jmin (valueMax, newValue);
  34768. else
  34769. newValue = jmin (currentValue, newValue);
  34770. if (valueMin != newValue)
  34771. {
  34772. valueMin = newValue;
  34773. repaint();
  34774. if (popupDisplay != 0)
  34775. {
  34776. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMin));
  34777. popupDisplay->repaint();
  34778. }
  34779. if (sendUpdateMessage)
  34780. triggerChangeMessage (sendMessageSynchronously);
  34781. }
  34782. }
  34783. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously)
  34784. {
  34785. // The maximum value only applies to sliders that are in two- or three-value mode.
  34786. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34787. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34788. newValue = constrainedValue (newValue);
  34789. if (style == TwoValueHorizontal || style == TwoValueVertical)
  34790. newValue = jmax (valueMin, newValue);
  34791. else
  34792. newValue = jmax (currentValue, newValue);
  34793. if (valueMax != newValue)
  34794. {
  34795. valueMax = newValue;
  34796. repaint();
  34797. if (popupDisplay != 0)
  34798. {
  34799. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMax));
  34800. popupDisplay->repaint();
  34801. }
  34802. if (sendUpdateMessage)
  34803. triggerChangeMessage (sendMessageSynchronously);
  34804. }
  34805. }
  34806. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  34807. const double valueToSetOnDoubleClick) throw()
  34808. {
  34809. doubleClickToValue = isDoubleClickEnabled;
  34810. doubleClickReturnValue = valueToSetOnDoubleClick;
  34811. }
  34812. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const throw()
  34813. {
  34814. isEnabled_ = doubleClickToValue;
  34815. return doubleClickReturnValue;
  34816. }
  34817. void Slider::updateText()
  34818. {
  34819. if (valueBox != 0)
  34820. valueBox->setText (getTextFromValue (currentValue), false);
  34821. }
  34822. void Slider::setTextValueSuffix (const String& suffix)
  34823. {
  34824. if (textSuffix != suffix)
  34825. {
  34826. textSuffix = suffix;
  34827. updateText();
  34828. }
  34829. }
  34830. const String Slider::getTextFromValue (double v)
  34831. {
  34832. if (numDecimalPlaces > 0)
  34833. return String (v, numDecimalPlaces) + textSuffix;
  34834. else
  34835. return String (roundDoubleToInt (v)) + textSuffix;
  34836. }
  34837. double Slider::getValueFromText (const String& text)
  34838. {
  34839. String t (text.trimStart());
  34840. if (t.endsWith (textSuffix))
  34841. t = t.substring (0, t.length() - textSuffix.length());
  34842. while (t.startsWithChar (T('+')))
  34843. t = t.substring (1).trimStart();
  34844. return t.initialSectionContainingOnly (T("0123456789.,-"))
  34845. .getDoubleValue();
  34846. }
  34847. double Slider::proportionOfLengthToValue (double proportion)
  34848. {
  34849. if (skewFactor != 1.0 && proportion > 0.0)
  34850. proportion = exp (log (proportion) / skewFactor);
  34851. return minimum + (maximum - minimum) * proportion;
  34852. }
  34853. double Slider::valueToProportionOfLength (double value)
  34854. {
  34855. const double n = (value - minimum) / (maximum - minimum);
  34856. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  34857. }
  34858. double Slider::snapValue (double attemptedValue, const bool)
  34859. {
  34860. return attemptedValue;
  34861. }
  34862. void Slider::startedDragging()
  34863. {
  34864. }
  34865. void Slider::stoppedDragging()
  34866. {
  34867. }
  34868. void Slider::valueChanged()
  34869. {
  34870. }
  34871. void Slider::enablementChanged()
  34872. {
  34873. repaint();
  34874. }
  34875. void Slider::setPopupMenuEnabled (const bool menuEnabled_) throw()
  34876. {
  34877. menuEnabled = menuEnabled_;
  34878. }
  34879. void Slider::setScrollWheelEnabled (const bool enabled) throw()
  34880. {
  34881. scrollWheelEnabled = enabled;
  34882. }
  34883. void Slider::labelTextChanged (Label* label)
  34884. {
  34885. const double newValue = snapValue (getValueFromText (label->getText()), false);
  34886. if (getValue() != newValue)
  34887. {
  34888. sendDragStart();
  34889. setValue (newValue, true, true);
  34890. sendDragEnd();
  34891. }
  34892. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  34893. }
  34894. void Slider::buttonClicked (Button* button)
  34895. {
  34896. if (style == IncDecButtons)
  34897. {
  34898. sendDragStart();
  34899. if (button == incButton)
  34900. setValue (snapValue (getValue() + interval, false), true, true);
  34901. else if (button == decButton)
  34902. setValue (snapValue (getValue() - interval, false), true, true);
  34903. sendDragEnd();
  34904. }
  34905. }
  34906. double Slider::constrainedValue (double value) const throw()
  34907. {
  34908. if (interval > 0)
  34909. value = minimum + interval * floor ((value - minimum) / interval + 0.5);
  34910. if (value <= minimum || maximum <= minimum)
  34911. value = minimum;
  34912. else if (value >= maximum)
  34913. value = maximum;
  34914. return value;
  34915. }
  34916. float Slider::getLinearSliderPos (const double value)
  34917. {
  34918. double sliderPosProportional;
  34919. if (maximum > minimum)
  34920. {
  34921. if (value < minimum)
  34922. {
  34923. sliderPosProportional = 0.0;
  34924. }
  34925. else if (value > maximum)
  34926. {
  34927. sliderPosProportional = 1.0;
  34928. }
  34929. else
  34930. {
  34931. sliderPosProportional = valueToProportionOfLength (value);
  34932. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  34933. }
  34934. }
  34935. else
  34936. {
  34937. sliderPosProportional = 0.5;
  34938. }
  34939. if (style == LinearVertical || style == IncDecButtons)
  34940. sliderPosProportional = 1.0 - sliderPosProportional;
  34941. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  34942. }
  34943. bool Slider::isHorizontal() const throw()
  34944. {
  34945. return style == LinearHorizontal
  34946. || style == LinearBar
  34947. || style == TwoValueHorizontal
  34948. || style == ThreeValueHorizontal;
  34949. }
  34950. bool Slider::isVertical() const throw()
  34951. {
  34952. return style == LinearVertical
  34953. || style == TwoValueVertical
  34954. || style == ThreeValueVertical;
  34955. }
  34956. bool Slider::incDecDragDirectionIsHorizontal() const throw()
  34957. {
  34958. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  34959. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  34960. }
  34961. float Slider::getPositionOfValue (const double value)
  34962. {
  34963. if (isHorizontal() || isVertical())
  34964. {
  34965. return getLinearSliderPos (value);
  34966. }
  34967. else
  34968. {
  34969. jassertfalse // not a valid call on a slider that doesn't work linearly!
  34970. return 0.0f;
  34971. }
  34972. }
  34973. void Slider::paint (Graphics& g)
  34974. {
  34975. if (style != IncDecButtons)
  34976. {
  34977. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  34978. {
  34979. const float sliderPos = (float) valueToProportionOfLength (currentValue);
  34980. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  34981. getLookAndFeel().drawRotarySlider (g,
  34982. sliderRect.getX(),
  34983. sliderRect.getY(),
  34984. sliderRect.getWidth(),
  34985. sliderRect.getHeight(),
  34986. sliderPos,
  34987. rotaryStart, rotaryEnd,
  34988. *this);
  34989. }
  34990. else
  34991. {
  34992. getLookAndFeel().drawLinearSlider (g,
  34993. sliderRect.getX(),
  34994. sliderRect.getY(),
  34995. sliderRect.getWidth(),
  34996. sliderRect.getHeight(),
  34997. getLinearSliderPos (currentValue),
  34998. getLinearSliderPos (valueMin),
  34999. getLinearSliderPos (valueMax),
  35000. style,
  35001. *this);
  35002. }
  35003. if (style == LinearBar && valueBox == 0)
  35004. {
  35005. g.setColour (findColour (Slider::textBoxOutlineColourId));
  35006. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  35007. }
  35008. }
  35009. }
  35010. void Slider::resized()
  35011. {
  35012. int minXSpace = 0;
  35013. int minYSpace = 0;
  35014. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  35015. minXSpace = 30;
  35016. else
  35017. minYSpace = 15;
  35018. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  35019. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  35020. if (style == LinearBar)
  35021. {
  35022. if (valueBox != 0)
  35023. valueBox->setBounds (0, 0, getWidth(), getHeight());
  35024. }
  35025. else
  35026. {
  35027. if (textBoxPos == NoTextBox)
  35028. {
  35029. sliderRect.setBounds (0, 0, getWidth(), getHeight());
  35030. }
  35031. else if (textBoxPos == TextBoxLeft)
  35032. {
  35033. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  35034. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  35035. }
  35036. else if (textBoxPos == TextBoxRight)
  35037. {
  35038. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  35039. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  35040. }
  35041. else if (textBoxPos == TextBoxAbove)
  35042. {
  35043. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  35044. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  35045. }
  35046. else if (textBoxPos == TextBoxBelow)
  35047. {
  35048. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  35049. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  35050. }
  35051. }
  35052. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  35053. if (style == LinearBar)
  35054. {
  35055. const int barIndent = 1;
  35056. sliderRegionStart = barIndent;
  35057. sliderRegionSize = getWidth() - barIndent * 2;
  35058. sliderRect.setBounds (sliderRegionStart, barIndent,
  35059. sliderRegionSize, getHeight() - barIndent * 2);
  35060. }
  35061. else if (isHorizontal())
  35062. {
  35063. sliderRegionStart = sliderRect.getX() + indent;
  35064. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  35065. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  35066. sliderRegionSize, sliderRect.getHeight());
  35067. }
  35068. else if (isVertical())
  35069. {
  35070. sliderRegionStart = sliderRect.getY() + indent;
  35071. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  35072. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  35073. sliderRect.getWidth(), sliderRegionSize);
  35074. }
  35075. else
  35076. {
  35077. sliderRegionStart = 0;
  35078. sliderRegionSize = 100;
  35079. }
  35080. if (style == IncDecButtons)
  35081. {
  35082. Rectangle buttonRect (sliderRect);
  35083. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  35084. buttonRect.expand (-2, 0);
  35085. else
  35086. buttonRect.expand (0, -2);
  35087. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  35088. if (incDecButtonsSideBySide)
  35089. {
  35090. decButton->setBounds (buttonRect.getX(),
  35091. buttonRect.getY(),
  35092. buttonRect.getWidth() / 2,
  35093. buttonRect.getHeight());
  35094. decButton->setConnectedEdges (Button::ConnectedOnRight);
  35095. incButton->setBounds (buttonRect.getCentreX(),
  35096. buttonRect.getY(),
  35097. buttonRect.getWidth() / 2,
  35098. buttonRect.getHeight());
  35099. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  35100. }
  35101. else
  35102. {
  35103. incButton->setBounds (buttonRect.getX(),
  35104. buttonRect.getY(),
  35105. buttonRect.getWidth(),
  35106. buttonRect.getHeight() / 2);
  35107. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  35108. decButton->setBounds (buttonRect.getX(),
  35109. buttonRect.getCentreY(),
  35110. buttonRect.getWidth(),
  35111. buttonRect.getHeight() / 2);
  35112. decButton->setConnectedEdges (Button::ConnectedOnTop);
  35113. }
  35114. }
  35115. }
  35116. void Slider::focusOfChildComponentChanged (FocusChangeType)
  35117. {
  35118. repaint();
  35119. }
  35120. void Slider::mouseDown (const MouseEvent& e)
  35121. {
  35122. mouseWasHidden = false;
  35123. incDecDragged = false;
  35124. if (isEnabled())
  35125. {
  35126. if (e.mods.isPopupMenu() && menuEnabled)
  35127. {
  35128. menuShown = true;
  35129. PopupMenu m;
  35130. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  35131. m.addSeparator();
  35132. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  35133. {
  35134. PopupMenu rotaryMenu;
  35135. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  35136. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  35137. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  35138. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  35139. }
  35140. const int r = m.show();
  35141. if (r == 1)
  35142. {
  35143. setVelocityBasedMode (! isVelocityBased);
  35144. }
  35145. else if (r == 2)
  35146. {
  35147. setSliderStyle (Rotary);
  35148. }
  35149. else if (r == 3)
  35150. {
  35151. setSliderStyle (RotaryHorizontalDrag);
  35152. }
  35153. else if (r == 4)
  35154. {
  35155. setSliderStyle (RotaryVerticalDrag);
  35156. }
  35157. }
  35158. else if (maximum > minimum)
  35159. {
  35160. menuShown = false;
  35161. if (valueBox != 0)
  35162. valueBox->hideEditor (true);
  35163. sliderBeingDragged = 0;
  35164. if (style == TwoValueHorizontal
  35165. || style == TwoValueVertical
  35166. || style == ThreeValueHorizontal
  35167. || style == ThreeValueVertical)
  35168. {
  35169. const float mousePos = (float) (isVertical() ? e.y : e.x);
  35170. const float normalPosDistance = fabsf (getLinearSliderPos (currentValue) - mousePos);
  35171. const float minPosDistance = fabsf (getLinearSliderPos (valueMin) - 0.1f - mousePos);
  35172. const float maxPosDistance = fabsf (getLinearSliderPos (valueMax) + 0.1f - mousePos);
  35173. if (style == TwoValueHorizontal || style == TwoValueVertical)
  35174. {
  35175. if (maxPosDistance <= minPosDistance)
  35176. sliderBeingDragged = 2;
  35177. else
  35178. sliderBeingDragged = 1;
  35179. }
  35180. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  35181. {
  35182. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  35183. sliderBeingDragged = 1;
  35184. else if (normalPosDistance >= maxPosDistance)
  35185. sliderBeingDragged = 2;
  35186. }
  35187. }
  35188. minMaxDiff = valueMax - valueMin;
  35189. mouseXWhenLastDragged = e.x;
  35190. mouseYWhenLastDragged = e.y;
  35191. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  35192. * valueToProportionOfLength (currentValue);
  35193. if (sliderBeingDragged == 2)
  35194. valueWhenLastDragged = valueMax;
  35195. else if (sliderBeingDragged == 1)
  35196. valueWhenLastDragged = valueMin;
  35197. else
  35198. valueWhenLastDragged = currentValue;
  35199. valueOnMouseDown = valueWhenLastDragged;
  35200. if (popupDisplayEnabled)
  35201. {
  35202. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  35203. popupDisplay = popup;
  35204. if (parentForPopupDisplay != 0)
  35205. {
  35206. parentForPopupDisplay->addChildComponent (popup);
  35207. }
  35208. else
  35209. {
  35210. popup->addToDesktop (0);
  35211. }
  35212. popup->setVisible (true);
  35213. }
  35214. sendDragStart();
  35215. mouseDrag (e);
  35216. }
  35217. }
  35218. }
  35219. void Slider::mouseUp (const MouseEvent&)
  35220. {
  35221. if (isEnabled()
  35222. && (! menuShown)
  35223. && (maximum > minimum)
  35224. && (style != IncDecButtons || incDecDragged))
  35225. {
  35226. restoreMouseIfHidden();
  35227. if (sendChangeOnlyOnRelease && valueOnMouseDown != currentValue)
  35228. triggerChangeMessage (false);
  35229. sendDragEnd();
  35230. deleteAndZero (popupDisplay);
  35231. if (style == IncDecButtons)
  35232. {
  35233. incButton->setState (Button::buttonNormal);
  35234. decButton->setState (Button::buttonNormal);
  35235. }
  35236. }
  35237. }
  35238. void Slider::restoreMouseIfHidden()
  35239. {
  35240. if (mouseWasHidden)
  35241. {
  35242. mouseWasHidden = false;
  35243. Component* c = Component::getComponentUnderMouse();
  35244. if (c == 0)
  35245. c = this;
  35246. c->enableUnboundedMouseMovement (false);
  35247. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  35248. : ((sliderBeingDragged == 1) ? getMinValue()
  35249. : currentValue);
  35250. const int pixelPos = (int) getLinearSliderPos (pos);
  35251. int x = isHorizontal() ? pixelPos : (getWidth() / 2);
  35252. int y = isVertical() ? pixelPos : (getHeight() / 2);
  35253. relativePositionToGlobal (x, y);
  35254. Desktop::setMousePosition (x, y);
  35255. }
  35256. }
  35257. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  35258. {
  35259. if (isEnabled()
  35260. && style != IncDecButtons
  35261. && style != Rotary
  35262. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  35263. {
  35264. restoreMouseIfHidden();
  35265. }
  35266. }
  35267. static double smallestAngleBetween (double a1, double a2)
  35268. {
  35269. return jmin (fabs (a1 - a2),
  35270. fabs (a1 + double_Pi * 2.0 - a2),
  35271. fabs (a2 + double_Pi * 2.0 - a1));
  35272. }
  35273. void Slider::mouseDrag (const MouseEvent& e)
  35274. {
  35275. if (isEnabled()
  35276. && (! menuShown)
  35277. && (maximum > minimum))
  35278. {
  35279. if (style == Rotary)
  35280. {
  35281. int dx = e.x - sliderRect.getCentreX();
  35282. int dy = e.y - sliderRect.getCentreY();
  35283. if (dx * dx + dy * dy > 25)
  35284. {
  35285. double angle = atan2 ((double) dx, (double) -dy);
  35286. while (angle < 0.0)
  35287. angle += double_Pi * 2.0;
  35288. if (rotaryStop && ! e.mouseWasClicked())
  35289. {
  35290. if (fabs (angle - lastAngle) > double_Pi)
  35291. {
  35292. if (angle >= lastAngle)
  35293. angle -= double_Pi * 2.0;
  35294. else
  35295. angle += double_Pi * 2.0;
  35296. }
  35297. if (angle >= lastAngle)
  35298. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  35299. else
  35300. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  35301. }
  35302. else
  35303. {
  35304. while (angle < rotaryStart)
  35305. angle += double_Pi * 2.0;
  35306. if (angle > rotaryEnd)
  35307. {
  35308. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  35309. angle = rotaryStart;
  35310. else
  35311. angle = rotaryEnd;
  35312. }
  35313. }
  35314. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  35315. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  35316. lastAngle = angle;
  35317. }
  35318. }
  35319. else
  35320. {
  35321. if (style == LinearBar && e.mouseWasClicked()
  35322. && valueBox != 0 && valueBox->isEditable())
  35323. return;
  35324. if (style == IncDecButtons)
  35325. {
  35326. if (! incDecDragged)
  35327. incDecDragged = e.getDistanceFromDragStart() > 10 && ! e.mouseWasClicked();
  35328. if (! incDecDragged)
  35329. return;
  35330. }
  35331. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  35332. : false))
  35333. || ((maximum - minimum) / sliderRegionSize < interval))
  35334. {
  35335. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  35336. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  35337. if (style == RotaryHorizontalDrag
  35338. || style == RotaryVerticalDrag
  35339. || style == IncDecButtons
  35340. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  35341. && ! snapsToMousePos))
  35342. {
  35343. const int mouseDiff = (style == RotaryHorizontalDrag
  35344. || style == LinearHorizontal
  35345. || style == LinearBar
  35346. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  35347. ? e.getDistanceFromDragStartX()
  35348. : -e.getDistanceFromDragStartY();
  35349. double newPos = valueToProportionOfLength (valueOnMouseDown)
  35350. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  35351. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  35352. if (style == IncDecButtons)
  35353. {
  35354. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  35355. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  35356. }
  35357. }
  35358. else
  35359. {
  35360. if (style == LinearVertical)
  35361. scaledMousePos = 1.0 - scaledMousePos;
  35362. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  35363. }
  35364. }
  35365. else
  35366. {
  35367. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  35368. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  35369. ? e.x - mouseXWhenLastDragged
  35370. : e.y - mouseYWhenLastDragged;
  35371. const double maxSpeed = jmax (200, sliderRegionSize);
  35372. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  35373. if (speed != 0)
  35374. {
  35375. speed = 0.2 * velocityModeSensitivity
  35376. * (1.0 + sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  35377. + jmax (0.0, (double) (speed - velocityModeThreshold))
  35378. / maxSpeed))));
  35379. if (mouseDiff < 0)
  35380. speed = -speed;
  35381. if (style == LinearVertical || style == RotaryVerticalDrag
  35382. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  35383. speed = -speed;
  35384. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  35385. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  35386. e.originalComponent->enableUnboundedMouseMovement (true, false);
  35387. mouseWasHidden = true;
  35388. }
  35389. }
  35390. }
  35391. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  35392. if (sliderBeingDragged == 0)
  35393. {
  35394. setValue (snapValue (valueWhenLastDragged, true),
  35395. ! sendChangeOnlyOnRelease, true);
  35396. }
  35397. else if (sliderBeingDragged == 1)
  35398. {
  35399. setMinValue (snapValue (valueWhenLastDragged, true),
  35400. ! sendChangeOnlyOnRelease, false);
  35401. if (e.mods.isShiftDown())
  35402. setMaxValue (getMinValue() + minMaxDiff, false);
  35403. else
  35404. minMaxDiff = valueMax - valueMin;
  35405. }
  35406. else
  35407. {
  35408. jassert (sliderBeingDragged == 2);
  35409. setMaxValue (snapValue (valueWhenLastDragged, true),
  35410. ! sendChangeOnlyOnRelease, false);
  35411. if (e.mods.isShiftDown())
  35412. setMinValue (getMaxValue() - minMaxDiff, false);
  35413. else
  35414. minMaxDiff = valueMax - valueMin;
  35415. }
  35416. mouseXWhenLastDragged = e.x;
  35417. mouseYWhenLastDragged = e.y;
  35418. }
  35419. }
  35420. void Slider::mouseDoubleClick (const MouseEvent&)
  35421. {
  35422. if (doubleClickToValue
  35423. && isEnabled()
  35424. && style != IncDecButtons
  35425. && minimum <= doubleClickReturnValue
  35426. && maximum >= doubleClickReturnValue)
  35427. {
  35428. sendDragStart();
  35429. setValue (doubleClickReturnValue, true, true);
  35430. sendDragEnd();
  35431. }
  35432. }
  35433. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  35434. {
  35435. if (scrollWheelEnabled && isEnabled())
  35436. {
  35437. if (maximum > minimum && ! isMouseButtonDownAnywhere())
  35438. {
  35439. if (valueBox != 0)
  35440. valueBox->hideEditor (false);
  35441. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  35442. const double currentPos = valueToProportionOfLength (currentValue);
  35443. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  35444. double delta = (newValue != currentValue)
  35445. ? jmax (fabs (newValue - currentValue), interval) : 0;
  35446. if (currentValue > newValue)
  35447. delta = -delta;
  35448. sendDragStart();
  35449. setValue (snapValue (currentValue + delta, false), true, true);
  35450. sendDragEnd();
  35451. }
  35452. }
  35453. else
  35454. {
  35455. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  35456. }
  35457. }
  35458. void SliderListener::sliderDragStarted (Slider*)
  35459. {
  35460. }
  35461. void SliderListener::sliderDragEnded (Slider*)
  35462. {
  35463. }
  35464. END_JUCE_NAMESPACE
  35465. /********* End of inlined file: juce_Slider.cpp *********/
  35466. /********* Start of inlined file: juce_TableHeaderComponent.cpp *********/
  35467. BEGIN_JUCE_NAMESPACE
  35468. class DragOverlayComp : public Component
  35469. {
  35470. public:
  35471. DragOverlayComp (Image* const image_)
  35472. : image (image_)
  35473. {
  35474. image->multiplyAllAlphas (0.8f);
  35475. setAlwaysOnTop (true);
  35476. }
  35477. ~DragOverlayComp()
  35478. {
  35479. delete image;
  35480. }
  35481. void paint (Graphics& g)
  35482. {
  35483. g.drawImageAt (image, 0, 0);
  35484. }
  35485. private:
  35486. Image* image;
  35487. DragOverlayComp (const DragOverlayComp&);
  35488. const DragOverlayComp& operator= (const DragOverlayComp&);
  35489. };
  35490. TableHeaderComponent::TableHeaderComponent()
  35491. : listeners (2),
  35492. dragOverlayComp (0),
  35493. columnsChanged (false),
  35494. columnsResized (false),
  35495. sortChanged (false),
  35496. menuActive (true),
  35497. stretchToFit (false),
  35498. columnIdBeingResized (0),
  35499. columnIdBeingDragged (0),
  35500. columnIdUnderMouse (0),
  35501. lastDeliberateWidth (0)
  35502. {
  35503. }
  35504. TableHeaderComponent::~TableHeaderComponent()
  35505. {
  35506. delete dragOverlayComp;
  35507. }
  35508. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  35509. {
  35510. menuActive = hasMenu;
  35511. }
  35512. bool TableHeaderComponent::isPopupMenuActive() const throw() { return menuActive; }
  35513. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const throw()
  35514. {
  35515. if (onlyCountVisibleColumns)
  35516. {
  35517. int num = 0;
  35518. for (int i = columns.size(); --i >= 0;)
  35519. if (columns.getUnchecked(i)->isVisible())
  35520. ++num;
  35521. return num;
  35522. }
  35523. else
  35524. {
  35525. return columns.size();
  35526. }
  35527. }
  35528. const String TableHeaderComponent::getColumnName (const int columnId) const throw()
  35529. {
  35530. const ColumnInfo* const ci = getInfoForId (columnId);
  35531. return ci != 0 ? ci->name : String::empty;
  35532. }
  35533. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  35534. {
  35535. ColumnInfo* const ci = getInfoForId (columnId);
  35536. if (ci != 0 && ci->name != newName)
  35537. {
  35538. ci->name = newName;
  35539. sendColumnsChanged();
  35540. }
  35541. }
  35542. void TableHeaderComponent::addColumn (const String& columnName,
  35543. const int columnId,
  35544. const int width,
  35545. const int minimumWidth,
  35546. const int maximumWidth,
  35547. const int propertyFlags,
  35548. const int insertIndex)
  35549. {
  35550. // can't have a duplicate or null ID!
  35551. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  35552. jassert (width > 0);
  35553. ColumnInfo* const ci = new ColumnInfo();
  35554. ci->name = columnName;
  35555. ci->id = columnId;
  35556. ci->width = width;
  35557. ci->lastDeliberateWidth = width;
  35558. ci->minimumWidth = minimumWidth;
  35559. ci->maximumWidth = maximumWidth;
  35560. if (ci->maximumWidth < 0)
  35561. ci->maximumWidth = INT_MAX;
  35562. jassert (ci->maximumWidth >= ci->minimumWidth);
  35563. ci->propertyFlags = propertyFlags;
  35564. columns.insert (insertIndex, ci);
  35565. sendColumnsChanged();
  35566. }
  35567. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  35568. {
  35569. const int index = getIndexOfColumnId (columnIdToRemove, false);
  35570. if (index >= 0)
  35571. {
  35572. columns.remove (index);
  35573. sortChanged = true;
  35574. sendColumnsChanged();
  35575. }
  35576. }
  35577. void TableHeaderComponent::removeAllColumns()
  35578. {
  35579. if (columns.size() > 0)
  35580. {
  35581. columns.clear();
  35582. sendColumnsChanged();
  35583. }
  35584. }
  35585. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  35586. {
  35587. const int currentIndex = getIndexOfColumnId (columnId, false);
  35588. newIndex = visibleIndexToTotalIndex (newIndex);
  35589. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  35590. {
  35591. columns.move (currentIndex, newIndex);
  35592. sendColumnsChanged();
  35593. }
  35594. }
  35595. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  35596. {
  35597. ColumnInfo* const ci = getInfoForId (columnId);
  35598. if (ci != 0 && ci->width != newWidth)
  35599. {
  35600. const int numColumns = getNumColumns (true);
  35601. ci->lastDeliberateWidth = ci->width
  35602. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  35603. if (stretchToFit)
  35604. {
  35605. const int index = getIndexOfColumnId (columnId, true) + 1;
  35606. if (((unsigned int) index) < (unsigned int) numColumns)
  35607. {
  35608. const int x = getColumnPosition (index).getX();
  35609. if (lastDeliberateWidth == 0)
  35610. lastDeliberateWidth = getTotalWidth();
  35611. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  35612. }
  35613. }
  35614. repaint();
  35615. columnsResized = true;
  35616. triggerAsyncUpdate();
  35617. }
  35618. }
  35619. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw()
  35620. {
  35621. int n = 0;
  35622. for (int i = 0; i < columns.size(); ++i)
  35623. {
  35624. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  35625. {
  35626. if (columns.getUnchecked(i)->id == columnId)
  35627. return n;
  35628. ++n;
  35629. }
  35630. }
  35631. return -1;
  35632. }
  35633. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw()
  35634. {
  35635. if (onlyCountVisibleColumns)
  35636. index = visibleIndexToTotalIndex (index);
  35637. const ColumnInfo* const ci = columns [index];
  35638. return (ci != 0) ? ci->id : 0;
  35639. }
  35640. const Rectangle TableHeaderComponent::getColumnPosition (const int index) const throw()
  35641. {
  35642. int x = 0, width = 0, n = 0;
  35643. for (int i = 0; i < columns.size(); ++i)
  35644. {
  35645. x += width;
  35646. if (columns.getUnchecked(i)->isVisible())
  35647. {
  35648. width = columns.getUnchecked(i)->width;
  35649. if (n++ == index)
  35650. break;
  35651. }
  35652. else
  35653. {
  35654. width = 0;
  35655. }
  35656. }
  35657. return Rectangle (x, 0, width, getHeight());
  35658. }
  35659. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const throw()
  35660. {
  35661. if (xToFind >= 0)
  35662. {
  35663. int x = 0;
  35664. for (int i = 0; i < columns.size(); ++i)
  35665. {
  35666. const ColumnInfo* const ci = columns.getUnchecked(i);
  35667. if (ci->isVisible())
  35668. {
  35669. x += ci->width;
  35670. if (xToFind < x)
  35671. return ci->id;
  35672. }
  35673. }
  35674. }
  35675. return 0;
  35676. }
  35677. int TableHeaderComponent::getTotalWidth() const throw()
  35678. {
  35679. int w = 0;
  35680. for (int i = columns.size(); --i >= 0;)
  35681. if (columns.getUnchecked(i)->isVisible())
  35682. w += columns.getUnchecked(i)->width;
  35683. return w;
  35684. }
  35685. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  35686. {
  35687. stretchToFit = shouldStretchToFit;
  35688. lastDeliberateWidth = getTotalWidth();
  35689. resized();
  35690. }
  35691. bool TableHeaderComponent::isStretchToFitActive() const throw()
  35692. {
  35693. return stretchToFit;
  35694. }
  35695. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  35696. {
  35697. if (stretchToFit && getWidth() > 0
  35698. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  35699. {
  35700. lastDeliberateWidth = targetTotalWidth;
  35701. resizeColumnsToFit (0, targetTotalWidth);
  35702. }
  35703. }
  35704. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  35705. {
  35706. targetTotalWidth = jmax (targetTotalWidth, 0);
  35707. StretchableObjectResizer sor;
  35708. int i;
  35709. for (i = firstColumnIndex; i < columns.size(); ++i)
  35710. {
  35711. ColumnInfo* const ci = columns.getUnchecked(i);
  35712. if (ci->isVisible())
  35713. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  35714. }
  35715. sor.resizeToFit (targetTotalWidth);
  35716. int visIndex = 0;
  35717. for (i = firstColumnIndex; i < columns.size(); ++i)
  35718. {
  35719. ColumnInfo* const ci = columns.getUnchecked(i);
  35720. if (ci->isVisible())
  35721. {
  35722. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  35723. (int) floor (sor.getItemSize (visIndex++)));
  35724. if (newWidth != ci->width)
  35725. {
  35726. ci->width = newWidth;
  35727. repaint();
  35728. columnsResized = true;
  35729. triggerAsyncUpdate();
  35730. }
  35731. }
  35732. }
  35733. }
  35734. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  35735. {
  35736. ColumnInfo* const ci = getInfoForId (columnId);
  35737. if (ci != 0 && shouldBeVisible != ci->isVisible())
  35738. {
  35739. if (shouldBeVisible)
  35740. ci->propertyFlags |= visible;
  35741. else
  35742. ci->propertyFlags &= ~visible;
  35743. sendColumnsChanged();
  35744. resized();
  35745. }
  35746. }
  35747. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  35748. {
  35749. const ColumnInfo* const ci = getInfoForId (columnId);
  35750. return ci != 0 && ci->isVisible();
  35751. }
  35752. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  35753. {
  35754. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  35755. {
  35756. for (int i = columns.size(); --i >= 0;)
  35757. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  35758. ColumnInfo* const ci = getInfoForId (columnId);
  35759. if (ci != 0)
  35760. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  35761. reSortTable();
  35762. }
  35763. }
  35764. int TableHeaderComponent::getSortColumnId() const throw()
  35765. {
  35766. for (int i = columns.size(); --i >= 0;)
  35767. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  35768. return columns.getUnchecked(i)->id;
  35769. return 0;
  35770. }
  35771. bool TableHeaderComponent::isSortedForwards() const throw()
  35772. {
  35773. for (int i = columns.size(); --i >= 0;)
  35774. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  35775. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  35776. return true;
  35777. }
  35778. void TableHeaderComponent::reSortTable()
  35779. {
  35780. sortChanged = true;
  35781. repaint();
  35782. triggerAsyncUpdate();
  35783. }
  35784. const String TableHeaderComponent::toString() const
  35785. {
  35786. String s;
  35787. XmlElement doc (T("TABLELAYOUT"));
  35788. doc.setAttribute (T("sortedCol"), getSortColumnId());
  35789. doc.setAttribute (T("sortForwards"), isSortedForwards());
  35790. for (int i = 0; i < columns.size(); ++i)
  35791. {
  35792. const ColumnInfo* const ci = columns.getUnchecked (i);
  35793. XmlElement* const e = new XmlElement (T("COLUMN"));
  35794. doc.addChildElement (e);
  35795. e->setAttribute (T("id"), ci->id);
  35796. e->setAttribute (T("visible"), ci->isVisible());
  35797. e->setAttribute (T("width"), ci->width);
  35798. }
  35799. return doc.createDocument (String::empty, true, false);
  35800. }
  35801. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  35802. {
  35803. XmlDocument doc (storedVersion);
  35804. XmlElement* const storedXml = doc.getDocumentElement();
  35805. int index = 0;
  35806. if (storedXml != 0 && storedXml->hasTagName (T("TABLELAYOUT")))
  35807. {
  35808. forEachXmlChildElement (*storedXml, col)
  35809. {
  35810. const int tabId = col->getIntAttribute (T("id"));
  35811. ColumnInfo* const ci = getInfoForId (tabId);
  35812. if (ci != 0)
  35813. {
  35814. columns.move (columns.indexOf (ci), index);
  35815. ci->width = col->getIntAttribute (T("width"));
  35816. setColumnVisible (tabId, col->getBoolAttribute (T("visible")));
  35817. }
  35818. ++index;
  35819. }
  35820. columnsResized = true;
  35821. sendColumnsChanged();
  35822. setSortColumnId (storedXml->getIntAttribute (T("sortedCol")),
  35823. storedXml->getBoolAttribute (T("sortForwards"), true));
  35824. }
  35825. delete storedXml;
  35826. }
  35827. void TableHeaderComponent::addListener (TableHeaderListener* const newListener) throw()
  35828. {
  35829. listeners.addIfNotAlreadyThere (newListener);
  35830. }
  35831. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove) throw()
  35832. {
  35833. listeners.removeValue (listenerToRemove);
  35834. }
  35835. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  35836. {
  35837. const ColumnInfo* const ci = getInfoForId (columnId);
  35838. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  35839. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  35840. }
  35841. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  35842. {
  35843. for (int i = 0; i < columns.size(); ++i)
  35844. {
  35845. const ColumnInfo* const ci = columns.getUnchecked(i);
  35846. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  35847. menu.addItem (ci->id, ci->name,
  35848. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  35849. isColumnVisible (ci->id));
  35850. }
  35851. }
  35852. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  35853. {
  35854. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  35855. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  35856. }
  35857. void TableHeaderComponent::paint (Graphics& g)
  35858. {
  35859. LookAndFeel& lf = getLookAndFeel();
  35860. lf.drawTableHeaderBackground (g, *this);
  35861. const Rectangle clip (g.getClipBounds());
  35862. int x = 0;
  35863. for (int i = 0; i < columns.size(); ++i)
  35864. {
  35865. const ColumnInfo* const ci = columns.getUnchecked(i);
  35866. if (ci->isVisible())
  35867. {
  35868. if (x + ci->width > clip.getX()
  35869. && (ci->id != columnIdBeingDragged
  35870. || dragOverlayComp == 0
  35871. || ! dragOverlayComp->isVisible()))
  35872. {
  35873. g.saveState();
  35874. g.setOrigin (x, 0);
  35875. g.reduceClipRegion (0, 0, ci->width, getHeight());
  35876. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  35877. ci->id == columnIdUnderMouse,
  35878. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  35879. ci->propertyFlags);
  35880. g.restoreState();
  35881. }
  35882. x += ci->width;
  35883. if (x >= clip.getRight())
  35884. break;
  35885. }
  35886. }
  35887. }
  35888. void TableHeaderComponent::resized()
  35889. {
  35890. }
  35891. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  35892. {
  35893. updateColumnUnderMouse (e.x, e.y);
  35894. }
  35895. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  35896. {
  35897. updateColumnUnderMouse (e.x, e.y);
  35898. }
  35899. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  35900. {
  35901. updateColumnUnderMouse (e.x, e.y);
  35902. }
  35903. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  35904. {
  35905. repaint();
  35906. columnIdBeingResized = 0;
  35907. columnIdBeingDragged = 0;
  35908. if (columnIdUnderMouse != 0)
  35909. {
  35910. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  35911. if (e.mods.isPopupMenu())
  35912. columnClicked (columnIdUnderMouse, e.mods);
  35913. }
  35914. if (menuActive && e.mods.isPopupMenu())
  35915. showColumnChooserMenu (columnIdUnderMouse);
  35916. }
  35917. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  35918. {
  35919. if (columnIdBeingResized == 0
  35920. && columnIdBeingDragged == 0
  35921. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  35922. {
  35923. deleteAndZero (dragOverlayComp);
  35924. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  35925. if (columnIdBeingResized != 0)
  35926. {
  35927. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  35928. initialColumnWidth = ci->width;
  35929. }
  35930. else
  35931. {
  35932. beginDrag (e);
  35933. }
  35934. }
  35935. if (columnIdBeingResized != 0)
  35936. {
  35937. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  35938. if (ci != 0)
  35939. {
  35940. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  35941. initialColumnWidth + e.getDistanceFromDragStartX());
  35942. if (stretchToFit)
  35943. {
  35944. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  35945. int minWidthOnRight = 0;
  35946. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  35947. if (columns.getUnchecked (i)->isVisible())
  35948. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  35949. const Rectangle currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  35950. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  35951. }
  35952. setColumnWidth (columnIdBeingResized, w);
  35953. }
  35954. }
  35955. else if (columnIdBeingDragged != 0)
  35956. {
  35957. if (e.y >= -50 && e.y < getHeight() + 50)
  35958. {
  35959. beginDrag (e);
  35960. if (dragOverlayComp != 0)
  35961. {
  35962. dragOverlayComp->setVisible (true);
  35963. dragOverlayComp->setBounds (jlimit (0,
  35964. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  35965. e.x - draggingColumnOffset),
  35966. 0,
  35967. dragOverlayComp->getWidth(),
  35968. getHeight());
  35969. for (int i = columns.size(); --i >= 0;)
  35970. {
  35971. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  35972. int newIndex = currentIndex;
  35973. if (newIndex > 0)
  35974. {
  35975. // if the previous column isn't draggable, we can't move our column
  35976. // past it, because that'd change the undraggable column's position..
  35977. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  35978. if ((previous->propertyFlags & draggable) != 0)
  35979. {
  35980. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  35981. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  35982. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  35983. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  35984. {
  35985. --newIndex;
  35986. }
  35987. }
  35988. }
  35989. if (newIndex < columns.size() - 1)
  35990. {
  35991. // if the next column isn't draggable, we can't move our column
  35992. // past it, because that'd change the undraggable column's position..
  35993. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  35994. if ((nextCol->propertyFlags & draggable) != 0)
  35995. {
  35996. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  35997. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  35998. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  35999. > abs (dragOverlayComp->getRight() - rightOfNext))
  36000. {
  36001. ++newIndex;
  36002. }
  36003. }
  36004. }
  36005. if (newIndex != currentIndex)
  36006. moveColumn (columnIdBeingDragged, newIndex);
  36007. else
  36008. break;
  36009. }
  36010. }
  36011. }
  36012. else
  36013. {
  36014. endDrag (draggingColumnOriginalIndex);
  36015. }
  36016. }
  36017. }
  36018. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  36019. {
  36020. if (columnIdBeingDragged == 0)
  36021. {
  36022. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  36023. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  36024. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  36025. {
  36026. columnIdBeingDragged = 0;
  36027. }
  36028. else
  36029. {
  36030. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  36031. const Rectangle columnRect (getColumnPosition (draggingColumnOriginalIndex));
  36032. const int temp = columnIdBeingDragged;
  36033. columnIdBeingDragged = 0;
  36034. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  36035. columnIdBeingDragged = temp;
  36036. dragOverlayComp->setBounds (columnRect);
  36037. for (int i = listeners.size(); --i >= 0;)
  36038. {
  36039. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  36040. i = jmin (i, listeners.size() - 1);
  36041. }
  36042. }
  36043. }
  36044. }
  36045. void TableHeaderComponent::endDrag (const int finalIndex)
  36046. {
  36047. if (columnIdBeingDragged != 0)
  36048. {
  36049. moveColumn (columnIdBeingDragged, finalIndex);
  36050. columnIdBeingDragged = 0;
  36051. repaint();
  36052. for (int i = listeners.size(); --i >= 0;)
  36053. {
  36054. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  36055. i = jmin (i, listeners.size() - 1);
  36056. }
  36057. }
  36058. }
  36059. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  36060. {
  36061. mouseDrag (e);
  36062. for (int i = columns.size(); --i >= 0;)
  36063. if (columns.getUnchecked (i)->isVisible())
  36064. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  36065. columnIdBeingResized = 0;
  36066. repaint();
  36067. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  36068. updateColumnUnderMouse (e.x, e.y);
  36069. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  36070. columnClicked (columnIdUnderMouse, e.mods);
  36071. deleteAndZero (dragOverlayComp);
  36072. }
  36073. const MouseCursor TableHeaderComponent::getMouseCursor()
  36074. {
  36075. int x, y;
  36076. getMouseXYRelative (x, y);
  36077. if (columnIdBeingResized != 0 || (getResizeDraggerAt (x) != 0 && ! isMouseButtonDown()))
  36078. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  36079. return Component::getMouseCursor();
  36080. }
  36081. bool TableHeaderComponent::ColumnInfo::isVisible() const throw()
  36082. {
  36083. return (propertyFlags & TableHeaderComponent::visible) != 0;
  36084. }
  36085. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const throw()
  36086. {
  36087. for (int i = columns.size(); --i >= 0;)
  36088. if (columns.getUnchecked(i)->id == id)
  36089. return columns.getUnchecked(i);
  36090. return 0;
  36091. }
  36092. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const throw()
  36093. {
  36094. int n = 0;
  36095. for (int i = 0; i < columns.size(); ++i)
  36096. {
  36097. if (columns.getUnchecked(i)->isVisible())
  36098. {
  36099. if (n == visibleIndex)
  36100. return i;
  36101. ++n;
  36102. }
  36103. }
  36104. return -1;
  36105. }
  36106. void TableHeaderComponent::sendColumnsChanged()
  36107. {
  36108. if (stretchToFit && lastDeliberateWidth > 0)
  36109. resizeAllColumnsToFit (lastDeliberateWidth);
  36110. repaint();
  36111. columnsChanged = true;
  36112. triggerAsyncUpdate();
  36113. }
  36114. void TableHeaderComponent::handleAsyncUpdate()
  36115. {
  36116. const bool changed = columnsChanged || sortChanged;
  36117. const bool sized = columnsResized || changed;
  36118. const bool sorted = sortChanged;
  36119. columnsChanged = false;
  36120. columnsResized = false;
  36121. sortChanged = false;
  36122. if (sorted)
  36123. {
  36124. for (int i = listeners.size(); --i >= 0;)
  36125. {
  36126. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  36127. i = jmin (i, listeners.size() - 1);
  36128. }
  36129. }
  36130. if (changed)
  36131. {
  36132. for (int i = listeners.size(); --i >= 0;)
  36133. {
  36134. listeners.getUnchecked(i)->tableColumnsChanged (this);
  36135. i = jmin (i, listeners.size() - 1);
  36136. }
  36137. }
  36138. if (sized)
  36139. {
  36140. for (int i = listeners.size(); --i >= 0;)
  36141. {
  36142. listeners.getUnchecked(i)->tableColumnsResized (this);
  36143. i = jmin (i, listeners.size() - 1);
  36144. }
  36145. }
  36146. }
  36147. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const throw()
  36148. {
  36149. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  36150. {
  36151. const int draggableDistance = 3;
  36152. int x = 0;
  36153. for (int i = 0; i < columns.size(); ++i)
  36154. {
  36155. const ColumnInfo* const ci = columns.getUnchecked(i);
  36156. if (ci->isVisible())
  36157. {
  36158. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  36159. && (ci->propertyFlags & resizable) != 0)
  36160. return ci->id;
  36161. x += ci->width;
  36162. }
  36163. }
  36164. }
  36165. return 0;
  36166. }
  36167. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  36168. {
  36169. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  36170. ? getColumnIdAtX (x) : 0;
  36171. if (newCol != columnIdUnderMouse)
  36172. {
  36173. columnIdUnderMouse = newCol;
  36174. repaint();
  36175. }
  36176. }
  36177. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  36178. {
  36179. PopupMenu m;
  36180. addMenuItems (m, columnIdClicked);
  36181. if (m.getNumItems() > 0)
  36182. {
  36183. const int result = m.show();
  36184. if (result != 0)
  36185. reactToMenuItem (result, columnIdClicked);
  36186. }
  36187. }
  36188. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  36189. {
  36190. }
  36191. END_JUCE_NAMESPACE
  36192. /********* End of inlined file: juce_TableHeaderComponent.cpp *********/
  36193. /********* Start of inlined file: juce_TableListBox.cpp *********/
  36194. BEGIN_JUCE_NAMESPACE
  36195. static const tchar* const tableColumnPropertyTag = T("_tableColumnID");
  36196. class TableListRowComp : public Component
  36197. {
  36198. public:
  36199. TableListRowComp (TableListBox& owner_)
  36200. : owner (owner_),
  36201. row (-1),
  36202. isSelected (false)
  36203. {
  36204. }
  36205. ~TableListRowComp()
  36206. {
  36207. deleteAllChildren();
  36208. }
  36209. void paint (Graphics& g)
  36210. {
  36211. TableListBoxModel* const model = owner.getModel();
  36212. if (model != 0)
  36213. {
  36214. const TableHeaderComponent* const header = owner.getHeader();
  36215. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  36216. const int numColumns = header->getNumColumns (true);
  36217. for (int i = 0; i < numColumns; ++i)
  36218. {
  36219. if (! columnsWithComponents [i])
  36220. {
  36221. const int columnId = header->getColumnIdOfIndex (i, true);
  36222. Rectangle columnRect (header->getColumnPosition (i));
  36223. columnRect.setSize (columnRect.getWidth(), getHeight());
  36224. g.saveState();
  36225. g.reduceClipRegion (columnRect);
  36226. g.setOrigin (columnRect.getX(), 0);
  36227. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  36228. g.restoreState();
  36229. }
  36230. }
  36231. }
  36232. }
  36233. void update (const int newRow, const bool isNowSelected)
  36234. {
  36235. if (newRow != row || isNowSelected != isSelected)
  36236. {
  36237. row = newRow;
  36238. isSelected = isNowSelected;
  36239. repaint();
  36240. }
  36241. if (row < owner.getNumRows())
  36242. {
  36243. jassert (row >= 0);
  36244. const tchar* const tagPropertyName = T("_tableLastUseNum");
  36245. const int newTag = Random::getSystemRandom().nextInt();
  36246. const TableHeaderComponent* const header = owner.getHeader();
  36247. const int numColumns = header->getNumColumns (true);
  36248. int i;
  36249. columnsWithComponents.clear();
  36250. if (owner.getModel() != 0)
  36251. {
  36252. for (i = 0; i < numColumns; ++i)
  36253. {
  36254. const int columnId = header->getColumnIdOfIndex (i, true);
  36255. Component* const newComp
  36256. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  36257. findChildComponentForColumn (columnId));
  36258. if (newComp != 0)
  36259. {
  36260. addAndMakeVisible (newComp);
  36261. newComp->setComponentProperty (tagPropertyName, newTag);
  36262. newComp->setComponentProperty (tableColumnPropertyTag, columnId);
  36263. const Rectangle columnRect (header->getColumnPosition (i));
  36264. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  36265. columnsWithComponents.setBit (i);
  36266. }
  36267. }
  36268. }
  36269. for (i = getNumChildComponents(); --i >= 0;)
  36270. {
  36271. Component* const c = getChildComponent (i);
  36272. if (c->getComponentPropertyInt (tagPropertyName, false, 0) != newTag)
  36273. delete c;
  36274. }
  36275. }
  36276. else
  36277. {
  36278. columnsWithComponents.clear();
  36279. deleteAllChildren();
  36280. }
  36281. }
  36282. void resized()
  36283. {
  36284. for (int i = getNumChildComponents(); --i >= 0;)
  36285. {
  36286. Component* const c = getChildComponent (i);
  36287. const int columnId = c->getComponentPropertyInt (tableColumnPropertyTag, false, 0);
  36288. if (columnId != 0)
  36289. {
  36290. const Rectangle columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  36291. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  36292. }
  36293. }
  36294. }
  36295. void mouseDown (const MouseEvent& e)
  36296. {
  36297. isDragging = false;
  36298. selectRowOnMouseUp = false;
  36299. if (isEnabled())
  36300. {
  36301. if (! isSelected)
  36302. {
  36303. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  36304. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  36305. if (columnId != 0 && owner.getModel() != 0)
  36306. owner.getModel()->cellClicked (row, columnId, e);
  36307. }
  36308. else
  36309. {
  36310. selectRowOnMouseUp = true;
  36311. }
  36312. }
  36313. }
  36314. void mouseDrag (const MouseEvent& e)
  36315. {
  36316. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  36317. {
  36318. const SparseSet <int> selectedRows (owner.getSelectedRows());
  36319. if (selectedRows.size() > 0)
  36320. {
  36321. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  36322. if (dragDescription.isNotEmpty())
  36323. {
  36324. isDragging = true;
  36325. DragAndDropContainer* const dragContainer
  36326. = DragAndDropContainer::findParentDragContainerFor (this);
  36327. if (dragContainer != 0)
  36328. {
  36329. Image* dragImage = owner.createSnapshotOfSelectedRows();
  36330. dragImage->multiplyAllAlphas (0.6f);
  36331. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  36332. }
  36333. else
  36334. {
  36335. // to be able to do a drag-and-drop operation, the listbox needs to
  36336. // be inside a component which is also a DragAndDropContainer.
  36337. jassertfalse
  36338. }
  36339. }
  36340. }
  36341. }
  36342. }
  36343. void mouseUp (const MouseEvent& e)
  36344. {
  36345. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  36346. {
  36347. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  36348. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  36349. if (columnId != 0 && owner.getModel() != 0)
  36350. owner.getModel()->cellClicked (row, columnId, e);
  36351. }
  36352. }
  36353. void mouseDoubleClick (const MouseEvent& e)
  36354. {
  36355. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  36356. if (columnId != 0 && owner.getModel() != 0)
  36357. owner.getModel()->cellDoubleClicked (row, columnId, e);
  36358. }
  36359. juce_UseDebuggingNewOperator
  36360. private:
  36361. TableListBox& owner;
  36362. int row;
  36363. bool isSelected, isDragging, selectRowOnMouseUp;
  36364. BitArray columnsWithComponents;
  36365. Component* findChildComponentForColumn (const int columnId) const
  36366. {
  36367. for (int i = getNumChildComponents(); --i >= 0;)
  36368. {
  36369. Component* const c = getChildComponent (i);
  36370. if (c->getComponentPropertyInt (tableColumnPropertyTag, false, 0) == columnId)
  36371. return c;
  36372. }
  36373. return 0;
  36374. }
  36375. TableListRowComp (const TableListRowComp&);
  36376. const TableListRowComp& operator= (const TableListRowComp&);
  36377. };
  36378. class TableListBoxHeader : public TableHeaderComponent
  36379. {
  36380. public:
  36381. TableListBoxHeader (TableListBox& owner_)
  36382. : owner (owner_)
  36383. {
  36384. }
  36385. ~TableListBoxHeader()
  36386. {
  36387. }
  36388. void addMenuItems (PopupMenu& menu, const int columnIdClicked)
  36389. {
  36390. if (owner.isAutoSizeMenuOptionShown())
  36391. {
  36392. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  36393. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  36394. menu.addSeparator();
  36395. }
  36396. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  36397. }
  36398. void reactToMenuItem (const int menuReturnId, const int columnIdClicked)
  36399. {
  36400. if (menuReturnId == 0xf836743)
  36401. {
  36402. owner.autoSizeColumn (columnIdClicked);
  36403. }
  36404. else if (menuReturnId == 0xf836744)
  36405. {
  36406. owner.autoSizeAllColumns();
  36407. }
  36408. else
  36409. {
  36410. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  36411. }
  36412. }
  36413. juce_UseDebuggingNewOperator
  36414. private:
  36415. TableListBox& owner;
  36416. TableListBoxHeader (const TableListBoxHeader&);
  36417. const TableListBoxHeader& operator= (const TableListBoxHeader&);
  36418. };
  36419. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  36420. : ListBox (name, 0),
  36421. model (model_),
  36422. autoSizeOptionsShown (true)
  36423. {
  36424. ListBox::model = this;
  36425. header = new TableListBoxHeader (*this);
  36426. header->setSize (100, 28);
  36427. header->addListener (this);
  36428. setHeaderComponent (header);
  36429. }
  36430. TableListBox::~TableListBox()
  36431. {
  36432. deleteAllChildren();
  36433. }
  36434. void TableListBox::setModel (TableListBoxModel* const newModel)
  36435. {
  36436. if (model != newModel)
  36437. {
  36438. model = newModel;
  36439. updateContent();
  36440. }
  36441. }
  36442. int TableListBox::getHeaderHeight() const throw()
  36443. {
  36444. return header->getHeight();
  36445. }
  36446. void TableListBox::setHeaderHeight (const int newHeight)
  36447. {
  36448. header->setSize (header->getWidth(), newHeight);
  36449. resized();
  36450. }
  36451. void TableListBox::autoSizeColumn (const int columnId)
  36452. {
  36453. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  36454. if (width > 0)
  36455. header->setColumnWidth (columnId, width);
  36456. }
  36457. void TableListBox::autoSizeAllColumns()
  36458. {
  36459. for (int i = 0; i < header->getNumColumns (true); ++i)
  36460. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  36461. }
  36462. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  36463. {
  36464. autoSizeOptionsShown = shouldBeShown;
  36465. }
  36466. bool TableListBox::isAutoSizeMenuOptionShown() const throw()
  36467. {
  36468. return autoSizeOptionsShown;
  36469. }
  36470. const Rectangle TableListBox::getCellPosition (const int columnId,
  36471. const int rowNumber,
  36472. const bool relativeToComponentTopLeft) const
  36473. {
  36474. Rectangle headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  36475. if (relativeToComponentTopLeft)
  36476. headerCell.translate (header->getX(), 0);
  36477. const Rectangle row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  36478. return Rectangle (headerCell.getX(), row.getY(),
  36479. headerCell.getWidth(), row.getHeight());
  36480. }
  36481. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  36482. {
  36483. ScrollBar* const scrollbar = getHorizontalScrollBar();
  36484. if (scrollbar != 0)
  36485. {
  36486. const Rectangle pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  36487. double x = scrollbar->getCurrentRangeStart();
  36488. const double w = scrollbar->getCurrentRangeSize();
  36489. if (pos.getX() < x)
  36490. x = pos.getX();
  36491. else if (pos.getRight() > x + w)
  36492. x += jmax (0.0, pos.getRight() - (x + w));
  36493. scrollbar->setCurrentRangeStart (x);
  36494. }
  36495. }
  36496. int TableListBox::getNumRows()
  36497. {
  36498. return model != 0 ? model->getNumRows() : 0;
  36499. }
  36500. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  36501. {
  36502. }
  36503. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate)
  36504. {
  36505. if (existingComponentToUpdate == 0)
  36506. existingComponentToUpdate = new TableListRowComp (*this);
  36507. ((TableListRowComp*) existingComponentToUpdate)->update (rowNumber, isRowSelected);
  36508. return existingComponentToUpdate;
  36509. }
  36510. void TableListBox::selectedRowsChanged (int row)
  36511. {
  36512. if (model != 0)
  36513. model->selectedRowsChanged (row);
  36514. }
  36515. void TableListBox::deleteKeyPressed (int row)
  36516. {
  36517. if (model != 0)
  36518. model->deleteKeyPressed (row);
  36519. }
  36520. void TableListBox::returnKeyPressed (int row)
  36521. {
  36522. if (model != 0)
  36523. model->returnKeyPressed (row);
  36524. }
  36525. void TableListBox::backgroundClicked()
  36526. {
  36527. if (model != 0)
  36528. model->backgroundClicked();
  36529. }
  36530. void TableListBox::listWasScrolled()
  36531. {
  36532. if (model != 0)
  36533. model->listWasScrolled();
  36534. }
  36535. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  36536. {
  36537. setMinimumContentWidth (header->getTotalWidth());
  36538. repaint();
  36539. updateColumnComponents();
  36540. }
  36541. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  36542. {
  36543. setMinimumContentWidth (header->getTotalWidth());
  36544. repaint();
  36545. updateColumnComponents();
  36546. }
  36547. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  36548. {
  36549. if (model != 0)
  36550. model->sortOrderChanged (header->getSortColumnId(),
  36551. header->isSortedForwards());
  36552. }
  36553. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  36554. {
  36555. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  36556. repaint();
  36557. }
  36558. void TableListBox::resized()
  36559. {
  36560. ListBox::resized();
  36561. header->resizeAllColumnsToFit (getVisibleContentWidth());
  36562. setMinimumContentWidth (header->getTotalWidth());
  36563. }
  36564. void TableListBox::updateColumnComponents() const
  36565. {
  36566. const int firstRow = getRowContainingPosition (0, 0);
  36567. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  36568. {
  36569. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  36570. if (rowComp != 0)
  36571. rowComp->resized();
  36572. }
  36573. }
  36574. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  36575. {
  36576. }
  36577. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  36578. {
  36579. }
  36580. void TableListBoxModel::backgroundClicked()
  36581. {
  36582. }
  36583. void TableListBoxModel::sortOrderChanged (int, const bool)
  36584. {
  36585. }
  36586. int TableListBoxModel::getColumnAutoSizeWidth (int)
  36587. {
  36588. return 0;
  36589. }
  36590. void TableListBoxModel::selectedRowsChanged (int)
  36591. {
  36592. }
  36593. void TableListBoxModel::deleteKeyPressed (int)
  36594. {
  36595. }
  36596. void TableListBoxModel::returnKeyPressed (int)
  36597. {
  36598. }
  36599. void TableListBoxModel::listWasScrolled()
  36600. {
  36601. }
  36602. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  36603. {
  36604. return String::empty;
  36605. }
  36606. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  36607. {
  36608. (void) existingComponentToUpdate;
  36609. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  36610. return 0;
  36611. }
  36612. END_JUCE_NAMESPACE
  36613. /********* End of inlined file: juce_TableListBox.cpp *********/
  36614. /********* Start of inlined file: juce_TextEditor.cpp *********/
  36615. BEGIN_JUCE_NAMESPACE
  36616. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  36617. // a word or space that can't be broken down any further
  36618. struct TextAtom
  36619. {
  36620. String atomText;
  36621. float width;
  36622. uint16 numChars;
  36623. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (atomText[0]); }
  36624. bool isNewLine() const throw() { return atomText[0] == T('\r') || atomText[0] == T('\n'); }
  36625. const String getText (const tchar passwordCharacter) const throw()
  36626. {
  36627. if (passwordCharacter == 0)
  36628. return atomText;
  36629. else
  36630. return String::repeatedString (String::charToString (passwordCharacter),
  36631. atomText.length());
  36632. }
  36633. const String getTrimmedText (const tchar passwordCharacter) const throw()
  36634. {
  36635. if (passwordCharacter == 0)
  36636. return atomText.substring (0, numChars);
  36637. else if (isNewLine())
  36638. return String::empty;
  36639. else
  36640. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  36641. }
  36642. };
  36643. // a run of text with a single font and colour
  36644. class UniformTextSection
  36645. {
  36646. public:
  36647. UniformTextSection (const String& text,
  36648. const Font& font_,
  36649. const Colour& colour_,
  36650. const tchar passwordCharacter) throw()
  36651. : font (font_),
  36652. colour (colour_),
  36653. atoms (64)
  36654. {
  36655. initialiseAtoms (text, passwordCharacter);
  36656. }
  36657. UniformTextSection (const UniformTextSection& other) throw()
  36658. : font (other.font),
  36659. colour (other.colour),
  36660. atoms (64)
  36661. {
  36662. for (int i = 0; i < other.atoms.size(); ++i)
  36663. atoms.add (new TextAtom (*(const TextAtom*) other.atoms.getUnchecked(i)));
  36664. }
  36665. ~UniformTextSection() throw()
  36666. {
  36667. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  36668. }
  36669. void clear() throw()
  36670. {
  36671. for (int i = atoms.size(); --i >= 0;)
  36672. {
  36673. TextAtom* const atom = getAtom(i);
  36674. delete atom;
  36675. }
  36676. atoms.clear();
  36677. }
  36678. int getNumAtoms() const throw()
  36679. {
  36680. return atoms.size();
  36681. }
  36682. TextAtom* getAtom (const int index) const throw()
  36683. {
  36684. return (TextAtom*) atoms.getUnchecked (index);
  36685. }
  36686. void append (const UniformTextSection& other, const tchar passwordCharacter) throw()
  36687. {
  36688. if (other.atoms.size() > 0)
  36689. {
  36690. TextAtom* const lastAtom = (TextAtom*) atoms.getLast();
  36691. int i = 0;
  36692. if (lastAtom != 0)
  36693. {
  36694. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  36695. {
  36696. TextAtom* const first = other.getAtom(0);
  36697. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  36698. {
  36699. lastAtom->atomText += first->atomText;
  36700. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  36701. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  36702. delete first;
  36703. ++i;
  36704. }
  36705. }
  36706. }
  36707. while (i < other.atoms.size())
  36708. {
  36709. atoms.add (other.getAtom(i));
  36710. ++i;
  36711. }
  36712. }
  36713. }
  36714. UniformTextSection* split (const int indexToBreakAt,
  36715. const tchar passwordCharacter) throw()
  36716. {
  36717. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  36718. font, colour,
  36719. passwordCharacter);
  36720. int index = 0;
  36721. for (int i = 0; i < atoms.size(); ++i)
  36722. {
  36723. TextAtom* const atom = getAtom(i);
  36724. const int nextIndex = index + atom->numChars;
  36725. if (index == indexToBreakAt)
  36726. {
  36727. int j;
  36728. for (j = i; j < atoms.size(); ++j)
  36729. section2->atoms.add (getAtom (j));
  36730. for (j = atoms.size(); --j >= i;)
  36731. atoms.remove (j);
  36732. break;
  36733. }
  36734. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  36735. {
  36736. TextAtom* const secondAtom = new TextAtom();
  36737. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  36738. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  36739. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  36740. section2->atoms.add (secondAtom);
  36741. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  36742. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  36743. atom->numChars = (uint16) (indexToBreakAt - index);
  36744. int j;
  36745. for (j = i + 1; j < atoms.size(); ++j)
  36746. section2->atoms.add (getAtom (j));
  36747. for (j = atoms.size(); --j > i;)
  36748. atoms.remove (j);
  36749. break;
  36750. }
  36751. index = nextIndex;
  36752. }
  36753. return section2;
  36754. }
  36755. const String getAllText() const throw()
  36756. {
  36757. String s;
  36758. s.preallocateStorage (getTotalLength());
  36759. tchar* endOfString = (tchar*) &(s[0]);
  36760. for (int i = 0; i < atoms.size(); ++i)
  36761. {
  36762. const TextAtom* const atom = getAtom(i);
  36763. memcpy (endOfString, &(atom->atomText[0]), atom->numChars * sizeof (tchar));
  36764. endOfString += atom->numChars;
  36765. }
  36766. *endOfString = 0;
  36767. jassert ((endOfString - (tchar*) &(s[0])) <= getTotalLength());
  36768. return s;
  36769. }
  36770. const String getTextSubstring (const int startCharacter,
  36771. const int endCharacter) const throw()
  36772. {
  36773. int index = 0;
  36774. int totalLen = 0;
  36775. int i;
  36776. for (i = 0; i < atoms.size(); ++i)
  36777. {
  36778. const TextAtom* const atom = getAtom (i);
  36779. const int nextIndex = index + atom->numChars;
  36780. if (startCharacter < nextIndex)
  36781. {
  36782. if (endCharacter <= index)
  36783. break;
  36784. const int start = jmax (0, startCharacter - index);
  36785. const int end = jmin (endCharacter - index, atom->numChars);
  36786. jassert (end >= start);
  36787. totalLen += end - start;
  36788. }
  36789. index = nextIndex;
  36790. }
  36791. String s;
  36792. s.preallocateStorage (totalLen + 1);
  36793. tchar* psz = (tchar*) (const tchar*) s;
  36794. index = 0;
  36795. for (i = 0; i < atoms.size(); ++i)
  36796. {
  36797. const TextAtom* const atom = getAtom (i);
  36798. const int nextIndex = index + atom->numChars;
  36799. if (startCharacter < nextIndex)
  36800. {
  36801. if (endCharacter <= index)
  36802. break;
  36803. const int start = jmax (0, startCharacter - index);
  36804. const int len = jmin (endCharacter - index, atom->numChars) - start;
  36805. memcpy (psz, ((const tchar*) atom->atomText) + start, len * sizeof (tchar));
  36806. psz += len;
  36807. *psz = 0;
  36808. }
  36809. index = nextIndex;
  36810. }
  36811. return s;
  36812. }
  36813. int getTotalLength() const throw()
  36814. {
  36815. int c = 0;
  36816. for (int i = atoms.size(); --i >= 0;)
  36817. c += getAtom(i)->numChars;
  36818. return c;
  36819. }
  36820. void setFont (const Font& newFont,
  36821. const tchar passwordCharacter) throw()
  36822. {
  36823. if (font != newFont)
  36824. {
  36825. font = newFont;
  36826. for (int i = atoms.size(); --i >= 0;)
  36827. {
  36828. TextAtom* const atom = (TextAtom*) atoms.getUnchecked(i);
  36829. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  36830. }
  36831. }
  36832. }
  36833. juce_UseDebuggingNewOperator
  36834. Font font;
  36835. Colour colour;
  36836. private:
  36837. VoidArray atoms;
  36838. void initialiseAtoms (const String& textToParse,
  36839. const tchar passwordCharacter) throw()
  36840. {
  36841. int i = 0;
  36842. const int len = textToParse.length();
  36843. const tchar* const text = (const tchar*) textToParse;
  36844. while (i < len)
  36845. {
  36846. int start = i;
  36847. // create a whitespace atom unless it starts with non-ws
  36848. if (CharacterFunctions::isWhitespace (text[i])
  36849. && text[i] != T('\r')
  36850. && text[i] != T('\n'))
  36851. {
  36852. while (i < len
  36853. && CharacterFunctions::isWhitespace (text[i])
  36854. && text[i] != T('\r')
  36855. && text[i] != T('\n'))
  36856. {
  36857. ++i;
  36858. }
  36859. }
  36860. else
  36861. {
  36862. if (text[i] == T('\r'))
  36863. {
  36864. ++i;
  36865. if ((i < len) && (text[i] == T('\n')))
  36866. {
  36867. ++start;
  36868. ++i;
  36869. }
  36870. }
  36871. else if (text[i] == T('\n'))
  36872. {
  36873. ++i;
  36874. }
  36875. else
  36876. {
  36877. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  36878. ++i;
  36879. }
  36880. }
  36881. TextAtom* const atom = new TextAtom();
  36882. atom->atomText = String (text + start, i - start);
  36883. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  36884. atom->numChars = (uint16) (i - start);
  36885. atoms.add (atom);
  36886. }
  36887. }
  36888. const UniformTextSection& operator= (const UniformTextSection& other);
  36889. };
  36890. class TextEditorIterator
  36891. {
  36892. public:
  36893. TextEditorIterator (const VoidArray& sections_,
  36894. const float wordWrapWidth_,
  36895. const tchar passwordCharacter_) throw()
  36896. : indexInText (0),
  36897. lineY (0),
  36898. lineHeight (0),
  36899. maxDescent (0),
  36900. atomX (0),
  36901. atomRight (0),
  36902. atom (0),
  36903. currentSection (0),
  36904. sections (sections_),
  36905. sectionIndex (0),
  36906. atomIndex (0),
  36907. wordWrapWidth (wordWrapWidth_),
  36908. passwordCharacter (passwordCharacter_)
  36909. {
  36910. jassert (wordWrapWidth_ > 0);
  36911. if (sections.size() > 0)
  36912. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  36913. if (currentSection != 0)
  36914. {
  36915. lineHeight = currentSection->font.getHeight();
  36916. maxDescent = currentSection->font.getDescent();
  36917. }
  36918. }
  36919. TextEditorIterator (const TextEditorIterator& other) throw()
  36920. : indexInText (other.indexInText),
  36921. lineY (other.lineY),
  36922. lineHeight (other.lineHeight),
  36923. maxDescent (other.maxDescent),
  36924. atomX (other.atomX),
  36925. atomRight (other.atomRight),
  36926. atom (other.atom),
  36927. currentSection (other.currentSection),
  36928. sections (other.sections),
  36929. sectionIndex (other.sectionIndex),
  36930. atomIndex (other.atomIndex),
  36931. wordWrapWidth (other.wordWrapWidth),
  36932. passwordCharacter (other.passwordCharacter),
  36933. tempAtom (other.tempAtom)
  36934. {
  36935. }
  36936. ~TextEditorIterator() throw()
  36937. {
  36938. }
  36939. bool next() throw()
  36940. {
  36941. if (atom == &tempAtom)
  36942. {
  36943. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  36944. if (numRemaining > 0)
  36945. {
  36946. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  36947. atomX = 0;
  36948. if (tempAtom.numChars > 0)
  36949. lineY += lineHeight;
  36950. indexInText += tempAtom.numChars;
  36951. GlyphArrangement g;
  36952. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  36953. int split;
  36954. for (split = 0; split < g.getNumGlyphs(); ++split)
  36955. if (SHOULD_WRAP (g.getGlyph (split).getRight(), wordWrapWidth))
  36956. break;
  36957. if (split > 0 && split <= numRemaining)
  36958. {
  36959. tempAtom.numChars = (uint16) split;
  36960. tempAtom.width = g.getGlyph (split - 1).getRight();
  36961. atomRight = atomX + tempAtom.width;
  36962. return true;
  36963. }
  36964. }
  36965. }
  36966. bool forceNewLine = false;
  36967. if (sectionIndex >= sections.size())
  36968. {
  36969. moveToEndOfLastAtom();
  36970. return false;
  36971. }
  36972. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  36973. {
  36974. if (atomIndex >= currentSection->getNumAtoms())
  36975. {
  36976. if (++sectionIndex >= sections.size())
  36977. {
  36978. moveToEndOfLastAtom();
  36979. return false;
  36980. }
  36981. atomIndex = 0;
  36982. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  36983. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  36984. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  36985. }
  36986. else
  36987. {
  36988. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  36989. if (! lastAtom->isWhitespace())
  36990. {
  36991. // handle the case where the last atom in a section is actually part of the same
  36992. // word as the first atom of the next section...
  36993. float right = atomRight + lastAtom->width;
  36994. float lineHeight2 = lineHeight;
  36995. float maxDescent2 = maxDescent;
  36996. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  36997. {
  36998. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked (section);
  36999. if (s->getNumAtoms() == 0)
  37000. break;
  37001. const TextAtom* const nextAtom = s->getAtom (0);
  37002. if (nextAtom->isWhitespace())
  37003. break;
  37004. right += nextAtom->width;
  37005. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  37006. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  37007. if (SHOULD_WRAP (right, wordWrapWidth))
  37008. {
  37009. lineHeight = lineHeight2;
  37010. maxDescent = maxDescent2;
  37011. forceNewLine = true;
  37012. break;
  37013. }
  37014. if (s->getNumAtoms() > 1)
  37015. break;
  37016. }
  37017. }
  37018. }
  37019. }
  37020. if (atom != 0)
  37021. {
  37022. atomX = atomRight;
  37023. indexInText += atom->numChars;
  37024. if (atom->isNewLine())
  37025. {
  37026. atomX = 0;
  37027. lineY += lineHeight;
  37028. }
  37029. }
  37030. atom = currentSection->getAtom (atomIndex);
  37031. atomRight = atomX + atom->width;
  37032. ++atomIndex;
  37033. if (SHOULD_WRAP (atomRight, wordWrapWidth) || forceNewLine)
  37034. {
  37035. if (atom->isWhitespace())
  37036. {
  37037. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  37038. atomRight = jmin (atomRight, wordWrapWidth);
  37039. }
  37040. else
  37041. {
  37042. return wrapCurrentAtom();
  37043. }
  37044. }
  37045. return true;
  37046. }
  37047. bool wrapCurrentAtom() throw()
  37048. {
  37049. atomRight = atom->width;
  37050. if (SHOULD_WRAP (atomRight, wordWrapWidth)) // atom too big to fit on a line, so break it up..
  37051. {
  37052. tempAtom = *atom;
  37053. tempAtom.width = 0;
  37054. tempAtom.numChars = 0;
  37055. atom = &tempAtom;
  37056. if (atomX > 0)
  37057. {
  37058. atomX = 0;
  37059. lineY += lineHeight;
  37060. }
  37061. return next();
  37062. }
  37063. atomX = 0;
  37064. lineY += lineHeight;
  37065. return true;
  37066. }
  37067. void draw (Graphics& g, const UniformTextSection*& lastSection) const throw()
  37068. {
  37069. if (passwordCharacter != 0 || ! atom->isWhitespace())
  37070. {
  37071. if (lastSection != currentSection)
  37072. {
  37073. lastSection = currentSection;
  37074. g.setColour (currentSection->colour);
  37075. g.setFont (currentSection->font);
  37076. }
  37077. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  37078. GlyphArrangement ga;
  37079. ga.addLineOfText (currentSection->font,
  37080. atom->getTrimmedText (passwordCharacter),
  37081. atomX,
  37082. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  37083. ga.draw (g);
  37084. }
  37085. }
  37086. void drawSelection (Graphics& g,
  37087. const int selectionStart,
  37088. const int selectionEnd) const throw()
  37089. {
  37090. const int startX = roundFloatToInt (indexToX (selectionStart));
  37091. const int endX = roundFloatToInt (indexToX (selectionEnd));
  37092. const int y = roundFloatToInt (lineY);
  37093. const int nextY = roundFloatToInt (lineY + lineHeight);
  37094. g.fillRect (startX, y, endX - startX, nextY - y);
  37095. }
  37096. void drawSelectedText (Graphics& g,
  37097. const int selectionStart,
  37098. const int selectionEnd,
  37099. const Colour& selectedTextColour) const throw()
  37100. {
  37101. if (passwordCharacter != 0 || ! atom->isWhitespace())
  37102. {
  37103. GlyphArrangement ga;
  37104. ga.addLineOfText (currentSection->font,
  37105. atom->getTrimmedText (passwordCharacter),
  37106. atomX,
  37107. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  37108. if (selectionEnd < indexInText + atom->numChars)
  37109. {
  37110. GlyphArrangement ga2 (ga);
  37111. ga2.removeRangeOfGlyphs (0, selectionEnd - indexInText);
  37112. ga.removeRangeOfGlyphs (selectionEnd - indexInText, -1);
  37113. g.setColour (currentSection->colour);
  37114. ga2.draw (g);
  37115. }
  37116. if (selectionStart > indexInText)
  37117. {
  37118. GlyphArrangement ga2 (ga);
  37119. ga2.removeRangeOfGlyphs (selectionStart - indexInText, -1);
  37120. ga.removeRangeOfGlyphs (0, selectionStart - indexInText);
  37121. g.setColour (currentSection->colour);
  37122. ga2.draw (g);
  37123. }
  37124. g.setColour (selectedTextColour);
  37125. ga.draw (g);
  37126. }
  37127. }
  37128. float indexToX (const int indexToFind) const throw()
  37129. {
  37130. if (indexToFind <= indexInText)
  37131. return atomX;
  37132. if (indexToFind >= indexInText + atom->numChars)
  37133. return atomRight;
  37134. GlyphArrangement g;
  37135. g.addLineOfText (currentSection->font,
  37136. atom->getText (passwordCharacter),
  37137. atomX, 0.0f);
  37138. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  37139. }
  37140. int xToIndex (const float xToFind) const throw()
  37141. {
  37142. if (xToFind <= atomX || atom->isNewLine())
  37143. return indexInText;
  37144. if (xToFind >= atomRight)
  37145. return indexInText + atom->numChars;
  37146. GlyphArrangement g;
  37147. g.addLineOfText (currentSection->font,
  37148. atom->getText (passwordCharacter),
  37149. atomX, 0.0f);
  37150. int j;
  37151. for (j = 0; j < atom->numChars; ++j)
  37152. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  37153. break;
  37154. return indexInText + j;
  37155. }
  37156. void updateLineHeight() throw()
  37157. {
  37158. float x = atomRight;
  37159. int tempSectionIndex = sectionIndex;
  37160. int tempAtomIndex = atomIndex;
  37161. const UniformTextSection* currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  37162. while (! SHOULD_WRAP (x, wordWrapWidth))
  37163. {
  37164. if (tempSectionIndex >= sections.size())
  37165. break;
  37166. bool checkSize = false;
  37167. if (tempAtomIndex >= currentSection->getNumAtoms())
  37168. {
  37169. if (++tempSectionIndex >= sections.size())
  37170. break;
  37171. tempAtomIndex = 0;
  37172. currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  37173. checkSize = true;
  37174. }
  37175. const TextAtom* const atom = currentSection->getAtom (tempAtomIndex);
  37176. if (atom == 0)
  37177. break;
  37178. x += atom->width;
  37179. if (SHOULD_WRAP (x, wordWrapWidth) || atom->isNewLine())
  37180. break;
  37181. if (checkSize)
  37182. {
  37183. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  37184. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  37185. }
  37186. ++tempAtomIndex;
  37187. }
  37188. }
  37189. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_) throw()
  37190. {
  37191. while (next())
  37192. {
  37193. if (indexInText + atom->numChars >= index)
  37194. {
  37195. updateLineHeight();
  37196. if (indexInText + atom->numChars > index)
  37197. {
  37198. cx = indexToX (index);
  37199. cy = lineY;
  37200. lineHeight_ = lineHeight;
  37201. return true;
  37202. }
  37203. }
  37204. }
  37205. cx = atomX;
  37206. cy = lineY;
  37207. lineHeight_ = lineHeight;
  37208. return false;
  37209. }
  37210. juce_UseDebuggingNewOperator
  37211. int indexInText;
  37212. float lineY, lineHeight, maxDescent;
  37213. float atomX, atomRight;
  37214. const TextAtom* atom;
  37215. const UniformTextSection* currentSection;
  37216. private:
  37217. const VoidArray& sections;
  37218. int sectionIndex, atomIndex;
  37219. const float wordWrapWidth;
  37220. const tchar passwordCharacter;
  37221. TextAtom tempAtom;
  37222. const TextEditorIterator& operator= (const TextEditorIterator&);
  37223. void moveToEndOfLastAtom() throw()
  37224. {
  37225. if (atom != 0)
  37226. {
  37227. atomX = atomRight;
  37228. if (atom->isNewLine())
  37229. {
  37230. atomX = 0.0f;
  37231. lineY += lineHeight;
  37232. }
  37233. }
  37234. }
  37235. };
  37236. class TextEditorInsertAction : public UndoableAction
  37237. {
  37238. TextEditor& owner;
  37239. const String text;
  37240. const int insertIndex, oldCaretPos, newCaretPos;
  37241. const Font font;
  37242. const Colour colour;
  37243. TextEditorInsertAction (const TextEditorInsertAction&);
  37244. const TextEditorInsertAction& operator= (const TextEditorInsertAction&);
  37245. public:
  37246. TextEditorInsertAction (TextEditor& owner_,
  37247. const String& text_,
  37248. const int insertIndex_,
  37249. const Font& font_,
  37250. const Colour& colour_,
  37251. const int oldCaretPos_,
  37252. const int newCaretPos_) throw()
  37253. : owner (owner_),
  37254. text (text_),
  37255. insertIndex (insertIndex_),
  37256. oldCaretPos (oldCaretPos_),
  37257. newCaretPos (newCaretPos_),
  37258. font (font_),
  37259. colour (colour_)
  37260. {
  37261. }
  37262. ~TextEditorInsertAction()
  37263. {
  37264. }
  37265. bool perform()
  37266. {
  37267. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  37268. return true;
  37269. }
  37270. bool undo()
  37271. {
  37272. owner.remove (insertIndex, insertIndex + text.length(), 0, oldCaretPos);
  37273. return true;
  37274. }
  37275. int getSizeInUnits()
  37276. {
  37277. return text.length() + 16;
  37278. }
  37279. };
  37280. class TextEditorRemoveAction : public UndoableAction
  37281. {
  37282. TextEditor& owner;
  37283. const int startIndex, endIndex, oldCaretPos, newCaretPos;
  37284. VoidArray removedSections;
  37285. TextEditorRemoveAction (const TextEditorRemoveAction&);
  37286. const TextEditorRemoveAction& operator= (const TextEditorRemoveAction&);
  37287. public:
  37288. TextEditorRemoveAction (TextEditor& owner_,
  37289. const int startIndex_,
  37290. const int endIndex_,
  37291. const int oldCaretPos_,
  37292. const int newCaretPos_,
  37293. const VoidArray& removedSections_) throw()
  37294. : owner (owner_),
  37295. startIndex (startIndex_),
  37296. endIndex (endIndex_),
  37297. oldCaretPos (oldCaretPos_),
  37298. newCaretPos (newCaretPos_),
  37299. removedSections (removedSections_)
  37300. {
  37301. }
  37302. ~TextEditorRemoveAction()
  37303. {
  37304. for (int i = removedSections.size(); --i >= 0;)
  37305. {
  37306. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  37307. section->clear();
  37308. delete section;
  37309. }
  37310. }
  37311. bool perform()
  37312. {
  37313. owner.remove (startIndex, endIndex, 0, newCaretPos);
  37314. return true;
  37315. }
  37316. bool undo()
  37317. {
  37318. owner.reinsert (startIndex, removedSections);
  37319. owner.moveCursorTo (oldCaretPos, false);
  37320. return true;
  37321. }
  37322. int getSizeInUnits()
  37323. {
  37324. int n = 0;
  37325. for (int i = removedSections.size(); --i >= 0;)
  37326. {
  37327. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  37328. n += section->getTotalLength();
  37329. }
  37330. return n + 16;
  37331. }
  37332. };
  37333. class TextHolderComponent : public Component,
  37334. public Timer
  37335. {
  37336. TextEditor* const owner;
  37337. TextHolderComponent (const TextHolderComponent&);
  37338. const TextHolderComponent& operator= (const TextHolderComponent&);
  37339. public:
  37340. TextHolderComponent (TextEditor* const owner_)
  37341. : owner (owner_)
  37342. {
  37343. setWantsKeyboardFocus (false);
  37344. setInterceptsMouseClicks (false, true);
  37345. }
  37346. ~TextHolderComponent()
  37347. {
  37348. }
  37349. void paint (Graphics& g)
  37350. {
  37351. owner->drawContent (g);
  37352. }
  37353. void timerCallback()
  37354. {
  37355. owner->timerCallbackInt();
  37356. }
  37357. const MouseCursor getMouseCursor()
  37358. {
  37359. return owner->getMouseCursor();
  37360. }
  37361. };
  37362. class TextEditorViewport : public Viewport
  37363. {
  37364. TextEditor* const owner;
  37365. float lastWordWrapWidth;
  37366. TextEditorViewport (const TextEditorViewport&);
  37367. const TextEditorViewport& operator= (const TextEditorViewport&);
  37368. public:
  37369. TextEditorViewport (TextEditor* const owner_)
  37370. : owner (owner_),
  37371. lastWordWrapWidth (0)
  37372. {
  37373. }
  37374. ~TextEditorViewport()
  37375. {
  37376. }
  37377. void visibleAreaChanged (int, int, int, int)
  37378. {
  37379. const float wordWrapWidth = owner->getWordWrapWidth();
  37380. if (wordWrapWidth != lastWordWrapWidth)
  37381. {
  37382. lastWordWrapWidth = wordWrapWidth;
  37383. owner->updateTextHolderSize();
  37384. }
  37385. }
  37386. };
  37387. const int flashSpeedIntervalMs = 380;
  37388. const int textChangeMessageId = 0x10003001;
  37389. const int returnKeyMessageId = 0x10003002;
  37390. const int escapeKeyMessageId = 0x10003003;
  37391. const int focusLossMessageId = 0x10003004;
  37392. TextEditor::TextEditor (const String& name,
  37393. const tchar passwordCharacter_)
  37394. : Component (name),
  37395. borderSize (1, 1, 1, 3),
  37396. readOnly (false),
  37397. multiline (false),
  37398. wordWrap (false),
  37399. returnKeyStartsNewLine (false),
  37400. caretVisible (true),
  37401. popupMenuEnabled (true),
  37402. selectAllTextWhenFocused (false),
  37403. scrollbarVisible (true),
  37404. wasFocused (false),
  37405. caretFlashState (true),
  37406. keepCursorOnScreen (true),
  37407. tabKeyUsed (false),
  37408. menuActive (false),
  37409. cursorX (0),
  37410. cursorY (0),
  37411. cursorHeight (0),
  37412. maxTextLength (0),
  37413. selectionStart (0),
  37414. selectionEnd (0),
  37415. leftIndent (4),
  37416. topIndent (4),
  37417. lastTransactionTime (0),
  37418. currentFont (14.0f),
  37419. totalNumChars (0),
  37420. caretPosition (0),
  37421. sections (8),
  37422. passwordCharacter (passwordCharacter_),
  37423. dragType (notDragging),
  37424. listeners (2)
  37425. {
  37426. setOpaque (true);
  37427. addAndMakeVisible (viewport = new TextEditorViewport (this));
  37428. viewport->setViewedComponent (textHolder = new TextHolderComponent (this));
  37429. viewport->setWantsKeyboardFocus (false);
  37430. viewport->setScrollBarsShown (false, false);
  37431. setMouseCursor (MouseCursor::IBeamCursor);
  37432. setWantsKeyboardFocus (true);
  37433. }
  37434. TextEditor::~TextEditor()
  37435. {
  37436. clearInternal (0);
  37437. delete viewport;
  37438. }
  37439. void TextEditor::newTransaction() throw()
  37440. {
  37441. lastTransactionTime = Time::getApproximateMillisecondCounter();
  37442. undoManager.beginNewTransaction();
  37443. }
  37444. void TextEditor::doUndoRedo (const bool isRedo)
  37445. {
  37446. if (! isReadOnly())
  37447. {
  37448. if ((isRedo) ? undoManager.redo()
  37449. : undoManager.undo())
  37450. {
  37451. scrollToMakeSureCursorIsVisible();
  37452. repaint();
  37453. textChanged();
  37454. }
  37455. }
  37456. }
  37457. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  37458. const bool shouldWordWrap)
  37459. {
  37460. multiline = shouldBeMultiLine;
  37461. wordWrap = shouldWordWrap && shouldBeMultiLine;
  37462. setScrollbarsShown (scrollbarVisible);
  37463. viewport->setViewPosition (0, 0);
  37464. resized();
  37465. scrollToMakeSureCursorIsVisible();
  37466. }
  37467. bool TextEditor::isMultiLine() const throw()
  37468. {
  37469. return multiline;
  37470. }
  37471. void TextEditor::setScrollbarsShown (bool enabled) throw()
  37472. {
  37473. scrollbarVisible = enabled;
  37474. enabled = enabled && isMultiLine();
  37475. viewport->setScrollBarsShown (enabled, enabled);
  37476. }
  37477. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  37478. {
  37479. readOnly = shouldBeReadOnly;
  37480. enablementChanged();
  37481. }
  37482. bool TextEditor::isReadOnly() const throw()
  37483. {
  37484. return readOnly || ! isEnabled();
  37485. }
  37486. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  37487. {
  37488. returnKeyStartsNewLine = shouldStartNewLine;
  37489. }
  37490. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw()
  37491. {
  37492. tabKeyUsed = shouldTabKeyBeUsed;
  37493. }
  37494. void TextEditor::setPopupMenuEnabled (const bool b) throw()
  37495. {
  37496. popupMenuEnabled = b;
  37497. }
  37498. void TextEditor::setSelectAllWhenFocused (const bool b) throw()
  37499. {
  37500. selectAllTextWhenFocused = b;
  37501. }
  37502. const Font TextEditor::getFont() const throw()
  37503. {
  37504. return currentFont;
  37505. }
  37506. void TextEditor::setFont (const Font& newFont) throw()
  37507. {
  37508. currentFont = newFont;
  37509. scrollToMakeSureCursorIsVisible();
  37510. }
  37511. void TextEditor::applyFontToAllText (const Font& newFont)
  37512. {
  37513. currentFont = newFont;
  37514. const Colour overallColour (findColour (textColourId));
  37515. for (int i = sections.size(); --i >= 0;)
  37516. {
  37517. UniformTextSection* const uts = (UniformTextSection*) sections.getUnchecked(i);
  37518. uts->setFont (newFont, passwordCharacter);
  37519. uts->colour = overallColour;
  37520. }
  37521. coalesceSimilarSections();
  37522. updateTextHolderSize();
  37523. scrollToMakeSureCursorIsVisible();
  37524. repaint();
  37525. }
  37526. void TextEditor::colourChanged()
  37527. {
  37528. setOpaque (findColour (backgroundColourId).isOpaque());
  37529. repaint();
  37530. }
  37531. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible) throw()
  37532. {
  37533. caretVisible = shouldCaretBeVisible;
  37534. if (shouldCaretBeVisible)
  37535. textHolder->startTimer (flashSpeedIntervalMs);
  37536. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  37537. : MouseCursor::NormalCursor);
  37538. }
  37539. void TextEditor::setInputRestrictions (const int maxLen,
  37540. const String& chars) throw()
  37541. {
  37542. maxTextLength = jmax (0, maxLen);
  37543. allowedCharacters = chars;
  37544. }
  37545. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw()
  37546. {
  37547. textToShowWhenEmpty = text;
  37548. colourForTextWhenEmpty = colourToUse;
  37549. }
  37550. void TextEditor::setPasswordCharacter (const tchar newPasswordCharacter) throw()
  37551. {
  37552. if (passwordCharacter != newPasswordCharacter)
  37553. {
  37554. passwordCharacter = newPasswordCharacter;
  37555. resized();
  37556. repaint();
  37557. }
  37558. }
  37559. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  37560. {
  37561. viewport->setScrollBarThickness (newThicknessPixels);
  37562. }
  37563. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  37564. {
  37565. viewport->setScrollBarButtonVisibility (buttonsVisible);
  37566. }
  37567. void TextEditor::clear()
  37568. {
  37569. clearInternal (0);
  37570. updateTextHolderSize();
  37571. undoManager.clearUndoHistory();
  37572. }
  37573. void TextEditor::setText (const String& newText,
  37574. const bool sendTextChangeMessage)
  37575. {
  37576. const int newLength = newText.length();
  37577. if (newLength != getTotalNumChars() || getText() != newText)
  37578. {
  37579. const int oldCursorPos = caretPosition;
  37580. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  37581. clearInternal (0);
  37582. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  37583. // if you're adding text with line-feeds to a single-line text editor, it
  37584. // ain't gonna look right!
  37585. jassert (multiline || ! newText.containsAnyOf (T("\r\n")));
  37586. if (cursorWasAtEnd && ! isMultiLine())
  37587. moveCursorTo (getTotalNumChars(), false);
  37588. else
  37589. moveCursorTo (oldCursorPos, false);
  37590. if (sendTextChangeMessage)
  37591. textChanged();
  37592. repaint();
  37593. }
  37594. updateTextHolderSize();
  37595. scrollToMakeSureCursorIsVisible();
  37596. undoManager.clearUndoHistory();
  37597. }
  37598. void TextEditor::textChanged() throw()
  37599. {
  37600. updateTextHolderSize();
  37601. postCommandMessage (textChangeMessageId);
  37602. }
  37603. void TextEditor::returnPressed()
  37604. {
  37605. postCommandMessage (returnKeyMessageId);
  37606. }
  37607. void TextEditor::escapePressed()
  37608. {
  37609. postCommandMessage (escapeKeyMessageId);
  37610. }
  37611. void TextEditor::addListener (TextEditorListener* const newListener) throw()
  37612. {
  37613. jassert (newListener != 0)
  37614. if (newListener != 0)
  37615. listeners.add (newListener);
  37616. }
  37617. void TextEditor::removeListener (TextEditorListener* const listenerToRemove) throw()
  37618. {
  37619. listeners.removeValue (listenerToRemove);
  37620. }
  37621. void TextEditor::timerCallbackInt()
  37622. {
  37623. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  37624. if (caretFlashState != newState)
  37625. {
  37626. caretFlashState = newState;
  37627. if (caretFlashState)
  37628. wasFocused = true;
  37629. if (caretVisible
  37630. && hasKeyboardFocus (false)
  37631. && ! isReadOnly())
  37632. {
  37633. repaintCaret();
  37634. }
  37635. }
  37636. const unsigned int now = Time::getApproximateMillisecondCounter();
  37637. if (now > lastTransactionTime + 200)
  37638. newTransaction();
  37639. }
  37640. void TextEditor::repaintCaret()
  37641. {
  37642. if (! findColour (caretColourId).isTransparent())
  37643. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundFloatToInt (cursorX) - 1,
  37644. borderSize.getTop() + textHolder->getY() + topIndent + roundFloatToInt (cursorY) - 1,
  37645. 4,
  37646. roundFloatToInt (cursorHeight) + 2);
  37647. }
  37648. void TextEditor::repaintText (int textStartIndex, int textEndIndex)
  37649. {
  37650. if (textStartIndex > textEndIndex && textEndIndex > 0)
  37651. swapVariables (textStartIndex, textEndIndex);
  37652. float x = 0, y = 0, lh = currentFont.getHeight();
  37653. const float wordWrapWidth = getWordWrapWidth();
  37654. if (wordWrapWidth > 0)
  37655. {
  37656. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  37657. i.getCharPosition (textStartIndex, x, y, lh);
  37658. const int y1 = (int) y;
  37659. int y2;
  37660. if (textEndIndex >= 0)
  37661. {
  37662. i.getCharPosition (textEndIndex, x, y, lh);
  37663. y2 = (int) (y + lh * 2.0f);
  37664. }
  37665. else
  37666. {
  37667. y2 = textHolder->getHeight();
  37668. }
  37669. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  37670. }
  37671. }
  37672. void TextEditor::moveCaret (int newCaretPos) throw()
  37673. {
  37674. if (newCaretPos < 0)
  37675. newCaretPos = 0;
  37676. else if (newCaretPos > getTotalNumChars())
  37677. newCaretPos = getTotalNumChars();
  37678. if (newCaretPos != getCaretPosition())
  37679. {
  37680. repaintCaret();
  37681. caretFlashState = true;
  37682. caretPosition = newCaretPos;
  37683. textHolder->startTimer (flashSpeedIntervalMs);
  37684. scrollToMakeSureCursorIsVisible();
  37685. repaintCaret();
  37686. }
  37687. }
  37688. void TextEditor::setCaretPosition (const int newIndex) throw()
  37689. {
  37690. moveCursorTo (newIndex, false);
  37691. }
  37692. int TextEditor::getCaretPosition() const throw()
  37693. {
  37694. return caretPosition;
  37695. }
  37696. float TextEditor::getWordWrapWidth() const throw()
  37697. {
  37698. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  37699. : 1.0e10f;
  37700. }
  37701. void TextEditor::updateTextHolderSize() throw()
  37702. {
  37703. const float wordWrapWidth = getWordWrapWidth();
  37704. if (wordWrapWidth > 0)
  37705. {
  37706. float maxWidth = 0.0f;
  37707. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  37708. while (i.next())
  37709. maxWidth = jmax (maxWidth, i.atomRight);
  37710. const int w = leftIndent + roundFloatToInt (maxWidth);
  37711. const int h = topIndent + roundFloatToInt (jmax (i.lineY + i.lineHeight,
  37712. currentFont.getHeight()));
  37713. textHolder->setSize (w + 1, h + 1);
  37714. }
  37715. }
  37716. int TextEditor::getTextWidth() const throw()
  37717. {
  37718. return textHolder->getWidth();
  37719. }
  37720. int TextEditor::getTextHeight() const throw()
  37721. {
  37722. return textHolder->getHeight();
  37723. }
  37724. void TextEditor::setIndents (const int newLeftIndent,
  37725. const int newTopIndent) throw()
  37726. {
  37727. leftIndent = newLeftIndent;
  37728. topIndent = newTopIndent;
  37729. }
  37730. void TextEditor::setBorder (const BorderSize& border) throw()
  37731. {
  37732. borderSize = border;
  37733. resized();
  37734. }
  37735. const BorderSize TextEditor::getBorder() const throw()
  37736. {
  37737. return borderSize;
  37738. }
  37739. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor) throw()
  37740. {
  37741. keepCursorOnScreen = shouldScrollToShowCursor;
  37742. }
  37743. void TextEditor::scrollToMakeSureCursorIsVisible() throw()
  37744. {
  37745. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  37746. getCharPosition (caretPosition,
  37747. cursorX, cursorY,
  37748. cursorHeight);
  37749. if (keepCursorOnScreen)
  37750. {
  37751. int x = viewport->getViewPositionX();
  37752. int y = viewport->getViewPositionY();
  37753. const int relativeCursorX = roundFloatToInt (cursorX) - x;
  37754. const int relativeCursorY = roundFloatToInt (cursorY) - y;
  37755. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  37756. {
  37757. x += relativeCursorX - proportionOfWidth (0.2f);
  37758. }
  37759. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  37760. {
  37761. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  37762. }
  37763. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  37764. if (! isMultiLine())
  37765. {
  37766. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  37767. }
  37768. else
  37769. {
  37770. const int curH = roundFloatToInt (cursorHeight);
  37771. if (relativeCursorY < 0)
  37772. {
  37773. y = jmax (0, relativeCursorY + y);
  37774. }
  37775. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  37776. {
  37777. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  37778. }
  37779. }
  37780. viewport->setViewPosition (x, y);
  37781. }
  37782. }
  37783. void TextEditor::moveCursorTo (const int newPosition,
  37784. const bool isSelecting) throw()
  37785. {
  37786. if (isSelecting)
  37787. {
  37788. moveCaret (newPosition);
  37789. const int oldSelStart = selectionStart;
  37790. const int oldSelEnd = selectionEnd;
  37791. if (dragType == notDragging)
  37792. {
  37793. if (abs (getCaretPosition() - selectionStart) < abs (getCaretPosition() - selectionEnd))
  37794. dragType = draggingSelectionStart;
  37795. else
  37796. dragType = draggingSelectionEnd;
  37797. }
  37798. if (dragType == draggingSelectionStart)
  37799. {
  37800. selectionStart = getCaretPosition();
  37801. if (selectionEnd < selectionStart)
  37802. {
  37803. swapVariables (selectionStart, selectionEnd);
  37804. dragType = draggingSelectionEnd;
  37805. }
  37806. }
  37807. else
  37808. {
  37809. selectionEnd = getCaretPosition();
  37810. if (selectionEnd < selectionStart)
  37811. {
  37812. swapVariables (selectionStart, selectionEnd);
  37813. dragType = draggingSelectionStart;
  37814. }
  37815. }
  37816. jassert (selectionStart <= selectionEnd);
  37817. jassert (oldSelStart <= oldSelEnd);
  37818. repaintText (jmin (oldSelStart, selectionStart),
  37819. jmax (oldSelEnd, selectionEnd));
  37820. }
  37821. else
  37822. {
  37823. dragType = notDragging;
  37824. if (selectionEnd > selectionStart)
  37825. repaintText (selectionStart, selectionEnd);
  37826. moveCaret (newPosition);
  37827. selectionStart = getCaretPosition();
  37828. selectionEnd = getCaretPosition();
  37829. }
  37830. }
  37831. int TextEditor::getTextIndexAt (const int x,
  37832. const int y) throw()
  37833. {
  37834. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  37835. (float) (y + viewport->getViewPositionY() - topIndent));
  37836. }
  37837. void TextEditor::insertTextAtCursor (String newText)
  37838. {
  37839. if (allowedCharacters.isNotEmpty())
  37840. newText = newText.retainCharacters (allowedCharacters);
  37841. if (! isMultiLine())
  37842. newText = newText.replaceCharacters (T("\r\n"), T(" "));
  37843. else
  37844. newText = newText.replace (T("\r\n"), T("\n"));
  37845. const int newCaretPos = selectionStart + newText.length();
  37846. const int insertIndex = selectionStart;
  37847. remove (selectionStart, selectionEnd,
  37848. &undoManager,
  37849. newCaretPos);
  37850. if (maxTextLength > 0)
  37851. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  37852. if (newText.isNotEmpty())
  37853. insert (newText,
  37854. insertIndex,
  37855. currentFont,
  37856. findColour (textColourId),
  37857. &undoManager,
  37858. newCaretPos);
  37859. textChanged();
  37860. }
  37861. void TextEditor::setHighlightedRegion (int startPos, int numChars) throw()
  37862. {
  37863. moveCursorTo (startPos, false);
  37864. moveCursorTo (startPos + numChars, true);
  37865. }
  37866. void TextEditor::copy()
  37867. {
  37868. const String selection (getTextSubstring (selectionStart, selectionEnd));
  37869. if (selection.isNotEmpty())
  37870. SystemClipboard::copyTextToClipboard (selection);
  37871. }
  37872. void TextEditor::paste()
  37873. {
  37874. if (! isReadOnly())
  37875. {
  37876. const String clip (SystemClipboard::getTextFromClipboard());
  37877. if (clip.isNotEmpty())
  37878. insertTextAtCursor (clip);
  37879. }
  37880. }
  37881. void TextEditor::cut()
  37882. {
  37883. if (! isReadOnly())
  37884. {
  37885. moveCaret (selectionEnd);
  37886. insertTextAtCursor (String::empty);
  37887. }
  37888. }
  37889. void TextEditor::drawContent (Graphics& g)
  37890. {
  37891. const float wordWrapWidth = getWordWrapWidth();
  37892. if (wordWrapWidth > 0)
  37893. {
  37894. g.setOrigin (leftIndent, topIndent);
  37895. const Rectangle clip (g.getClipBounds());
  37896. Colour selectedTextColour;
  37897. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  37898. while (i.lineY + 200.0 < clip.getY() && i.next())
  37899. {}
  37900. if (selectionStart < selectionEnd)
  37901. {
  37902. g.setColour (findColour (highlightColourId)
  37903. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  37904. selectedTextColour = findColour (highlightedTextColourId);
  37905. TextEditorIterator i2 (i);
  37906. while (i2.next() && i2.lineY < clip.getBottom())
  37907. {
  37908. i2.updateLineHeight();
  37909. if (i2.lineY + i2.lineHeight >= clip.getY()
  37910. && selectionEnd >= i2.indexInText
  37911. && selectionStart <= i2.indexInText + i2.atom->numChars)
  37912. {
  37913. i2.drawSelection (g, selectionStart, selectionEnd);
  37914. }
  37915. }
  37916. }
  37917. const UniformTextSection* lastSection = 0;
  37918. while (i.next() && i.lineY < clip.getBottom())
  37919. {
  37920. i.updateLineHeight();
  37921. if (i.lineY + i.lineHeight >= clip.getY())
  37922. {
  37923. if (selectionEnd >= i.indexInText
  37924. && selectionStart <= i.indexInText + i.atom->numChars)
  37925. {
  37926. i.drawSelectedText (g, selectionStart, selectionEnd, selectedTextColour);
  37927. lastSection = 0;
  37928. }
  37929. else
  37930. {
  37931. i.draw (g, lastSection);
  37932. }
  37933. }
  37934. }
  37935. }
  37936. }
  37937. void TextEditor::paint (Graphics& g)
  37938. {
  37939. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  37940. }
  37941. void TextEditor::paintOverChildren (Graphics& g)
  37942. {
  37943. if (caretFlashState
  37944. && hasKeyboardFocus (false)
  37945. && caretVisible
  37946. && ! isReadOnly())
  37947. {
  37948. g.setColour (findColour (caretColourId));
  37949. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  37950. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  37951. 2.0f, cursorHeight);
  37952. }
  37953. if (textToShowWhenEmpty.isNotEmpty()
  37954. && (! hasKeyboardFocus (false))
  37955. && getTotalNumChars() == 0)
  37956. {
  37957. g.setColour (colourForTextWhenEmpty);
  37958. g.setFont (getFont());
  37959. if (isMultiLine())
  37960. {
  37961. g.drawText (textToShowWhenEmpty,
  37962. 0, 0, getWidth(), getHeight(),
  37963. Justification::centred, true);
  37964. }
  37965. else
  37966. {
  37967. g.drawText (textToShowWhenEmpty,
  37968. leftIndent, topIndent,
  37969. viewport->getWidth() - leftIndent,
  37970. viewport->getHeight() - topIndent,
  37971. Justification::centredLeft, true);
  37972. }
  37973. }
  37974. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  37975. }
  37976. void TextEditor::mouseDown (const MouseEvent& e)
  37977. {
  37978. beginDragAutoRepeat (100);
  37979. newTransaction();
  37980. if (wasFocused || ! selectAllTextWhenFocused)
  37981. {
  37982. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  37983. {
  37984. moveCursorTo (getTextIndexAt (e.x, e.y),
  37985. e.mods.isShiftDown());
  37986. }
  37987. else
  37988. {
  37989. PopupMenu m;
  37990. addPopupMenuItems (m, &e);
  37991. menuActive = true;
  37992. const int result = m.show();
  37993. menuActive = false;
  37994. if (result != 0)
  37995. performPopupMenuAction (result);
  37996. }
  37997. }
  37998. }
  37999. void TextEditor::mouseDrag (const MouseEvent& e)
  38000. {
  38001. if (wasFocused || ! selectAllTextWhenFocused)
  38002. {
  38003. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  38004. {
  38005. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  38006. }
  38007. }
  38008. }
  38009. void TextEditor::mouseUp (const MouseEvent& e)
  38010. {
  38011. newTransaction();
  38012. textHolder->startTimer (flashSpeedIntervalMs);
  38013. if (wasFocused || ! selectAllTextWhenFocused)
  38014. {
  38015. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  38016. {
  38017. moveCaret (getTextIndexAt (e.x, e.y));
  38018. }
  38019. }
  38020. wasFocused = true;
  38021. }
  38022. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  38023. {
  38024. int tokenEnd = getTextIndexAt (e.x, e.y);
  38025. int tokenStart = tokenEnd;
  38026. if (e.getNumberOfClicks() > 3)
  38027. {
  38028. tokenStart = 0;
  38029. tokenEnd = getTotalNumChars();
  38030. }
  38031. else
  38032. {
  38033. const String t (getText());
  38034. const int totalLength = getTotalNumChars();
  38035. while (tokenEnd < totalLength)
  38036. {
  38037. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]))
  38038. ++tokenEnd;
  38039. else
  38040. break;
  38041. }
  38042. tokenStart = tokenEnd;
  38043. while (tokenStart > 0)
  38044. {
  38045. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]))
  38046. --tokenStart;
  38047. else
  38048. break;
  38049. }
  38050. if (e.getNumberOfClicks() > 2)
  38051. {
  38052. while (tokenEnd < totalLength)
  38053. {
  38054. if (t [tokenEnd] != T('\r') && t [tokenEnd] != T('\n'))
  38055. ++tokenEnd;
  38056. else
  38057. break;
  38058. }
  38059. while (tokenStart > 0)
  38060. {
  38061. if (t [tokenStart - 1] != T('\r') && t [tokenStart - 1] != T('\n'))
  38062. --tokenStart;
  38063. else
  38064. break;
  38065. }
  38066. }
  38067. }
  38068. moveCursorTo (tokenEnd, false);
  38069. moveCursorTo (tokenStart, true);
  38070. }
  38071. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  38072. {
  38073. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  38074. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  38075. }
  38076. bool TextEditor::keyPressed (const KeyPress& key)
  38077. {
  38078. if (isReadOnly() && key != KeyPress (T('c'), ModifierKeys::commandModifier, 0))
  38079. return false;
  38080. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  38081. if (key.isKeyCode (KeyPress::leftKey)
  38082. || key.isKeyCode (KeyPress::upKey))
  38083. {
  38084. newTransaction();
  38085. int newPos;
  38086. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  38087. newPos = indexAtPosition (cursorX, cursorY - 1);
  38088. else if (moveInWholeWordSteps)
  38089. newPos = findWordBreakBefore (getCaretPosition());
  38090. else
  38091. newPos = getCaretPosition() - 1;
  38092. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  38093. }
  38094. else if (key.isKeyCode (KeyPress::rightKey)
  38095. || key.isKeyCode (KeyPress::downKey))
  38096. {
  38097. newTransaction();
  38098. int newPos;
  38099. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  38100. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  38101. else if (moveInWholeWordSteps)
  38102. newPos = findWordBreakAfter (getCaretPosition());
  38103. else
  38104. newPos = getCaretPosition() + 1;
  38105. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  38106. }
  38107. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  38108. {
  38109. newTransaction();
  38110. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  38111. key.getModifiers().isShiftDown());
  38112. }
  38113. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  38114. {
  38115. newTransaction();
  38116. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  38117. key.getModifiers().isShiftDown());
  38118. }
  38119. else if (key.isKeyCode (KeyPress::homeKey))
  38120. {
  38121. newTransaction();
  38122. if (isMultiLine() && ! moveInWholeWordSteps)
  38123. moveCursorTo (indexAtPosition (0.0f, cursorY),
  38124. key.getModifiers().isShiftDown());
  38125. else
  38126. moveCursorTo (0, key.getModifiers().isShiftDown());
  38127. }
  38128. else if (key.isKeyCode (KeyPress::endKey))
  38129. {
  38130. newTransaction();
  38131. if (isMultiLine() && ! moveInWholeWordSteps)
  38132. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  38133. key.getModifiers().isShiftDown());
  38134. else
  38135. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  38136. }
  38137. else if (key.isKeyCode (KeyPress::backspaceKey))
  38138. {
  38139. if (moveInWholeWordSteps)
  38140. {
  38141. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  38142. }
  38143. else
  38144. {
  38145. if (selectionStart == selectionEnd && selectionStart > 0)
  38146. --selectionStart;
  38147. }
  38148. cut();
  38149. }
  38150. else if (key.isKeyCode (KeyPress::deleteKey))
  38151. {
  38152. if (key.getModifiers().isShiftDown())
  38153. copy();
  38154. if (selectionStart == selectionEnd
  38155. && selectionEnd < getTotalNumChars())
  38156. {
  38157. ++selectionEnd;
  38158. }
  38159. cut();
  38160. }
  38161. else if (key == KeyPress (T('c'), ModifierKeys::commandModifier, 0)
  38162. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  38163. {
  38164. newTransaction();
  38165. copy();
  38166. }
  38167. else if (key == KeyPress (T('x'), ModifierKeys::commandModifier, 0))
  38168. {
  38169. newTransaction();
  38170. copy();
  38171. cut();
  38172. }
  38173. else if (key == KeyPress (T('v'), ModifierKeys::commandModifier, 0)
  38174. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  38175. {
  38176. newTransaction();
  38177. paste();
  38178. }
  38179. else if (key == KeyPress (T('z'), ModifierKeys::commandModifier, 0))
  38180. {
  38181. newTransaction();
  38182. doUndoRedo (false);
  38183. }
  38184. else if (key == KeyPress (T('y'), ModifierKeys::commandModifier, 0))
  38185. {
  38186. newTransaction();
  38187. doUndoRedo (true);
  38188. }
  38189. else if (key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  38190. {
  38191. newTransaction();
  38192. moveCursorTo (getTotalNumChars(), false);
  38193. moveCursorTo (0, true);
  38194. }
  38195. else if (key == KeyPress::returnKey)
  38196. {
  38197. newTransaction();
  38198. if (returnKeyStartsNewLine)
  38199. insertTextAtCursor (T("\n"));
  38200. else
  38201. returnPressed();
  38202. }
  38203. else if (key.isKeyCode (KeyPress::escapeKey))
  38204. {
  38205. newTransaction();
  38206. moveCursorTo (getCaretPosition(), false);
  38207. escapePressed();
  38208. }
  38209. else if (key.getTextCharacter() >= ' '
  38210. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  38211. {
  38212. insertTextAtCursor (String::charToString (key.getTextCharacter()));
  38213. lastTransactionTime = Time::getApproximateMillisecondCounter();
  38214. }
  38215. else
  38216. {
  38217. return false;
  38218. }
  38219. return true;
  38220. }
  38221. bool TextEditor::keyStateChanged()
  38222. {
  38223. // (overridden to avoid forwarding key events to the parent)
  38224. return true;
  38225. }
  38226. const int baseMenuItemID = 0x7fff0000;
  38227. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  38228. {
  38229. const bool writable = ! isReadOnly();
  38230. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  38231. m.addItem (baseMenuItemID + 2, TRANS("copy"), selectionStart < selectionEnd);
  38232. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  38233. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  38234. m.addSeparator();
  38235. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  38236. m.addSeparator();
  38237. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  38238. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  38239. }
  38240. void TextEditor::performPopupMenuAction (const int menuItemID)
  38241. {
  38242. switch (menuItemID)
  38243. {
  38244. case baseMenuItemID + 1:
  38245. copy();
  38246. cut();
  38247. break;
  38248. case baseMenuItemID + 2:
  38249. copy();
  38250. break;
  38251. case baseMenuItemID + 3:
  38252. paste();
  38253. break;
  38254. case baseMenuItemID + 4:
  38255. cut();
  38256. break;
  38257. case baseMenuItemID + 5:
  38258. moveCursorTo (getTotalNumChars(), false);
  38259. moveCursorTo (0, true);
  38260. break;
  38261. case baseMenuItemID + 6:
  38262. doUndoRedo (false);
  38263. break;
  38264. case baseMenuItemID + 7:
  38265. doUndoRedo (true);
  38266. break;
  38267. default:
  38268. break;
  38269. }
  38270. }
  38271. void TextEditor::focusGained (FocusChangeType)
  38272. {
  38273. newTransaction();
  38274. caretFlashState = true;
  38275. if (selectAllTextWhenFocused)
  38276. {
  38277. moveCursorTo (0, false);
  38278. moveCursorTo (getTotalNumChars(), true);
  38279. }
  38280. repaint();
  38281. if (caretVisible)
  38282. textHolder->startTimer (flashSpeedIntervalMs);
  38283. ComponentPeer* const peer = getPeer();
  38284. if (peer != 0)
  38285. peer->textInputRequired (getScreenX() - peer->getScreenX(),
  38286. getScreenY() - peer->getScreenY());
  38287. }
  38288. void TextEditor::focusLost (FocusChangeType)
  38289. {
  38290. newTransaction();
  38291. wasFocused = false;
  38292. textHolder->stopTimer();
  38293. caretFlashState = false;
  38294. postCommandMessage (focusLossMessageId);
  38295. repaint();
  38296. }
  38297. void TextEditor::resized()
  38298. {
  38299. viewport->setBoundsInset (borderSize);
  38300. viewport->setSingleStepSizes (16, roundFloatToInt (currentFont.getHeight()));
  38301. updateTextHolderSize();
  38302. if (! isMultiLine())
  38303. {
  38304. scrollToMakeSureCursorIsVisible();
  38305. }
  38306. else
  38307. {
  38308. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  38309. getCharPosition (caretPosition,
  38310. cursorX, cursorY,
  38311. cursorHeight);
  38312. }
  38313. }
  38314. void TextEditor::handleCommandMessage (const int commandId)
  38315. {
  38316. const ComponentDeletionWatcher deletionChecker (this);
  38317. for (int i = listeners.size(); --i >= 0;)
  38318. {
  38319. TextEditorListener* const tl = (TextEditorListener*) listeners [i];
  38320. if (tl != 0)
  38321. {
  38322. switch (commandId)
  38323. {
  38324. case textChangeMessageId:
  38325. tl->textEditorTextChanged (*this);
  38326. break;
  38327. case returnKeyMessageId:
  38328. tl->textEditorReturnKeyPressed (*this);
  38329. break;
  38330. case escapeKeyMessageId:
  38331. tl->textEditorEscapeKeyPressed (*this);
  38332. break;
  38333. case focusLossMessageId:
  38334. tl->textEditorFocusLost (*this);
  38335. break;
  38336. default:
  38337. jassertfalse
  38338. break;
  38339. }
  38340. if (i > 0 && deletionChecker.hasBeenDeleted())
  38341. return;
  38342. }
  38343. }
  38344. }
  38345. void TextEditor::enablementChanged()
  38346. {
  38347. setMouseCursor (MouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  38348. : MouseCursor::IBeamCursor));
  38349. repaint();
  38350. }
  38351. void TextEditor::clearInternal (UndoManager* const um) throw()
  38352. {
  38353. remove (0, getTotalNumChars(), um, caretPosition);
  38354. }
  38355. void TextEditor::insert (const String& text,
  38356. const int insertIndex,
  38357. const Font& font,
  38358. const Colour& colour,
  38359. UndoManager* const um,
  38360. const int caretPositionToMoveTo) throw()
  38361. {
  38362. if (text.isNotEmpty())
  38363. {
  38364. if (um != 0)
  38365. {
  38366. um->perform (new TextEditorInsertAction (*this,
  38367. text,
  38368. insertIndex,
  38369. font,
  38370. colour,
  38371. caretPosition,
  38372. caretPositionToMoveTo));
  38373. }
  38374. else
  38375. {
  38376. repaintText (insertIndex, -1); // must do this before and after changing the data, in case
  38377. // a line gets moved due to word wrap
  38378. int index = 0;
  38379. int nextIndex = 0;
  38380. for (int i = 0; i < sections.size(); ++i)
  38381. {
  38382. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  38383. if (insertIndex == index)
  38384. {
  38385. sections.insert (i, new UniformTextSection (text,
  38386. font, colour,
  38387. passwordCharacter));
  38388. break;
  38389. }
  38390. else if (insertIndex > index && insertIndex < nextIndex)
  38391. {
  38392. splitSection (i, insertIndex - index);
  38393. sections.insert (i + 1, new UniformTextSection (text,
  38394. font, colour,
  38395. passwordCharacter));
  38396. break;
  38397. }
  38398. index = nextIndex;
  38399. }
  38400. if (nextIndex == insertIndex)
  38401. sections.add (new UniformTextSection (text,
  38402. font, colour,
  38403. passwordCharacter));
  38404. coalesceSimilarSections();
  38405. totalNumChars = -1;
  38406. moveCursorTo (caretPositionToMoveTo, false);
  38407. repaintText (insertIndex, -1);
  38408. }
  38409. }
  38410. }
  38411. void TextEditor::reinsert (const int insertIndex,
  38412. const VoidArray& sectionsToInsert) throw()
  38413. {
  38414. int index = 0;
  38415. int nextIndex = 0;
  38416. for (int i = 0; i < sections.size(); ++i)
  38417. {
  38418. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  38419. if (insertIndex == index)
  38420. {
  38421. for (int j = sectionsToInsert.size(); --j >= 0;)
  38422. sections.insert (i, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  38423. break;
  38424. }
  38425. else if (insertIndex > index && insertIndex < nextIndex)
  38426. {
  38427. splitSection (i, insertIndex - index);
  38428. for (int j = sectionsToInsert.size(); --j >= 0;)
  38429. sections.insert (i + 1, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  38430. break;
  38431. }
  38432. index = nextIndex;
  38433. }
  38434. if (nextIndex == insertIndex)
  38435. {
  38436. for (int j = 0; j < sectionsToInsert.size(); ++j)
  38437. sections.add (new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  38438. }
  38439. coalesceSimilarSections();
  38440. totalNumChars = -1;
  38441. }
  38442. void TextEditor::remove (const int startIndex,
  38443. int endIndex,
  38444. UndoManager* const um,
  38445. const int caretPositionToMoveTo) throw()
  38446. {
  38447. if (endIndex > startIndex)
  38448. {
  38449. int index = 0;
  38450. for (int i = 0; i < sections.size(); ++i)
  38451. {
  38452. const int nextIndex = index + ((UniformTextSection*) sections[i])->getTotalLength();
  38453. if (startIndex > index && startIndex < nextIndex)
  38454. {
  38455. splitSection (i, startIndex - index);
  38456. --i;
  38457. }
  38458. else if (endIndex > index && endIndex < nextIndex)
  38459. {
  38460. splitSection (i, endIndex - index);
  38461. --i;
  38462. }
  38463. else
  38464. {
  38465. index = nextIndex;
  38466. if (index > endIndex)
  38467. break;
  38468. }
  38469. }
  38470. index = 0;
  38471. if (um != 0)
  38472. {
  38473. VoidArray removedSections;
  38474. for (int i = 0; i < sections.size(); ++i)
  38475. {
  38476. if (endIndex <= startIndex)
  38477. break;
  38478. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  38479. const int nextIndex = index + section->getTotalLength();
  38480. if (startIndex <= index && endIndex >= nextIndex)
  38481. removedSections.add (new UniformTextSection (*section));
  38482. index = nextIndex;
  38483. }
  38484. um->perform (new TextEditorRemoveAction (*this,
  38485. startIndex,
  38486. endIndex,
  38487. caretPosition,
  38488. caretPositionToMoveTo,
  38489. removedSections));
  38490. }
  38491. else
  38492. {
  38493. for (int i = 0; i < sections.size(); ++i)
  38494. {
  38495. if (endIndex <= startIndex)
  38496. break;
  38497. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  38498. const int nextIndex = index + section->getTotalLength();
  38499. if (startIndex <= index && endIndex >= nextIndex)
  38500. {
  38501. sections.remove(i);
  38502. endIndex -= (nextIndex - index);
  38503. section->clear();
  38504. delete section;
  38505. --i;
  38506. }
  38507. else
  38508. {
  38509. index = nextIndex;
  38510. }
  38511. }
  38512. coalesceSimilarSections();
  38513. totalNumChars = -1;
  38514. moveCursorTo (caretPositionToMoveTo, false);
  38515. repaintText (startIndex, -1);
  38516. }
  38517. }
  38518. }
  38519. const String TextEditor::getText() const throw()
  38520. {
  38521. String t;
  38522. for (int i = 0; i < sections.size(); ++i)
  38523. t += ((const UniformTextSection*) sections.getUnchecked(i))->getAllText();
  38524. return t;
  38525. }
  38526. const String TextEditor::getTextSubstring (const int startCharacter, const int endCharacter) const throw()
  38527. {
  38528. String t;
  38529. int index = 0;
  38530. for (int i = 0; i < sections.size(); ++i)
  38531. {
  38532. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked(i);
  38533. const int nextIndex = index + s->getTotalLength();
  38534. if (startCharacter < nextIndex)
  38535. {
  38536. if (endCharacter <= index)
  38537. break;
  38538. const int start = jmax (index, startCharacter);
  38539. t += s->getTextSubstring (start - index, endCharacter - index);
  38540. }
  38541. index = nextIndex;
  38542. }
  38543. return t;
  38544. }
  38545. const String TextEditor::getHighlightedText() const throw()
  38546. {
  38547. return getTextSubstring (getHighlightedRegionStart(),
  38548. getHighlightedRegionStart() + getHighlightedRegionLength());
  38549. }
  38550. int TextEditor::getTotalNumChars() throw()
  38551. {
  38552. if (totalNumChars < 0)
  38553. {
  38554. totalNumChars = 0;
  38555. for (int i = sections.size(); --i >= 0;)
  38556. totalNumChars += ((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  38557. }
  38558. return totalNumChars;
  38559. }
  38560. bool TextEditor::isEmpty() const throw()
  38561. {
  38562. if (totalNumChars != 0)
  38563. {
  38564. for (int i = sections.size(); --i >= 0;)
  38565. if (((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength() > 0)
  38566. return false;
  38567. }
  38568. return true;
  38569. }
  38570. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const throw()
  38571. {
  38572. const float wordWrapWidth = getWordWrapWidth();
  38573. if (wordWrapWidth > 0 && sections.size() > 0)
  38574. {
  38575. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  38576. i.getCharPosition (index, cx, cy, lineHeight);
  38577. }
  38578. else
  38579. {
  38580. cx = cy = 0;
  38581. lineHeight = currentFont.getHeight();
  38582. }
  38583. }
  38584. int TextEditor::indexAtPosition (const float x, const float y) throw()
  38585. {
  38586. const float wordWrapWidth = getWordWrapWidth();
  38587. if (wordWrapWidth > 0)
  38588. {
  38589. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  38590. while (i.next())
  38591. {
  38592. if (i.lineY + getHeight() > y)
  38593. i.updateLineHeight();
  38594. if (i.lineY + i.lineHeight > y)
  38595. {
  38596. if (i.lineY > y)
  38597. return jmax (0, i.indexInText - 1);
  38598. if (i.atomX >= x)
  38599. return i.indexInText;
  38600. if (x < i.atomRight)
  38601. return i.xToIndex (x);
  38602. }
  38603. }
  38604. }
  38605. return getTotalNumChars();
  38606. }
  38607. static int getCharacterCategory (const tchar character) throw()
  38608. {
  38609. return CharacterFunctions::isLetterOrDigit (character)
  38610. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  38611. }
  38612. int TextEditor::findWordBreakAfter (const int position) const throw()
  38613. {
  38614. const String t (getTextSubstring (position, position + 512));
  38615. const int totalLength = t.length();
  38616. int i = 0;
  38617. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  38618. ++i;
  38619. const int type = getCharacterCategory (t[i]);
  38620. while (i < totalLength && type == getCharacterCategory (t[i]))
  38621. ++i;
  38622. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  38623. ++i;
  38624. return position + i;
  38625. }
  38626. int TextEditor::findWordBreakBefore (const int position) const throw()
  38627. {
  38628. if (position <= 0)
  38629. return 0;
  38630. const int startOfBuffer = jmax (0, position - 512);
  38631. const String t (getTextSubstring (startOfBuffer, position));
  38632. int i = position - startOfBuffer;
  38633. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  38634. --i;
  38635. if (i > 0)
  38636. {
  38637. const int type = getCharacterCategory (t [i - 1]);
  38638. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  38639. --i;
  38640. }
  38641. jassert (startOfBuffer + i >= 0);
  38642. return startOfBuffer + i;
  38643. }
  38644. void TextEditor::splitSection (const int sectionIndex,
  38645. const int charToSplitAt) throw()
  38646. {
  38647. jassert (sections[sectionIndex] != 0);
  38648. sections.insert (sectionIndex + 1,
  38649. ((UniformTextSection*) sections.getUnchecked (sectionIndex))
  38650. ->split (charToSplitAt, passwordCharacter));
  38651. }
  38652. void TextEditor::coalesceSimilarSections() throw()
  38653. {
  38654. for (int i = 0; i < sections.size() - 1; ++i)
  38655. {
  38656. UniformTextSection* const s1 = (UniformTextSection*) (sections.getUnchecked (i));
  38657. UniformTextSection* const s2 = (UniformTextSection*) (sections.getUnchecked (i + 1));
  38658. if (s1->font == s2->font
  38659. && s1->colour == s2->colour)
  38660. {
  38661. s1->append (*s2, passwordCharacter);
  38662. sections.remove (i + 1);
  38663. delete s2;
  38664. --i;
  38665. }
  38666. }
  38667. }
  38668. END_JUCE_NAMESPACE
  38669. /********* End of inlined file: juce_TextEditor.cpp *********/
  38670. /********* Start of inlined file: juce_Toolbar.cpp *********/
  38671. BEGIN_JUCE_NAMESPACE
  38672. const tchar* const Toolbar::toolbarDragDescriptor = T("_toolbarItem_");
  38673. class ToolbarSpacerComp : public ToolbarItemComponent
  38674. {
  38675. public:
  38676. ToolbarSpacerComp (const int itemId, const float fixedSize_, const bool drawBar_)
  38677. : ToolbarItemComponent (itemId, String::empty, false),
  38678. fixedSize (fixedSize_),
  38679. drawBar (drawBar_)
  38680. {
  38681. }
  38682. ~ToolbarSpacerComp()
  38683. {
  38684. }
  38685. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  38686. int& preferredSize, int& minSize, int& maxSize)
  38687. {
  38688. if (fixedSize <= 0)
  38689. {
  38690. preferredSize = toolbarThickness * 2;
  38691. minSize = 4;
  38692. maxSize = 32768;
  38693. }
  38694. else
  38695. {
  38696. maxSize = roundFloatToInt (toolbarThickness * fixedSize);
  38697. minSize = drawBar ? maxSize : jmin (4, maxSize);
  38698. preferredSize = maxSize;
  38699. if (getEditingMode() == editableOnPalette)
  38700. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  38701. }
  38702. return true;
  38703. }
  38704. void paintButtonArea (Graphics&, int, int, bool, bool)
  38705. {
  38706. }
  38707. void contentAreaChanged (const Rectangle&)
  38708. {
  38709. }
  38710. int getResizeOrder() const throw()
  38711. {
  38712. return fixedSize <= 0 ? 0 : 1;
  38713. }
  38714. void paint (Graphics& g)
  38715. {
  38716. const int w = getWidth();
  38717. const int h = getHeight();
  38718. if (drawBar)
  38719. {
  38720. g.setColour (findColour (Toolbar::separatorColourId, true));
  38721. const float thickness = 0.2f;
  38722. if (isToolbarVertical())
  38723. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  38724. else
  38725. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  38726. }
  38727. if (getEditingMode() != normalMode && ! drawBar)
  38728. {
  38729. g.setColour (findColour (Toolbar::separatorColourId, true));
  38730. const int indentX = jmin (2, (w - 3) / 2);
  38731. const int indentY = jmin (2, (h - 3) / 2);
  38732. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  38733. if (fixedSize <= 0)
  38734. {
  38735. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  38736. if (isToolbarVertical())
  38737. {
  38738. x1 = w * 0.5f;
  38739. y1 = h * 0.4f;
  38740. x2 = x1;
  38741. y2 = indentX * 2.0f;
  38742. x3 = x1;
  38743. y3 = h * 0.6f;
  38744. x4 = x1;
  38745. y4 = h - y2;
  38746. hw = w * 0.15f;
  38747. hl = w * 0.2f;
  38748. }
  38749. else
  38750. {
  38751. x1 = w * 0.4f;
  38752. y1 = h * 0.5f;
  38753. x2 = indentX * 2.0f;
  38754. y2 = y1;
  38755. x3 = w * 0.6f;
  38756. y3 = y1;
  38757. x4 = w - x2;
  38758. y4 = y1;
  38759. hw = h * 0.15f;
  38760. hl = h * 0.2f;
  38761. }
  38762. Path p;
  38763. p.addArrow (x1, y1, x2, y2, 1.5f, hw, hl);
  38764. p.addArrow (x3, y3, x4, y4, 1.5f, hw, hl);
  38765. g.fillPath (p);
  38766. }
  38767. }
  38768. }
  38769. juce_UseDebuggingNewOperator
  38770. private:
  38771. const float fixedSize;
  38772. const bool drawBar;
  38773. ToolbarSpacerComp (const ToolbarSpacerComp&);
  38774. const ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  38775. };
  38776. class MissingItemsComponent : public PopupMenuCustomComponent
  38777. {
  38778. public:
  38779. MissingItemsComponent (Toolbar& owner_, const int height_)
  38780. : PopupMenuCustomComponent (true),
  38781. owner (owner_),
  38782. height (height_)
  38783. {
  38784. for (int i = owner_.items.size(); --i >= 0;)
  38785. {
  38786. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  38787. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  38788. {
  38789. oldIndexes.insert (0, i);
  38790. addAndMakeVisible (tc, 0);
  38791. }
  38792. }
  38793. layout (400);
  38794. }
  38795. ~MissingItemsComponent()
  38796. {
  38797. // deleting the toolbar while its menu it open??
  38798. jassert (owner.isValidComponent());
  38799. for (int i = 0; i < getNumChildComponents(); ++i)
  38800. {
  38801. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  38802. if (tc != 0)
  38803. {
  38804. tc->setVisible (false);
  38805. const int index = oldIndexes.remove (i);
  38806. owner.addChildComponent (tc, index);
  38807. --i;
  38808. }
  38809. }
  38810. owner.resized();
  38811. }
  38812. void layout (const int preferredWidth)
  38813. {
  38814. const int indent = 8;
  38815. int x = indent;
  38816. int y = indent;
  38817. int maxX = 0;
  38818. for (int i = 0; i < getNumChildComponents(); ++i)
  38819. {
  38820. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  38821. if (tc != 0)
  38822. {
  38823. int preferredSize = 1, minSize = 1, maxSize = 1;
  38824. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  38825. {
  38826. if (x + preferredSize > preferredWidth && x > indent)
  38827. {
  38828. x = indent;
  38829. y += height;
  38830. }
  38831. tc->setBounds (x, y, preferredSize, height);
  38832. x += preferredSize;
  38833. maxX = jmax (maxX, x);
  38834. }
  38835. }
  38836. }
  38837. setSize (maxX + 8, y + height + 8);
  38838. }
  38839. void getIdealSize (int& idealWidth, int& idealHeight)
  38840. {
  38841. idealWidth = getWidth();
  38842. idealHeight = getHeight();
  38843. }
  38844. juce_UseDebuggingNewOperator
  38845. private:
  38846. Toolbar& owner;
  38847. const int height;
  38848. Array <int> oldIndexes;
  38849. MissingItemsComponent (const MissingItemsComponent&);
  38850. const MissingItemsComponent& operator= (const MissingItemsComponent&);
  38851. };
  38852. Toolbar::Toolbar()
  38853. : vertical (false),
  38854. isEditingActive (false),
  38855. toolbarStyle (Toolbar::iconsOnly)
  38856. {
  38857. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  38858. missingItemsButton->setAlwaysOnTop (true);
  38859. missingItemsButton->addButtonListener (this);
  38860. }
  38861. Toolbar::~Toolbar()
  38862. {
  38863. animator.cancelAllAnimations (true);
  38864. deleteAllChildren();
  38865. }
  38866. void Toolbar::setVertical (const bool shouldBeVertical)
  38867. {
  38868. if (vertical != shouldBeVertical)
  38869. {
  38870. vertical = shouldBeVertical;
  38871. resized();
  38872. }
  38873. }
  38874. void Toolbar::clear()
  38875. {
  38876. for (int i = items.size(); --i >= 0;)
  38877. {
  38878. ToolbarItemComponent* const tc = items.getUnchecked(i);
  38879. items.remove (i);
  38880. delete tc;
  38881. }
  38882. resized();
  38883. }
  38884. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  38885. {
  38886. if (itemId == ToolbarItemFactory::separatorBarId)
  38887. return new ToolbarSpacerComp (itemId, 0.1f, true);
  38888. else if (itemId == ToolbarItemFactory::spacerId)
  38889. return new ToolbarSpacerComp (itemId, 0.5f, false);
  38890. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  38891. return new ToolbarSpacerComp (itemId, 0, false);
  38892. return factory.createItem (itemId);
  38893. }
  38894. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  38895. const int itemId,
  38896. const int insertIndex)
  38897. {
  38898. // An ID can't be zero - this might indicate a mistake somewhere?
  38899. jassert (itemId != 0);
  38900. ToolbarItemComponent* const tc = createItem (factory, itemId);
  38901. if (tc != 0)
  38902. {
  38903. #ifdef JUCE_DEBUG
  38904. Array <int> allowedIds;
  38905. factory.getAllToolbarItemIds (allowedIds);
  38906. // If your factory can create an item for a given ID, it must also return
  38907. // that ID from its getAllToolbarItemIds() method!
  38908. jassert (allowedIds.contains (itemId));
  38909. #endif
  38910. items.insert (insertIndex, tc);
  38911. addAndMakeVisible (tc, insertIndex);
  38912. }
  38913. }
  38914. void Toolbar::addItem (ToolbarItemFactory& factory,
  38915. const int itemId,
  38916. const int insertIndex)
  38917. {
  38918. addItemInternal (factory, itemId, insertIndex);
  38919. resized();
  38920. }
  38921. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  38922. {
  38923. Array <int> ids;
  38924. factoryToUse.getDefaultItemSet (ids);
  38925. clear();
  38926. for (int i = 0; i < ids.size(); ++i)
  38927. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  38928. resized();
  38929. }
  38930. void Toolbar::removeToolbarItem (const int itemIndex)
  38931. {
  38932. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  38933. if (tc != 0)
  38934. {
  38935. items.removeValue (tc);
  38936. delete tc;
  38937. resized();
  38938. }
  38939. }
  38940. int Toolbar::getNumItems() const throw()
  38941. {
  38942. return items.size();
  38943. }
  38944. int Toolbar::getItemId (const int itemIndex) const throw()
  38945. {
  38946. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  38947. return tc != 0 ? tc->getItemId() : 0;
  38948. }
  38949. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  38950. {
  38951. return items [itemIndex];
  38952. }
  38953. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  38954. {
  38955. for (;;)
  38956. {
  38957. index += delta;
  38958. ToolbarItemComponent* const tc = getItemComponent (index);
  38959. if (tc == 0)
  38960. break;
  38961. if (tc->isActive)
  38962. return tc;
  38963. }
  38964. return 0;
  38965. }
  38966. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  38967. {
  38968. if (toolbarStyle != newStyle)
  38969. {
  38970. toolbarStyle = newStyle;
  38971. updateAllItemPositions (false);
  38972. }
  38973. }
  38974. const String Toolbar::toString() const
  38975. {
  38976. String s (T("TB:"));
  38977. for (int i = 0; i < getNumItems(); ++i)
  38978. s << getItemId(i) << T(' ');
  38979. return s.trimEnd();
  38980. }
  38981. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  38982. const String& savedVersion)
  38983. {
  38984. if (! savedVersion.startsWith (T("TB:")))
  38985. return false;
  38986. StringArray tokens;
  38987. tokens.addTokens (savedVersion.substring (3), false);
  38988. clear();
  38989. for (int i = 0; i < tokens.size(); ++i)
  38990. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  38991. resized();
  38992. return true;
  38993. }
  38994. void Toolbar::paint (Graphics& g)
  38995. {
  38996. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  38997. }
  38998. int Toolbar::getThickness() const throw()
  38999. {
  39000. return vertical ? getWidth() : getHeight();
  39001. }
  39002. int Toolbar::getLength() const throw()
  39003. {
  39004. return vertical ? getHeight() : getWidth();
  39005. }
  39006. void Toolbar::setEditingActive (const bool active)
  39007. {
  39008. if (isEditingActive != active)
  39009. {
  39010. isEditingActive = active;
  39011. updateAllItemPositions (false);
  39012. }
  39013. }
  39014. void Toolbar::resized()
  39015. {
  39016. updateAllItemPositions (false);
  39017. }
  39018. void Toolbar::updateAllItemPositions (const bool animate)
  39019. {
  39020. if (getWidth() > 0 && getHeight() > 0)
  39021. {
  39022. StretchableObjectResizer resizer;
  39023. int i;
  39024. for (i = 0; i < items.size(); ++i)
  39025. {
  39026. ToolbarItemComponent* const tc = items.getUnchecked(i);
  39027. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  39028. : ToolbarItemComponent::normalMode);
  39029. tc->setStyle (toolbarStyle);
  39030. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  39031. int preferredSize = 1, minSize = 1, maxSize = 1;
  39032. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  39033. preferredSize, minSize, maxSize))
  39034. {
  39035. tc->isActive = true;
  39036. resizer.addItem (preferredSize, minSize, maxSize,
  39037. spacer != 0 ? spacer->getResizeOrder() : 2);
  39038. }
  39039. else
  39040. {
  39041. tc->isActive = false;
  39042. tc->setVisible (false);
  39043. }
  39044. }
  39045. resizer.resizeToFit (getLength());
  39046. int totalLength = 0;
  39047. for (i = 0; i < resizer.getNumItems(); ++i)
  39048. totalLength += (int) resizer.getItemSize (i);
  39049. const bool itemsOffTheEnd = totalLength > getLength();
  39050. const int extrasButtonSize = getThickness() / 2;
  39051. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  39052. missingItemsButton->setVisible (itemsOffTheEnd);
  39053. missingItemsButton->setEnabled (! isEditingActive);
  39054. if (vertical)
  39055. missingItemsButton->setCentrePosition (getWidth() / 2,
  39056. getHeight() - 4 - extrasButtonSize / 2);
  39057. else
  39058. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  39059. getHeight() / 2);
  39060. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  39061. : missingItemsButton->getX()) - 4
  39062. : getLength();
  39063. int pos = 0, activeIndex = 0;
  39064. for (i = 0; i < items.size(); ++i)
  39065. {
  39066. ToolbarItemComponent* const tc = items.getUnchecked(i);
  39067. if (tc->isActive)
  39068. {
  39069. const int size = (int) resizer.getItemSize (activeIndex++);
  39070. Rectangle newBounds;
  39071. if (vertical)
  39072. newBounds.setBounds (0, pos, getWidth(), size);
  39073. else
  39074. newBounds.setBounds (pos, 0, size, getHeight());
  39075. if (animate)
  39076. {
  39077. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  39078. }
  39079. else
  39080. {
  39081. animator.cancelAnimation (tc, false);
  39082. tc->setBounds (newBounds);
  39083. }
  39084. pos += size;
  39085. tc->setVisible (pos <= maxLength
  39086. && ((! tc->isBeingDragged)
  39087. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  39088. }
  39089. }
  39090. }
  39091. }
  39092. void Toolbar::buttonClicked (Button*)
  39093. {
  39094. jassert (missingItemsButton->isShowing());
  39095. if (missingItemsButton->isShowing())
  39096. {
  39097. PopupMenu m;
  39098. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  39099. m.showAt (missingItemsButton);
  39100. }
  39101. }
  39102. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  39103. Component* /*sourceComponent*/)
  39104. {
  39105. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  39106. }
  39107. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  39108. {
  39109. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  39110. if (tc != 0)
  39111. {
  39112. if (getNumItems() == 0)
  39113. {
  39114. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  39115. {
  39116. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  39117. if (palette != 0)
  39118. palette->replaceComponent (tc);
  39119. }
  39120. else
  39121. {
  39122. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  39123. }
  39124. items.add (tc);
  39125. addChildComponent (tc);
  39126. updateAllItemPositions (false);
  39127. }
  39128. else
  39129. {
  39130. for (int i = getNumItems(); --i >= 0;)
  39131. {
  39132. int currentIndex = getIndexOfChildComponent (tc);
  39133. if (currentIndex < 0)
  39134. {
  39135. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  39136. {
  39137. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  39138. if (palette != 0)
  39139. palette->replaceComponent (tc);
  39140. }
  39141. else
  39142. {
  39143. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  39144. }
  39145. items.add (tc);
  39146. addChildComponent (tc);
  39147. currentIndex = getIndexOfChildComponent (tc);
  39148. updateAllItemPositions (true);
  39149. }
  39150. int newIndex = currentIndex;
  39151. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  39152. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  39153. const Rectangle current (animator.getComponentDestination (getChildComponent (newIndex)));
  39154. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  39155. if (prev != 0)
  39156. {
  39157. const Rectangle previousPos (animator.getComponentDestination (prev));
  39158. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  39159. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  39160. {
  39161. newIndex = getIndexOfChildComponent (prev);
  39162. }
  39163. }
  39164. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  39165. if (next != 0)
  39166. {
  39167. const Rectangle nextPos (animator.getComponentDestination (next));
  39168. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  39169. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  39170. {
  39171. newIndex = getIndexOfChildComponent (next) + 1;
  39172. }
  39173. }
  39174. if (newIndex != currentIndex)
  39175. {
  39176. items.removeValue (tc);
  39177. removeChildComponent (tc);
  39178. addChildComponent (tc, newIndex);
  39179. items.insert (newIndex, tc);
  39180. updateAllItemPositions (true);
  39181. }
  39182. else
  39183. {
  39184. break;
  39185. }
  39186. }
  39187. }
  39188. }
  39189. }
  39190. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  39191. {
  39192. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  39193. if (tc != 0)
  39194. {
  39195. if (isParentOf (tc))
  39196. {
  39197. items.removeValue (tc);
  39198. removeChildComponent (tc);
  39199. updateAllItemPositions (true);
  39200. }
  39201. }
  39202. }
  39203. void Toolbar::itemDropped (const String&, Component*, int, int)
  39204. {
  39205. }
  39206. void Toolbar::mouseDown (const MouseEvent& e)
  39207. {
  39208. if (e.mods.isPopupMenu())
  39209. {
  39210. }
  39211. }
  39212. class ToolbarCustomisationDialog : public DialogWindow
  39213. {
  39214. public:
  39215. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  39216. Toolbar* const toolbar_,
  39217. const int optionFlags)
  39218. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  39219. toolbar (toolbar_)
  39220. {
  39221. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  39222. setResizable (true, true);
  39223. setResizeLimits (400, 300, 1500, 1000);
  39224. positionNearBar();
  39225. }
  39226. ~ToolbarCustomisationDialog()
  39227. {
  39228. setContentComponent (0, true);
  39229. }
  39230. void closeButtonPressed()
  39231. {
  39232. setVisible (false);
  39233. }
  39234. bool canModalEventBeSentToComponent (const Component* comp)
  39235. {
  39236. return toolbar->isParentOf (comp);
  39237. }
  39238. void positionNearBar()
  39239. {
  39240. const Rectangle screenSize (toolbar->getParentMonitorArea());
  39241. const int tbx = toolbar->getScreenX();
  39242. const int tby = toolbar->getScreenY();
  39243. const int gap = 8;
  39244. int x, y;
  39245. if (toolbar->isVertical())
  39246. {
  39247. y = tby;
  39248. if (tbx > screenSize.getCentreX())
  39249. x = tbx - getWidth() - gap;
  39250. else
  39251. x = tbx + toolbar->getWidth() + gap;
  39252. }
  39253. else
  39254. {
  39255. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  39256. if (tby > screenSize.getCentreY())
  39257. y = tby - getHeight() - gap;
  39258. else
  39259. y = tby + toolbar->getHeight() + gap;
  39260. }
  39261. setTopLeftPosition (x, y);
  39262. }
  39263. private:
  39264. Toolbar* const toolbar;
  39265. class CustomiserPanel : public Component,
  39266. private ComboBoxListener,
  39267. private ButtonListener
  39268. {
  39269. public:
  39270. CustomiserPanel (ToolbarItemFactory& factory_,
  39271. Toolbar* const toolbar_,
  39272. const int optionFlags)
  39273. : factory (factory_),
  39274. toolbar (toolbar_),
  39275. styleBox (0),
  39276. defaultButton (0)
  39277. {
  39278. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  39279. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  39280. | Toolbar::allowIconsWithTextChoice
  39281. | Toolbar::allowTextOnlyChoice)) != 0)
  39282. {
  39283. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  39284. styleBox->setEditableText (false);
  39285. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  39286. styleBox->addItem (TRANS("Show icons only"), 1);
  39287. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  39288. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  39289. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  39290. styleBox->addItem (TRANS("Show descriptions only"), 3);
  39291. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  39292. styleBox->setSelectedId (1);
  39293. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  39294. styleBox->setSelectedId (2);
  39295. else if (toolbar_->getStyle() == Toolbar::textOnly)
  39296. styleBox->setSelectedId (3);
  39297. styleBox->addListener (this);
  39298. }
  39299. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  39300. {
  39301. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  39302. defaultButton->addButtonListener (this);
  39303. }
  39304. addAndMakeVisible (instructions = new Label (String::empty,
  39305. 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.")));
  39306. instructions->setFont (Font (13.0f));
  39307. setSize (500, 300);
  39308. }
  39309. ~CustomiserPanel()
  39310. {
  39311. deleteAllChildren();
  39312. }
  39313. void comboBoxChanged (ComboBox*)
  39314. {
  39315. if (styleBox->getSelectedId() == 1)
  39316. toolbar->setStyle (Toolbar::iconsOnly);
  39317. else if (styleBox->getSelectedId() == 2)
  39318. toolbar->setStyle (Toolbar::iconsWithText);
  39319. else if (styleBox->getSelectedId() == 3)
  39320. toolbar->setStyle (Toolbar::textOnly);
  39321. palette->resized(); // to make it update the styles
  39322. }
  39323. void buttonClicked (Button*)
  39324. {
  39325. toolbar->addDefaultItems (factory);
  39326. }
  39327. void paint (Graphics& g)
  39328. {
  39329. Colour background;
  39330. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  39331. if (dw != 0)
  39332. background = dw->getBackgroundColour();
  39333. g.setColour (background.contrasting().withAlpha (0.3f));
  39334. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  39335. }
  39336. void resized()
  39337. {
  39338. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  39339. if (styleBox != 0)
  39340. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  39341. if (defaultButton != 0)
  39342. {
  39343. defaultButton->changeWidthToFitText (22);
  39344. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  39345. }
  39346. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  39347. }
  39348. private:
  39349. ToolbarItemFactory& factory;
  39350. Toolbar* const toolbar;
  39351. Label* instructions;
  39352. ToolbarItemPalette* palette;
  39353. ComboBox* styleBox;
  39354. TextButton* defaultButton;
  39355. };
  39356. };
  39357. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  39358. {
  39359. setEditingActive (true);
  39360. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  39361. dw.runModalLoop();
  39362. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  39363. setEditingActive (false);
  39364. }
  39365. END_JUCE_NAMESPACE
  39366. /********* End of inlined file: juce_Toolbar.cpp *********/
  39367. /********* Start of inlined file: juce_ToolbarItemComponent.cpp *********/
  39368. BEGIN_JUCE_NAMESPACE
  39369. ToolbarItemFactory::ToolbarItemFactory()
  39370. {
  39371. }
  39372. ToolbarItemFactory::~ToolbarItemFactory()
  39373. {
  39374. }
  39375. class ItemDragAndDropOverlayComponent : public Component
  39376. {
  39377. public:
  39378. ItemDragAndDropOverlayComponent()
  39379. : isDragging (false)
  39380. {
  39381. setAlwaysOnTop (true);
  39382. setRepaintsOnMouseActivity (true);
  39383. setMouseCursor (MouseCursor::DraggingHandCursor);
  39384. }
  39385. ~ItemDragAndDropOverlayComponent()
  39386. {
  39387. }
  39388. void paint (Graphics& g)
  39389. {
  39390. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39391. if (isMouseOverOrDragging()
  39392. && tc != 0
  39393. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  39394. {
  39395. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  39396. g.drawRect (0, 0, getWidth(), getHeight(),
  39397. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  39398. }
  39399. }
  39400. void mouseDown (const MouseEvent& e)
  39401. {
  39402. isDragging = false;
  39403. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39404. if (tc != 0)
  39405. {
  39406. tc->dragOffsetX = e.x;
  39407. tc->dragOffsetY = e.y;
  39408. }
  39409. }
  39410. void mouseDrag (const MouseEvent& e)
  39411. {
  39412. if (! (isDragging || e.mouseWasClicked()))
  39413. {
  39414. isDragging = true;
  39415. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  39416. if (dnd != 0)
  39417. {
  39418. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), 0, true);
  39419. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39420. if (tc != 0)
  39421. {
  39422. tc->isBeingDragged = true;
  39423. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  39424. tc->setVisible (false);
  39425. }
  39426. }
  39427. }
  39428. }
  39429. void mouseUp (const MouseEvent&)
  39430. {
  39431. isDragging = false;
  39432. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39433. if (tc != 0)
  39434. {
  39435. tc->isBeingDragged = false;
  39436. Toolbar* const tb = tc->getToolbar();
  39437. if (tb != 0)
  39438. tb->updateAllItemPositions (true);
  39439. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  39440. delete tc;
  39441. }
  39442. }
  39443. void parentSizeChanged()
  39444. {
  39445. setBounds (0, 0, getParentWidth(), getParentHeight());
  39446. }
  39447. juce_UseDebuggingNewOperator
  39448. private:
  39449. bool isDragging;
  39450. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  39451. const ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  39452. };
  39453. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  39454. const String& labelText,
  39455. const bool isBeingUsedAsAButton_)
  39456. : Button (labelText),
  39457. itemId (itemId_),
  39458. mode (normalMode),
  39459. toolbarStyle (Toolbar::iconsOnly),
  39460. overlayComp (0),
  39461. dragOffsetX (0),
  39462. dragOffsetY (0),
  39463. isActive (true),
  39464. isBeingDragged (false),
  39465. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  39466. {
  39467. // Your item ID can't be 0!
  39468. jassert (itemId_ != 0);
  39469. }
  39470. ToolbarItemComponent::~ToolbarItemComponent()
  39471. {
  39472. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  39473. delete overlayComp;
  39474. }
  39475. Toolbar* ToolbarItemComponent::getToolbar() const
  39476. {
  39477. return dynamic_cast <Toolbar*> (getParentComponent());
  39478. }
  39479. bool ToolbarItemComponent::isToolbarVertical() const
  39480. {
  39481. const Toolbar* const t = getToolbar();
  39482. return t != 0 && t->isVertical();
  39483. }
  39484. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  39485. {
  39486. if (toolbarStyle != newStyle)
  39487. {
  39488. toolbarStyle = newStyle;
  39489. repaint();
  39490. resized();
  39491. }
  39492. }
  39493. void ToolbarItemComponent::paintButton (Graphics& g, bool isMouseOver, bool isMouseDown)
  39494. {
  39495. if (isBeingUsedAsAButton)
  39496. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  39497. isMouseOver, isMouseDown, *this);
  39498. if (toolbarStyle != Toolbar::iconsOnly)
  39499. {
  39500. const int indent = contentArea.getX();
  39501. int y = indent;
  39502. int h = getHeight() - indent * 2;
  39503. if (toolbarStyle == Toolbar::iconsWithText)
  39504. {
  39505. y = contentArea.getBottom() + indent / 2;
  39506. h -= contentArea.getHeight();
  39507. }
  39508. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  39509. getButtonText(), *this);
  39510. }
  39511. if (! contentArea.isEmpty())
  39512. {
  39513. g.saveState();
  39514. g.setOrigin (contentArea.getX(), contentArea.getY());
  39515. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  39516. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), isMouseOver, isMouseDown);
  39517. g.restoreState();
  39518. }
  39519. }
  39520. void ToolbarItemComponent::resized()
  39521. {
  39522. if (toolbarStyle != Toolbar::textOnly)
  39523. {
  39524. const int indent = jmin (proportionOfWidth (0.08f),
  39525. proportionOfHeight (0.08f));
  39526. contentArea = Rectangle (indent, indent,
  39527. getWidth() - indent * 2,
  39528. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  39529. : (getHeight() - indent * 2));
  39530. }
  39531. else
  39532. {
  39533. contentArea = Rectangle();
  39534. }
  39535. contentAreaChanged (contentArea);
  39536. }
  39537. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  39538. {
  39539. if (mode != newMode)
  39540. {
  39541. mode = newMode;
  39542. repaint();
  39543. if (mode == normalMode)
  39544. {
  39545. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  39546. delete overlayComp;
  39547. overlayComp = 0;
  39548. }
  39549. else if (overlayComp == 0)
  39550. {
  39551. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  39552. overlayComp->parentSizeChanged();
  39553. }
  39554. resized();
  39555. }
  39556. }
  39557. END_JUCE_NAMESPACE
  39558. /********* End of inlined file: juce_ToolbarItemComponent.cpp *********/
  39559. /********* Start of inlined file: juce_ToolbarItemPalette.cpp *********/
  39560. BEGIN_JUCE_NAMESPACE
  39561. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  39562. Toolbar* const toolbar_)
  39563. : factory (factory_),
  39564. toolbar (toolbar_)
  39565. {
  39566. Component* const itemHolder = new Component();
  39567. Array <int> allIds;
  39568. factory_.getAllToolbarItemIds (allIds);
  39569. for (int i = 0; i < allIds.size(); ++i)
  39570. {
  39571. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  39572. jassert (tc != 0);
  39573. if (tc != 0)
  39574. {
  39575. itemHolder->addAndMakeVisible (tc);
  39576. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  39577. }
  39578. }
  39579. viewport = new Viewport();
  39580. viewport->setViewedComponent (itemHolder);
  39581. addAndMakeVisible (viewport);
  39582. }
  39583. ToolbarItemPalette::~ToolbarItemPalette()
  39584. {
  39585. viewport->getViewedComponent()->deleteAllChildren();
  39586. deleteAllChildren();
  39587. }
  39588. void ToolbarItemPalette::resized()
  39589. {
  39590. viewport->setBoundsInset (BorderSize (1));
  39591. Component* const itemHolder = viewport->getViewedComponent();
  39592. const int indent = 8;
  39593. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  39594. const int height = toolbar->getThickness();
  39595. int x = indent;
  39596. int y = indent;
  39597. int maxX = 0;
  39598. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  39599. {
  39600. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  39601. if (tc != 0)
  39602. {
  39603. tc->setStyle (toolbar->getStyle());
  39604. int preferredSize = 1, minSize = 1, maxSize = 1;
  39605. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  39606. {
  39607. if (x + preferredSize > preferredWidth && x > indent)
  39608. {
  39609. x = indent;
  39610. y += height;
  39611. }
  39612. tc->setBounds (x, y, preferredSize, height);
  39613. x += preferredSize + 8;
  39614. maxX = jmax (maxX, x);
  39615. }
  39616. }
  39617. }
  39618. itemHolder->setSize (maxX, y + height + 8);
  39619. }
  39620. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  39621. {
  39622. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  39623. jassert (tc != 0);
  39624. if (tc != 0)
  39625. {
  39626. tc->setBounds (comp->getBounds());
  39627. tc->setStyle (toolbar->getStyle());
  39628. tc->setEditingMode (comp->getEditingMode());
  39629. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  39630. }
  39631. }
  39632. END_JUCE_NAMESPACE
  39633. /********* End of inlined file: juce_ToolbarItemPalette.cpp *********/
  39634. /********* Start of inlined file: juce_TreeView.cpp *********/
  39635. BEGIN_JUCE_NAMESPACE
  39636. class TreeViewContentComponent : public Component
  39637. {
  39638. public:
  39639. TreeViewContentComponent (TreeView* const owner_)
  39640. : owner (owner_),
  39641. isDragging (false)
  39642. {
  39643. }
  39644. ~TreeViewContentComponent()
  39645. {
  39646. deleteAllChildren();
  39647. }
  39648. void mouseDown (const MouseEvent& e)
  39649. {
  39650. isDragging = false;
  39651. needSelectionOnMouseUp = false;
  39652. Rectangle pos;
  39653. TreeViewItem* const item = findItemAt (e.y, pos);
  39654. if (item != 0 && e.x >= pos.getX())
  39655. {
  39656. if (! owner->isMultiSelectEnabled())
  39657. item->setSelected (true, true);
  39658. else if (item->isSelected())
  39659. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  39660. else
  39661. selectBasedOnModifiers (item, e.mods);
  39662. MouseEvent e2 (e);
  39663. e2.x -= pos.getX();
  39664. e2.y -= pos.getY();
  39665. item->itemClicked (e2);
  39666. }
  39667. }
  39668. void mouseUp (const MouseEvent& e)
  39669. {
  39670. Rectangle pos;
  39671. TreeViewItem* const item = findItemAt (e.y, pos);
  39672. if (item != 0 && e.mouseWasClicked())
  39673. {
  39674. if (needSelectionOnMouseUp)
  39675. {
  39676. selectBasedOnModifiers (item, e.mods);
  39677. }
  39678. else if (e.mouseWasClicked())
  39679. {
  39680. if (e.x >= pos.getX() - owner->getIndentSize()
  39681. && e.x < pos.getX())
  39682. {
  39683. item->setOpen (! item->isOpen());
  39684. }
  39685. }
  39686. }
  39687. }
  39688. void mouseDoubleClick (const MouseEvent& e)
  39689. {
  39690. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  39691. {
  39692. Rectangle pos;
  39693. TreeViewItem* const item = findItemAt (e.y, pos);
  39694. if (item != 0 && e.x >= pos.getX())
  39695. {
  39696. MouseEvent e2 (e);
  39697. e2.x -= pos.getX();
  39698. e2.y -= pos.getY();
  39699. item->itemDoubleClicked (e2);
  39700. }
  39701. }
  39702. }
  39703. void mouseDrag (const MouseEvent& e)
  39704. {
  39705. if (isEnabled() && ! (e.mouseWasClicked() || isDragging))
  39706. {
  39707. isDragging = true;
  39708. Rectangle pos;
  39709. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  39710. if (item != 0 && e.getMouseDownX() >= pos.getX())
  39711. {
  39712. const String dragDescription (item->getDragSourceDescription());
  39713. if (dragDescription.isNotEmpty())
  39714. {
  39715. DragAndDropContainer* const dragContainer
  39716. = DragAndDropContainer::findParentDragContainerFor (this);
  39717. if (dragContainer != 0)
  39718. {
  39719. pos.setSize (pos.getWidth(), item->itemHeight);
  39720. Image* dragImage = Component::createComponentSnapshot (pos, true);
  39721. dragImage->multiplyAllAlphas (0.6f);
  39722. dragContainer->startDragging (dragDescription, owner, dragImage, true);
  39723. }
  39724. else
  39725. {
  39726. // to be able to do a drag-and-drop operation, the treeview needs to
  39727. // be inside a component which is also a DragAndDropContainer.
  39728. jassertfalse
  39729. }
  39730. }
  39731. }
  39732. }
  39733. }
  39734. void paint (Graphics& g);
  39735. TreeViewItem* findItemAt (int y, Rectangle& itemPosition) const;
  39736. void updateComponents()
  39737. {
  39738. int xAdjust = 0, yAdjust = 0;
  39739. if ((! owner->rootItemVisible) && owner->rootItem != 0)
  39740. {
  39741. yAdjust = owner->rootItem->itemHeight;
  39742. xAdjust = owner->getIndentSize();
  39743. }
  39744. const int visibleTop = -getY();
  39745. const int visibleBottom = visibleTop + getParentHeight();
  39746. BitArray itemsToKeep;
  39747. TreeViewItem* item = owner->rootItem;
  39748. int y = -yAdjust;
  39749. while (item != 0 && y < visibleBottom)
  39750. {
  39751. y += item->itemHeight;
  39752. if (y >= visibleTop)
  39753. {
  39754. const int index = rowComponentIds.indexOf (item->uid);
  39755. if (index < 0)
  39756. {
  39757. Component* const comp = item->createItemComponent();
  39758. if (comp != 0)
  39759. {
  39760. addAndMakeVisible (comp);
  39761. itemsToKeep.setBit (rowComponentItems.size());
  39762. rowComponentItems.add (item);
  39763. rowComponentIds.add (item->uid);
  39764. rowComponents.add (comp);
  39765. }
  39766. }
  39767. else
  39768. {
  39769. itemsToKeep.setBit (index);
  39770. }
  39771. }
  39772. item = item->getNextVisibleItem (true);
  39773. }
  39774. for (int i = rowComponentItems.size(); --i >= 0;)
  39775. {
  39776. Component* const comp = (Component*) (rowComponents.getUnchecked(i));
  39777. bool keep = false;
  39778. if ((itemsToKeep[i] || (comp == Component::getComponentUnderMouse() && comp->isMouseButtonDown()))
  39779. && isParentOf (comp))
  39780. {
  39781. if (itemsToKeep[i])
  39782. {
  39783. const TreeViewItem* const item = (TreeViewItem*) rowComponentItems.getUnchecked(i);
  39784. Rectangle pos (item->getItemPosition (false));
  39785. pos.translate (-xAdjust, -yAdjust);
  39786. pos.setSize (pos.getWidth() + xAdjust, item->itemHeight);
  39787. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  39788. {
  39789. keep = true;
  39790. comp->setBounds (pos);
  39791. }
  39792. }
  39793. else
  39794. {
  39795. comp->setSize (0, 0);
  39796. }
  39797. }
  39798. if (! keep)
  39799. {
  39800. delete comp;
  39801. rowComponents.remove (i);
  39802. rowComponentIds.remove (i);
  39803. rowComponentItems.remove (i);
  39804. }
  39805. }
  39806. }
  39807. void resized()
  39808. {
  39809. owner->itemsChanged();
  39810. }
  39811. juce_UseDebuggingNewOperator
  39812. private:
  39813. TreeView* const owner;
  39814. VoidArray rowComponentItems;
  39815. Array <int> rowComponentIds;
  39816. VoidArray rowComponents;
  39817. bool isDragging, needSelectionOnMouseUp;
  39818. TreeViewContentComponent (const TreeViewContentComponent&);
  39819. const TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  39820. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  39821. {
  39822. TreeViewItem* firstSelected = 0;
  39823. if (modifiers.isShiftDown() && ((firstSelected = owner->getSelectedItem (0)) != 0))
  39824. {
  39825. TreeViewItem* const lastSelected = owner->getSelectedItem (owner->getNumSelectedItems() - 1);
  39826. jassert (lastSelected != 0);
  39827. int rowStart = firstSelected->getRowNumberInTree();
  39828. int rowEnd = lastSelected->getRowNumberInTree();
  39829. if (rowStart > rowEnd)
  39830. swapVariables (rowStart, rowEnd);
  39831. int ourRow = item->getRowNumberInTree();
  39832. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  39833. if (ourRow > otherEnd)
  39834. swapVariables (ourRow, otherEnd);
  39835. for (int i = ourRow; i <= otherEnd; ++i)
  39836. owner->getItemOnRow (i)->setSelected (true, false);
  39837. }
  39838. else
  39839. {
  39840. const bool cmd = modifiers.isCommandDown();
  39841. item->setSelected ((! cmd) || (! item->isSelected()), ! cmd);
  39842. }
  39843. }
  39844. };
  39845. class TreeViewport : public Viewport
  39846. {
  39847. public:
  39848. TreeViewport() throw() {}
  39849. ~TreeViewport() throw() {}
  39850. void updateComponents()
  39851. {
  39852. if (getViewedComponent() != 0)
  39853. ((TreeViewContentComponent*) getViewedComponent())->updateComponents();
  39854. repaint();
  39855. }
  39856. void visibleAreaChanged (int, int, int, int)
  39857. {
  39858. updateComponents();
  39859. }
  39860. juce_UseDebuggingNewOperator
  39861. private:
  39862. TreeViewport (const TreeViewport&);
  39863. const TreeViewport& operator= (const TreeViewport&);
  39864. };
  39865. TreeView::TreeView (const String& componentName)
  39866. : Component (componentName),
  39867. rootItem (0),
  39868. indentSize (24),
  39869. defaultOpenness (false),
  39870. needsRecalculating (true),
  39871. rootItemVisible (true),
  39872. multiSelectEnabled (false)
  39873. {
  39874. addAndMakeVisible (viewport = new TreeViewport());
  39875. viewport->setViewedComponent (new TreeViewContentComponent (this));
  39876. viewport->setWantsKeyboardFocus (false);
  39877. setWantsKeyboardFocus (true);
  39878. }
  39879. TreeView::~TreeView()
  39880. {
  39881. if (rootItem != 0)
  39882. rootItem->setOwnerView (0);
  39883. deleteAllChildren();
  39884. }
  39885. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  39886. {
  39887. if (rootItem != newRootItem)
  39888. {
  39889. if (newRootItem != 0)
  39890. {
  39891. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  39892. if (newRootItem->ownerView != 0)
  39893. newRootItem->ownerView->setRootItem (0);
  39894. }
  39895. if (rootItem != 0)
  39896. rootItem->setOwnerView (0);
  39897. rootItem = newRootItem;
  39898. if (newRootItem != 0)
  39899. newRootItem->setOwnerView (this);
  39900. needsRecalculating = true;
  39901. handleAsyncUpdate();
  39902. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  39903. {
  39904. rootItem->setOpen (false); // force a re-open
  39905. rootItem->setOpen (true);
  39906. }
  39907. }
  39908. }
  39909. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  39910. {
  39911. rootItemVisible = shouldBeVisible;
  39912. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  39913. {
  39914. rootItem->setOpen (false); // force a re-open
  39915. rootItem->setOpen (true);
  39916. }
  39917. itemsChanged();
  39918. }
  39919. void TreeView::colourChanged()
  39920. {
  39921. setOpaque (findColour (backgroundColourId).isOpaque());
  39922. repaint();
  39923. }
  39924. void TreeView::setIndentSize (const int newIndentSize)
  39925. {
  39926. if (indentSize != newIndentSize)
  39927. {
  39928. indentSize = newIndentSize;
  39929. resized();
  39930. }
  39931. }
  39932. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  39933. {
  39934. if (defaultOpenness != isOpenByDefault)
  39935. {
  39936. defaultOpenness = isOpenByDefault;
  39937. itemsChanged();
  39938. }
  39939. }
  39940. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  39941. {
  39942. multiSelectEnabled = canMultiSelect;
  39943. }
  39944. void TreeView::clearSelectedItems()
  39945. {
  39946. if (rootItem != 0)
  39947. rootItem->deselectAllRecursively();
  39948. }
  39949. int TreeView::getNumSelectedItems() const throw()
  39950. {
  39951. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  39952. }
  39953. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  39954. {
  39955. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  39956. }
  39957. int TreeView::getNumRowsInTree() const
  39958. {
  39959. if (rootItem != 0)
  39960. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  39961. return 0;
  39962. }
  39963. TreeViewItem* TreeView::getItemOnRow (int index) const
  39964. {
  39965. if (! rootItemVisible)
  39966. ++index;
  39967. if (rootItem != 0 && index >= 0)
  39968. return rootItem->getItemOnRow (index);
  39969. return 0;
  39970. }
  39971. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  39972. {
  39973. XmlElement* e = 0;
  39974. if (rootItem != 0)
  39975. {
  39976. e = rootItem->createXmlOpenness();
  39977. if (e != 0 && alsoIncludeScrollPosition)
  39978. e->setAttribute (T("scrollPos"), viewport->getViewPositionY());
  39979. }
  39980. return e;
  39981. }
  39982. void TreeView::restoreOpennessState (const XmlElement& newState)
  39983. {
  39984. if (rootItem != 0)
  39985. {
  39986. rootItem->restoreFromXml (newState);
  39987. if (newState.hasAttribute (T("scrollPos")))
  39988. viewport->setViewPosition (viewport->getViewPositionX(),
  39989. newState.getIntAttribute (T("scrollPos")));
  39990. }
  39991. }
  39992. void TreeView::paint (Graphics& g)
  39993. {
  39994. g.fillAll (findColour (backgroundColourId));
  39995. }
  39996. void TreeView::resized()
  39997. {
  39998. viewport->setBounds (0, 0, getWidth(), getHeight());
  39999. itemsChanged();
  40000. }
  40001. void TreeView::moveSelectedRow (int delta)
  40002. {
  40003. int rowSelected = 0;
  40004. TreeViewItem* const firstSelected = getSelectedItem (0);
  40005. if (firstSelected != 0)
  40006. rowSelected = firstSelected->getRowNumberInTree();
  40007. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  40008. TreeViewItem* item = getItemOnRow (rowSelected);
  40009. if (item != 0)
  40010. {
  40011. item->setSelected (true, true);
  40012. scrollToKeepItemVisible (item);
  40013. }
  40014. }
  40015. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  40016. {
  40017. if (item != 0 && item->ownerView == this)
  40018. {
  40019. handleAsyncUpdate();
  40020. item = item->getDeepestOpenParentItem();
  40021. int y = item->y;
  40022. if (! rootItemVisible)
  40023. y -= rootItem->itemHeight;
  40024. int viewTop = viewport->getViewPositionY();
  40025. if (y < viewTop)
  40026. {
  40027. viewport->setViewPosition (viewport->getViewPositionX(), y);
  40028. }
  40029. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  40030. {
  40031. viewport->setViewPosition (viewport->getViewPositionX(),
  40032. (y + item->itemHeight) - viewport->getViewHeight());
  40033. }
  40034. }
  40035. }
  40036. bool TreeView::keyPressed (const KeyPress& key)
  40037. {
  40038. if (key.isKeyCode (KeyPress::upKey))
  40039. {
  40040. moveSelectedRow (-1);
  40041. }
  40042. else if (key.isKeyCode (KeyPress::downKey))
  40043. {
  40044. moveSelectedRow (1);
  40045. }
  40046. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  40047. {
  40048. if (rootItem != 0)
  40049. {
  40050. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  40051. if (key.isKeyCode (KeyPress::pageUpKey))
  40052. rowsOnScreen = -rowsOnScreen;
  40053. moveSelectedRow (rowsOnScreen);
  40054. }
  40055. }
  40056. else if (key.isKeyCode (KeyPress::homeKey))
  40057. {
  40058. moveSelectedRow (-0x3fffffff);
  40059. }
  40060. else if (key.isKeyCode (KeyPress::endKey))
  40061. {
  40062. moveSelectedRow (0x3fffffff);
  40063. }
  40064. else if (key.isKeyCode (KeyPress::returnKey))
  40065. {
  40066. TreeViewItem* const firstSelected = getSelectedItem (0);
  40067. if (firstSelected != 0)
  40068. firstSelected->setOpen (! firstSelected->isOpen());
  40069. }
  40070. else if (key.isKeyCode (KeyPress::leftKey))
  40071. {
  40072. TreeViewItem* const firstSelected = getSelectedItem (0);
  40073. if (firstSelected != 0)
  40074. {
  40075. if (firstSelected->isOpen())
  40076. {
  40077. firstSelected->setOpen (false);
  40078. }
  40079. else
  40080. {
  40081. TreeViewItem* parent = firstSelected->parentItem;
  40082. if ((! rootItemVisible) && parent == rootItem)
  40083. parent = 0;
  40084. if (parent != 0)
  40085. {
  40086. parent->setSelected (true, true);
  40087. scrollToKeepItemVisible (parent);
  40088. }
  40089. }
  40090. }
  40091. }
  40092. else if (key.isKeyCode (KeyPress::rightKey))
  40093. {
  40094. TreeViewItem* const firstSelected = getSelectedItem (0);
  40095. if (firstSelected != 0)
  40096. {
  40097. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  40098. moveSelectedRow (1);
  40099. else
  40100. firstSelected->setOpen (true);
  40101. }
  40102. }
  40103. else
  40104. {
  40105. return false;
  40106. }
  40107. return true;
  40108. }
  40109. void TreeView::itemsChanged() throw()
  40110. {
  40111. needsRecalculating = true;
  40112. repaint();
  40113. triggerAsyncUpdate();
  40114. }
  40115. void TreeView::handleAsyncUpdate()
  40116. {
  40117. if (needsRecalculating)
  40118. {
  40119. needsRecalculating = false;
  40120. const ScopedLock sl (nodeAlterationLock);
  40121. if (rootItem != 0)
  40122. rootItem->updatePositions (0);
  40123. ((TreeViewport*) viewport)->updateComponents();
  40124. if (rootItem != 0)
  40125. {
  40126. viewport->getViewedComponent()
  40127. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  40128. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  40129. }
  40130. else
  40131. {
  40132. viewport->getViewedComponent()->setSize (0, 0);
  40133. }
  40134. }
  40135. }
  40136. void TreeViewContentComponent::paint (Graphics& g)
  40137. {
  40138. if (owner->rootItem != 0)
  40139. {
  40140. owner->handleAsyncUpdate();
  40141. int w = getWidth();
  40142. if (! owner->rootItemVisible)
  40143. {
  40144. const int indentWidth = owner->getIndentSize();
  40145. g.setOrigin (-indentWidth, -owner->rootItem->itemHeight);
  40146. w += indentWidth;
  40147. }
  40148. owner->rootItem->paintRecursively (g, w);
  40149. }
  40150. }
  40151. TreeViewItem* TreeViewContentComponent::findItemAt (int y, Rectangle& itemPosition) const
  40152. {
  40153. if (owner->rootItem != 0)
  40154. {
  40155. owner->handleAsyncUpdate();
  40156. if (! owner->rootItemVisible)
  40157. y += owner->rootItem->itemHeight;
  40158. TreeViewItem* const ti = owner->rootItem->findItemRecursively (y);
  40159. if (ti != 0)
  40160. {
  40161. itemPosition = ti->getItemPosition (false);
  40162. if (! owner->rootItemVisible)
  40163. itemPosition.translate (-owner->getIndentSize(),
  40164. -owner->rootItem->itemHeight);
  40165. }
  40166. return ti;
  40167. }
  40168. return 0;
  40169. }
  40170. #define opennessDefault 0
  40171. #define opennessClosed 1
  40172. #define opennessOpen 2
  40173. TreeViewItem::TreeViewItem()
  40174. : ownerView (0),
  40175. parentItem (0),
  40176. subItems (8),
  40177. y (0),
  40178. itemHeight (0),
  40179. totalHeight (0),
  40180. selected (false),
  40181. redrawNeeded (true),
  40182. drawLinesInside (true),
  40183. openness (opennessDefault)
  40184. {
  40185. static int nextUID = 0;
  40186. uid = nextUID++;
  40187. }
  40188. TreeViewItem::~TreeViewItem()
  40189. {
  40190. }
  40191. const String TreeViewItem::getUniqueName() const
  40192. {
  40193. return String::empty;
  40194. }
  40195. void TreeViewItem::itemOpennessChanged (bool)
  40196. {
  40197. }
  40198. int TreeViewItem::getNumSubItems() const throw()
  40199. {
  40200. return subItems.size();
  40201. }
  40202. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  40203. {
  40204. return subItems [index];
  40205. }
  40206. void TreeViewItem::clearSubItems()
  40207. {
  40208. if (subItems.size() > 0)
  40209. {
  40210. if (ownerView != 0)
  40211. {
  40212. const ScopedLock sl (ownerView->nodeAlterationLock);
  40213. subItems.clear();
  40214. treeHasChanged();
  40215. }
  40216. else
  40217. {
  40218. subItems.clear();
  40219. }
  40220. }
  40221. }
  40222. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  40223. {
  40224. if (newItem != 0)
  40225. {
  40226. newItem->parentItem = this;
  40227. newItem->setOwnerView (ownerView);
  40228. newItem->y = 0;
  40229. newItem->itemHeight = newItem->getItemHeight();
  40230. newItem->totalHeight = 0;
  40231. newItem->itemWidth = newItem->getItemWidth();
  40232. newItem->totalWidth = 0;
  40233. if (ownerView != 0)
  40234. {
  40235. const ScopedLock sl (ownerView->nodeAlterationLock);
  40236. subItems.insert (insertPosition, newItem);
  40237. treeHasChanged();
  40238. if (newItem->isOpen())
  40239. newItem->itemOpennessChanged (true);
  40240. }
  40241. else
  40242. {
  40243. subItems.insert (insertPosition, newItem);
  40244. if (newItem->isOpen())
  40245. newItem->itemOpennessChanged (true);
  40246. }
  40247. }
  40248. }
  40249. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  40250. {
  40251. if (ownerView != 0)
  40252. ownerView->nodeAlterationLock.enter();
  40253. if (((unsigned int) index) < (unsigned int) subItems.size())
  40254. {
  40255. subItems.remove (index, deleteItem);
  40256. treeHasChanged();
  40257. }
  40258. if (ownerView != 0)
  40259. ownerView->nodeAlterationLock.exit();
  40260. }
  40261. bool TreeViewItem::isOpen() const throw()
  40262. {
  40263. if (openness == opennessDefault)
  40264. return ownerView != 0 && ownerView->defaultOpenness;
  40265. else
  40266. return openness == opennessOpen;
  40267. }
  40268. void TreeViewItem::setOpen (const bool shouldBeOpen)
  40269. {
  40270. if (isOpen() != shouldBeOpen)
  40271. {
  40272. openness = shouldBeOpen ? opennessOpen
  40273. : opennessClosed;
  40274. treeHasChanged();
  40275. itemOpennessChanged (isOpen());
  40276. }
  40277. }
  40278. bool TreeViewItem::isSelected() const throw()
  40279. {
  40280. return selected;
  40281. }
  40282. void TreeViewItem::deselectAllRecursively()
  40283. {
  40284. setSelected (false, false);
  40285. for (int i = 0; i < subItems.size(); ++i)
  40286. subItems.getUnchecked(i)->deselectAllRecursively();
  40287. }
  40288. void TreeViewItem::setSelected (const bool shouldBeSelected,
  40289. const bool deselectOtherItemsFirst)
  40290. {
  40291. if (deselectOtherItemsFirst)
  40292. getTopLevelItem()->deselectAllRecursively();
  40293. if (shouldBeSelected != selected)
  40294. {
  40295. selected = shouldBeSelected;
  40296. if (ownerView != 0)
  40297. ownerView->repaint();
  40298. itemSelectionChanged (shouldBeSelected);
  40299. }
  40300. }
  40301. void TreeViewItem::paintItem (Graphics&, int, int)
  40302. {
  40303. }
  40304. void TreeViewItem::itemClicked (const MouseEvent&)
  40305. {
  40306. }
  40307. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  40308. {
  40309. if (mightContainSubItems())
  40310. setOpen (! isOpen());
  40311. }
  40312. void TreeViewItem::itemSelectionChanged (bool)
  40313. {
  40314. }
  40315. const String TreeViewItem::getDragSourceDescription()
  40316. {
  40317. return String::empty;
  40318. }
  40319. const Rectangle TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  40320. {
  40321. const int indentX = getIndentX();
  40322. int width = itemWidth;
  40323. if (ownerView != 0 && width < 0)
  40324. width = ownerView->viewport->getViewWidth() - indentX;
  40325. Rectangle r (indentX, y, jmax (0, width), totalHeight);
  40326. if (relativeToTreeViewTopLeft)
  40327. r.setPosition (r.getX() - ownerView->viewport->getViewPositionX(),
  40328. r.getY() - ownerView->viewport->getViewPositionY());
  40329. return r;
  40330. }
  40331. void TreeViewItem::treeHasChanged() const throw()
  40332. {
  40333. if (ownerView != 0)
  40334. ownerView->itemsChanged();
  40335. }
  40336. void TreeViewItem::updatePositions (int newY)
  40337. {
  40338. y = newY;
  40339. itemHeight = getItemHeight();
  40340. totalHeight = itemHeight;
  40341. itemWidth = getItemWidth();
  40342. totalWidth = jmax (itemWidth, 0);
  40343. if (isOpen())
  40344. {
  40345. const int ourIndent = getIndentX();
  40346. newY += totalHeight;
  40347. for (int i = 0; i < subItems.size(); ++i)
  40348. {
  40349. TreeViewItem* const ti = subItems.getUnchecked(i);
  40350. ti->updatePositions (newY);
  40351. newY += ti->totalHeight;
  40352. totalHeight += ti->totalHeight;
  40353. totalWidth = jmax (totalWidth, ti->totalWidth + ourIndent);
  40354. }
  40355. }
  40356. }
  40357. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  40358. {
  40359. TreeViewItem* result = this;
  40360. TreeViewItem* item = this;
  40361. while (item->parentItem != 0)
  40362. {
  40363. item = item->parentItem;
  40364. if (! item->isOpen())
  40365. result = item;
  40366. }
  40367. return result;
  40368. }
  40369. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  40370. {
  40371. ownerView = newOwner;
  40372. for (int i = subItems.size(); --i >= 0;)
  40373. subItems.getUnchecked(i)->setOwnerView (newOwner);
  40374. }
  40375. int TreeViewItem::getIndentX() const throw()
  40376. {
  40377. const int indentWidth = ownerView->getIndentSize();
  40378. int x = indentWidth;
  40379. TreeViewItem* p = parentItem;
  40380. while (p != 0)
  40381. {
  40382. x += indentWidth;
  40383. p = p->parentItem;
  40384. }
  40385. return x;
  40386. }
  40387. void TreeViewItem::paintRecursively (Graphics& g, int width)
  40388. {
  40389. jassert (ownerView != 0);
  40390. if (ownerView == 0)
  40391. return;
  40392. const int indent = getIndentX();
  40393. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  40394. g.setColour (ownerView->findColour (TreeView::linesColourId));
  40395. const float halfH = itemHeight * 0.5f;
  40396. int depth = 0;
  40397. TreeViewItem* p = parentItem;
  40398. while (p != 0)
  40399. {
  40400. ++depth;
  40401. p = p->parentItem;
  40402. }
  40403. const int indentWidth = ownerView->getIndentSize();
  40404. float x = (depth + 0.5f) * indentWidth;
  40405. if (x > 0)
  40406. {
  40407. if (depth >= 0)
  40408. {
  40409. if (parentItem != 0 && parentItem->drawLinesInside)
  40410. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  40411. if ((parentItem != 0 && parentItem->drawLinesInside)
  40412. || (parentItem == 0 && drawLinesInside))
  40413. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  40414. }
  40415. p = parentItem;
  40416. int d = depth;
  40417. while (p != 0 && --d >= 0)
  40418. {
  40419. x -= (float) indentWidth;
  40420. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  40421. && ! p->isLastOfSiblings())
  40422. {
  40423. g.drawLine (x, 0, x, (float) itemHeight);
  40424. }
  40425. p = p->parentItem;
  40426. }
  40427. if (mightContainSubItems())
  40428. {
  40429. ownerView->getLookAndFeel()
  40430. .drawTreeviewPlusMinusBox (g,
  40431. depth * indentWidth, 0,
  40432. indentWidth, itemHeight,
  40433. ! isOpen());
  40434. }
  40435. }
  40436. {
  40437. g.saveState();
  40438. g.setOrigin (indent, 0);
  40439. if (g.reduceClipRegion (0, 0, itemW, itemHeight))
  40440. paintItem (g, itemW, itemHeight);
  40441. g.restoreState();
  40442. }
  40443. if (isOpen())
  40444. {
  40445. const Rectangle clip (g.getClipBounds());
  40446. for (int i = 0; i < subItems.size(); ++i)
  40447. {
  40448. TreeViewItem* const ti = subItems.getUnchecked(i);
  40449. const int relY = ti->y - y;
  40450. if (relY >= clip.getBottom())
  40451. break;
  40452. if (relY + ti->totalHeight >= clip.getY())
  40453. {
  40454. g.saveState();
  40455. g.setOrigin (0, relY);
  40456. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  40457. ti->paintRecursively (g, width);
  40458. g.restoreState();
  40459. }
  40460. }
  40461. }
  40462. }
  40463. bool TreeViewItem::isLastOfSiblings() const throw()
  40464. {
  40465. return parentItem == 0
  40466. || parentItem->subItems.getLast() == this;
  40467. }
  40468. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  40469. {
  40470. return (parentItem == 0) ? this
  40471. : parentItem->getTopLevelItem();
  40472. }
  40473. int TreeViewItem::getNumRows() const throw()
  40474. {
  40475. int num = 1;
  40476. if (isOpen())
  40477. {
  40478. for (int i = subItems.size(); --i >= 0;)
  40479. num += subItems.getUnchecked(i)->getNumRows();
  40480. }
  40481. return num;
  40482. }
  40483. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  40484. {
  40485. if (index == 0)
  40486. return this;
  40487. if (index > 0 && isOpen())
  40488. {
  40489. --index;
  40490. for (int i = 0; i < subItems.size(); ++i)
  40491. {
  40492. TreeViewItem* const item = subItems.getUnchecked(i);
  40493. if (index == 0)
  40494. return item;
  40495. const int numRows = item->getNumRows();
  40496. if (numRows > index)
  40497. return item->getItemOnRow (index);
  40498. index -= numRows;
  40499. }
  40500. }
  40501. return 0;
  40502. }
  40503. TreeViewItem* TreeViewItem::findItemRecursively (int y) throw()
  40504. {
  40505. if (((unsigned int) y) < (unsigned int) totalHeight)
  40506. {
  40507. const int h = itemHeight;
  40508. if (y < h)
  40509. return this;
  40510. if (isOpen())
  40511. {
  40512. y -= h;
  40513. for (int i = 0; i < subItems.size(); ++i)
  40514. {
  40515. TreeViewItem* const ti = subItems.getUnchecked(i);
  40516. if (ti->totalHeight >= y)
  40517. return ti->findItemRecursively (y);
  40518. y -= ti->totalHeight;
  40519. }
  40520. }
  40521. }
  40522. return 0;
  40523. }
  40524. int TreeViewItem::countSelectedItemsRecursively() const throw()
  40525. {
  40526. int total = 0;
  40527. if (isSelected())
  40528. ++total;
  40529. for (int i = subItems.size(); --i >= 0;)
  40530. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  40531. return total;
  40532. }
  40533. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  40534. {
  40535. if (isSelected())
  40536. {
  40537. if (index == 0)
  40538. return this;
  40539. --index;
  40540. }
  40541. if (index >= 0)
  40542. {
  40543. for (int i = 0; i < subItems.size(); ++i)
  40544. {
  40545. TreeViewItem* const item = subItems.getUnchecked(i);
  40546. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  40547. if (found != 0)
  40548. return found;
  40549. index -= item->countSelectedItemsRecursively();
  40550. }
  40551. }
  40552. return 0;
  40553. }
  40554. int TreeViewItem::getRowNumberInTree() const throw()
  40555. {
  40556. if (parentItem != 0 && ownerView != 0)
  40557. {
  40558. int n = 1 + parentItem->getRowNumberInTree();
  40559. int ourIndex = parentItem->subItems.indexOf (this);
  40560. jassert (ourIndex >= 0);
  40561. while (--ourIndex >= 0)
  40562. n += parentItem->subItems [ourIndex]->getNumRows();
  40563. if (parentItem->parentItem == 0
  40564. && ! ownerView->rootItemVisible)
  40565. --n;
  40566. return n;
  40567. }
  40568. else
  40569. {
  40570. return 0;
  40571. }
  40572. }
  40573. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  40574. {
  40575. drawLinesInside = drawLines;
  40576. }
  40577. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  40578. {
  40579. if (recurse && isOpen() && subItems.size() > 0)
  40580. return subItems [0];
  40581. if (parentItem != 0)
  40582. {
  40583. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  40584. if (nextIndex >= parentItem->subItems.size())
  40585. return parentItem->getNextVisibleItem (false);
  40586. return parentItem->subItems [nextIndex];
  40587. }
  40588. return 0;
  40589. }
  40590. void TreeViewItem::restoreFromXml (const XmlElement& e)
  40591. {
  40592. if (e.hasTagName (T("CLOSED")))
  40593. {
  40594. setOpen (false);
  40595. }
  40596. else if (e.hasTagName (T("OPEN")))
  40597. {
  40598. setOpen (true);
  40599. forEachXmlChildElement (e, n)
  40600. {
  40601. const String id (n->getStringAttribute (T("id")));
  40602. for (int i = 0; i < subItems.size(); ++i)
  40603. {
  40604. TreeViewItem* const ti = subItems.getUnchecked(i);
  40605. if (ti->getUniqueName() == id)
  40606. {
  40607. ti->restoreFromXml (*n);
  40608. break;
  40609. }
  40610. }
  40611. }
  40612. }
  40613. }
  40614. XmlElement* TreeViewItem::createXmlOpenness() const
  40615. {
  40616. if (openness != opennessDefault)
  40617. {
  40618. const String name (getUniqueName());
  40619. if (name.isNotEmpty())
  40620. {
  40621. XmlElement* e;
  40622. if (isOpen())
  40623. {
  40624. e = new XmlElement (T("OPEN"));
  40625. for (int i = 0; i < subItems.size(); ++i)
  40626. e->addChildElement (subItems.getUnchecked(i)->createXmlOpenness());
  40627. }
  40628. else
  40629. {
  40630. e = new XmlElement (T("CLOSED"));
  40631. }
  40632. e->setAttribute (T("id"), name);
  40633. return e;
  40634. }
  40635. else
  40636. {
  40637. // trying to save the openness for an element that has no name - this won't
  40638. // work because it needs the names to identify what to open.
  40639. jassertfalse
  40640. }
  40641. }
  40642. return 0;
  40643. }
  40644. END_JUCE_NAMESPACE
  40645. /********* End of inlined file: juce_TreeView.cpp *********/
  40646. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  40647. BEGIN_JUCE_NAMESPACE
  40648. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  40649. : fileList (listToShow),
  40650. listeners (2)
  40651. {
  40652. }
  40653. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  40654. {
  40655. }
  40656. FileBrowserListener::~FileBrowserListener()
  40657. {
  40658. }
  40659. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener) throw()
  40660. {
  40661. jassert (listener != 0);
  40662. if (listener != 0)
  40663. listeners.add (listener);
  40664. }
  40665. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener) throw()
  40666. {
  40667. listeners.removeValue (listener);
  40668. }
  40669. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  40670. {
  40671. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  40672. for (int i = listeners.size(); --i >= 0;)
  40673. {
  40674. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  40675. if (deletionWatcher.hasBeenDeleted())
  40676. return;
  40677. i = jmin (i, listeners.size() - 1);
  40678. }
  40679. }
  40680. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  40681. {
  40682. if (fileList.getDirectory().exists())
  40683. {
  40684. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  40685. for (int i = listeners.size(); --i >= 0;)
  40686. {
  40687. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (file, e);
  40688. if (deletionWatcher.hasBeenDeleted())
  40689. return;
  40690. i = jmin (i, listeners.size() - 1);
  40691. }
  40692. }
  40693. }
  40694. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  40695. {
  40696. if (fileList.getDirectory().exists())
  40697. {
  40698. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  40699. for (int i = listeners.size(); --i >= 0;)
  40700. {
  40701. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (file);
  40702. if (deletionWatcher.hasBeenDeleted())
  40703. return;
  40704. i = jmin (i, listeners.size() - 1);
  40705. }
  40706. }
  40707. }
  40708. END_JUCE_NAMESPACE
  40709. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  40710. /********* Start of inlined file: juce_DirectoryContentsList.cpp *********/
  40711. BEGIN_JUCE_NAMESPACE
  40712. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  40713. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  40714. Time* creationTime, bool* isReadOnly) throw();
  40715. bool juce_findFileNext (void* handle, String& resultFile,
  40716. bool* isDirectory, bool* isHidden, int64* fileSize,
  40717. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  40718. void juce_findFileClose (void* handle) throw();
  40719. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  40720. TimeSliceThread& thread_)
  40721. : fileFilter (fileFilter_),
  40722. thread (thread_),
  40723. includeDirectories (false),
  40724. includeFiles (false),
  40725. ignoreHiddenFiles (true),
  40726. fileFindHandle (0),
  40727. shouldStop (true)
  40728. {
  40729. }
  40730. DirectoryContentsList::~DirectoryContentsList()
  40731. {
  40732. clear();
  40733. }
  40734. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  40735. {
  40736. ignoreHiddenFiles = shouldIgnoreHiddenFiles;
  40737. }
  40738. const File& DirectoryContentsList::getDirectory() const throw()
  40739. {
  40740. return root;
  40741. }
  40742. void DirectoryContentsList::setDirectory (const File& directory,
  40743. const bool includeDirectories_,
  40744. const bool includeFiles_)
  40745. {
  40746. if (directory != root
  40747. || includeDirectories != includeDirectories_
  40748. || includeFiles != includeFiles_)
  40749. {
  40750. clear();
  40751. root = directory;
  40752. includeDirectories = includeDirectories_;
  40753. includeFiles = includeFiles_;
  40754. refresh();
  40755. }
  40756. }
  40757. void DirectoryContentsList::clear()
  40758. {
  40759. shouldStop = true;
  40760. thread.removeTimeSliceClient (this);
  40761. if (fileFindHandle != 0)
  40762. {
  40763. juce_findFileClose (fileFindHandle);
  40764. fileFindHandle = 0;
  40765. }
  40766. if (files.size() > 0)
  40767. {
  40768. files.clear();
  40769. changed();
  40770. }
  40771. }
  40772. void DirectoryContentsList::refresh()
  40773. {
  40774. clear();
  40775. if (root.isDirectory())
  40776. {
  40777. String fileFound;
  40778. bool fileFoundIsDir, isHidden, isReadOnly;
  40779. int64 fileSize;
  40780. Time modTime, creationTime;
  40781. String path (root.getFullPathName());
  40782. if (! path.endsWithChar (File::separator))
  40783. path += File::separator;
  40784. jassert (fileFindHandle == 0);
  40785. fileFindHandle = juce_findFileStart (path, T("*"), fileFound,
  40786. &fileFoundIsDir,
  40787. &isHidden,
  40788. &fileSize,
  40789. &modTime,
  40790. &creationTime,
  40791. &isReadOnly);
  40792. if (fileFindHandle != 0 && fileFound.isNotEmpty())
  40793. {
  40794. if (addFile (fileFound, fileFoundIsDir, isHidden,
  40795. fileSize, modTime, creationTime, isReadOnly))
  40796. {
  40797. changed();
  40798. }
  40799. }
  40800. shouldStop = false;
  40801. thread.addTimeSliceClient (this);
  40802. }
  40803. }
  40804. int DirectoryContentsList::getNumFiles() const
  40805. {
  40806. return files.size();
  40807. }
  40808. bool DirectoryContentsList::getFileInfo (const int index,
  40809. FileInfo& result) const
  40810. {
  40811. const ScopedLock sl (fileListLock);
  40812. const FileInfo* const info = files [index];
  40813. if (info != 0)
  40814. {
  40815. result = *info;
  40816. return true;
  40817. }
  40818. return false;
  40819. }
  40820. const File DirectoryContentsList::getFile (const int index) const
  40821. {
  40822. const ScopedLock sl (fileListLock);
  40823. const FileInfo* const info = files [index];
  40824. if (info != 0)
  40825. return root.getChildFile (info->filename);
  40826. return File::nonexistent;
  40827. }
  40828. bool DirectoryContentsList::isStillLoading() const
  40829. {
  40830. return fileFindHandle != 0;
  40831. }
  40832. void DirectoryContentsList::changed()
  40833. {
  40834. sendChangeMessage (this);
  40835. }
  40836. bool DirectoryContentsList::useTimeSlice()
  40837. {
  40838. const uint32 startTime = Time::getApproximateMillisecondCounter();
  40839. bool hasChanged = false;
  40840. for (int i = 100; --i >= 0;)
  40841. {
  40842. if (! checkNextFile (hasChanged))
  40843. {
  40844. if (hasChanged)
  40845. changed();
  40846. return false;
  40847. }
  40848. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  40849. break;
  40850. }
  40851. if (hasChanged)
  40852. changed();
  40853. return true;
  40854. }
  40855. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  40856. {
  40857. if (fileFindHandle != 0)
  40858. {
  40859. String fileFound;
  40860. bool fileFoundIsDir, isHidden, isReadOnly;
  40861. int64 fileSize;
  40862. Time modTime, creationTime;
  40863. if (juce_findFileNext (fileFindHandle, fileFound,
  40864. &fileFoundIsDir, &isHidden,
  40865. &fileSize,
  40866. &modTime,
  40867. &creationTime,
  40868. &isReadOnly))
  40869. {
  40870. if (addFile (fileFound, fileFoundIsDir, isHidden, fileSize,
  40871. modTime, creationTime, isReadOnly))
  40872. {
  40873. hasChanged = true;
  40874. }
  40875. return true;
  40876. }
  40877. else
  40878. {
  40879. juce_findFileClose (fileFindHandle);
  40880. fileFindHandle = 0;
  40881. }
  40882. }
  40883. return false;
  40884. }
  40885. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  40886. const DirectoryContentsList::FileInfo* const second) throw()
  40887. {
  40888. #if JUCE_WIN32
  40889. if (first->isDirectory != second->isDirectory)
  40890. return first->isDirectory ? -1 : 1;
  40891. #endif
  40892. return first->filename.compareIgnoreCase (second->filename);
  40893. }
  40894. bool DirectoryContentsList::addFile (const String& filename,
  40895. const bool isDir,
  40896. const bool isHidden,
  40897. const int64 fileSize,
  40898. const Time& modTime,
  40899. const Time& creationTime,
  40900. const bool isReadOnly)
  40901. {
  40902. if (filename == T("..")
  40903. || filename == T(".")
  40904. || (ignoreHiddenFiles && isHidden))
  40905. return false;
  40906. const File file (root.getChildFile (filename));
  40907. if (((isDir && includeDirectories) || ((! isDir) && includeFiles))
  40908. && (fileFilter == 0
  40909. || ((! isDir) && fileFilter->isFileSuitable (file))
  40910. || (isDir && fileFilter->isDirectorySuitable (file))))
  40911. {
  40912. FileInfo* const info = new FileInfo();
  40913. info->filename = filename;
  40914. info->fileSize = fileSize;
  40915. info->modificationTime = modTime;
  40916. info->creationTime = creationTime;
  40917. info->isDirectory = isDir;
  40918. info->isReadOnly = isReadOnly;
  40919. const ScopedLock sl (fileListLock);
  40920. for (int i = files.size(); --i >= 0;)
  40921. {
  40922. if (files.getUnchecked(i)->filename == info->filename)
  40923. {
  40924. delete info;
  40925. return false;
  40926. }
  40927. }
  40928. files.addSorted (*this, info);
  40929. return true;
  40930. }
  40931. return false;
  40932. }
  40933. END_JUCE_NAMESPACE
  40934. /********* End of inlined file: juce_DirectoryContentsList.cpp *********/
  40935. /********* Start of inlined file: juce_FileBrowserComponent.cpp *********/
  40936. BEGIN_JUCE_NAMESPACE
  40937. class DirectoriesOnlyFilter : public FileFilter
  40938. {
  40939. public:
  40940. DirectoriesOnlyFilter() : FileFilter (String::empty) {}
  40941. bool isFileSuitable (const File&) const { return false; }
  40942. bool isDirectorySuitable (const File&) const { return true; }
  40943. };
  40944. FileBrowserComponent::FileBrowserComponent (FileChooserMode mode_,
  40945. const File& initialFileOrDirectory,
  40946. const FileFilter* fileFilter,
  40947. FilePreviewComponent* previewComp_,
  40948. const bool useTreeView,
  40949. const bool filenameTextBoxIsReadOnly)
  40950. : directoriesOnlyFilter (0),
  40951. mode (mode_),
  40952. listeners (2),
  40953. previewComp (previewComp_),
  40954. thread ("Juce FileBrowser")
  40955. {
  40956. String filename;
  40957. if (initialFileOrDirectory == File::nonexistent)
  40958. {
  40959. currentRoot = File::getCurrentWorkingDirectory();
  40960. }
  40961. else if (initialFileOrDirectory.isDirectory())
  40962. {
  40963. currentRoot = initialFileOrDirectory;
  40964. }
  40965. else
  40966. {
  40967. currentRoot = initialFileOrDirectory.getParentDirectory();
  40968. filename = initialFileOrDirectory.getFileName();
  40969. }
  40970. if (mode_ == chooseDirectoryMode)
  40971. fileFilter = directoriesOnlyFilter = new DirectoriesOnlyFilter();
  40972. fileList = new DirectoryContentsList (fileFilter, thread);
  40973. if (useTreeView)
  40974. {
  40975. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  40976. addAndMakeVisible (tree);
  40977. fileListComponent = tree;
  40978. }
  40979. else
  40980. {
  40981. FileListComponent* const list = new FileListComponent (*fileList);
  40982. list->setOutlineThickness (1);
  40983. addAndMakeVisible (list);
  40984. fileListComponent = list;
  40985. }
  40986. fileListComponent->addListener (this);
  40987. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  40988. currentPathBox->setEditableText (true);
  40989. StringArray rootNames, rootPaths;
  40990. const BitArray separators (getRoots (rootNames, rootPaths));
  40991. for (int i = 0; i < rootNames.size(); ++i)
  40992. {
  40993. if (separators [i])
  40994. currentPathBox->addSeparator();
  40995. currentPathBox->addItem (rootNames[i], i + 1);
  40996. }
  40997. currentPathBox->addSeparator();
  40998. currentPathBox->addListener (this);
  40999. addAndMakeVisible (filenameBox = new TextEditor());
  41000. filenameBox->setMultiLine (false);
  41001. filenameBox->setSelectAllWhenFocused (true);
  41002. filenameBox->setText (filename, false);
  41003. filenameBox->addListener (this);
  41004. filenameBox->setReadOnly (filenameTextBoxIsReadOnly);
  41005. Label* label = new Label ("f", (mode == chooseDirectoryMode) ? TRANS("folder:")
  41006. : TRANS("file:"));
  41007. addAndMakeVisible (label);
  41008. label->attachToComponent (filenameBox, true);
  41009. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  41010. goUpButton->addButtonListener (this);
  41011. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  41012. if (previewComp != 0)
  41013. addAndMakeVisible (previewComp);
  41014. setRoot (currentRoot);
  41015. thread.startThread (4);
  41016. }
  41017. FileBrowserComponent::~FileBrowserComponent()
  41018. {
  41019. if (previewComp != 0)
  41020. removeChildComponent (previewComp);
  41021. deleteAllChildren();
  41022. deleteAndZero (fileList);
  41023. delete directoriesOnlyFilter;
  41024. thread.stopThread (10000);
  41025. }
  41026. void FileBrowserComponent::addListener (FileBrowserListener* const newListener) throw()
  41027. {
  41028. jassert (newListener != 0)
  41029. if (newListener != 0)
  41030. listeners.add (newListener);
  41031. }
  41032. void FileBrowserComponent::removeListener (FileBrowserListener* const listener) throw()
  41033. {
  41034. listeners.removeValue (listener);
  41035. }
  41036. const File FileBrowserComponent::getCurrentFile() const throw()
  41037. {
  41038. return currentRoot.getChildFile (filenameBox->getText());
  41039. }
  41040. bool FileBrowserComponent::currentFileIsValid() const
  41041. {
  41042. if (mode == saveFileMode)
  41043. return ! getCurrentFile().isDirectory();
  41044. else if (mode == loadFileMode)
  41045. return getCurrentFile().existsAsFile();
  41046. else if (mode == chooseDirectoryMode)
  41047. return getCurrentFile().isDirectory();
  41048. jassertfalse
  41049. return false;
  41050. }
  41051. const File FileBrowserComponent::getRoot() const
  41052. {
  41053. return currentRoot;
  41054. }
  41055. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  41056. {
  41057. if (currentRoot != newRootDirectory)
  41058. {
  41059. fileListComponent->scrollToTop();
  41060. if (mode == chooseDirectoryMode)
  41061. filenameBox->setText (String::empty, false);
  41062. String path (newRootDirectory.getFullPathName());
  41063. if (path.isEmpty())
  41064. path += File::separator;
  41065. StringArray rootNames, rootPaths;
  41066. getRoots (rootNames, rootPaths);
  41067. if (! rootPaths.contains (path, true))
  41068. {
  41069. bool alreadyListed = false;
  41070. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  41071. {
  41072. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  41073. {
  41074. alreadyListed = true;
  41075. break;
  41076. }
  41077. }
  41078. if (! alreadyListed)
  41079. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  41080. }
  41081. }
  41082. currentRoot = newRootDirectory;
  41083. fileList->setDirectory (currentRoot, true, true);
  41084. String currentRootName (currentRoot.getFullPathName());
  41085. if (currentRootName.isEmpty())
  41086. currentRootName += File::separator;
  41087. currentPathBox->setText (currentRootName, true);
  41088. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  41089. && currentRoot.getParentDirectory() != currentRoot);
  41090. }
  41091. void FileBrowserComponent::goUp()
  41092. {
  41093. setRoot (getRoot().getParentDirectory());
  41094. }
  41095. void FileBrowserComponent::refresh()
  41096. {
  41097. fileList->refresh();
  41098. }
  41099. const String FileBrowserComponent::getActionVerb() const
  41100. {
  41101. return (mode == chooseDirectoryMode) ? TRANS("Choose")
  41102. : ((mode == saveFileMode) ? TRANS("Save") : TRANS("Open"));
  41103. }
  41104. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  41105. {
  41106. return previewComp;
  41107. }
  41108. void FileBrowserComponent::resized()
  41109. {
  41110. getLookAndFeel()
  41111. .layoutFileBrowserComponent (*this, fileListComponent,
  41112. previewComp, currentPathBox,
  41113. filenameBox, goUpButton);
  41114. }
  41115. void FileBrowserComponent::sendListenerChangeMessage()
  41116. {
  41117. ComponentDeletionWatcher deletionWatcher (this);
  41118. if (previewComp != 0)
  41119. previewComp->selectedFileChanged (getCurrentFile());
  41120. jassert (! deletionWatcher.hasBeenDeleted());
  41121. for (int i = listeners.size(); --i >= 0;)
  41122. {
  41123. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  41124. if (deletionWatcher.hasBeenDeleted())
  41125. return;
  41126. i = jmin (i, listeners.size() - 1);
  41127. }
  41128. }
  41129. void FileBrowserComponent::selectionChanged()
  41130. {
  41131. const File selected (fileListComponent->getSelectedFile());
  41132. if ((mode == chooseDirectoryMode && selected.isDirectory())
  41133. || selected.existsAsFile())
  41134. {
  41135. filenameBox->setText (selected.getRelativePathFrom (getRoot()), false);
  41136. }
  41137. sendListenerChangeMessage();
  41138. }
  41139. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  41140. {
  41141. ComponentDeletionWatcher deletionWatcher (this);
  41142. for (int i = listeners.size(); --i >= 0;)
  41143. {
  41144. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (f, e);
  41145. if (deletionWatcher.hasBeenDeleted())
  41146. return;
  41147. i = jmin (i, listeners.size() - 1);
  41148. }
  41149. }
  41150. void FileBrowserComponent::fileDoubleClicked (const File& f)
  41151. {
  41152. if (f.isDirectory())
  41153. {
  41154. setRoot (f);
  41155. }
  41156. else
  41157. {
  41158. ComponentDeletionWatcher deletionWatcher (this);
  41159. for (int i = listeners.size(); --i >= 0;)
  41160. {
  41161. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (f);
  41162. if (deletionWatcher.hasBeenDeleted())
  41163. return;
  41164. i = jmin (i, listeners.size() - 1);
  41165. }
  41166. }
  41167. }
  41168. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  41169. {
  41170. sendListenerChangeMessage();
  41171. }
  41172. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  41173. {
  41174. if (filenameBox->getText().containsChar (File::separator))
  41175. {
  41176. const File f (currentRoot.getChildFile (filenameBox->getText()));
  41177. if (f.isDirectory())
  41178. {
  41179. setRoot (f);
  41180. filenameBox->setText (String::empty);
  41181. }
  41182. else
  41183. {
  41184. setRoot (f.getParentDirectory());
  41185. filenameBox->setText (f.getFileName());
  41186. }
  41187. }
  41188. else
  41189. {
  41190. fileDoubleClicked (getCurrentFile());
  41191. }
  41192. }
  41193. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  41194. {
  41195. }
  41196. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  41197. {
  41198. if (mode != saveFileMode)
  41199. selectionChanged();
  41200. }
  41201. void FileBrowserComponent::buttonClicked (Button*)
  41202. {
  41203. goUp();
  41204. }
  41205. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  41206. {
  41207. const String newText (currentPathBox->getText().trim().unquoted());
  41208. if (newText.isNotEmpty())
  41209. {
  41210. const int index = currentPathBox->getSelectedId() - 1;
  41211. StringArray rootNames, rootPaths;
  41212. getRoots (rootNames, rootPaths);
  41213. if (rootPaths [index].isNotEmpty())
  41214. {
  41215. setRoot (File (rootPaths [index]));
  41216. }
  41217. else
  41218. {
  41219. File f (newText);
  41220. for (;;)
  41221. {
  41222. if (f.isDirectory())
  41223. {
  41224. setRoot (f);
  41225. break;
  41226. }
  41227. if (f.getParentDirectory() == f)
  41228. break;
  41229. f = f.getParentDirectory();
  41230. }
  41231. }
  41232. }
  41233. }
  41234. const BitArray FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  41235. {
  41236. BitArray separators;
  41237. #if JUCE_WIN32
  41238. OwnedArray<File> roots;
  41239. File::findFileSystemRoots (roots);
  41240. rootPaths.clear();
  41241. for (int i = 0; i < roots.size(); ++i)
  41242. {
  41243. const File* const drive = roots.getUnchecked(i);
  41244. String name (drive->getFullPathName());
  41245. rootPaths.add (name);
  41246. if (drive->isOnHardDisk())
  41247. {
  41248. String volume (drive->getVolumeLabel());
  41249. if (volume.isEmpty())
  41250. volume = TRANS("Hard Drive");
  41251. name << " [" << drive->getVolumeLabel() << ']';
  41252. }
  41253. else if (drive->isOnCDRomDrive())
  41254. {
  41255. name << TRANS(" [CD/DVD drive]");
  41256. }
  41257. rootNames.add (name);
  41258. }
  41259. separators.setBit (rootPaths.size());
  41260. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  41261. rootNames.add ("Documents");
  41262. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  41263. rootNames.add ("Desktop");
  41264. #endif
  41265. #if JUCE_MAC
  41266. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  41267. rootNames.add ("Home folder");
  41268. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  41269. rootNames.add ("Documents");
  41270. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  41271. rootNames.add ("Desktop");
  41272. separators.setBit (rootPaths.size());
  41273. OwnedArray <File> volumes;
  41274. File vol ("/Volumes");
  41275. vol.findChildFiles (volumes, File::findDirectories, false);
  41276. for (int i = 0; i < volumes.size(); ++i)
  41277. {
  41278. const File* const volume = volumes.getUnchecked(i);
  41279. if (volume->isDirectory() && ! volume->getFileName().startsWithChar (T('.')))
  41280. {
  41281. rootPaths.add (volume->getFullPathName());
  41282. rootNames.add (volume->getFileName());
  41283. }
  41284. }
  41285. #endif
  41286. #if JUCE_LINUX
  41287. rootPaths.add ("/");
  41288. rootNames.add ("/");
  41289. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  41290. rootNames.add ("Home folder");
  41291. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  41292. rootNames.add ("Desktop");
  41293. #endif
  41294. return separators;
  41295. }
  41296. END_JUCE_NAMESPACE
  41297. /********* End of inlined file: juce_FileBrowserComponent.cpp *********/
  41298. /********* Start of inlined file: juce_FileChooser.cpp *********/
  41299. BEGIN_JUCE_NAMESPACE
  41300. FileChooser::FileChooser (const String& chooserBoxTitle,
  41301. const File& currentFileOrDirectory,
  41302. const String& fileFilters,
  41303. const bool useNativeDialogBox_)
  41304. : title (chooserBoxTitle),
  41305. filters (fileFilters),
  41306. startingFile (currentFileOrDirectory),
  41307. useNativeDialogBox (useNativeDialogBox_)
  41308. {
  41309. #if JUCE_LINUX
  41310. useNativeDialogBox = false;
  41311. #endif
  41312. if (fileFilters.trim().isEmpty())
  41313. filters = T("*");
  41314. }
  41315. FileChooser::~FileChooser()
  41316. {
  41317. }
  41318. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  41319. {
  41320. return showDialog (false, false, false, false, previewComponent);
  41321. }
  41322. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  41323. {
  41324. return showDialog (false, false, false, true, previewComponent);
  41325. }
  41326. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  41327. {
  41328. return showDialog (false, true, warnAboutOverwritingExistingFiles, false, 0);
  41329. }
  41330. bool FileChooser::browseForDirectory()
  41331. {
  41332. return showDialog (true, false, false, false, 0);
  41333. }
  41334. const File FileChooser::getResult() const
  41335. {
  41336. // if you've used a multiple-file select, you should use the getResults() method
  41337. // to retrieve all the files that were chosen.
  41338. jassert (results.size() <= 1);
  41339. const File* const f = results.getFirst();
  41340. if (f != 0)
  41341. return *f;
  41342. return File::nonexistent;
  41343. }
  41344. const OwnedArray <File>& FileChooser::getResults() const
  41345. {
  41346. return results;
  41347. }
  41348. bool FileChooser::showDialog (const bool isDirectory,
  41349. const bool isSave,
  41350. const bool warnAboutOverwritingExistingFiles,
  41351. const bool selectMultipleFiles,
  41352. FilePreviewComponent* const previewComponent)
  41353. {
  41354. ComponentDeletionWatcher* currentlyFocusedChecker = 0;
  41355. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  41356. if (currentlyFocused != 0)
  41357. currentlyFocusedChecker = new ComponentDeletionWatcher (currentlyFocused);
  41358. results.clear();
  41359. // the preview component needs to be the right size before you pass it in here..
  41360. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  41361. && previewComponent->getHeight() > 10));
  41362. #if JUCE_WIN32
  41363. if (useNativeDialogBox)
  41364. #else
  41365. if (useNativeDialogBox && (previewComponent == 0))
  41366. #endif
  41367. {
  41368. showPlatformDialog (results, title, startingFile, filters,
  41369. isDirectory, isSave,
  41370. warnAboutOverwritingExistingFiles,
  41371. selectMultipleFiles,
  41372. previewComponent);
  41373. }
  41374. else
  41375. {
  41376. jassert (! selectMultipleFiles); // not yet implemented for juce dialogs!
  41377. WildcardFileFilter wildcard (filters, String::empty);
  41378. FileBrowserComponent browserComponent (isDirectory ? FileBrowserComponent::chooseDirectoryMode
  41379. : (isSave ? FileBrowserComponent::saveFileMode
  41380. : FileBrowserComponent::loadFileMode),
  41381. startingFile, &wildcard, previewComponent);
  41382. FileChooserDialogBox box (title, String::empty,
  41383. browserComponent,
  41384. warnAboutOverwritingExistingFiles,
  41385. browserComponent.findColour (AlertWindow::backgroundColourId));
  41386. if (box.show())
  41387. results.add (new File (browserComponent.getCurrentFile()));
  41388. }
  41389. if (currentlyFocused != 0 && ! currentlyFocusedChecker->hasBeenDeleted())
  41390. currentlyFocused->grabKeyboardFocus();
  41391. delete currentlyFocusedChecker;
  41392. return results.size() > 0;
  41393. }
  41394. FilePreviewComponent::FilePreviewComponent()
  41395. {
  41396. }
  41397. FilePreviewComponent::~FilePreviewComponent()
  41398. {
  41399. }
  41400. END_JUCE_NAMESPACE
  41401. /********* End of inlined file: juce_FileChooser.cpp *********/
  41402. /********* Start of inlined file: juce_FileChooserDialogBox.cpp *********/
  41403. BEGIN_JUCE_NAMESPACE
  41404. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  41405. const String& instructions,
  41406. FileBrowserComponent& chooserComponent,
  41407. const bool warnAboutOverwritingExistingFiles_,
  41408. const Colour& backgroundColour)
  41409. : ResizableWindow (name, backgroundColour, true),
  41410. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  41411. {
  41412. content = new ContentComponent();
  41413. content->setName (name);
  41414. content->instructions = instructions;
  41415. content->chooserComponent = &chooserComponent;
  41416. content->addAndMakeVisible (&chooserComponent);
  41417. content->okButton = new TextButton (chooserComponent.getActionVerb());
  41418. content->addAndMakeVisible (content->okButton);
  41419. content->okButton->addButtonListener (this);
  41420. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  41421. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  41422. content->cancelButton = new TextButton (TRANS("Cancel"));
  41423. content->addAndMakeVisible (content->cancelButton);
  41424. content->cancelButton->addButtonListener (this);
  41425. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  41426. setContentComponent (content);
  41427. setResizable (true, true);
  41428. setResizeLimits (300, 300, 1200, 1000);
  41429. content->chooserComponent->addListener (this);
  41430. }
  41431. FileChooserDialogBox::~FileChooserDialogBox()
  41432. {
  41433. content->chooserComponent->removeListener (this);
  41434. }
  41435. bool FileChooserDialogBox::show (int w, int h)
  41436. {
  41437. if (w <= 0)
  41438. {
  41439. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  41440. if (previewComp != 0)
  41441. w = 400 + previewComp->getWidth();
  41442. else
  41443. w = 600;
  41444. }
  41445. if (h <= 0)
  41446. h = 500;
  41447. centreWithSize (w, h);
  41448. const bool ok = (runModalLoop() != 0);
  41449. setVisible (false);
  41450. return ok;
  41451. }
  41452. void FileChooserDialogBox::buttonClicked (Button* button)
  41453. {
  41454. if (button == content->okButton)
  41455. {
  41456. if (warnAboutOverwritingExistingFiles
  41457. && content->chooserComponent->getMode() == FileBrowserComponent::saveFileMode
  41458. && content->chooserComponent->getCurrentFile().exists())
  41459. {
  41460. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  41461. TRANS("File already exists"),
  41462. TRANS("There's already a file called:\n\n")
  41463. + content->chooserComponent->getCurrentFile().getFullPathName()
  41464. + T("\n\nAre you sure you want to overwrite it?"),
  41465. TRANS("overwrite"),
  41466. TRANS("cancel")))
  41467. {
  41468. return;
  41469. }
  41470. }
  41471. exitModalState (1);
  41472. }
  41473. else if (button == content->cancelButton)
  41474. closeButtonPressed();
  41475. }
  41476. void FileChooserDialogBox::closeButtonPressed()
  41477. {
  41478. setVisible (false);
  41479. }
  41480. void FileChooserDialogBox::selectionChanged()
  41481. {
  41482. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  41483. }
  41484. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  41485. {
  41486. }
  41487. void FileChooserDialogBox::fileDoubleClicked (const File&)
  41488. {
  41489. selectionChanged();
  41490. content->okButton->triggerClick();
  41491. }
  41492. FileChooserDialogBox::ContentComponent::ContentComponent()
  41493. {
  41494. setInterceptsMouseClicks (false, true);
  41495. }
  41496. FileChooserDialogBox::ContentComponent::~ContentComponent()
  41497. {
  41498. delete okButton;
  41499. delete cancelButton;
  41500. }
  41501. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  41502. {
  41503. g.setColour (Colours::black);
  41504. text.draw (g);
  41505. }
  41506. void FileChooserDialogBox::ContentComponent::resized()
  41507. {
  41508. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  41509. float left, top, right, bottom;
  41510. text.getBoundingBox (0, text.getNumGlyphs(), left, top, right, bottom, false);
  41511. const int y = roundFloatToInt (bottom) + 10;
  41512. const int buttonHeight = 26;
  41513. const int buttonY = getHeight() - buttonHeight - 8;
  41514. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  41515. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  41516. proportionOfWidth (0.2f), buttonHeight);
  41517. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  41518. proportionOfWidth (0.2f), buttonHeight);
  41519. }
  41520. END_JUCE_NAMESPACE
  41521. /********* End of inlined file: juce_FileChooserDialogBox.cpp *********/
  41522. /********* Start of inlined file: juce_FileFilter.cpp *********/
  41523. BEGIN_JUCE_NAMESPACE
  41524. FileFilter::FileFilter (const String& filterDescription)
  41525. : description (filterDescription)
  41526. {
  41527. }
  41528. FileFilter::~FileFilter()
  41529. {
  41530. }
  41531. const String& FileFilter::getDescription() const throw()
  41532. {
  41533. return description;
  41534. }
  41535. END_JUCE_NAMESPACE
  41536. /********* End of inlined file: juce_FileFilter.cpp *********/
  41537. /********* Start of inlined file: juce_FileListComponent.cpp *********/
  41538. BEGIN_JUCE_NAMESPACE
  41539. Image* juce_createIconForFile (const File& file);
  41540. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  41541. : ListBox (String::empty, 0),
  41542. DirectoryContentsDisplayComponent (listToShow)
  41543. {
  41544. setModel (this);
  41545. fileList.addChangeListener (this);
  41546. }
  41547. FileListComponent::~FileListComponent()
  41548. {
  41549. fileList.removeChangeListener (this);
  41550. deleteAllChildren();
  41551. }
  41552. const File FileListComponent::getSelectedFile() const
  41553. {
  41554. return fileList.getFile (getSelectedRow());
  41555. }
  41556. void FileListComponent::scrollToTop()
  41557. {
  41558. getVerticalScrollBar()->setCurrentRangeStart (0);
  41559. }
  41560. void FileListComponent::changeListenerCallback (void*)
  41561. {
  41562. updateContent();
  41563. if (lastDirectory != fileList.getDirectory())
  41564. {
  41565. lastDirectory = fileList.getDirectory();
  41566. deselectAllRows();
  41567. }
  41568. }
  41569. class FileListItemComponent : public Component,
  41570. public TimeSliceClient,
  41571. public AsyncUpdater
  41572. {
  41573. public:
  41574. FileListItemComponent (FileListComponent& owner_,
  41575. TimeSliceThread& thread_) throw()
  41576. : owner (owner_),
  41577. thread (thread_),
  41578. icon (0)
  41579. {
  41580. }
  41581. ~FileListItemComponent() throw()
  41582. {
  41583. thread.removeTimeSliceClient (this);
  41584. clearIcon();
  41585. }
  41586. void paint (Graphics& g)
  41587. {
  41588. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  41589. file.getFileName(),
  41590. icon,
  41591. fileSize, modTime,
  41592. isDirectory, highlighted,
  41593. index);
  41594. }
  41595. void mouseDown (const MouseEvent& e)
  41596. {
  41597. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  41598. owner.sendMouseClickMessage (file, e);
  41599. }
  41600. void mouseDoubleClick (const MouseEvent&)
  41601. {
  41602. owner.sendDoubleClickMessage (file);
  41603. }
  41604. void update (const File& root,
  41605. const DirectoryContentsList::FileInfo* const fileInfo,
  41606. const int index_,
  41607. const bool highlighted_) throw()
  41608. {
  41609. thread.removeTimeSliceClient (this);
  41610. if (highlighted_ != highlighted
  41611. || index_ != index)
  41612. {
  41613. index = index_;
  41614. highlighted = highlighted_;
  41615. repaint();
  41616. }
  41617. File newFile;
  41618. String newFileSize;
  41619. String newModTime;
  41620. if (fileInfo != 0)
  41621. {
  41622. newFile = root.getChildFile (fileInfo->filename);
  41623. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  41624. newModTime = fileInfo->modificationTime.formatted (T("%d %b '%y %H:%M"));
  41625. }
  41626. if (newFile != file
  41627. || fileSize != newFileSize
  41628. || modTime != newModTime)
  41629. {
  41630. file = newFile;
  41631. fileSize = newFileSize;
  41632. modTime = newModTime;
  41633. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  41634. repaint();
  41635. clearIcon();
  41636. }
  41637. if (file != File::nonexistent
  41638. && icon == 0 && ! isDirectory)
  41639. {
  41640. updateIcon (true);
  41641. if (icon == 0)
  41642. thread.addTimeSliceClient (this);
  41643. }
  41644. }
  41645. bool useTimeSlice()
  41646. {
  41647. updateIcon (false);
  41648. return false;
  41649. }
  41650. void handleAsyncUpdate()
  41651. {
  41652. repaint();
  41653. }
  41654. juce_UseDebuggingNewOperator
  41655. private:
  41656. FileListComponent& owner;
  41657. TimeSliceThread& thread;
  41658. bool highlighted;
  41659. int index;
  41660. File file;
  41661. String fileSize;
  41662. String modTime;
  41663. Image* icon;
  41664. bool isDirectory;
  41665. void clearIcon() throw()
  41666. {
  41667. ImageCache::release (icon);
  41668. icon = 0;
  41669. }
  41670. void updateIcon (const bool onlyUpdateIfCached) throw()
  41671. {
  41672. if (icon == 0)
  41673. {
  41674. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  41675. Image* im = ImageCache::getFromHashCode (hashCode);
  41676. if (im == 0 && ! onlyUpdateIfCached)
  41677. {
  41678. im = juce_createIconForFile (file);
  41679. if (im != 0)
  41680. ImageCache::addImageToCache (im, hashCode);
  41681. }
  41682. if (im != 0)
  41683. {
  41684. icon = im;
  41685. triggerAsyncUpdate();
  41686. }
  41687. }
  41688. }
  41689. };
  41690. int FileListComponent::getNumRows()
  41691. {
  41692. return fileList.getNumFiles();
  41693. }
  41694. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  41695. {
  41696. }
  41697. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  41698. {
  41699. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  41700. if (comp == 0)
  41701. {
  41702. delete existingComponentToUpdate;
  41703. existingComponentToUpdate = comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  41704. }
  41705. DirectoryContentsList::FileInfo fileInfo;
  41706. if (fileList.getFileInfo (row, fileInfo))
  41707. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  41708. else
  41709. comp->update (fileList.getDirectory(), 0, row, isSelected);
  41710. return comp;
  41711. }
  41712. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  41713. {
  41714. sendSelectionChangeMessage();
  41715. }
  41716. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  41717. {
  41718. }
  41719. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  41720. {
  41721. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  41722. }
  41723. END_JUCE_NAMESPACE
  41724. /********* End of inlined file: juce_FileListComponent.cpp *********/
  41725. /********* Start of inlined file: juce_FilenameComponent.cpp *********/
  41726. BEGIN_JUCE_NAMESPACE
  41727. FilenameComponent::FilenameComponent (const String& name,
  41728. const File& currentFile,
  41729. const bool canEditFilename,
  41730. const bool isDirectory,
  41731. const bool isForSaving,
  41732. const String& fileBrowserWildcard,
  41733. const String& enforcedSuffix_,
  41734. const String& textWhenNothingSelected)
  41735. : Component (name),
  41736. maxRecentFiles (30),
  41737. isDir (isDirectory),
  41738. isSaving (isForSaving),
  41739. isFileDragOver (false),
  41740. wildcard (fileBrowserWildcard),
  41741. enforcedSuffix (enforcedSuffix_)
  41742. {
  41743. addAndMakeVisible (filenameBox = new ComboBox (T("fn")));
  41744. filenameBox->setEditableText (canEditFilename);
  41745. filenameBox->addListener (this);
  41746. filenameBox->setTextWhenNothingSelected (textWhenNothingSelected);
  41747. filenameBox->setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  41748. browseButton = 0;
  41749. setBrowseButtonText (T("..."));
  41750. setCurrentFile (currentFile, true);
  41751. }
  41752. FilenameComponent::~FilenameComponent()
  41753. {
  41754. deleteAllChildren();
  41755. }
  41756. void FilenameComponent::paintOverChildren (Graphics& g)
  41757. {
  41758. if (isFileDragOver)
  41759. {
  41760. g.setColour (Colours::red.withAlpha (0.2f));
  41761. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  41762. }
  41763. }
  41764. void FilenameComponent::resized()
  41765. {
  41766. getLookAndFeel().layoutFilenameComponent (*this, filenameBox, browseButton);
  41767. }
  41768. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  41769. {
  41770. browseButtonText = newBrowseButtonText;
  41771. lookAndFeelChanged();
  41772. }
  41773. void FilenameComponent::lookAndFeelChanged()
  41774. {
  41775. deleteAndZero (browseButton);
  41776. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  41777. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  41778. resized();
  41779. browseButton->addButtonListener (this);
  41780. }
  41781. void FilenameComponent::setTooltip (const String& newTooltip)
  41782. {
  41783. SettableTooltipClient::setTooltip (newTooltip);
  41784. filenameBox->setTooltip (newTooltip);
  41785. }
  41786. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  41787. {
  41788. defaultBrowseFile = newDefaultDirectory;
  41789. }
  41790. void FilenameComponent::buttonClicked (Button*)
  41791. {
  41792. FileChooser fc (TRANS("Choose a new file"),
  41793. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  41794. : getCurrentFile(),
  41795. wildcard);
  41796. if (isDir ? fc.browseForDirectory()
  41797. : (isSaving ? fc.browseForFileToSave (false)
  41798. : fc.browseForFileToOpen()))
  41799. {
  41800. setCurrentFile (fc.getResult(), true);
  41801. }
  41802. }
  41803. void FilenameComponent::comboBoxChanged (ComboBox*)
  41804. {
  41805. setCurrentFile (getCurrentFile(), true);
  41806. }
  41807. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  41808. {
  41809. return true;
  41810. }
  41811. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  41812. {
  41813. isFileDragOver = false;
  41814. repaint();
  41815. const File f (filenames[0]);
  41816. if (f.exists() && (f.isDirectory() == isDir))
  41817. setCurrentFile (f, true);
  41818. }
  41819. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  41820. {
  41821. isFileDragOver = true;
  41822. repaint();
  41823. }
  41824. void FilenameComponent::fileDragExit (const StringArray&)
  41825. {
  41826. isFileDragOver = false;
  41827. repaint();
  41828. }
  41829. const File FilenameComponent::getCurrentFile() const
  41830. {
  41831. File f (filenameBox->getText());
  41832. if (enforcedSuffix.isNotEmpty())
  41833. f = f.withFileExtension (enforcedSuffix);
  41834. return f;
  41835. }
  41836. void FilenameComponent::setCurrentFile (File newFile,
  41837. const bool addToRecentlyUsedList,
  41838. const bool sendChangeNotification)
  41839. {
  41840. if (enforcedSuffix.isNotEmpty())
  41841. newFile = newFile.withFileExtension (enforcedSuffix);
  41842. if (newFile.getFullPathName() != lastFilename)
  41843. {
  41844. lastFilename = newFile.getFullPathName();
  41845. if (addToRecentlyUsedList)
  41846. addRecentlyUsedFile (newFile);
  41847. filenameBox->setText (lastFilename, true);
  41848. if (sendChangeNotification)
  41849. triggerAsyncUpdate();
  41850. }
  41851. }
  41852. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  41853. {
  41854. filenameBox->setEditableText (shouldBeEditable);
  41855. }
  41856. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  41857. {
  41858. StringArray names;
  41859. for (int i = 0; i < filenameBox->getNumItems(); ++i)
  41860. names.add (filenameBox->getItemText (i));
  41861. return names;
  41862. }
  41863. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  41864. {
  41865. if (filenames != getRecentlyUsedFilenames())
  41866. {
  41867. filenameBox->clear();
  41868. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  41869. filenameBox->addItem (filenames[i], i + 1);
  41870. }
  41871. }
  41872. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  41873. {
  41874. maxRecentFiles = jmax (1, newMaximum);
  41875. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  41876. }
  41877. void FilenameComponent::addRecentlyUsedFile (const File& file)
  41878. {
  41879. StringArray files (getRecentlyUsedFilenames());
  41880. if (file.getFullPathName().isNotEmpty())
  41881. {
  41882. files.removeString (file.getFullPathName(), true);
  41883. files.insert (0, file.getFullPathName());
  41884. setRecentlyUsedFilenames (files);
  41885. }
  41886. }
  41887. void FilenameComponent::addListener (FilenameComponentListener* const listener) throw()
  41888. {
  41889. jassert (listener != 0);
  41890. if (listener != 0)
  41891. listeners.add (listener);
  41892. }
  41893. void FilenameComponent::removeListener (FilenameComponentListener* const listener) throw()
  41894. {
  41895. listeners.removeValue (listener);
  41896. }
  41897. void FilenameComponent::handleAsyncUpdate()
  41898. {
  41899. for (int i = listeners.size(); --i >= 0;)
  41900. {
  41901. ((FilenameComponentListener*) listeners.getUnchecked (i))->filenameComponentChanged (this);
  41902. i = jmin (i, listeners.size());
  41903. }
  41904. }
  41905. END_JUCE_NAMESPACE
  41906. /********* End of inlined file: juce_FilenameComponent.cpp *********/
  41907. /********* Start of inlined file: juce_FileSearchPathListComponent.cpp *********/
  41908. BEGIN_JUCE_NAMESPACE
  41909. FileSearchPathListComponent::FileSearchPathListComponent()
  41910. {
  41911. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  41912. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  41913. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  41914. listBox->setOutlineThickness (1);
  41915. addAndMakeVisible (addButton = new TextButton ("+"));
  41916. addButton->addButtonListener (this);
  41917. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  41918. addAndMakeVisible (removeButton = new TextButton ("-"));
  41919. removeButton->addButtonListener (this);
  41920. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  41921. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  41922. changeButton->addButtonListener (this);
  41923. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  41924. upButton->addButtonListener (this);
  41925. {
  41926. Path arrowPath;
  41927. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  41928. DrawablePath arrowImage;
  41929. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  41930. arrowImage.setPath (arrowPath);
  41931. ((DrawableButton*) upButton)->setImages (&arrowImage);
  41932. }
  41933. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  41934. downButton->addButtonListener (this);
  41935. {
  41936. Path arrowPath;
  41937. arrowPath.addArrow (50.0f, 0.0f, 50.0f, 100.0f, 40.0f, 100.0f, 50.0f);
  41938. DrawablePath arrowImage;
  41939. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  41940. arrowImage.setPath (arrowPath);
  41941. ((DrawableButton*) downButton)->setImages (&arrowImage);
  41942. }
  41943. updateButtons();
  41944. }
  41945. FileSearchPathListComponent::~FileSearchPathListComponent()
  41946. {
  41947. deleteAllChildren();
  41948. }
  41949. void FileSearchPathListComponent::updateButtons() throw()
  41950. {
  41951. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  41952. removeButton->setEnabled (anythingSelected);
  41953. changeButton->setEnabled (anythingSelected);
  41954. upButton->setEnabled (anythingSelected);
  41955. downButton->setEnabled (anythingSelected);
  41956. }
  41957. void FileSearchPathListComponent::changed() throw()
  41958. {
  41959. listBox->updateContent();
  41960. listBox->repaint();
  41961. updateButtons();
  41962. }
  41963. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  41964. {
  41965. if (newPath.toString() != path.toString())
  41966. {
  41967. path = newPath;
  41968. changed();
  41969. }
  41970. }
  41971. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  41972. {
  41973. defaultBrowseTarget = newDefaultDirectory;
  41974. }
  41975. int FileSearchPathListComponent::getNumRows()
  41976. {
  41977. return path.getNumPaths();
  41978. }
  41979. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  41980. {
  41981. if (rowIsSelected)
  41982. g.fillAll (findColour (TextEditor::highlightColourId));
  41983. g.setColour (findColour (ListBox::textColourId));
  41984. Font f (height * 0.7f);
  41985. f.setHorizontalScale (0.9f);
  41986. g.setFont (f);
  41987. g.drawText (path [rowNumber].getFullPathName(),
  41988. 4, 0, width - 6, height,
  41989. Justification::centredLeft, true);
  41990. }
  41991. void FileSearchPathListComponent::deleteKeyPressed (int row)
  41992. {
  41993. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  41994. {
  41995. path.remove (row);
  41996. changed();
  41997. }
  41998. }
  41999. void FileSearchPathListComponent::returnKeyPressed (int row)
  42000. {
  42001. FileChooser chooser (TRANS("Change folder..."), path [row], T("*"));
  42002. if (chooser.browseForDirectory())
  42003. {
  42004. path.remove (row);
  42005. path.add (chooser.getResult(), row);
  42006. changed();
  42007. }
  42008. }
  42009. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  42010. {
  42011. returnKeyPressed (row);
  42012. }
  42013. void FileSearchPathListComponent::selectedRowsChanged (int)
  42014. {
  42015. updateButtons();
  42016. }
  42017. void FileSearchPathListComponent::paint (Graphics& g)
  42018. {
  42019. g.fillAll (findColour (backgroundColourId));
  42020. }
  42021. void FileSearchPathListComponent::resized()
  42022. {
  42023. const int buttonH = 22;
  42024. const int buttonY = getHeight() - buttonH - 4;
  42025. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  42026. addButton->setBounds (2, buttonY, buttonH, buttonH);
  42027. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  42028. ((TextButton*) changeButton)->changeWidthToFitText (buttonH);
  42029. downButton->setSize (buttonH * 2, buttonH);
  42030. upButton->setSize (buttonH * 2, buttonH);
  42031. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  42032. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  42033. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  42034. }
  42035. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  42036. {
  42037. return true;
  42038. }
  42039. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  42040. {
  42041. for (int i = filenames.size(); --i >= 0;)
  42042. {
  42043. const File f (filenames[i]);
  42044. if (f.isDirectory())
  42045. {
  42046. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  42047. path.add (f, row);
  42048. changed();
  42049. }
  42050. }
  42051. }
  42052. void FileSearchPathListComponent::buttonClicked (Button* button)
  42053. {
  42054. const int currentRow = listBox->getSelectedRow();
  42055. if (button == removeButton)
  42056. {
  42057. deleteKeyPressed (currentRow);
  42058. }
  42059. else if (button == addButton)
  42060. {
  42061. File start (defaultBrowseTarget);
  42062. if (start == File::nonexistent)
  42063. start = path [0];
  42064. if (start == File::nonexistent)
  42065. start = File::getCurrentWorkingDirectory();
  42066. FileChooser chooser (TRANS("Add a folder..."), start, T("*"));
  42067. if (chooser.browseForDirectory())
  42068. {
  42069. path.add (chooser.getResult(), currentRow);
  42070. }
  42071. }
  42072. else if (button == changeButton)
  42073. {
  42074. returnKeyPressed (currentRow);
  42075. }
  42076. else if (button == upButton)
  42077. {
  42078. if (currentRow > 0 && currentRow < path.getNumPaths())
  42079. {
  42080. const File f (path[currentRow]);
  42081. path.remove (currentRow);
  42082. path.add (f, currentRow - 1);
  42083. listBox->selectRow (currentRow - 1);
  42084. }
  42085. }
  42086. else if (button == downButton)
  42087. {
  42088. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  42089. {
  42090. const File f (path[currentRow]);
  42091. path.remove (currentRow);
  42092. path.add (f, currentRow + 1);
  42093. listBox->selectRow (currentRow + 1);
  42094. }
  42095. }
  42096. changed();
  42097. }
  42098. END_JUCE_NAMESPACE
  42099. /********* End of inlined file: juce_FileSearchPathListComponent.cpp *********/
  42100. /********* Start of inlined file: juce_FileTreeComponent.cpp *********/
  42101. BEGIN_JUCE_NAMESPACE
  42102. Image* juce_createIconForFile (const File& file);
  42103. class FileListTreeItem : public TreeViewItem,
  42104. public TimeSliceClient,
  42105. public AsyncUpdater,
  42106. public ChangeListener
  42107. {
  42108. public:
  42109. FileListTreeItem (FileTreeComponent& owner_,
  42110. DirectoryContentsList* const parentContentsList_,
  42111. const int indexInContentsList_,
  42112. const File& file_,
  42113. TimeSliceThread& thread_) throw()
  42114. : file (file_),
  42115. owner (owner_),
  42116. parentContentsList (parentContentsList_),
  42117. indexInContentsList (indexInContentsList_),
  42118. subContentsList (0),
  42119. canDeleteSubContentsList (false),
  42120. thread (thread_),
  42121. icon (0)
  42122. {
  42123. DirectoryContentsList::FileInfo fileInfo;
  42124. if (parentContentsList_ != 0
  42125. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  42126. {
  42127. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  42128. modTime = fileInfo.modificationTime.formatted (T("%d %b '%y %H:%M"));
  42129. isDirectory = fileInfo.isDirectory;
  42130. }
  42131. else
  42132. {
  42133. isDirectory = true;
  42134. }
  42135. }
  42136. ~FileListTreeItem() throw()
  42137. {
  42138. thread.removeTimeSliceClient (this);
  42139. clearSubItems();
  42140. ImageCache::release (icon);
  42141. if (canDeleteSubContentsList)
  42142. delete subContentsList;
  42143. }
  42144. bool mightContainSubItems() { return isDirectory; }
  42145. const String getUniqueName() const { return file.getFullPathName(); }
  42146. int getItemHeight() const { return 22; }
  42147. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  42148. void itemOpennessChanged (bool isNowOpen)
  42149. {
  42150. if (isNowOpen)
  42151. {
  42152. clearSubItems();
  42153. isDirectory = file.isDirectory();
  42154. if (isDirectory)
  42155. {
  42156. if (subContentsList == 0)
  42157. {
  42158. jassert (parentContentsList != 0);
  42159. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  42160. l->setDirectory (file, true, true);
  42161. setSubContentsList (l);
  42162. canDeleteSubContentsList = true;
  42163. }
  42164. changeListenerCallback (0);
  42165. }
  42166. }
  42167. }
  42168. void setSubContentsList (DirectoryContentsList* newList) throw()
  42169. {
  42170. jassert (subContentsList == 0);
  42171. subContentsList = newList;
  42172. newList->addChangeListener (this);
  42173. }
  42174. void changeListenerCallback (void*)
  42175. {
  42176. clearSubItems();
  42177. if (isOpen() && subContentsList != 0)
  42178. {
  42179. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  42180. {
  42181. FileListTreeItem* const item
  42182. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  42183. addSubItem (item);
  42184. }
  42185. }
  42186. }
  42187. void paintItem (Graphics& g, int width, int height)
  42188. {
  42189. if (file != File::nonexistent && ! isDirectory)
  42190. {
  42191. updateIcon (true);
  42192. if (icon == 0)
  42193. thread.addTimeSliceClient (this);
  42194. }
  42195. owner.getLookAndFeel()
  42196. .drawFileBrowserRow (g, width, height,
  42197. file.getFileName(),
  42198. icon,
  42199. fileSize, modTime,
  42200. isDirectory, isSelected(),
  42201. indexInContentsList);
  42202. }
  42203. void itemClicked (const MouseEvent& e)
  42204. {
  42205. owner.sendMouseClickMessage (file, e);
  42206. }
  42207. void itemDoubleClicked (const MouseEvent& e)
  42208. {
  42209. TreeViewItem::itemDoubleClicked (e);
  42210. owner.sendDoubleClickMessage (file);
  42211. }
  42212. void itemSelectionChanged (bool)
  42213. {
  42214. owner.sendSelectionChangeMessage();
  42215. }
  42216. bool useTimeSlice()
  42217. {
  42218. updateIcon (false);
  42219. thread.removeTimeSliceClient (this);
  42220. return false;
  42221. }
  42222. void handleAsyncUpdate()
  42223. {
  42224. owner.repaint();
  42225. }
  42226. const File file;
  42227. juce_UseDebuggingNewOperator
  42228. private:
  42229. FileTreeComponent& owner;
  42230. DirectoryContentsList* parentContentsList;
  42231. int indexInContentsList;
  42232. DirectoryContentsList* subContentsList;
  42233. bool isDirectory, canDeleteSubContentsList;
  42234. TimeSliceThread& thread;
  42235. Image* icon;
  42236. String fileSize;
  42237. String modTime;
  42238. void updateIcon (const bool onlyUpdateIfCached) throw()
  42239. {
  42240. if (icon == 0)
  42241. {
  42242. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  42243. Image* im = ImageCache::getFromHashCode (hashCode);
  42244. if (im == 0 && ! onlyUpdateIfCached)
  42245. {
  42246. im = juce_createIconForFile (file);
  42247. if (im != 0)
  42248. ImageCache::addImageToCache (im, hashCode);
  42249. }
  42250. if (im != 0)
  42251. {
  42252. icon = im;
  42253. triggerAsyncUpdate();
  42254. }
  42255. }
  42256. }
  42257. };
  42258. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  42259. : DirectoryContentsDisplayComponent (listToShow)
  42260. {
  42261. FileListTreeItem* const root
  42262. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  42263. listToShow.getTimeSliceThread());
  42264. root->setSubContentsList (&listToShow);
  42265. setRootItemVisible (false);
  42266. setRootItem (root);
  42267. }
  42268. FileTreeComponent::~FileTreeComponent()
  42269. {
  42270. TreeViewItem* const root = getRootItem();
  42271. setRootItem (0);
  42272. delete root;
  42273. }
  42274. const File FileTreeComponent::getSelectedFile() const
  42275. {
  42276. return getSelectedFile (0);
  42277. }
  42278. const File FileTreeComponent::getSelectedFile (const int index) const throw()
  42279. {
  42280. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  42281. if (item != 0)
  42282. return item->file;
  42283. return File::nonexistent;
  42284. }
  42285. void FileTreeComponent::scrollToTop()
  42286. {
  42287. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  42288. }
  42289. void FileTreeComponent::setDragAndDropDescription (const String& description) throw()
  42290. {
  42291. dragAndDropDescription = description;
  42292. }
  42293. END_JUCE_NAMESPACE
  42294. /********* End of inlined file: juce_FileTreeComponent.cpp *********/
  42295. /********* Start of inlined file: juce_ImagePreviewComponent.cpp *********/
  42296. BEGIN_JUCE_NAMESPACE
  42297. ImagePreviewComponent::ImagePreviewComponent()
  42298. : currentThumbnail (0)
  42299. {
  42300. }
  42301. ImagePreviewComponent::~ImagePreviewComponent()
  42302. {
  42303. delete currentThumbnail;
  42304. }
  42305. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  42306. {
  42307. const int availableW = proportionOfWidth (0.97f);
  42308. const int availableH = getHeight() - 13 * 4;
  42309. const double scale = jmin (1.0,
  42310. availableW / (double) w,
  42311. availableH / (double) h);
  42312. w = roundDoubleToInt (scale * w);
  42313. h = roundDoubleToInt (scale * h);
  42314. }
  42315. void ImagePreviewComponent::selectedFileChanged (const File& file)
  42316. {
  42317. if (fileToLoad != file)
  42318. {
  42319. fileToLoad = file;
  42320. startTimer (100);
  42321. }
  42322. }
  42323. void ImagePreviewComponent::timerCallback()
  42324. {
  42325. stopTimer();
  42326. deleteAndZero (currentThumbnail);
  42327. currentDetails = String::empty;
  42328. repaint();
  42329. FileInputStream* const in = fileToLoad.createInputStream();
  42330. if (in != 0)
  42331. {
  42332. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  42333. if (format != 0)
  42334. {
  42335. currentThumbnail = format->decodeImage (*in);
  42336. if (currentThumbnail != 0)
  42337. {
  42338. int w = currentThumbnail->getWidth();
  42339. int h = currentThumbnail->getHeight();
  42340. currentDetails
  42341. << fileToLoad.getFileName() << "\n"
  42342. << format->getFormatName() << "\n"
  42343. << w << " x " << h << " pixels\n"
  42344. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  42345. getThumbSize (w, h);
  42346. Image* const reduced = currentThumbnail->createCopy (w, h);
  42347. delete currentThumbnail;
  42348. currentThumbnail = reduced;
  42349. }
  42350. }
  42351. delete in;
  42352. }
  42353. }
  42354. void ImagePreviewComponent::paint (Graphics& g)
  42355. {
  42356. if (currentThumbnail != 0)
  42357. {
  42358. g.setFont (13.0f);
  42359. int w = currentThumbnail->getWidth();
  42360. int h = currentThumbnail->getHeight();
  42361. getThumbSize (w, h);
  42362. const int numLines = 4;
  42363. const int totalH = 13 * numLines + h + 4;
  42364. const int y = (getHeight() - totalH) / 2;
  42365. g.drawImageWithin (currentThumbnail,
  42366. (getWidth() - w) / 2, y, w, h,
  42367. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  42368. false);
  42369. g.drawFittedText (currentDetails,
  42370. 0, y + h + 4, getWidth(), 100,
  42371. Justification::centredTop, numLines);
  42372. }
  42373. }
  42374. END_JUCE_NAMESPACE
  42375. /********* End of inlined file: juce_ImagePreviewComponent.cpp *********/
  42376. /********* Start of inlined file: juce_WildcardFileFilter.cpp *********/
  42377. BEGIN_JUCE_NAMESPACE
  42378. WildcardFileFilter::WildcardFileFilter (const String& wildcardPatterns,
  42379. const String& description)
  42380. : FileFilter (description.isEmpty() ? wildcardPatterns
  42381. : (description + T(" (") + wildcardPatterns + T(")")))
  42382. {
  42383. wildcards.addTokens (wildcardPatterns.toLowerCase(), T(";,"), T("\"'"));
  42384. wildcards.trim();
  42385. wildcards.removeEmptyStrings();
  42386. // special case for *.*, because people use it to mean "any file", but it
  42387. // would actually ignore files with no extension.
  42388. for (int i = wildcards.size(); --i >= 0;)
  42389. if (wildcards[i] == T("*.*"))
  42390. wildcards.set (i, T("*"));
  42391. }
  42392. WildcardFileFilter::~WildcardFileFilter()
  42393. {
  42394. }
  42395. bool WildcardFileFilter::isFileSuitable (const File& file) const
  42396. {
  42397. const String filename (file.getFileName());
  42398. for (int i = wildcards.size(); --i >= 0;)
  42399. if (filename.matchesWildcard (wildcards[i], true))
  42400. return true;
  42401. return false;
  42402. }
  42403. bool WildcardFileFilter::isDirectorySuitable (const File&) const
  42404. {
  42405. return true;
  42406. }
  42407. END_JUCE_NAMESPACE
  42408. /********* End of inlined file: juce_WildcardFileFilter.cpp *********/
  42409. /********* Start of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  42410. BEGIN_JUCE_NAMESPACE
  42411. KeyboardFocusTraverser::KeyboardFocusTraverser()
  42412. {
  42413. }
  42414. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  42415. {
  42416. }
  42417. // This will sort a set of components, so that they are ordered in terms of
  42418. // left-to-right and then top-to-bottom.
  42419. class ScreenPositionComparator
  42420. {
  42421. public:
  42422. ScreenPositionComparator() {}
  42423. static int compareElements (const Component* const first, const Component* const second) throw()
  42424. {
  42425. int explicitOrder1 = first->getExplicitFocusOrder();
  42426. if (explicitOrder1 <= 0)
  42427. explicitOrder1 = INT_MAX / 2;
  42428. int explicitOrder2 = second->getExplicitFocusOrder();
  42429. if (explicitOrder2 <= 0)
  42430. explicitOrder2 = INT_MAX / 2;
  42431. if (explicitOrder1 != explicitOrder2)
  42432. return explicitOrder1 - explicitOrder2;
  42433. const int diff = first->getY() - second->getY();
  42434. return (diff == 0) ? first->getX() - second->getX()
  42435. : diff;
  42436. }
  42437. };
  42438. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  42439. {
  42440. if (parent->getNumChildComponents() > 0)
  42441. {
  42442. Array <Component*> localComps;
  42443. ScreenPositionComparator comparator;
  42444. int i;
  42445. for (i = parent->getNumChildComponents(); --i >= 0;)
  42446. {
  42447. Component* const c = parent->getChildComponent (i);
  42448. if (c->isVisible() && c->isEnabled())
  42449. localComps.addSorted (comparator, c);
  42450. }
  42451. for (i = 0; i < localComps.size(); ++i)
  42452. {
  42453. Component* const c = localComps.getUnchecked (i);
  42454. if (c->getWantsKeyboardFocus())
  42455. comps.add (c);
  42456. if (! c->isFocusContainer())
  42457. findAllFocusableComponents (c, comps);
  42458. }
  42459. }
  42460. }
  42461. static Component* getIncrementedComponent (Component* const current, const int delta) throw()
  42462. {
  42463. Component* focusContainer = current->getParentComponent();
  42464. if (focusContainer != 0)
  42465. {
  42466. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  42467. focusContainer = focusContainer->getParentComponent();
  42468. if (focusContainer != 0)
  42469. {
  42470. Array <Component*> comps;
  42471. findAllFocusableComponents (focusContainer, comps);
  42472. if (comps.size() > 0)
  42473. {
  42474. const int index = comps.indexOf (current);
  42475. return comps [(index + comps.size() + delta) % comps.size()];
  42476. }
  42477. }
  42478. }
  42479. return 0;
  42480. }
  42481. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  42482. {
  42483. return getIncrementedComponent (current, 1);
  42484. }
  42485. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  42486. {
  42487. return getIncrementedComponent (current, -1);
  42488. }
  42489. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  42490. {
  42491. Array <Component*> comps;
  42492. if (parentComponent != 0)
  42493. findAllFocusableComponents (parentComponent, comps);
  42494. return comps.getFirst();
  42495. }
  42496. END_JUCE_NAMESPACE
  42497. /********* End of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  42498. /********* Start of inlined file: juce_KeyListener.cpp *********/
  42499. BEGIN_JUCE_NAMESPACE
  42500. bool KeyListener::keyStateChanged (Component*)
  42501. {
  42502. return false;
  42503. }
  42504. END_JUCE_NAMESPACE
  42505. /********* End of inlined file: juce_KeyListener.cpp *********/
  42506. /********* Start of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  42507. BEGIN_JUCE_NAMESPACE
  42508. // N.B. these two includes are put here deliberately to avoid problems with
  42509. // old GCCs failing on long include paths
  42510. const int maxKeys = 3;
  42511. class KeyMappingChangeButton : public Button
  42512. {
  42513. public:
  42514. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  42515. const CommandID commandID_,
  42516. const String& keyName,
  42517. const int keyNum_)
  42518. : Button (keyName),
  42519. owner (owner_),
  42520. commandID (commandID_),
  42521. keyNum (keyNum_)
  42522. {
  42523. setWantsKeyboardFocus (false);
  42524. setTriggeredOnMouseDown (keyNum >= 0);
  42525. if (keyNum_ < 0)
  42526. setTooltip (TRANS("adds a new key-mapping"));
  42527. else
  42528. setTooltip (TRANS("click to change this key-mapping"));
  42529. }
  42530. ~KeyMappingChangeButton()
  42531. {
  42532. }
  42533. void paintButton (Graphics& g, bool isOver, bool isDown)
  42534. {
  42535. if (keyNum >= 0)
  42536. {
  42537. if (isEnabled())
  42538. {
  42539. const float alpha = isDown ? 0.3f : (isOver ? 0.15f : 0.08f);
  42540. g.fillAll (owner->textColour.withAlpha (alpha));
  42541. g.setOpacity (0.3f);
  42542. g.drawBevel (0, 0, getWidth(), getHeight(), 2);
  42543. }
  42544. g.setColour (owner->textColour);
  42545. g.setFont (getHeight() * 0.6f);
  42546. g.drawFittedText (getName(),
  42547. 3, 0, getWidth() - 6, getHeight(),
  42548. Justification::centred, 1);
  42549. }
  42550. else
  42551. {
  42552. const float thickness = 7.0f;
  42553. const float indent = 22.0f;
  42554. Path p;
  42555. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  42556. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  42557. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  42558. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  42559. p.setUsingNonZeroWinding (false);
  42560. g.setColour (owner->textColour.withAlpha (isDown ? 0.7f : (isOver ? 0.5f : 0.3f)));
  42561. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, true));
  42562. }
  42563. if (hasKeyboardFocus (false))
  42564. {
  42565. g.setColour (owner->textColour.withAlpha (0.4f));
  42566. g.drawRect (0, 0, getWidth(), getHeight());
  42567. }
  42568. }
  42569. void clicked()
  42570. {
  42571. if (keyNum >= 0)
  42572. {
  42573. // existing key clicked..
  42574. PopupMenu m;
  42575. m.addItem (1, TRANS("change this key-mapping"));
  42576. m.addSeparator();
  42577. m.addItem (2, TRANS("remove this key-mapping"));
  42578. const int res = m.show();
  42579. if (res == 1)
  42580. {
  42581. owner->assignNewKey (commandID, keyNum);
  42582. }
  42583. else if (res == 2)
  42584. {
  42585. owner->getMappings()->removeKeyPress (commandID, keyNum);
  42586. }
  42587. }
  42588. else
  42589. {
  42590. // + button pressed..
  42591. owner->assignNewKey (commandID, -1);
  42592. }
  42593. }
  42594. void fitToContent (const int h) throw()
  42595. {
  42596. if (keyNum < 0)
  42597. {
  42598. setSize (h, h);
  42599. }
  42600. else
  42601. {
  42602. Font f (h * 0.6f);
  42603. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  42604. }
  42605. }
  42606. juce_UseDebuggingNewOperator
  42607. private:
  42608. KeyMappingEditorComponent* const owner;
  42609. const CommandID commandID;
  42610. const int keyNum;
  42611. KeyMappingChangeButton (const KeyMappingChangeButton&);
  42612. const KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  42613. };
  42614. class KeyMappingItemComponent : public Component
  42615. {
  42616. public:
  42617. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  42618. const CommandID commandID_)
  42619. : owner (owner_),
  42620. commandID (commandID_)
  42621. {
  42622. setInterceptsMouseClicks (false, true);
  42623. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  42624. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  42625. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  42626. {
  42627. KeyMappingChangeButton* const kb
  42628. = new KeyMappingChangeButton (owner_, commandID,
  42629. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  42630. kb->setEnabled (! isReadOnly);
  42631. addAndMakeVisible (kb);
  42632. }
  42633. KeyMappingChangeButton* const kb
  42634. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  42635. addChildComponent (kb);
  42636. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  42637. }
  42638. ~KeyMappingItemComponent()
  42639. {
  42640. deleteAllChildren();
  42641. }
  42642. void paint (Graphics& g)
  42643. {
  42644. g.setFont (getHeight() * 0.7f);
  42645. g.setColour (owner->textColour);
  42646. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  42647. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  42648. Justification::centredLeft, true);
  42649. }
  42650. void resized()
  42651. {
  42652. int x = getWidth() - 4;
  42653. for (int i = getNumChildComponents(); --i >= 0;)
  42654. {
  42655. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  42656. kb->fitToContent (getHeight() - 2);
  42657. kb->setTopRightPosition (x, 1);
  42658. x -= kb->getWidth() + 5;
  42659. }
  42660. }
  42661. juce_UseDebuggingNewOperator
  42662. private:
  42663. KeyMappingEditorComponent* const owner;
  42664. const CommandID commandID;
  42665. KeyMappingItemComponent (const KeyMappingItemComponent&);
  42666. const KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  42667. };
  42668. class KeyMappingTreeViewItem : public TreeViewItem
  42669. {
  42670. public:
  42671. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  42672. const CommandID commandID_)
  42673. : owner (owner_),
  42674. commandID (commandID_)
  42675. {
  42676. }
  42677. ~KeyMappingTreeViewItem()
  42678. {
  42679. }
  42680. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  42681. bool mightContainSubItems() { return false; }
  42682. int getItemHeight() const { return 20; }
  42683. Component* createItemComponent()
  42684. {
  42685. return new KeyMappingItemComponent (owner, commandID);
  42686. }
  42687. juce_UseDebuggingNewOperator
  42688. private:
  42689. KeyMappingEditorComponent* const owner;
  42690. const CommandID commandID;
  42691. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  42692. const KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  42693. };
  42694. class KeyCategoryTreeViewItem : public TreeViewItem
  42695. {
  42696. public:
  42697. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  42698. const String& name)
  42699. : owner (owner_),
  42700. categoryName (name)
  42701. {
  42702. }
  42703. ~KeyCategoryTreeViewItem()
  42704. {
  42705. }
  42706. const String getUniqueName() const { return categoryName + "_cat"; }
  42707. bool mightContainSubItems() { return true; }
  42708. int getItemHeight() const { return 28; }
  42709. void paintItem (Graphics& g, int width, int height)
  42710. {
  42711. g.setFont (height * 0.6f, Font::bold);
  42712. g.setColour (owner->textColour);
  42713. g.drawText (categoryName,
  42714. 2, 0, width - 2, height,
  42715. Justification::centredLeft, true);
  42716. }
  42717. void itemOpennessChanged (bool isNowOpen)
  42718. {
  42719. if (isNowOpen)
  42720. {
  42721. if (getNumSubItems() == 0)
  42722. {
  42723. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  42724. for (int i = 0; i < commands.size(); ++i)
  42725. {
  42726. if (owner->shouldCommandBeIncluded (commands[i]))
  42727. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  42728. }
  42729. }
  42730. }
  42731. else
  42732. {
  42733. clearSubItems();
  42734. }
  42735. }
  42736. juce_UseDebuggingNewOperator
  42737. private:
  42738. KeyMappingEditorComponent* owner;
  42739. String categoryName;
  42740. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  42741. const KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  42742. };
  42743. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  42744. const bool showResetToDefaultButton)
  42745. : mappings (mappingManager),
  42746. textColour (Colours::black)
  42747. {
  42748. jassert (mappingManager != 0); // can't be null!
  42749. mappingManager->addChangeListener (this);
  42750. setLinesDrawnForSubItems (false);
  42751. resetButton = 0;
  42752. if (showResetToDefaultButton)
  42753. {
  42754. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  42755. resetButton->addButtonListener (this);
  42756. }
  42757. addAndMakeVisible (tree = new TreeView());
  42758. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  42759. tree->setRootItemVisible (false);
  42760. tree->setDefaultOpenness (true);
  42761. tree->setRootItem (this);
  42762. }
  42763. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  42764. {
  42765. mappings->removeChangeListener (this);
  42766. deleteAllChildren();
  42767. }
  42768. bool KeyMappingEditorComponent::mightContainSubItems()
  42769. {
  42770. return true;
  42771. }
  42772. const String KeyMappingEditorComponent::getUniqueName() const
  42773. {
  42774. return T("keys");
  42775. }
  42776. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  42777. const Colour& textColour_)
  42778. {
  42779. backgroundColour = mainBackground;
  42780. textColour = textColour_;
  42781. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  42782. }
  42783. void KeyMappingEditorComponent::parentHierarchyChanged()
  42784. {
  42785. changeListenerCallback (0);
  42786. }
  42787. void KeyMappingEditorComponent::resized()
  42788. {
  42789. int h = getHeight();
  42790. if (resetButton != 0)
  42791. {
  42792. const int buttonHeight = 20;
  42793. h -= buttonHeight + 8;
  42794. int x = getWidth() - 8;
  42795. const int y = h + 6;
  42796. resetButton->changeWidthToFitText (buttonHeight);
  42797. resetButton->setTopRightPosition (x, y);
  42798. }
  42799. tree->setBounds (0, 0, getWidth(), h);
  42800. }
  42801. void KeyMappingEditorComponent::buttonClicked (Button* button)
  42802. {
  42803. if (button == resetButton)
  42804. {
  42805. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  42806. TRANS("Reset to defaults"),
  42807. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  42808. TRANS("Reset")))
  42809. {
  42810. mappings->resetToDefaultMappings();
  42811. }
  42812. }
  42813. }
  42814. void KeyMappingEditorComponent::changeListenerCallback (void*)
  42815. {
  42816. XmlElement* openness = tree->getOpennessState (true);
  42817. clearSubItems();
  42818. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  42819. for (int i = 0; i < categories.size(); ++i)
  42820. {
  42821. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  42822. int count = 0;
  42823. for (int j = 0; j < commands.size(); ++j)
  42824. if (shouldCommandBeIncluded (commands[j]))
  42825. ++count;
  42826. if (count > 0)
  42827. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  42828. }
  42829. if (openness != 0)
  42830. {
  42831. tree->restoreOpennessState (*openness);
  42832. delete openness;
  42833. }
  42834. }
  42835. class KeyEntryWindow : public AlertWindow
  42836. {
  42837. public:
  42838. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  42839. : AlertWindow (TRANS("New key-mapping"),
  42840. TRANS("Please press a key combination now..."),
  42841. AlertWindow::NoIcon),
  42842. owner (owner_)
  42843. {
  42844. addButton (TRANS("ok"), 1);
  42845. addButton (TRANS("cancel"), 0);
  42846. // (avoid return + escape keys getting processed by the buttons..)
  42847. for (int i = getNumChildComponents(); --i >= 0;)
  42848. getChildComponent (i)->setWantsKeyboardFocus (false);
  42849. setWantsKeyboardFocus (true);
  42850. grabKeyboardFocus();
  42851. }
  42852. ~KeyEntryWindow()
  42853. {
  42854. }
  42855. bool keyPressed (const KeyPress& key)
  42856. {
  42857. lastPress = key;
  42858. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  42859. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  42860. if (previousCommand != 0)
  42861. {
  42862. message << "\n\n"
  42863. << TRANS("(Currently assigned to \"")
  42864. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  42865. << "\")";
  42866. }
  42867. setMessage (message);
  42868. return true;
  42869. }
  42870. bool keyStateChanged()
  42871. {
  42872. return true;
  42873. }
  42874. KeyPress lastPress;
  42875. juce_UseDebuggingNewOperator
  42876. private:
  42877. KeyMappingEditorComponent* owner;
  42878. KeyEntryWindow (const KeyEntryWindow&);
  42879. const KeyEntryWindow& operator= (const KeyEntryWindow&);
  42880. };
  42881. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  42882. {
  42883. KeyEntryWindow entryWindow (this);
  42884. if (entryWindow.runModalLoop() != 0)
  42885. {
  42886. entryWindow.setVisible (false);
  42887. if (entryWindow.lastPress.isValid())
  42888. {
  42889. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  42890. if (previousCommand != 0)
  42891. {
  42892. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  42893. TRANS("Change key-mapping"),
  42894. TRANS("This key is already assigned to the command \"")
  42895. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  42896. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  42897. TRANS("re-assign"),
  42898. TRANS("cancel")))
  42899. {
  42900. return;
  42901. }
  42902. }
  42903. mappings->removeKeyPress (entryWindow.lastPress);
  42904. if (index >= 0)
  42905. mappings->removeKeyPress (commandID, index);
  42906. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  42907. }
  42908. }
  42909. }
  42910. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  42911. {
  42912. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  42913. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  42914. }
  42915. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  42916. {
  42917. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  42918. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  42919. }
  42920. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  42921. {
  42922. return key.getTextDescription();
  42923. }
  42924. END_JUCE_NAMESPACE
  42925. /********* End of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  42926. /********* Start of inlined file: juce_KeyPress.cpp *********/
  42927. BEGIN_JUCE_NAMESPACE
  42928. KeyPress::KeyPress() throw()
  42929. : keyCode (0),
  42930. mods (0),
  42931. textCharacter (0)
  42932. {
  42933. }
  42934. KeyPress::KeyPress (const int keyCode_,
  42935. const ModifierKeys& mods_,
  42936. const juce_wchar textCharacter_) throw()
  42937. : keyCode (keyCode_),
  42938. mods (mods_),
  42939. textCharacter (textCharacter_)
  42940. {
  42941. }
  42942. KeyPress::KeyPress (const int keyCode_) throw()
  42943. : keyCode (keyCode_),
  42944. textCharacter (0)
  42945. {
  42946. }
  42947. KeyPress::KeyPress (const KeyPress& other) throw()
  42948. : keyCode (other.keyCode),
  42949. mods (other.mods),
  42950. textCharacter (other.textCharacter)
  42951. {
  42952. }
  42953. const KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  42954. {
  42955. keyCode = other.keyCode;
  42956. mods = other.mods;
  42957. textCharacter = other.textCharacter;
  42958. return *this;
  42959. }
  42960. bool KeyPress::operator== (const KeyPress& other) const throw()
  42961. {
  42962. return mods.getRawFlags() == other.mods.getRawFlags()
  42963. && (textCharacter == other.textCharacter
  42964. || textCharacter == 0
  42965. || other.textCharacter == 0)
  42966. && (keyCode == other.keyCode
  42967. || (keyCode < 256
  42968. && other.keyCode < 256
  42969. && CharacterFunctions::toLowerCase ((tchar) keyCode)
  42970. == CharacterFunctions::toLowerCase ((tchar) other.keyCode)));
  42971. }
  42972. bool KeyPress::operator!= (const KeyPress& other) const throw()
  42973. {
  42974. return ! operator== (other);
  42975. }
  42976. bool KeyPress::isCurrentlyDown() const throw()
  42977. {
  42978. return isKeyCurrentlyDown (keyCode)
  42979. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  42980. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  42981. }
  42982. struct KeyNameAndCode
  42983. {
  42984. const char* name;
  42985. int code;
  42986. };
  42987. static const KeyNameAndCode keyNameTranslations[] =
  42988. {
  42989. { "spacebar", KeyPress::spaceKey },
  42990. { "return", KeyPress::returnKey },
  42991. { "escape", KeyPress::escapeKey },
  42992. { "backspace", KeyPress::backspaceKey },
  42993. { "cursor left", KeyPress::leftKey },
  42994. { "cursor right", KeyPress::rightKey },
  42995. { "cursor up", KeyPress::upKey },
  42996. { "cursor down", KeyPress::downKey },
  42997. { "page up", KeyPress::pageUpKey },
  42998. { "page down", KeyPress::pageDownKey },
  42999. { "home", KeyPress::homeKey },
  43000. { "end", KeyPress::endKey },
  43001. { "delete", KeyPress::deleteKey },
  43002. { "insert", KeyPress::insertKey },
  43003. { "tab", KeyPress::tabKey },
  43004. { "play", KeyPress::playKey },
  43005. { "stop", KeyPress::stopKey },
  43006. { "fast forward", KeyPress::fastForwardKey },
  43007. { "rewind", KeyPress::rewindKey }
  43008. };
  43009. static const tchar* const numberPadPrefix = T("numpad ");
  43010. const KeyPress KeyPress::createFromDescription (const String& desc) throw()
  43011. {
  43012. int modifiers = 0;
  43013. if (desc.containsWholeWordIgnoreCase (T("ctrl"))
  43014. || desc.containsWholeWordIgnoreCase (T("control"))
  43015. || desc.containsWholeWordIgnoreCase (T("ctl")))
  43016. modifiers |= ModifierKeys::ctrlModifier;
  43017. if (desc.containsWholeWordIgnoreCase (T("shift"))
  43018. || desc.containsWholeWordIgnoreCase (T("shft")))
  43019. modifiers |= ModifierKeys::shiftModifier;
  43020. if (desc.containsWholeWordIgnoreCase (T("alt"))
  43021. || desc.containsWholeWordIgnoreCase (T("option")))
  43022. modifiers |= ModifierKeys::altModifier;
  43023. if (desc.containsWholeWordIgnoreCase (T("command"))
  43024. || desc.containsWholeWordIgnoreCase (T("cmd")))
  43025. modifiers |= ModifierKeys::commandModifier;
  43026. int key = 0;
  43027. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  43028. {
  43029. if (desc.containsWholeWordIgnoreCase (String (keyNameTranslations[i].name)))
  43030. {
  43031. key = keyNameTranslations[i].code;
  43032. break;
  43033. }
  43034. }
  43035. if (key == 0)
  43036. {
  43037. // see if it's a numpad key..
  43038. if (desc.containsIgnoreCase (numberPadPrefix))
  43039. {
  43040. const tchar lastChar = desc.trimEnd().getLastCharacter();
  43041. if (lastChar >= T('0') && lastChar <= T('9'))
  43042. key = numberPad0 + lastChar - T('0');
  43043. else if (lastChar == T('+'))
  43044. key = numberPadAdd;
  43045. else if (lastChar == T('-'))
  43046. key = numberPadSubtract;
  43047. else if (lastChar == T('*'))
  43048. key = numberPadMultiply;
  43049. else if (lastChar == T('/'))
  43050. key = numberPadDivide;
  43051. else if (lastChar == T('.'))
  43052. key = numberPadDecimalPoint;
  43053. else if (lastChar == T('='))
  43054. key = numberPadEquals;
  43055. else if (desc.endsWith (T("separator")))
  43056. key = numberPadSeparator;
  43057. else if (desc.endsWith (T("delete")))
  43058. key = numberPadDelete;
  43059. }
  43060. if (key == 0)
  43061. {
  43062. // see if it's a function key..
  43063. for (int i = 1; i <= 12; ++i)
  43064. if (desc.containsWholeWordIgnoreCase (T("f") + String (i)))
  43065. key = F1Key + i - 1;
  43066. if (key == 0)
  43067. {
  43068. // give up and use the hex code..
  43069. const int hexCode = desc.fromFirstOccurrenceOf (T("#"), false, false)
  43070. .toLowerCase()
  43071. .retainCharacters (T("0123456789abcdef"))
  43072. .getHexValue32();
  43073. if (hexCode > 0)
  43074. key = hexCode;
  43075. else
  43076. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  43077. }
  43078. }
  43079. }
  43080. return KeyPress (key, ModifierKeys (modifiers), 0);
  43081. }
  43082. const String KeyPress::getTextDescription() const throw()
  43083. {
  43084. String desc;
  43085. if (keyCode > 0)
  43086. {
  43087. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  43088. // want to store it as being a slash, not shift+whatever.
  43089. if (textCharacter == T('/'))
  43090. return "/";
  43091. if (mods.isCtrlDown())
  43092. desc << "ctrl + ";
  43093. if (mods.isShiftDown())
  43094. desc << "shift + ";
  43095. #if JUCE_MAC
  43096. // only do this on the mac, because on Windows ctrl and command are the same,
  43097. // and this would get confusing
  43098. if (mods.isCommandDown())
  43099. desc << "command + ";
  43100. if (mods.isAltDown())
  43101. desc << "option + ";
  43102. #else
  43103. if (mods.isAltDown())
  43104. desc << "alt + ";
  43105. #endif
  43106. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  43107. if (keyCode == keyNameTranslations[i].code)
  43108. return desc + keyNameTranslations[i].name;
  43109. if (keyCode >= F1Key && keyCode <= F16Key)
  43110. desc << 'F' << (1 + keyCode - F1Key);
  43111. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  43112. desc << numberPadPrefix << (keyCode - numberPad0);
  43113. else if (keyCode >= 33 && keyCode < 176)
  43114. desc += CharacterFunctions::toUpperCase ((tchar) keyCode);
  43115. else if (keyCode == numberPadAdd)
  43116. desc << numberPadPrefix << '+';
  43117. else if (keyCode == numberPadSubtract)
  43118. desc << numberPadPrefix << '-';
  43119. else if (keyCode == numberPadMultiply)
  43120. desc << numberPadPrefix << '*';
  43121. else if (keyCode == numberPadDivide)
  43122. desc << numberPadPrefix << '/';
  43123. else if (keyCode == numberPadSeparator)
  43124. desc << numberPadPrefix << "separator";
  43125. else if (keyCode == numberPadDecimalPoint)
  43126. desc << numberPadPrefix << '.';
  43127. else if (keyCode == numberPadDelete)
  43128. desc << numberPadPrefix << "delete";
  43129. else
  43130. desc << '#' << String::toHexString (keyCode);
  43131. }
  43132. return desc;
  43133. }
  43134. END_JUCE_NAMESPACE
  43135. /********* End of inlined file: juce_KeyPress.cpp *********/
  43136. /********* Start of inlined file: juce_KeyPressMappingSet.cpp *********/
  43137. BEGIN_JUCE_NAMESPACE
  43138. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_) throw()
  43139. : commandManager (commandManager_)
  43140. {
  43141. // A manager is needed to get the descriptions of commands, and will be called when
  43142. // a command is invoked. So you can't leave this null..
  43143. jassert (commandManager_ != 0);
  43144. Desktop::getInstance().addFocusChangeListener (this);
  43145. }
  43146. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other) throw()
  43147. : commandManager (other.commandManager)
  43148. {
  43149. Desktop::getInstance().addFocusChangeListener (this);
  43150. }
  43151. KeyPressMappingSet::~KeyPressMappingSet()
  43152. {
  43153. Desktop::getInstance().removeFocusChangeListener (this);
  43154. }
  43155. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const throw()
  43156. {
  43157. for (int i = 0; i < mappings.size(); ++i)
  43158. if (mappings.getUnchecked(i)->commandID == commandID)
  43159. return mappings.getUnchecked (i)->keypresses;
  43160. return Array <KeyPress> ();
  43161. }
  43162. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  43163. const KeyPress& newKeyPress,
  43164. int insertIndex) throw()
  43165. {
  43166. if (findCommandForKeyPress (newKeyPress) != commandID)
  43167. {
  43168. removeKeyPress (newKeyPress);
  43169. if (newKeyPress.isValid())
  43170. {
  43171. for (int i = mappings.size(); --i >= 0;)
  43172. {
  43173. if (mappings.getUnchecked(i)->commandID == commandID)
  43174. {
  43175. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  43176. sendChangeMessage (this);
  43177. return;
  43178. }
  43179. }
  43180. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  43181. if (ci != 0)
  43182. {
  43183. CommandMapping* const cm = new CommandMapping();
  43184. cm->commandID = commandID;
  43185. cm->keypresses.add (newKeyPress);
  43186. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  43187. mappings.add (cm);
  43188. sendChangeMessage (this);
  43189. }
  43190. }
  43191. }
  43192. }
  43193. void KeyPressMappingSet::resetToDefaultMappings() throw()
  43194. {
  43195. mappings.clear();
  43196. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  43197. {
  43198. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  43199. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  43200. {
  43201. addKeyPress (ci->commandID,
  43202. ci->defaultKeypresses.getReference (j));
  43203. }
  43204. }
  43205. sendChangeMessage (this);
  43206. }
  43207. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID) throw()
  43208. {
  43209. clearAllKeyPresses (commandID);
  43210. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  43211. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  43212. {
  43213. addKeyPress (ci->commandID,
  43214. ci->defaultKeypresses.getReference (j));
  43215. }
  43216. }
  43217. void KeyPressMappingSet::clearAllKeyPresses() throw()
  43218. {
  43219. if (mappings.size() > 0)
  43220. {
  43221. sendChangeMessage (this);
  43222. mappings.clear();
  43223. }
  43224. }
  43225. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID) throw()
  43226. {
  43227. for (int i = mappings.size(); --i >= 0;)
  43228. {
  43229. if (mappings.getUnchecked(i)->commandID == commandID)
  43230. {
  43231. mappings.remove (i);
  43232. sendChangeMessage (this);
  43233. }
  43234. }
  43235. }
  43236. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress) throw()
  43237. {
  43238. if (keypress.isValid())
  43239. {
  43240. for (int i = mappings.size(); --i >= 0;)
  43241. {
  43242. CommandMapping* const cm = mappings.getUnchecked(i);
  43243. for (int j = cm->keypresses.size(); --j >= 0;)
  43244. {
  43245. if (keypress == cm->keypresses [j])
  43246. {
  43247. cm->keypresses.remove (j);
  43248. sendChangeMessage (this);
  43249. }
  43250. }
  43251. }
  43252. }
  43253. }
  43254. void KeyPressMappingSet::removeKeyPress (const CommandID commandID,
  43255. const int keyPressIndex) throw()
  43256. {
  43257. for (int i = mappings.size(); --i >= 0;)
  43258. {
  43259. if (mappings.getUnchecked(i)->commandID == commandID)
  43260. {
  43261. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  43262. sendChangeMessage (this);
  43263. break;
  43264. }
  43265. }
  43266. }
  43267. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  43268. {
  43269. for (int i = 0; i < mappings.size(); ++i)
  43270. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  43271. return mappings.getUnchecked(i)->commandID;
  43272. return 0;
  43273. }
  43274. bool KeyPressMappingSet::containsMapping (const CommandID commandID,
  43275. const KeyPress& keyPress) const throw()
  43276. {
  43277. for (int i = mappings.size(); --i >= 0;)
  43278. if (mappings.getUnchecked(i)->commandID == commandID)
  43279. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  43280. return false;
  43281. }
  43282. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  43283. const KeyPress& key,
  43284. const bool isKeyDown,
  43285. const int millisecsSinceKeyPressed,
  43286. Component* const originatingComponent) const
  43287. {
  43288. ApplicationCommandTarget::InvocationInfo info (commandID);
  43289. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  43290. info.isKeyDown = isKeyDown;
  43291. info.keyPress = key;
  43292. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  43293. info.originatingComponent = originatingComponent;
  43294. commandManager->invoke (info, false);
  43295. }
  43296. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  43297. {
  43298. if (xmlVersion.hasTagName (T("KEYMAPPINGS")))
  43299. {
  43300. if (xmlVersion.getBoolAttribute (T("basedOnDefaults"), true))
  43301. {
  43302. // if the XML was created as a set of differences from the default mappings,
  43303. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  43304. resetToDefaultMappings();
  43305. }
  43306. else
  43307. {
  43308. // if the XML was created calling createXml (false), then we need to clear all
  43309. // the keys and treat the xml as describing the entire set of mappings.
  43310. clearAllKeyPresses();
  43311. }
  43312. forEachXmlChildElement (xmlVersion, map)
  43313. {
  43314. const CommandID commandId = map->getStringAttribute (T("commandId")).getHexValue32();
  43315. if (commandId != 0)
  43316. {
  43317. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute (T("key"))));
  43318. if (map->hasTagName (T("MAPPING")))
  43319. {
  43320. addKeyPress (commandId, key);
  43321. }
  43322. else if (map->hasTagName (T("UNMAPPING")))
  43323. {
  43324. if (containsMapping (commandId, key))
  43325. removeKeyPress (key);
  43326. }
  43327. }
  43328. }
  43329. return true;
  43330. }
  43331. return false;
  43332. }
  43333. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  43334. {
  43335. KeyPressMappingSet* defaultSet = 0;
  43336. if (saveDifferencesFromDefaultSet)
  43337. {
  43338. defaultSet = new KeyPressMappingSet (commandManager);
  43339. defaultSet->resetToDefaultMappings();
  43340. }
  43341. XmlElement* const doc = new XmlElement (T("KEYMAPPINGS"));
  43342. doc->setAttribute (T("basedOnDefaults"), saveDifferencesFromDefaultSet);
  43343. int i;
  43344. for (i = 0; i < mappings.size(); ++i)
  43345. {
  43346. const CommandMapping* const cm = mappings.getUnchecked(i);
  43347. for (int j = 0; j < cm->keypresses.size(); ++j)
  43348. {
  43349. if (defaultSet == 0
  43350. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  43351. {
  43352. XmlElement* const map = new XmlElement (T("MAPPING"));
  43353. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  43354. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  43355. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  43356. doc->addChildElement (map);
  43357. }
  43358. }
  43359. }
  43360. if (defaultSet != 0)
  43361. {
  43362. for (i = 0; i < defaultSet->mappings.size(); ++i)
  43363. {
  43364. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  43365. for (int j = 0; j < cm->keypresses.size(); ++j)
  43366. {
  43367. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  43368. {
  43369. XmlElement* const map = new XmlElement (T("UNMAPPING"));
  43370. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  43371. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  43372. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  43373. doc->addChildElement (map);
  43374. }
  43375. }
  43376. }
  43377. delete defaultSet;
  43378. }
  43379. return doc;
  43380. }
  43381. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  43382. Component* originatingComponent)
  43383. {
  43384. bool used = false;
  43385. const CommandID commandID = findCommandForKeyPress (key);
  43386. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  43387. if (ci != 0
  43388. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  43389. {
  43390. ApplicationCommandInfo info (0);
  43391. if (commandManager->getTargetForCommand (commandID, info) != 0
  43392. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  43393. {
  43394. invokeCommand (commandID, key, true, 0, originatingComponent);
  43395. used = true;
  43396. }
  43397. else
  43398. {
  43399. if (originatingComponent != 0)
  43400. originatingComponent->getLookAndFeel().playAlertSound();
  43401. }
  43402. }
  43403. return used;
  43404. }
  43405. bool KeyPressMappingSet::keyStateChanged (Component* originatingComponent)
  43406. {
  43407. bool used = false;
  43408. const uint32 now = Time::getMillisecondCounter();
  43409. for (int i = mappings.size(); --i >= 0;)
  43410. {
  43411. CommandMapping* const cm = mappings.getUnchecked(i);
  43412. if (cm->wantsKeyUpDownCallbacks)
  43413. {
  43414. for (int j = cm->keypresses.size(); --j >= 0;)
  43415. {
  43416. const KeyPress key (cm->keypresses.getReference (j));
  43417. const bool isDown = key.isCurrentlyDown();
  43418. int keyPressEntryIndex = 0;
  43419. bool wasDown = false;
  43420. for (int k = keysDown.size(); --k >= 0;)
  43421. {
  43422. if (key == keysDown.getUnchecked(k)->key)
  43423. {
  43424. keyPressEntryIndex = k;
  43425. wasDown = true;
  43426. break;
  43427. }
  43428. }
  43429. if (isDown != wasDown)
  43430. {
  43431. int millisecs = 0;
  43432. if (isDown)
  43433. {
  43434. KeyPressTime* const k = new KeyPressTime();
  43435. k->key = key;
  43436. k->timeWhenPressed = now;
  43437. keysDown.add (k);
  43438. }
  43439. else
  43440. {
  43441. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  43442. if (now > pressTime)
  43443. millisecs = now - pressTime;
  43444. keysDown.remove (keyPressEntryIndex);
  43445. }
  43446. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  43447. used = true;
  43448. }
  43449. }
  43450. }
  43451. }
  43452. return used;
  43453. }
  43454. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  43455. {
  43456. if (focusedComponent != 0)
  43457. focusedComponent->keyStateChanged();
  43458. }
  43459. END_JUCE_NAMESPACE
  43460. /********* End of inlined file: juce_KeyPressMappingSet.cpp *********/
  43461. /********* Start of inlined file: juce_ModifierKeys.cpp *********/
  43462. BEGIN_JUCE_NAMESPACE
  43463. ModifierKeys::ModifierKeys (const int flags_) throw()
  43464. : flags (flags_)
  43465. {
  43466. }
  43467. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  43468. : flags (other.flags)
  43469. {
  43470. }
  43471. const ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  43472. {
  43473. flags = other.flags;
  43474. return *this;
  43475. }
  43476. int ModifierKeys::currentModifierFlags = 0;
  43477. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  43478. {
  43479. return ModifierKeys (currentModifierFlags);
  43480. }
  43481. END_JUCE_NAMESPACE
  43482. /********* End of inlined file: juce_ModifierKeys.cpp *********/
  43483. /********* Start of inlined file: juce_ComponentAnimator.cpp *********/
  43484. BEGIN_JUCE_NAMESPACE
  43485. struct AnimationTask
  43486. {
  43487. AnimationTask (Component* const comp)
  43488. : component (comp),
  43489. watcher (comp)
  43490. {
  43491. }
  43492. Component* component;
  43493. ComponentDeletionWatcher watcher;
  43494. Rectangle destination;
  43495. int msElapsed, msTotal;
  43496. double startSpeed, midSpeed, endSpeed, lastProgress;
  43497. double left, top, right, bottom;
  43498. bool useTimeslice (const int elapsed)
  43499. {
  43500. if (watcher.hasBeenDeleted())
  43501. return false;
  43502. msElapsed += elapsed;
  43503. double newProgress = msElapsed / (double) msTotal;
  43504. if (newProgress >= 0 && newProgress < 1.0)
  43505. {
  43506. newProgress = timeToDistance (newProgress);
  43507. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  43508. jassert (newProgress >= lastProgress);
  43509. lastProgress = newProgress;
  43510. left += (destination.getX() - left) * delta;
  43511. top += (destination.getY() - top) * delta;
  43512. right += (destination.getRight() - right) * delta;
  43513. bottom += (destination.getBottom() - bottom) * delta;
  43514. if (delta < 1.0)
  43515. {
  43516. const Rectangle newBounds (roundDoubleToInt (left),
  43517. roundDoubleToInt (top),
  43518. roundDoubleToInt (right - left),
  43519. roundDoubleToInt (bottom - top));
  43520. if (newBounds != destination)
  43521. {
  43522. component->setBounds (newBounds);
  43523. return true;
  43524. }
  43525. }
  43526. }
  43527. component->setBounds (destination);
  43528. return false;
  43529. }
  43530. void moveToFinalDestination()
  43531. {
  43532. if (! watcher.hasBeenDeleted())
  43533. component->setBounds (destination);
  43534. }
  43535. private:
  43536. inline double timeToDistance (const double time) const
  43537. {
  43538. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  43539. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  43540. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  43541. }
  43542. };
  43543. ComponentAnimator::ComponentAnimator()
  43544. : lastTime (0)
  43545. {
  43546. }
  43547. ComponentAnimator::~ComponentAnimator()
  43548. {
  43549. cancelAllAnimations (false);
  43550. jassert (tasks.size() == 0);
  43551. }
  43552. void* ComponentAnimator::findTaskFor (Component* const component) const
  43553. {
  43554. for (int i = tasks.size(); --i >= 0;)
  43555. if (component == ((AnimationTask*) tasks.getUnchecked(i))->component)
  43556. return tasks.getUnchecked(i);
  43557. return 0;
  43558. }
  43559. void ComponentAnimator::animateComponent (Component* const component,
  43560. const Rectangle& finalPosition,
  43561. const int millisecondsToSpendMoving,
  43562. const double startSpeed,
  43563. const double endSpeed)
  43564. {
  43565. if (component != 0)
  43566. {
  43567. AnimationTask* at = (AnimationTask*) findTaskFor (component);
  43568. if (at == 0)
  43569. {
  43570. at = new AnimationTask (component);
  43571. tasks.add (at);
  43572. }
  43573. at->msElapsed = 0;
  43574. at->lastProgress = 0;
  43575. at->msTotal = jmax (1, millisecondsToSpendMoving);
  43576. at->destination = finalPosition;
  43577. // the speeds must be 0 or greater!
  43578. jassert (startSpeed >= 0 && endSpeed >= 0)
  43579. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  43580. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  43581. at->midSpeed = invTotalDistance;
  43582. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  43583. at->left = component->getX();
  43584. at->top = component->getY();
  43585. at->right = component->getRight();
  43586. at->bottom = component->getBottom();
  43587. if (! isTimerRunning())
  43588. {
  43589. lastTime = Time::getMillisecondCounter();
  43590. startTimer (1000 / 50);
  43591. }
  43592. }
  43593. }
  43594. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  43595. {
  43596. for (int i = tasks.size(); --i >= 0;)
  43597. {
  43598. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  43599. if (moveComponentsToTheirFinalPositions)
  43600. at->moveToFinalDestination();
  43601. delete at;
  43602. tasks.remove (i);
  43603. }
  43604. }
  43605. void ComponentAnimator::cancelAnimation (Component* const component,
  43606. const bool moveComponentToItsFinalPosition)
  43607. {
  43608. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  43609. if (at != 0)
  43610. {
  43611. if (moveComponentToItsFinalPosition)
  43612. at->moveToFinalDestination();
  43613. tasks.removeValue (at);
  43614. delete at;
  43615. }
  43616. }
  43617. const Rectangle ComponentAnimator::getComponentDestination (Component* const component)
  43618. {
  43619. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  43620. if (at != 0)
  43621. return at->destination;
  43622. else if (component != 0)
  43623. return component->getBounds();
  43624. return Rectangle();
  43625. }
  43626. void ComponentAnimator::timerCallback()
  43627. {
  43628. const uint32 timeNow = Time::getMillisecondCounter();
  43629. if (lastTime == 0 || lastTime == timeNow)
  43630. lastTime = timeNow;
  43631. const int elapsed = timeNow - lastTime;
  43632. for (int i = tasks.size(); --i >= 0;)
  43633. {
  43634. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  43635. if (! at->useTimeslice (elapsed))
  43636. {
  43637. tasks.remove (i);
  43638. delete at;
  43639. }
  43640. }
  43641. lastTime = timeNow;
  43642. if (tasks.size() == 0)
  43643. stopTimer();
  43644. }
  43645. END_JUCE_NAMESPACE
  43646. /********* End of inlined file: juce_ComponentAnimator.cpp *********/
  43647. /********* Start of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  43648. BEGIN_JUCE_NAMESPACE
  43649. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  43650. : minW (0),
  43651. maxW (0x3fffffff),
  43652. minH (0),
  43653. maxH (0x3fffffff),
  43654. minOffTop (0),
  43655. minOffLeft (0),
  43656. minOffBottom (0),
  43657. minOffRight (0),
  43658. aspectRatio (0.0)
  43659. {
  43660. }
  43661. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  43662. {
  43663. }
  43664. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  43665. {
  43666. minW = minimumWidth;
  43667. }
  43668. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  43669. {
  43670. maxW = maximumWidth;
  43671. }
  43672. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  43673. {
  43674. minH = minimumHeight;
  43675. }
  43676. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  43677. {
  43678. maxH = maximumHeight;
  43679. }
  43680. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  43681. {
  43682. jassert (maxW >= minimumWidth);
  43683. jassert (maxH >= minimumHeight);
  43684. jassert (minimumWidth > 0 && minimumHeight > 0);
  43685. minW = minimumWidth;
  43686. minH = minimumHeight;
  43687. if (minW > maxW)
  43688. maxW = minW;
  43689. if (minH > maxH)
  43690. maxH = minH;
  43691. }
  43692. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  43693. {
  43694. jassert (maximumWidth >= minW);
  43695. jassert (maximumHeight >= minH);
  43696. jassert (maximumWidth > 0 && maximumHeight > 0);
  43697. maxW = jmax (minW, maximumWidth);
  43698. maxH = jmax (minH, maximumHeight);
  43699. }
  43700. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  43701. const int minimumHeight,
  43702. const int maximumWidth,
  43703. const int maximumHeight) throw()
  43704. {
  43705. jassert (maximumWidth >= minimumWidth);
  43706. jassert (maximumHeight >= minimumHeight);
  43707. jassert (maximumWidth > 0 && maximumHeight > 0);
  43708. jassert (minimumWidth > 0 && minimumHeight > 0);
  43709. minW = jmax (0, minimumWidth);
  43710. minH = jmax (0, minimumHeight);
  43711. maxW = jmax (minW, maximumWidth);
  43712. maxH = jmax (minH, maximumHeight);
  43713. }
  43714. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  43715. const int minimumWhenOffTheLeft,
  43716. const int minimumWhenOffTheBottom,
  43717. const int minimumWhenOffTheRight) throw()
  43718. {
  43719. minOffTop = minimumWhenOffTheTop;
  43720. minOffLeft = minimumWhenOffTheLeft;
  43721. minOffBottom = minimumWhenOffTheBottom;
  43722. minOffRight = minimumWhenOffTheRight;
  43723. }
  43724. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  43725. {
  43726. aspectRatio = jmax (0.0, widthOverHeight);
  43727. }
  43728. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  43729. {
  43730. return aspectRatio;
  43731. }
  43732. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  43733. int x, int y, int w, int h,
  43734. const bool isStretchingTop,
  43735. const bool isStretchingLeft,
  43736. const bool isStretchingBottom,
  43737. const bool isStretchingRight)
  43738. {
  43739. jassert (component != 0);
  43740. Rectangle limits;
  43741. Component* const p = component->getParentComponent();
  43742. if (p == 0)
  43743. limits = Desktop::getInstance().getAllMonitorDisplayAreas().getBounds();
  43744. else
  43745. limits.setSize (p->getWidth(), p->getHeight());
  43746. if (component->isOnDesktop())
  43747. {
  43748. ComponentPeer* const peer = component->getPeer();
  43749. const BorderSize border (peer->getFrameSize());
  43750. x -= border.getLeft();
  43751. y -= border.getTop();
  43752. w += border.getLeftAndRight();
  43753. h += border.getTopAndBottom();
  43754. checkBounds (x, y, w, h,
  43755. border.addedTo (component->getBounds()), limits,
  43756. isStretchingTop, isStretchingLeft,
  43757. isStretchingBottom, isStretchingRight);
  43758. x += border.getLeft();
  43759. y += border.getTop();
  43760. w -= border.getLeftAndRight();
  43761. h -= border.getTopAndBottom();
  43762. }
  43763. else
  43764. {
  43765. checkBounds (x, y, w, h,
  43766. component->getBounds(), limits,
  43767. isStretchingTop, isStretchingLeft,
  43768. isStretchingBottom, isStretchingRight);
  43769. }
  43770. applyBoundsToComponent (component, x, y, w, h);
  43771. }
  43772. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  43773. int x, int y, int w, int h)
  43774. {
  43775. component->setBounds (x, y, w, h);
  43776. }
  43777. void ComponentBoundsConstrainer::resizeStart()
  43778. {
  43779. }
  43780. void ComponentBoundsConstrainer::resizeEnd()
  43781. {
  43782. }
  43783. void ComponentBoundsConstrainer::checkBounds (int& x, int& y, int& w, int& h,
  43784. const Rectangle& old,
  43785. const Rectangle& limits,
  43786. const bool isStretchingTop,
  43787. const bool isStretchingLeft,
  43788. const bool isStretchingBottom,
  43789. const bool isStretchingRight)
  43790. {
  43791. // constrain the size if it's being stretched..
  43792. if (isStretchingLeft)
  43793. {
  43794. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  43795. w = old.getRight() - x;
  43796. }
  43797. if (isStretchingRight)
  43798. {
  43799. w = jlimit (minW, maxW, w);
  43800. }
  43801. if (isStretchingTop)
  43802. {
  43803. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  43804. h = old.getBottom() - y;
  43805. }
  43806. if (isStretchingBottom)
  43807. {
  43808. h = jlimit (minH, maxH, h);
  43809. }
  43810. // constrain the aspect ratio if one has been specified..
  43811. if (aspectRatio > 0.0 && w > 0 && h > 0)
  43812. {
  43813. bool adjustWidth;
  43814. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  43815. {
  43816. adjustWidth = true;
  43817. }
  43818. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  43819. {
  43820. adjustWidth = false;
  43821. }
  43822. else
  43823. {
  43824. const double oldRatio = (old.getHeight() > 0) ? fabs (old.getWidth() / (double) old.getHeight()) : 0.0;
  43825. const double newRatio = fabs (w / (double) h);
  43826. adjustWidth = (oldRatio > newRatio);
  43827. }
  43828. if (adjustWidth)
  43829. {
  43830. w = roundDoubleToInt (h * aspectRatio);
  43831. if (w > maxW || w < minW)
  43832. {
  43833. w = jlimit (minW, maxW, w);
  43834. h = roundDoubleToInt (w / aspectRatio);
  43835. }
  43836. }
  43837. else
  43838. {
  43839. h = roundDoubleToInt (w / aspectRatio);
  43840. if (h > maxH || h < minH)
  43841. {
  43842. h = jlimit (minH, maxH, h);
  43843. w = roundDoubleToInt (h * aspectRatio);
  43844. }
  43845. }
  43846. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  43847. {
  43848. x = old.getX() + (old.getWidth() - w) / 2;
  43849. }
  43850. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  43851. {
  43852. y = old.getY() + (old.getHeight() - h) / 2;
  43853. }
  43854. else
  43855. {
  43856. if (isStretchingLeft)
  43857. x = old.getRight() - w;
  43858. if (isStretchingTop)
  43859. y = old.getBottom() - h;
  43860. }
  43861. }
  43862. // ...and constrain the position if limits have been set for that.
  43863. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  43864. {
  43865. if (minOffTop > 0)
  43866. {
  43867. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  43868. if (y < limit)
  43869. {
  43870. if (isStretchingTop)
  43871. h -= (limit - y);
  43872. y = limit;
  43873. }
  43874. }
  43875. if (minOffLeft > 0)
  43876. {
  43877. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  43878. if (x < limit)
  43879. {
  43880. if (isStretchingLeft)
  43881. w -= (limit - x);
  43882. x = limit;
  43883. }
  43884. }
  43885. if (minOffBottom > 0)
  43886. {
  43887. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  43888. if (y > limit)
  43889. {
  43890. if (isStretchingBottom)
  43891. h += (limit - y);
  43892. else
  43893. y = limit;
  43894. }
  43895. }
  43896. if (minOffRight > 0)
  43897. {
  43898. const int limit = limits.getRight() - jmin (minOffRight, w);
  43899. if (x > limit)
  43900. {
  43901. if (isStretchingRight)
  43902. w += (limit - x);
  43903. else
  43904. x = limit;
  43905. }
  43906. }
  43907. }
  43908. jassert (w >= 0 && h >= 0);
  43909. }
  43910. END_JUCE_NAMESPACE
  43911. /********* End of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  43912. /********* Start of inlined file: juce_ComponentMovementWatcher.cpp *********/
  43913. BEGIN_JUCE_NAMESPACE
  43914. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  43915. : component (component_),
  43916. lastPeer (0),
  43917. registeredParentComps (4),
  43918. reentrant (false)
  43919. {
  43920. jassert (component != 0); // can't use this with a null pointer..
  43921. #ifdef JUCE_DEBUG
  43922. deletionWatcher = new ComponentDeletionWatcher (component_);
  43923. #endif
  43924. component->addComponentListener (this);
  43925. registerWithParentComps();
  43926. }
  43927. ComponentMovementWatcher::~ComponentMovementWatcher()
  43928. {
  43929. component->removeComponentListener (this);
  43930. unregister();
  43931. #ifdef JUCE_DEBUG
  43932. delete deletionWatcher;
  43933. #endif
  43934. }
  43935. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  43936. {
  43937. #ifdef JUCE_DEBUG
  43938. // agh! don't delete the target component without deleting this object first!
  43939. jassert (! deletionWatcher->hasBeenDeleted());
  43940. #endif
  43941. if (! reentrant)
  43942. {
  43943. reentrant = true;
  43944. ComponentPeer* const peer = component->getPeer();
  43945. if (peer != lastPeer)
  43946. {
  43947. ComponentDeletionWatcher watcher (component);
  43948. componentPeerChanged();
  43949. if (watcher.hasBeenDeleted())
  43950. return;
  43951. lastPeer = peer;
  43952. }
  43953. unregister();
  43954. registerWithParentComps();
  43955. reentrant = false;
  43956. componentMovedOrResized (*component, true, true);
  43957. }
  43958. }
  43959. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  43960. {
  43961. #ifdef JUCE_DEBUG
  43962. // agh! don't delete the target component without deleting this object first!
  43963. jassert (! deletionWatcher->hasBeenDeleted());
  43964. #endif
  43965. if (wasMoved)
  43966. {
  43967. int x = 0, y = 0;
  43968. component->relativePositionToOtherComponent (component->getTopLevelComponent(), x, y);
  43969. wasMoved = (lastX != x || lastY != y);
  43970. lastX = x;
  43971. lastY = y;
  43972. }
  43973. wasResized = (lastWidth != component->getWidth() || lastHeight != component->getHeight());
  43974. lastWidth = component->getWidth();
  43975. lastHeight = component->getHeight();
  43976. if (wasMoved || wasResized)
  43977. componentMovedOrResized (wasMoved, wasResized);
  43978. }
  43979. void ComponentMovementWatcher::registerWithParentComps() throw()
  43980. {
  43981. Component* p = component->getParentComponent();
  43982. while (p != 0)
  43983. {
  43984. p->addComponentListener (this);
  43985. registeredParentComps.add (p);
  43986. p = p->getParentComponent();
  43987. }
  43988. }
  43989. void ComponentMovementWatcher::unregister() throw()
  43990. {
  43991. for (int i = registeredParentComps.size(); --i >= 0;)
  43992. ((Component*) registeredParentComps.getUnchecked(i))->removeComponentListener (this);
  43993. registeredParentComps.clear();
  43994. }
  43995. END_JUCE_NAMESPACE
  43996. /********* End of inlined file: juce_ComponentMovementWatcher.cpp *********/
  43997. /********* Start of inlined file: juce_GroupComponent.cpp *********/
  43998. BEGIN_JUCE_NAMESPACE
  43999. GroupComponent::GroupComponent (const String& componentName,
  44000. const String& labelText)
  44001. : Component (componentName),
  44002. text (labelText),
  44003. justification (Justification::left)
  44004. {
  44005. setInterceptsMouseClicks (false, true);
  44006. }
  44007. GroupComponent::~GroupComponent()
  44008. {
  44009. }
  44010. void GroupComponent::setText (const String& newText) throw()
  44011. {
  44012. if (text != newText)
  44013. {
  44014. text = newText;
  44015. repaint();
  44016. }
  44017. }
  44018. const String GroupComponent::getText() const throw()
  44019. {
  44020. return text;
  44021. }
  44022. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  44023. {
  44024. if (justification.getFlags() != newJustification.getFlags())
  44025. {
  44026. justification = newJustification;
  44027. repaint();
  44028. }
  44029. }
  44030. void GroupComponent::paint (Graphics& g)
  44031. {
  44032. getLookAndFeel()
  44033. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  44034. text, justification,
  44035. *this);
  44036. }
  44037. void GroupComponent::enablementChanged()
  44038. {
  44039. repaint();
  44040. }
  44041. void GroupComponent::colourChanged()
  44042. {
  44043. repaint();
  44044. }
  44045. END_JUCE_NAMESPACE
  44046. /********* End of inlined file: juce_GroupComponent.cpp *********/
  44047. /********* Start of inlined file: juce_MultiDocumentPanel.cpp *********/
  44048. BEGIN_JUCE_NAMESPACE
  44049. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  44050. : DocumentWindow (String::empty, backgroundColour,
  44051. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  44052. {
  44053. }
  44054. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  44055. {
  44056. }
  44057. void MultiDocumentPanelWindow::maximiseButtonPressed()
  44058. {
  44059. MultiDocumentPanel* const owner = getOwner();
  44060. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  44061. if (owner != 0)
  44062. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  44063. }
  44064. void MultiDocumentPanelWindow::closeButtonPressed()
  44065. {
  44066. MultiDocumentPanel* const owner = getOwner();
  44067. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  44068. if (owner != 0)
  44069. owner->closeDocument (getContentComponent(), true);
  44070. }
  44071. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  44072. {
  44073. DocumentWindow::activeWindowStatusChanged();
  44074. updateOrder();
  44075. }
  44076. void MultiDocumentPanelWindow::broughtToFront()
  44077. {
  44078. DocumentWindow::broughtToFront();
  44079. updateOrder();
  44080. }
  44081. void MultiDocumentPanelWindow::updateOrder()
  44082. {
  44083. MultiDocumentPanel* const owner = getOwner();
  44084. if (owner != 0)
  44085. owner->updateOrder();
  44086. }
  44087. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  44088. {
  44089. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  44090. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  44091. }
  44092. class MDITabbedComponentInternal : public TabbedComponent
  44093. {
  44094. public:
  44095. MDITabbedComponentInternal()
  44096. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  44097. {
  44098. }
  44099. ~MDITabbedComponentInternal()
  44100. {
  44101. }
  44102. void currentTabChanged (const int, const String&)
  44103. {
  44104. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  44105. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  44106. if (owner != 0)
  44107. owner->updateOrder();
  44108. }
  44109. };
  44110. MultiDocumentPanel::MultiDocumentPanel()
  44111. : mode (MaximisedWindowsWithTabs),
  44112. tabComponent (0),
  44113. backgroundColour (Colours::lightblue),
  44114. maximumNumDocuments (0),
  44115. numDocsBeforeTabsUsed (0)
  44116. {
  44117. setOpaque (true);
  44118. }
  44119. MultiDocumentPanel::~MultiDocumentPanel()
  44120. {
  44121. closeAllDocuments (false);
  44122. }
  44123. static bool shouldDeleteComp (Component* const c)
  44124. {
  44125. return c->getComponentPropertyBool (T("mdiDocumentDelete_"), false);
  44126. }
  44127. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  44128. {
  44129. while (components.size() > 0)
  44130. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  44131. return false;
  44132. return true;
  44133. }
  44134. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  44135. {
  44136. return new MultiDocumentPanelWindow (backgroundColour);
  44137. }
  44138. void MultiDocumentPanel::addWindow (Component* component)
  44139. {
  44140. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  44141. dw->setResizable (true, false);
  44142. dw->setContentComponent (component, false, true);
  44143. dw->setName (component->getName());
  44144. dw->setBackgroundColour (component->getComponentPropertyColour (T("mdiDocumentBkg_"), false, backgroundColour));
  44145. int x = 4;
  44146. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  44147. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  44148. x += 16;
  44149. dw->setTopLeftPosition (x, x);
  44150. if (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty).isNotEmpty())
  44151. dw->restoreWindowStateFromString (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty));
  44152. addAndMakeVisible (dw);
  44153. dw->toFront (true);
  44154. }
  44155. bool MultiDocumentPanel::addDocument (Component* const component,
  44156. const Colour& backgroundColour,
  44157. const bool deleteWhenRemoved)
  44158. {
  44159. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  44160. // with a frame-within-a-frame! Just pass in the bare content component.
  44161. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  44162. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  44163. return false;
  44164. components.add (component);
  44165. component->setComponentProperty (T("mdiDocumentDelete_"), deleteWhenRemoved);
  44166. component->setComponentProperty (T("mdiDocumentBkg_"), backgroundColour);
  44167. component->addComponentListener (this);
  44168. if (mode == FloatingWindows)
  44169. {
  44170. if (isFullscreenWhenOneDocument())
  44171. {
  44172. if (components.size() == 1)
  44173. {
  44174. addAndMakeVisible (component);
  44175. }
  44176. else
  44177. {
  44178. if (components.size() == 2)
  44179. addWindow (components.getFirst());
  44180. addWindow (component);
  44181. }
  44182. }
  44183. else
  44184. {
  44185. addWindow (component);
  44186. }
  44187. }
  44188. else
  44189. {
  44190. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  44191. {
  44192. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  44193. Array <Component*> temp (components);
  44194. for (int i = 0; i < temp.size(); ++i)
  44195. tabComponent->addTab (temp[i]->getName(), backgroundColour, temp[i], false);
  44196. resized();
  44197. }
  44198. else
  44199. {
  44200. if (tabComponent != 0)
  44201. tabComponent->addTab (component->getName(), backgroundColour, component, false);
  44202. else
  44203. addAndMakeVisible (component);
  44204. }
  44205. setActiveDocument (component);
  44206. }
  44207. resized();
  44208. activeDocumentChanged();
  44209. return true;
  44210. }
  44211. bool MultiDocumentPanel::closeDocument (Component* component,
  44212. const bool checkItsOkToCloseFirst)
  44213. {
  44214. if (components.contains (component))
  44215. {
  44216. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  44217. return false;
  44218. component->removeComponentListener (this);
  44219. const bool shouldDelete = shouldDeleteComp (component);
  44220. component->removeComponentProperty (T("mdiDocumentDelete_"));
  44221. component->removeComponentProperty (T("mdiDocumentBkg_"));
  44222. if (mode == FloatingWindows)
  44223. {
  44224. for (int i = getNumChildComponents(); --i >= 0;)
  44225. {
  44226. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44227. if (dw != 0 && dw->getContentComponent() == component)
  44228. {
  44229. dw->setContentComponent (0, false);
  44230. delete dw;
  44231. break;
  44232. }
  44233. }
  44234. if (shouldDelete)
  44235. delete component;
  44236. components.removeValue (component);
  44237. if (isFullscreenWhenOneDocument() && components.size() == 1)
  44238. {
  44239. for (int i = getNumChildComponents(); --i >= 0;)
  44240. {
  44241. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44242. if (dw != 0)
  44243. {
  44244. dw->setContentComponent (0, false);
  44245. delete dw;
  44246. }
  44247. }
  44248. addAndMakeVisible (components.getFirst());
  44249. }
  44250. }
  44251. else
  44252. {
  44253. jassert (components.indexOf (component) >= 0);
  44254. if (tabComponent != 0)
  44255. {
  44256. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  44257. if (tabComponent->getTabContentComponent (i) == component)
  44258. tabComponent->removeTab (i);
  44259. }
  44260. else
  44261. {
  44262. removeChildComponent (component);
  44263. }
  44264. if (shouldDelete)
  44265. delete component;
  44266. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  44267. deleteAndZero (tabComponent);
  44268. components.removeValue (component);
  44269. if (components.size() > 0 && tabComponent == 0)
  44270. addAndMakeVisible (components.getFirst());
  44271. }
  44272. resized();
  44273. activeDocumentChanged();
  44274. }
  44275. else
  44276. {
  44277. jassertfalse
  44278. }
  44279. return true;
  44280. }
  44281. int MultiDocumentPanel::getNumDocuments() const throw()
  44282. {
  44283. return components.size();
  44284. }
  44285. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  44286. {
  44287. return components [index];
  44288. }
  44289. Component* MultiDocumentPanel::getActiveDocument() const throw()
  44290. {
  44291. if (mode == FloatingWindows)
  44292. {
  44293. for (int i = getNumChildComponents(); --i >= 0;)
  44294. {
  44295. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44296. if (dw != 0 && dw->isActiveWindow())
  44297. return dw->getContentComponent();
  44298. }
  44299. }
  44300. return components.getLast();
  44301. }
  44302. void MultiDocumentPanel::setActiveDocument (Component* component)
  44303. {
  44304. if (mode == FloatingWindows)
  44305. {
  44306. component = getContainerComp (component);
  44307. if (component != 0)
  44308. component->toFront (true);
  44309. }
  44310. else if (tabComponent != 0)
  44311. {
  44312. jassert (components.indexOf (component) >= 0);
  44313. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  44314. {
  44315. if (tabComponent->getTabContentComponent (i) == component)
  44316. {
  44317. tabComponent->setCurrentTabIndex (i);
  44318. break;
  44319. }
  44320. }
  44321. }
  44322. else
  44323. {
  44324. component->grabKeyboardFocus();
  44325. }
  44326. }
  44327. void MultiDocumentPanel::activeDocumentChanged()
  44328. {
  44329. }
  44330. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  44331. {
  44332. maximumNumDocuments = newNumber;
  44333. }
  44334. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  44335. {
  44336. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  44337. }
  44338. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  44339. {
  44340. return numDocsBeforeTabsUsed != 0;
  44341. }
  44342. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  44343. {
  44344. if (mode != newLayoutMode)
  44345. {
  44346. mode = newLayoutMode;
  44347. if (mode == FloatingWindows)
  44348. {
  44349. deleteAndZero (tabComponent);
  44350. }
  44351. else
  44352. {
  44353. for (int i = getNumChildComponents(); --i >= 0;)
  44354. {
  44355. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44356. if (dw != 0)
  44357. {
  44358. dw->getContentComponent()->setComponentProperty (T("mdiDocumentPos_"), dw->getWindowStateAsString());
  44359. dw->setContentComponent (0, false);
  44360. delete dw;
  44361. }
  44362. }
  44363. }
  44364. resized();
  44365. const Array <Component*> tempComps (components);
  44366. components.clear();
  44367. for (int i = 0; i < tempComps.size(); ++i)
  44368. {
  44369. Component* const c = tempComps.getUnchecked(i);
  44370. addDocument (c,
  44371. c->getComponentPropertyColour (T("mdiDocumentBkg_"), false, Colours::white),
  44372. shouldDeleteComp (c));
  44373. }
  44374. }
  44375. }
  44376. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  44377. {
  44378. if (backgroundColour != newBackgroundColour)
  44379. {
  44380. backgroundColour = newBackgroundColour;
  44381. setOpaque (newBackgroundColour.isOpaque());
  44382. repaint();
  44383. }
  44384. }
  44385. void MultiDocumentPanel::paint (Graphics& g)
  44386. {
  44387. g.fillAll (backgroundColour);
  44388. }
  44389. void MultiDocumentPanel::resized()
  44390. {
  44391. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  44392. {
  44393. for (int i = getNumChildComponents(); --i >= 0;)
  44394. getChildComponent (i)->setBounds (0, 0, getWidth(), getHeight());
  44395. }
  44396. setWantsKeyboardFocus (components.size() == 0);
  44397. }
  44398. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  44399. {
  44400. if (mode == FloatingWindows)
  44401. {
  44402. for (int i = 0; i < getNumChildComponents(); ++i)
  44403. {
  44404. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44405. if (dw != 0 && dw->getContentComponent() == c)
  44406. {
  44407. c = dw;
  44408. break;
  44409. }
  44410. }
  44411. }
  44412. return c;
  44413. }
  44414. void MultiDocumentPanel::componentNameChanged (Component&)
  44415. {
  44416. if (mode == FloatingWindows)
  44417. {
  44418. for (int i = 0; i < getNumChildComponents(); ++i)
  44419. {
  44420. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44421. if (dw != 0)
  44422. dw->setName (dw->getContentComponent()->getName());
  44423. }
  44424. }
  44425. else if (tabComponent != 0)
  44426. {
  44427. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  44428. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  44429. }
  44430. }
  44431. void MultiDocumentPanel::updateOrder()
  44432. {
  44433. const Array <Component*> oldList (components);
  44434. if (mode == FloatingWindows)
  44435. {
  44436. components.clear();
  44437. for (int i = 0; i < getNumChildComponents(); ++i)
  44438. {
  44439. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44440. if (dw != 0)
  44441. components.add (dw->getContentComponent());
  44442. }
  44443. }
  44444. else
  44445. {
  44446. if (tabComponent != 0)
  44447. {
  44448. Component* const current = tabComponent->getCurrentContentComponent();
  44449. if (current != 0)
  44450. {
  44451. components.removeValue (current);
  44452. components.add (current);
  44453. }
  44454. }
  44455. }
  44456. if (components != oldList)
  44457. activeDocumentChanged();
  44458. }
  44459. END_JUCE_NAMESPACE
  44460. /********* End of inlined file: juce_MultiDocumentPanel.cpp *********/
  44461. /********* Start of inlined file: juce_ResizableBorderComponent.cpp *********/
  44462. BEGIN_JUCE_NAMESPACE
  44463. const int zoneL = 1;
  44464. const int zoneR = 2;
  44465. const int zoneT = 4;
  44466. const int zoneB = 8;
  44467. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  44468. ComponentBoundsConstrainer* const constrainer_)
  44469. : component (componentToResize),
  44470. constrainer (constrainer_),
  44471. borderSize (5),
  44472. mouseZone (0)
  44473. {
  44474. }
  44475. ResizableBorderComponent::~ResizableBorderComponent()
  44476. {
  44477. }
  44478. void ResizableBorderComponent::paint (Graphics& g)
  44479. {
  44480. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  44481. }
  44482. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  44483. {
  44484. updateMouseZone (e);
  44485. }
  44486. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  44487. {
  44488. updateMouseZone (e);
  44489. }
  44490. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  44491. {
  44492. if (component->isValidComponent())
  44493. {
  44494. updateMouseZone (e);
  44495. originalX = component->getX();
  44496. originalY = component->getY();
  44497. originalW = component->getWidth();
  44498. originalH = component->getHeight();
  44499. if (constrainer != 0)
  44500. constrainer->resizeStart();
  44501. }
  44502. else
  44503. {
  44504. jassertfalse
  44505. }
  44506. }
  44507. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  44508. {
  44509. if (! component->isValidComponent())
  44510. {
  44511. jassertfalse
  44512. return;
  44513. }
  44514. int x = originalX;
  44515. int y = originalY;
  44516. int w = originalW;
  44517. int h = originalH;
  44518. const int dx = e.getDistanceFromDragStartX();
  44519. const int dy = e.getDistanceFromDragStartY();
  44520. if ((mouseZone & zoneL) != 0)
  44521. {
  44522. x += dx;
  44523. w -= dx;
  44524. }
  44525. if ((mouseZone & zoneT) != 0)
  44526. {
  44527. y += dy;
  44528. h -= dy;
  44529. }
  44530. if ((mouseZone & zoneR) != 0)
  44531. w += dx;
  44532. if ((mouseZone & zoneB) != 0)
  44533. h += dy;
  44534. if (constrainer != 0)
  44535. constrainer->setBoundsForComponent (component,
  44536. x, y, w, h,
  44537. (mouseZone & zoneT) != 0,
  44538. (mouseZone & zoneL) != 0,
  44539. (mouseZone & zoneB) != 0,
  44540. (mouseZone & zoneR) != 0);
  44541. else
  44542. component->setBounds (x, y, w, h);
  44543. }
  44544. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  44545. {
  44546. if (constrainer != 0)
  44547. constrainer->resizeEnd();
  44548. }
  44549. bool ResizableBorderComponent::hitTest (int x, int y)
  44550. {
  44551. return x < borderSize.getLeft()
  44552. || x >= getWidth() - borderSize.getRight()
  44553. || y < borderSize.getTop()
  44554. || y >= getHeight() - borderSize.getBottom();
  44555. }
  44556. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize) throw()
  44557. {
  44558. if (borderSize != newBorderSize)
  44559. {
  44560. borderSize = newBorderSize;
  44561. repaint();
  44562. }
  44563. }
  44564. const BorderSize ResizableBorderComponent::getBorderThickness() const throw()
  44565. {
  44566. return borderSize;
  44567. }
  44568. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e) throw()
  44569. {
  44570. int newZone = 0;
  44571. if (ResizableBorderComponent::hitTest (e.x, e.y))
  44572. {
  44573. if (e.x < jmax (borderSize.getLeft(), proportionOfWidth (0.1f)))
  44574. newZone |= zoneL;
  44575. else if (e.x >= jmin (getWidth() - borderSize.getRight(), proportionOfWidth (0.9f)))
  44576. newZone |= zoneR;
  44577. if (e.y < jmax (borderSize.getTop(), proportionOfHeight (0.1f)))
  44578. newZone |= zoneT;
  44579. else if (e.y >= jmin (getHeight() - borderSize.getBottom(), proportionOfHeight (0.9f)))
  44580. newZone |= zoneB;
  44581. }
  44582. if (mouseZone != newZone)
  44583. {
  44584. mouseZone = newZone;
  44585. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  44586. switch (newZone)
  44587. {
  44588. case (zoneL | zoneT):
  44589. mc = MouseCursor::TopLeftCornerResizeCursor;
  44590. break;
  44591. case zoneT:
  44592. mc = MouseCursor::TopEdgeResizeCursor;
  44593. break;
  44594. case (zoneR | zoneT):
  44595. mc = MouseCursor::TopRightCornerResizeCursor;
  44596. break;
  44597. case zoneL:
  44598. mc = MouseCursor::LeftEdgeResizeCursor;
  44599. break;
  44600. case zoneR:
  44601. mc = MouseCursor::RightEdgeResizeCursor;
  44602. break;
  44603. case (zoneL | zoneB):
  44604. mc = MouseCursor::BottomLeftCornerResizeCursor;
  44605. break;
  44606. case zoneB:
  44607. mc = MouseCursor::BottomEdgeResizeCursor;
  44608. break;
  44609. case (zoneR | zoneB):
  44610. mc = MouseCursor::BottomRightCornerResizeCursor;
  44611. break;
  44612. default:
  44613. break;
  44614. }
  44615. setMouseCursor (mc);
  44616. }
  44617. }
  44618. END_JUCE_NAMESPACE
  44619. /********* End of inlined file: juce_ResizableBorderComponent.cpp *********/
  44620. /********* Start of inlined file: juce_ResizableCornerComponent.cpp *********/
  44621. BEGIN_JUCE_NAMESPACE
  44622. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  44623. ComponentBoundsConstrainer* const constrainer_)
  44624. : component (componentToResize),
  44625. constrainer (constrainer_)
  44626. {
  44627. setRepaintsOnMouseActivity (true);
  44628. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  44629. }
  44630. ResizableCornerComponent::~ResizableCornerComponent()
  44631. {
  44632. }
  44633. void ResizableCornerComponent::paint (Graphics& g)
  44634. {
  44635. getLookAndFeel()
  44636. .drawCornerResizer (g, getWidth(), getHeight(),
  44637. isMouseOverOrDragging(),
  44638. isMouseButtonDown());
  44639. }
  44640. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  44641. {
  44642. if (component->isValidComponent())
  44643. {
  44644. originalX = component->getX();
  44645. originalY = component->getY();
  44646. originalW = component->getWidth();
  44647. originalH = component->getHeight();
  44648. if (constrainer != 0)
  44649. constrainer->resizeStart();
  44650. }
  44651. else
  44652. {
  44653. jassertfalse
  44654. }
  44655. }
  44656. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  44657. {
  44658. if (! component->isValidComponent())
  44659. {
  44660. jassertfalse
  44661. return;
  44662. }
  44663. int x = originalX;
  44664. int y = originalY;
  44665. int w = originalW + e.getDistanceFromDragStartX();
  44666. int h = originalH + e.getDistanceFromDragStartY();
  44667. if (constrainer != 0)
  44668. constrainer->setBoundsForComponent (component, x, y, w, h,
  44669. false, false, true, true);
  44670. else
  44671. component->setBounds (x, y, w, h);
  44672. }
  44673. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  44674. {
  44675. if (constrainer != 0)
  44676. constrainer->resizeStart();
  44677. }
  44678. bool ResizableCornerComponent::hitTest (int x, int y)
  44679. {
  44680. if (getWidth() <= 0)
  44681. return false;
  44682. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  44683. return y >= yAtX - getHeight() / 4;
  44684. }
  44685. END_JUCE_NAMESPACE
  44686. /********* End of inlined file: juce_ResizableCornerComponent.cpp *********/
  44687. /********* Start of inlined file: juce_ScrollBar.cpp *********/
  44688. BEGIN_JUCE_NAMESPACE
  44689. class ScrollbarButton : public Button
  44690. {
  44691. public:
  44692. int direction;
  44693. ScrollbarButton (const int direction_,
  44694. ScrollBar& owner_) throw()
  44695. : Button (String::empty),
  44696. direction (direction_),
  44697. owner (owner_)
  44698. {
  44699. setWantsKeyboardFocus (false);
  44700. }
  44701. ~ScrollbarButton()
  44702. {
  44703. }
  44704. void paintButton (Graphics& g,
  44705. bool isMouseOver,
  44706. bool isMouseDown)
  44707. {
  44708. getLookAndFeel()
  44709. .drawScrollbarButton (g, owner,
  44710. getWidth(), getHeight(),
  44711. direction,
  44712. owner.isVertical(),
  44713. isMouseOver, isMouseDown);
  44714. }
  44715. void clicked()
  44716. {
  44717. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  44718. }
  44719. juce_UseDebuggingNewOperator
  44720. private:
  44721. ScrollBar& owner;
  44722. ScrollbarButton (const ScrollbarButton&);
  44723. const ScrollbarButton& operator= (const ScrollbarButton&);
  44724. };
  44725. ScrollBar::ScrollBar (const bool vertical_,
  44726. const bool buttonsAreVisible)
  44727. : minimum (0.0),
  44728. maximum (1.0),
  44729. rangeStart (0.0),
  44730. rangeSize (0.1),
  44731. singleStepSize (0.1),
  44732. thumbAreaStart (0),
  44733. thumbAreaSize (0),
  44734. thumbStart (0),
  44735. thumbSize (0),
  44736. initialDelayInMillisecs (100),
  44737. repeatDelayInMillisecs (50),
  44738. minimumDelayInMillisecs (10),
  44739. vertical (vertical_),
  44740. isDraggingThumb (false),
  44741. alwaysVisible (false),
  44742. upButton (0),
  44743. downButton (0),
  44744. listeners (2)
  44745. {
  44746. setButtonVisibility (buttonsAreVisible);
  44747. setRepaintsOnMouseActivity (true);
  44748. setFocusContainer (true);
  44749. }
  44750. ScrollBar::~ScrollBar()
  44751. {
  44752. deleteAllChildren();
  44753. }
  44754. void ScrollBar::setRangeLimits (const double newMinimum,
  44755. const double newMaximum) throw()
  44756. {
  44757. minimum = newMinimum;
  44758. maximum = newMaximum;
  44759. jassert (maximum >= minimum); // these can't be the wrong way round!
  44760. setCurrentRangeStart (rangeStart);
  44761. updateThumbPosition();
  44762. }
  44763. void ScrollBar::setCurrentRange (double newStart,
  44764. double newSize) throw()
  44765. {
  44766. newSize = jlimit (0.0, maximum - minimum, newSize);
  44767. newStart = jlimit (minimum, maximum - newSize, newStart);
  44768. if (rangeStart != newStart
  44769. || rangeSize != newSize)
  44770. {
  44771. rangeStart = newStart;
  44772. rangeSize = newSize;
  44773. updateThumbPosition();
  44774. triggerAsyncUpdate();
  44775. }
  44776. }
  44777. void ScrollBar::setCurrentRangeStart (double newStart) throw()
  44778. {
  44779. setCurrentRange (newStart, rangeSize);
  44780. }
  44781. void ScrollBar::setSingleStepSize (const double newSingleStepSize) throw()
  44782. {
  44783. singleStepSize = newSingleStepSize;
  44784. }
  44785. void ScrollBar::moveScrollbarInSteps (const int howManySteps) throw()
  44786. {
  44787. setCurrentRangeStart (rangeStart + howManySteps * singleStepSize);
  44788. }
  44789. void ScrollBar::moveScrollbarInPages (const int howManyPages) throw()
  44790. {
  44791. setCurrentRangeStart (rangeStart + howManyPages * rangeSize);
  44792. }
  44793. void ScrollBar::scrollToTop() throw()
  44794. {
  44795. setCurrentRangeStart (minimum);
  44796. }
  44797. void ScrollBar::scrollToBottom() throw()
  44798. {
  44799. setCurrentRangeStart (maximum - rangeSize);
  44800. }
  44801. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  44802. const int repeatDelayInMillisecs_,
  44803. const int minimumDelayInMillisecs_) throw()
  44804. {
  44805. initialDelayInMillisecs = initialDelayInMillisecs_;
  44806. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  44807. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  44808. if (upButton != 0)
  44809. {
  44810. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  44811. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  44812. }
  44813. }
  44814. void ScrollBar::addListener (ScrollBarListener* const listener) throw()
  44815. {
  44816. jassert (listener != 0);
  44817. if (listener != 0)
  44818. listeners.add (listener);
  44819. }
  44820. void ScrollBar::removeListener (ScrollBarListener* const listener) throw()
  44821. {
  44822. listeners.removeValue (listener);
  44823. }
  44824. void ScrollBar::handleAsyncUpdate()
  44825. {
  44826. const double value = getCurrentRangeStart();
  44827. for (int i = listeners.size(); --i >= 0;)
  44828. {
  44829. ((ScrollBarListener*) listeners.getUnchecked (i))->scrollBarMoved (this, value);
  44830. i = jmin (i, listeners.size());
  44831. }
  44832. }
  44833. void ScrollBar::updateThumbPosition() throw()
  44834. {
  44835. int newThumbSize = roundDoubleToInt ((maximum > minimum) ? (rangeSize * thumbAreaSize) / (maximum - minimum)
  44836. : thumbAreaSize);
  44837. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  44838. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  44839. if (newThumbSize > thumbAreaSize)
  44840. newThumbSize = thumbAreaSize;
  44841. int newThumbStart = thumbAreaStart;
  44842. if (maximum - minimum > rangeSize)
  44843. newThumbStart += roundDoubleToInt (((rangeStart - minimum) * (thumbAreaSize - newThumbSize))
  44844. / ((maximum - minimum) - rangeSize));
  44845. setVisible (alwaysVisible || (maximum - minimum > rangeSize && rangeSize > 0.0));
  44846. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  44847. {
  44848. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  44849. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  44850. if (vertical)
  44851. repaint (0, repaintStart, getWidth(), repaintSize);
  44852. else
  44853. repaint (repaintStart, 0, repaintSize, getHeight());
  44854. thumbStart = newThumbStart;
  44855. thumbSize = newThumbSize;
  44856. }
  44857. }
  44858. void ScrollBar::setOrientation (const bool shouldBeVertical) throw()
  44859. {
  44860. if (vertical != shouldBeVertical)
  44861. {
  44862. vertical = shouldBeVertical;
  44863. if (upButton != 0)
  44864. {
  44865. ((ScrollbarButton*) upButton)->direction = (vertical) ? 0 : 3;
  44866. ((ScrollbarButton*) downButton)->direction = (vertical) ? 2 : 1;
  44867. }
  44868. updateThumbPosition();
  44869. }
  44870. }
  44871. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  44872. {
  44873. deleteAndZero (upButton);
  44874. deleteAndZero (downButton);
  44875. if (buttonsAreVisible)
  44876. {
  44877. addAndMakeVisible (upButton = new ScrollbarButton ((vertical) ? 0 : 3, *this));
  44878. addAndMakeVisible (downButton = new ScrollbarButton ((vertical) ? 2 : 1, *this));
  44879. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  44880. }
  44881. updateThumbPosition();
  44882. }
  44883. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  44884. {
  44885. alwaysVisible = ! shouldHideWhenFullRange;
  44886. updateThumbPosition();
  44887. }
  44888. void ScrollBar::paint (Graphics& g)
  44889. {
  44890. if (thumbAreaSize > 0)
  44891. {
  44892. LookAndFeel& lf = getLookAndFeel();
  44893. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  44894. ? thumbSize : 0;
  44895. if (vertical)
  44896. {
  44897. lf.drawScrollbar (g, *this,
  44898. 0, thumbAreaStart,
  44899. getWidth(), thumbAreaSize,
  44900. vertical,
  44901. thumbStart, thumb,
  44902. isMouseOver(), isMouseButtonDown());
  44903. }
  44904. else
  44905. {
  44906. lf.drawScrollbar (g, *this,
  44907. thumbAreaStart, 0,
  44908. thumbAreaSize, getHeight(),
  44909. vertical,
  44910. thumbStart, thumb,
  44911. isMouseOver(), isMouseButtonDown());
  44912. }
  44913. }
  44914. }
  44915. void ScrollBar::lookAndFeelChanged()
  44916. {
  44917. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  44918. }
  44919. void ScrollBar::resized()
  44920. {
  44921. const int length = ((vertical) ? getHeight() : getWidth());
  44922. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  44923. : 0;
  44924. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  44925. {
  44926. thumbAreaStart = length >> 1;
  44927. thumbAreaSize = 0;
  44928. }
  44929. else
  44930. {
  44931. thumbAreaStart = buttonSize;
  44932. thumbAreaSize = length - (buttonSize << 1);
  44933. }
  44934. if (upButton != 0)
  44935. {
  44936. if (vertical)
  44937. {
  44938. upButton->setBounds (0, 0, getWidth(), buttonSize);
  44939. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  44940. }
  44941. else
  44942. {
  44943. upButton->setBounds (0, 0, buttonSize, getHeight());
  44944. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  44945. }
  44946. }
  44947. updateThumbPosition();
  44948. }
  44949. void ScrollBar::mouseDown (const MouseEvent& e)
  44950. {
  44951. isDraggingThumb = false;
  44952. lastMousePos = vertical ? e.y : e.x;
  44953. dragStartMousePos = lastMousePos;
  44954. dragStartRange = rangeStart;
  44955. if (dragStartMousePos < thumbStart)
  44956. {
  44957. moveScrollbarInPages (-1);
  44958. startTimer (400);
  44959. }
  44960. else if (dragStartMousePos >= thumbStart + thumbSize)
  44961. {
  44962. moveScrollbarInPages (1);
  44963. startTimer (400);
  44964. }
  44965. else
  44966. {
  44967. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  44968. && (thumbAreaSize > thumbSize);
  44969. }
  44970. }
  44971. void ScrollBar::mouseDrag (const MouseEvent& e)
  44972. {
  44973. if (isDraggingThumb)
  44974. {
  44975. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  44976. setCurrentRangeStart (dragStartRange
  44977. + deltaPixels * ((maximum - minimum) - rangeSize)
  44978. / (thumbAreaSize - thumbSize));
  44979. }
  44980. else
  44981. {
  44982. lastMousePos = (vertical) ? e.y : e.x;
  44983. }
  44984. }
  44985. void ScrollBar::mouseUp (const MouseEvent&)
  44986. {
  44987. isDraggingThumb = false;
  44988. stopTimer();
  44989. repaint();
  44990. }
  44991. void ScrollBar::mouseWheelMove (const MouseEvent&,
  44992. float wheelIncrementX,
  44993. float wheelIncrementY)
  44994. {
  44995. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  44996. if (increment < 0)
  44997. increment = jmin (increment * 10.0f, -1.0f);
  44998. else if (increment > 0)
  44999. increment = jmax (increment * 10.0f, 1.0f);
  45000. setCurrentRangeStart (rangeStart - singleStepSize * increment);
  45001. }
  45002. void ScrollBar::timerCallback()
  45003. {
  45004. if (isMouseButtonDown())
  45005. {
  45006. startTimer (40);
  45007. if (lastMousePos < thumbStart)
  45008. setCurrentRangeStart (rangeStart - rangeSize);
  45009. else if (lastMousePos > thumbStart + thumbSize)
  45010. setCurrentRangeStart (rangeStart + rangeSize);
  45011. }
  45012. else
  45013. {
  45014. stopTimer();
  45015. }
  45016. }
  45017. bool ScrollBar::keyPressed (const KeyPress& key)
  45018. {
  45019. if (! isVisible())
  45020. return false;
  45021. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  45022. moveScrollbarInSteps (-1);
  45023. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  45024. moveScrollbarInSteps (1);
  45025. else if (key.isKeyCode (KeyPress::pageUpKey))
  45026. moveScrollbarInPages (-1);
  45027. else if (key.isKeyCode (KeyPress::pageDownKey))
  45028. moveScrollbarInPages (1);
  45029. else if (key.isKeyCode (KeyPress::homeKey))
  45030. scrollToTop();
  45031. else if (key.isKeyCode (KeyPress::endKey))
  45032. scrollToBottom();
  45033. else
  45034. return false;
  45035. return true;
  45036. }
  45037. END_JUCE_NAMESPACE
  45038. /********* End of inlined file: juce_ScrollBar.cpp *********/
  45039. /********* Start of inlined file: juce_StretchableLayoutManager.cpp *********/
  45040. BEGIN_JUCE_NAMESPACE
  45041. StretchableLayoutManager::StretchableLayoutManager()
  45042. : totalSize (0)
  45043. {
  45044. }
  45045. StretchableLayoutManager::~StretchableLayoutManager()
  45046. {
  45047. }
  45048. void StretchableLayoutManager::clearAllItems()
  45049. {
  45050. items.clear();
  45051. totalSize = 0;
  45052. }
  45053. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  45054. const double minimumSize,
  45055. const double maximumSize,
  45056. const double preferredSize)
  45057. {
  45058. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  45059. if (layout == 0)
  45060. {
  45061. layout = new ItemLayoutProperties();
  45062. layout->itemIndex = itemIndex;
  45063. int i;
  45064. for (i = 0; i < items.size(); ++i)
  45065. if (items.getUnchecked (i)->itemIndex > itemIndex)
  45066. break;
  45067. items.insert (i, layout);
  45068. }
  45069. layout->minSize = minimumSize;
  45070. layout->maxSize = maximumSize;
  45071. layout->preferredSize = preferredSize;
  45072. layout->currentSize = 0;
  45073. }
  45074. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  45075. double& minimumSize,
  45076. double& maximumSize,
  45077. double& preferredSize) const
  45078. {
  45079. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  45080. if (layout != 0)
  45081. {
  45082. minimumSize = layout->minSize;
  45083. maximumSize = layout->maxSize;
  45084. preferredSize = layout->preferredSize;
  45085. return true;
  45086. }
  45087. return false;
  45088. }
  45089. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  45090. {
  45091. totalSize = newTotalSize;
  45092. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  45093. }
  45094. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  45095. {
  45096. int pos = 0;
  45097. for (int i = 0; i < itemIndex; ++i)
  45098. {
  45099. const ItemLayoutProperties* const layout = getInfoFor (i);
  45100. if (layout != 0)
  45101. pos += layout->currentSize;
  45102. }
  45103. return pos;
  45104. }
  45105. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  45106. {
  45107. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  45108. if (layout != 0)
  45109. return layout->currentSize;
  45110. return 0;
  45111. }
  45112. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  45113. {
  45114. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  45115. if (layout != 0)
  45116. return -layout->currentSize / (double) totalSize;
  45117. return 0;
  45118. }
  45119. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  45120. int newPosition)
  45121. {
  45122. for (int i = items.size(); --i >= 0;)
  45123. {
  45124. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  45125. if (layout->itemIndex == itemIndex)
  45126. {
  45127. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  45128. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  45129. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  45130. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  45131. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  45132. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  45133. endPos += layout->currentSize;
  45134. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  45135. updatePrefSizesToMatchCurrentPositions();
  45136. break;
  45137. }
  45138. }
  45139. }
  45140. void StretchableLayoutManager::layOutComponents (Component** const components,
  45141. int numComponents,
  45142. int x, int y, int w, int h,
  45143. const bool vertically,
  45144. const bool resizeOtherDimension)
  45145. {
  45146. setTotalSize (vertically ? h : w);
  45147. int pos = vertically ? y : x;
  45148. for (int i = 0; i < numComponents; ++i)
  45149. {
  45150. const ItemLayoutProperties* const layout = getInfoFor (i);
  45151. if (layout != 0)
  45152. {
  45153. Component* const c = components[i];
  45154. if (c != 0)
  45155. {
  45156. if (i == numComponents - 1)
  45157. {
  45158. // if it's the last item, crop it to exactly fit the available space..
  45159. if (resizeOtherDimension)
  45160. {
  45161. if (vertically)
  45162. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  45163. else
  45164. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  45165. }
  45166. else
  45167. {
  45168. if (vertically)
  45169. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  45170. else
  45171. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  45172. }
  45173. }
  45174. else
  45175. {
  45176. if (resizeOtherDimension)
  45177. {
  45178. if (vertically)
  45179. c->setBounds (x, pos, w, layout->currentSize);
  45180. else
  45181. c->setBounds (pos, y, layout->currentSize, h);
  45182. }
  45183. else
  45184. {
  45185. if (vertically)
  45186. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  45187. else
  45188. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  45189. }
  45190. }
  45191. }
  45192. pos += layout->currentSize;
  45193. }
  45194. }
  45195. }
  45196. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  45197. {
  45198. for (int i = items.size(); --i >= 0;)
  45199. if (items.getUnchecked(i)->itemIndex == itemIndex)
  45200. return items.getUnchecked(i);
  45201. return 0;
  45202. }
  45203. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  45204. const int endIndex,
  45205. const int availableSpace,
  45206. int startPos)
  45207. {
  45208. // calculate the total sizes
  45209. int i;
  45210. double totalIdealSize = 0.0;
  45211. int totalMinimums = 0;
  45212. for (i = startIndex; i < endIndex; ++i)
  45213. {
  45214. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45215. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  45216. totalMinimums += layout->currentSize;
  45217. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  45218. }
  45219. if (totalIdealSize <= 0)
  45220. totalIdealSize = 1.0;
  45221. // now calc the best sizes..
  45222. int extraSpace = availableSpace - totalMinimums;
  45223. while (extraSpace > 0)
  45224. {
  45225. int numWantingMoreSpace = 0;
  45226. int numHavingTakenExtraSpace = 0;
  45227. // first figure out how many comps want a slice of the extra space..
  45228. for (i = startIndex; i < endIndex; ++i)
  45229. {
  45230. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45231. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  45232. const int bestSize = jlimit (layout->currentSize,
  45233. jmax (layout->currentSize,
  45234. sizeToRealSize (layout->maxSize, totalSize)),
  45235. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  45236. if (bestSize > layout->currentSize)
  45237. ++numWantingMoreSpace;
  45238. }
  45239. // ..share out the extra space..
  45240. for (i = startIndex; i < endIndex; ++i)
  45241. {
  45242. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45243. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  45244. int bestSize = jlimit (layout->currentSize,
  45245. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  45246. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  45247. const int extraWanted = bestSize - layout->currentSize;
  45248. if (extraWanted > 0)
  45249. {
  45250. const int extraAllowed = jmin (extraWanted,
  45251. extraSpace / jmax (1, numWantingMoreSpace));
  45252. if (extraAllowed > 0)
  45253. {
  45254. ++numHavingTakenExtraSpace;
  45255. --numWantingMoreSpace;
  45256. layout->currentSize += extraAllowed;
  45257. extraSpace -= extraAllowed;
  45258. }
  45259. }
  45260. }
  45261. if (numHavingTakenExtraSpace <= 0)
  45262. break;
  45263. }
  45264. // ..and calculate the end position
  45265. for (i = startIndex; i < endIndex; ++i)
  45266. {
  45267. ItemLayoutProperties* const layout = items.getUnchecked(i);
  45268. startPos += layout->currentSize;
  45269. }
  45270. return startPos;
  45271. }
  45272. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  45273. const int endIndex) const
  45274. {
  45275. int totalMinimums = 0;
  45276. for (int i = startIndex; i < endIndex; ++i)
  45277. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  45278. return totalMinimums;
  45279. }
  45280. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  45281. {
  45282. int totalMaximums = 0;
  45283. for (int i = startIndex; i < endIndex; ++i)
  45284. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  45285. return totalMaximums;
  45286. }
  45287. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  45288. {
  45289. for (int i = 0; i < items.size(); ++i)
  45290. {
  45291. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45292. layout->preferredSize
  45293. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  45294. : getItemCurrentAbsoluteSize (i);
  45295. }
  45296. }
  45297. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  45298. {
  45299. if (size < 0)
  45300. size *= -totalSpace;
  45301. return roundDoubleToInt (size);
  45302. }
  45303. END_JUCE_NAMESPACE
  45304. /********* End of inlined file: juce_StretchableLayoutManager.cpp *********/
  45305. /********* Start of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  45306. BEGIN_JUCE_NAMESPACE
  45307. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  45308. const int itemIndex_,
  45309. const bool isVertical_)
  45310. : layout (layout_),
  45311. itemIndex (itemIndex_),
  45312. isVertical (isVertical_)
  45313. {
  45314. setRepaintsOnMouseActivity (true);
  45315. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  45316. : MouseCursor::UpDownResizeCursor));
  45317. }
  45318. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  45319. {
  45320. }
  45321. void StretchableLayoutResizerBar::paint (Graphics& g)
  45322. {
  45323. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  45324. getWidth(), getHeight(),
  45325. isVertical,
  45326. isMouseOver(),
  45327. isMouseButtonDown());
  45328. }
  45329. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  45330. {
  45331. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  45332. }
  45333. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  45334. {
  45335. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  45336. : e.getDistanceFromDragStartY());
  45337. layout->setItemPosition (itemIndex, desiredPos);
  45338. hasBeenMoved();
  45339. }
  45340. void StretchableLayoutResizerBar::hasBeenMoved()
  45341. {
  45342. if (getParentComponent() != 0)
  45343. getParentComponent()->resized();
  45344. }
  45345. END_JUCE_NAMESPACE
  45346. /********* End of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  45347. /********* Start of inlined file: juce_StretchableObjectResizer.cpp *********/
  45348. BEGIN_JUCE_NAMESPACE
  45349. StretchableObjectResizer::StretchableObjectResizer()
  45350. {
  45351. }
  45352. StretchableObjectResizer::~StretchableObjectResizer()
  45353. {
  45354. }
  45355. void StretchableObjectResizer::addItem (const double size,
  45356. const double minSize, const double maxSize,
  45357. const int order)
  45358. {
  45359. jassert (order >= 0 && order < INT_MAX); // the order must be >= 0 and less than INT_MAX
  45360. Item* const item = new Item();
  45361. item->size = size;
  45362. item->minSize = minSize;
  45363. item->maxSize = maxSize;
  45364. item->order = order;
  45365. items.add (item);
  45366. }
  45367. double StretchableObjectResizer::getItemSize (const int index) const throw()
  45368. {
  45369. const Item* const it = items [index];
  45370. return it != 0 ? it->size : 0;
  45371. }
  45372. void StretchableObjectResizer::resizeToFit (const double targetSize)
  45373. {
  45374. int order = 0;
  45375. for (;;)
  45376. {
  45377. double currentSize = 0;
  45378. double minSize = 0;
  45379. double maxSize = 0;
  45380. int nextHighestOrder = INT_MAX;
  45381. for (int i = 0; i < items.size(); ++i)
  45382. {
  45383. const Item* const it = items.getUnchecked(i);
  45384. currentSize += it->size;
  45385. if (it->order <= order)
  45386. {
  45387. minSize += it->minSize;
  45388. maxSize += it->maxSize;
  45389. }
  45390. else
  45391. {
  45392. minSize += it->size;
  45393. maxSize += it->size;
  45394. nextHighestOrder = jmin (nextHighestOrder, it->order);
  45395. }
  45396. }
  45397. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  45398. if (thisIterationTarget >= currentSize)
  45399. {
  45400. const double availableExtraSpace = maxSize - currentSize;
  45401. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  45402. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  45403. for (int i = 0; i < items.size(); ++i)
  45404. {
  45405. Item* const it = items.getUnchecked(i);
  45406. if (it->order <= order)
  45407. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  45408. }
  45409. }
  45410. else
  45411. {
  45412. const double amountOfSlack = currentSize - minSize;
  45413. const double targetAmountOfSlack = thisIterationTarget - minSize;
  45414. const double scale = targetAmountOfSlack / amountOfSlack;
  45415. for (int i = 0; i < items.size(); ++i)
  45416. {
  45417. Item* const it = items.getUnchecked(i);
  45418. if (it->order <= order)
  45419. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  45420. }
  45421. }
  45422. if (nextHighestOrder < INT_MAX)
  45423. order = nextHighestOrder;
  45424. else
  45425. break;
  45426. }
  45427. }
  45428. END_JUCE_NAMESPACE
  45429. /********* End of inlined file: juce_StretchableObjectResizer.cpp *********/
  45430. /********* Start of inlined file: juce_TabbedButtonBar.cpp *********/
  45431. BEGIN_JUCE_NAMESPACE
  45432. TabBarButton::TabBarButton (const String& name,
  45433. TabbedButtonBar* const owner_,
  45434. const int index)
  45435. : Button (name),
  45436. owner (owner_),
  45437. tabIndex (index),
  45438. overlapPixels (0)
  45439. {
  45440. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  45441. setComponentEffect (&shadow);
  45442. setWantsKeyboardFocus (false);
  45443. }
  45444. TabBarButton::~TabBarButton()
  45445. {
  45446. }
  45447. void TabBarButton::paintButton (Graphics& g,
  45448. bool isMouseOverButton,
  45449. bool isButtonDown)
  45450. {
  45451. int x, y, w, h;
  45452. getActiveArea (x, y, w, h);
  45453. g.setOrigin (x, y);
  45454. getLookAndFeel()
  45455. .drawTabButton (g, w, h,
  45456. owner->getTabBackgroundColour (tabIndex),
  45457. tabIndex, getButtonText(), *this,
  45458. owner->getOrientation(),
  45459. isMouseOverButton, isButtonDown,
  45460. getToggleState());
  45461. }
  45462. void TabBarButton::clicked (const ModifierKeys& mods)
  45463. {
  45464. if (mods.isPopupMenu())
  45465. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  45466. else
  45467. owner->setCurrentTabIndex (tabIndex);
  45468. }
  45469. bool TabBarButton::hitTest (int mx, int my)
  45470. {
  45471. int x, y, w, h;
  45472. getActiveArea (x, y, w, h);
  45473. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  45474. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  45475. {
  45476. if (((unsigned int) mx) < (unsigned int) getWidth()
  45477. && my >= y + overlapPixels
  45478. && my < y + h - overlapPixels)
  45479. return true;
  45480. }
  45481. else
  45482. {
  45483. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  45484. && ((unsigned int) my) < (unsigned int) getHeight())
  45485. return true;
  45486. }
  45487. Path p;
  45488. getLookAndFeel()
  45489. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  45490. owner->getOrientation(),
  45491. false, false, getToggleState());
  45492. return p.contains ((float) (mx - x),
  45493. (float) (my - y));
  45494. }
  45495. int TabBarButton::getBestTabLength (const int depth)
  45496. {
  45497. return jlimit (depth * 2,
  45498. depth * 7,
  45499. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  45500. }
  45501. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  45502. {
  45503. x = 0;
  45504. y = 0;
  45505. int r = getWidth();
  45506. int b = getHeight();
  45507. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  45508. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  45509. r -= spaceAroundImage;
  45510. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  45511. x += spaceAroundImage;
  45512. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  45513. y += spaceAroundImage;
  45514. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  45515. b -= spaceAroundImage;
  45516. w = r - x;
  45517. h = b - y;
  45518. }
  45519. class TabAreaBehindFrontButtonComponent : public Component
  45520. {
  45521. public:
  45522. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  45523. : owner (owner_)
  45524. {
  45525. setInterceptsMouseClicks (false, false);
  45526. }
  45527. ~TabAreaBehindFrontButtonComponent()
  45528. {
  45529. }
  45530. void paint (Graphics& g)
  45531. {
  45532. getLookAndFeel()
  45533. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  45534. *owner, owner->getOrientation());
  45535. }
  45536. void enablementChanged()
  45537. {
  45538. repaint();
  45539. }
  45540. private:
  45541. TabbedButtonBar* const owner;
  45542. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  45543. const TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  45544. };
  45545. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  45546. : orientation (orientation_),
  45547. currentTabIndex (-1),
  45548. extraTabsButton (0)
  45549. {
  45550. setInterceptsMouseClicks (false, true);
  45551. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  45552. setFocusContainer (true);
  45553. }
  45554. TabbedButtonBar::~TabbedButtonBar()
  45555. {
  45556. deleteAllChildren();
  45557. }
  45558. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  45559. {
  45560. orientation = newOrientation;
  45561. for (int i = getNumChildComponents(); --i >= 0;)
  45562. getChildComponent (i)->resized();
  45563. resized();
  45564. }
  45565. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  45566. {
  45567. return new TabBarButton (name, this, index);
  45568. }
  45569. void TabbedButtonBar::clearTabs()
  45570. {
  45571. tabs.clear();
  45572. tabColours.clear();
  45573. currentTabIndex = -1;
  45574. deleteAndZero (extraTabsButton);
  45575. removeChildComponent (behindFrontTab);
  45576. deleteAllChildren();
  45577. addChildComponent (behindFrontTab);
  45578. setCurrentTabIndex (-1);
  45579. }
  45580. void TabbedButtonBar::addTab (const String& tabName,
  45581. const Colour& tabBackgroundColour,
  45582. int insertIndex)
  45583. {
  45584. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  45585. if (tabName.isNotEmpty())
  45586. {
  45587. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  45588. insertIndex = tabs.size();
  45589. for (int i = tabs.size(); --i >= insertIndex;)
  45590. {
  45591. TabBarButton* const tb = getTabButton (i);
  45592. if (tb != 0)
  45593. tb->tabIndex++;
  45594. }
  45595. tabs.insert (insertIndex, tabName);
  45596. tabColours.insert (insertIndex, tabBackgroundColour);
  45597. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  45598. jassert (tb != 0); // your createTabButton() mustn't return zero!
  45599. addAndMakeVisible (tb, insertIndex);
  45600. resized();
  45601. if (currentTabIndex < 0)
  45602. setCurrentTabIndex (0);
  45603. }
  45604. }
  45605. void TabbedButtonBar::setTabName (const int tabIndex,
  45606. const String& newName)
  45607. {
  45608. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  45609. && tabs[tabIndex] != newName)
  45610. {
  45611. tabs.set (tabIndex, newName);
  45612. TabBarButton* const tb = getTabButton (tabIndex);
  45613. if (tb != 0)
  45614. tb->setButtonText (newName);
  45615. resized();
  45616. }
  45617. }
  45618. void TabbedButtonBar::removeTab (const int tabIndex)
  45619. {
  45620. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  45621. {
  45622. const int oldTabIndex = currentTabIndex;
  45623. if (currentTabIndex == tabIndex)
  45624. currentTabIndex = -1;
  45625. tabs.remove (tabIndex);
  45626. tabColours.remove (tabIndex);
  45627. TabBarButton* const tb = getTabButton (tabIndex);
  45628. if (tb != 0)
  45629. delete tb;
  45630. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  45631. {
  45632. TabBarButton* const tb = getTabButton (i);
  45633. if (tb != 0)
  45634. tb->tabIndex--;
  45635. }
  45636. resized();
  45637. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  45638. }
  45639. }
  45640. void TabbedButtonBar::moveTab (const int currentIndex,
  45641. const int newIndex)
  45642. {
  45643. tabs.move (currentIndex, newIndex);
  45644. tabColours.move (currentIndex, newIndex);
  45645. resized();
  45646. }
  45647. int TabbedButtonBar::getNumTabs() const
  45648. {
  45649. return tabs.size();
  45650. }
  45651. const StringArray TabbedButtonBar::getTabNames() const
  45652. {
  45653. return tabs;
  45654. }
  45655. void TabbedButtonBar::setCurrentTabIndex (int newIndex)
  45656. {
  45657. if (currentTabIndex != newIndex)
  45658. {
  45659. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  45660. newIndex = -1;
  45661. currentTabIndex = newIndex;
  45662. for (int i = 0; i < getNumChildComponents(); ++i)
  45663. {
  45664. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  45665. if (tb != 0)
  45666. tb->setToggleState (tb->tabIndex == newIndex, false);
  45667. }
  45668. resized();
  45669. sendChangeMessage (this);
  45670. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  45671. }
  45672. }
  45673. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  45674. {
  45675. for (int i = getNumChildComponents(); --i >= 0;)
  45676. {
  45677. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  45678. if (tb != 0 && tb->tabIndex == index)
  45679. return tb;
  45680. }
  45681. return 0;
  45682. }
  45683. void TabbedButtonBar::lookAndFeelChanged()
  45684. {
  45685. deleteAndZero (extraTabsButton);
  45686. resized();
  45687. }
  45688. void TabbedButtonBar::resized()
  45689. {
  45690. const double minimumScale = 0.7;
  45691. int depth = getWidth();
  45692. int length = getHeight();
  45693. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  45694. swapVariables (depth, length);
  45695. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  45696. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  45697. int i, totalLength = overlap;
  45698. int numVisibleButtons = tabs.size();
  45699. for (i = 0; i < getNumChildComponents(); ++i)
  45700. {
  45701. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  45702. if (tb != 0)
  45703. {
  45704. totalLength += tb->getBestTabLength (depth) - overlap;
  45705. tb->overlapPixels = overlap / 2;
  45706. }
  45707. }
  45708. double scale = 1.0;
  45709. if (totalLength > length)
  45710. scale = jmax (minimumScale, length / (double) totalLength);
  45711. const bool isTooBig = totalLength * scale > length;
  45712. int tabsButtonPos = 0;
  45713. if (isTooBig)
  45714. {
  45715. if (extraTabsButton == 0)
  45716. {
  45717. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  45718. extraTabsButton->addButtonListener (this);
  45719. extraTabsButton->setAlwaysOnTop (true);
  45720. extraTabsButton->setTriggeredOnMouseDown (true);
  45721. }
  45722. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  45723. extraTabsButton->setSize (buttonSize, buttonSize);
  45724. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  45725. {
  45726. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  45727. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  45728. }
  45729. else
  45730. {
  45731. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  45732. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  45733. }
  45734. totalLength = 0;
  45735. for (i = 0; i < tabs.size(); ++i)
  45736. {
  45737. TabBarButton* const tb = getTabButton (i);
  45738. if (tb != 0)
  45739. {
  45740. const int newLength = totalLength + tb->getBestTabLength (depth);
  45741. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  45742. {
  45743. totalLength += overlap;
  45744. break;
  45745. }
  45746. numVisibleButtons = i + 1;
  45747. totalLength = newLength - overlap;
  45748. }
  45749. }
  45750. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  45751. }
  45752. else
  45753. {
  45754. deleteAndZero (extraTabsButton);
  45755. }
  45756. int pos = 0;
  45757. TabBarButton* frontTab = 0;
  45758. for (i = 0; i < tabs.size(); ++i)
  45759. {
  45760. TabBarButton* const tb = getTabButton (i);
  45761. if (tb != 0)
  45762. {
  45763. const int bestLength = roundDoubleToInt (scale * tb->getBestTabLength (depth));
  45764. if (i < numVisibleButtons)
  45765. {
  45766. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  45767. tb->setBounds (pos, 0, bestLength, getHeight());
  45768. else
  45769. tb->setBounds (0, pos, getWidth(), bestLength);
  45770. tb->toBack();
  45771. if (tb->tabIndex == currentTabIndex)
  45772. frontTab = tb;
  45773. tb->setVisible (true);
  45774. }
  45775. else
  45776. {
  45777. tb->setVisible (false);
  45778. }
  45779. pos += bestLength - overlap;
  45780. }
  45781. }
  45782. behindFrontTab->setBounds (0, 0, getWidth(), getHeight());
  45783. if (frontTab != 0)
  45784. {
  45785. frontTab->toFront (false);
  45786. behindFrontTab->toBehind (frontTab);
  45787. }
  45788. }
  45789. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  45790. {
  45791. return tabColours [tabIndex];
  45792. }
  45793. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  45794. {
  45795. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  45796. && tabColours [tabIndex] != newColour)
  45797. {
  45798. tabColours.set (tabIndex, newColour);
  45799. repaint();
  45800. }
  45801. }
  45802. void TabbedButtonBar::buttonClicked (Button* button)
  45803. {
  45804. if (extraTabsButton == button)
  45805. {
  45806. PopupMenu m;
  45807. for (int i = 0; i < tabs.size(); ++i)
  45808. {
  45809. TabBarButton* const tb = getTabButton (i);
  45810. if (tb != 0 && ! tb->isVisible())
  45811. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  45812. }
  45813. const int res = m.showAt (extraTabsButton);
  45814. if (res != 0)
  45815. setCurrentTabIndex (res - 1);
  45816. }
  45817. }
  45818. void TabbedButtonBar::currentTabChanged (const int, const String&)
  45819. {
  45820. }
  45821. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  45822. {
  45823. }
  45824. END_JUCE_NAMESPACE
  45825. /********* End of inlined file: juce_TabbedButtonBar.cpp *********/
  45826. /********* Start of inlined file: juce_TabbedComponent.cpp *********/
  45827. BEGIN_JUCE_NAMESPACE
  45828. class TabCompButtonBar : public TabbedButtonBar
  45829. {
  45830. public:
  45831. TabCompButtonBar (TabbedComponent* const owner_,
  45832. const TabbedButtonBar::Orientation orientation)
  45833. : TabbedButtonBar (orientation),
  45834. owner (owner_)
  45835. {
  45836. }
  45837. ~TabCompButtonBar()
  45838. {
  45839. }
  45840. void currentTabChanged (const int newCurrentTabIndex,
  45841. const String& newTabName)
  45842. {
  45843. owner->changeCallback (newCurrentTabIndex, newTabName);
  45844. }
  45845. void popupMenuClickOnTab (const int tabIndex,
  45846. const String& tabName)
  45847. {
  45848. owner->popupMenuClickOnTab (tabIndex, tabName);
  45849. }
  45850. const Colour getTabBackgroundColour (const int tabIndex)
  45851. {
  45852. return owner->tabs->getTabBackgroundColour (tabIndex);
  45853. }
  45854. TabBarButton* createTabButton (const String& tabName, const int tabIndex)
  45855. {
  45856. return owner->createTabButton (tabName, tabIndex);
  45857. }
  45858. juce_UseDebuggingNewOperator
  45859. private:
  45860. TabbedComponent* const owner;
  45861. TabCompButtonBar (const TabCompButtonBar&);
  45862. const TabCompButtonBar& operator= (const TabCompButtonBar&);
  45863. };
  45864. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  45865. : panelComponent (0),
  45866. tabDepth (30),
  45867. outlineColour (Colours::grey),
  45868. outlineThickness (1),
  45869. edgeIndent (0)
  45870. {
  45871. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  45872. }
  45873. TabbedComponent::~TabbedComponent()
  45874. {
  45875. clearTabs();
  45876. delete tabs;
  45877. }
  45878. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  45879. {
  45880. tabs->setOrientation (orientation);
  45881. resized();
  45882. }
  45883. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  45884. {
  45885. return tabs->getOrientation();
  45886. }
  45887. void TabbedComponent::setTabBarDepth (const int newDepth)
  45888. {
  45889. if (tabDepth != newDepth)
  45890. {
  45891. tabDepth = newDepth;
  45892. resized();
  45893. }
  45894. }
  45895. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  45896. {
  45897. return new TabBarButton (tabName, tabs, tabIndex);
  45898. }
  45899. void TabbedComponent::clearTabs()
  45900. {
  45901. if (panelComponent != 0)
  45902. {
  45903. panelComponent->setVisible (false);
  45904. removeChildComponent (panelComponent);
  45905. panelComponent = 0;
  45906. }
  45907. tabs->clearTabs();
  45908. for (int i = contentComponents.size(); --i >= 0;)
  45909. {
  45910. Component* const c = contentComponents.getUnchecked(i);
  45911. // be careful not to delete these components until they've been removed from the tab component
  45912. jassert (c == 0 || c->isValidComponent());
  45913. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  45914. delete c;
  45915. }
  45916. contentComponents.clear();
  45917. }
  45918. void TabbedComponent::addTab (const String& tabName,
  45919. const Colour& tabBackgroundColour,
  45920. Component* const contentComponent,
  45921. const bool deleteComponentWhenNotNeeded,
  45922. const int insertIndex)
  45923. {
  45924. contentComponents.insert (insertIndex, contentComponent);
  45925. if (contentComponent != 0)
  45926. contentComponent->setComponentProperty (T("deleteByTabComp_"), deleteComponentWhenNotNeeded);
  45927. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  45928. }
  45929. void TabbedComponent::setTabName (const int tabIndex,
  45930. const String& newName)
  45931. {
  45932. tabs->setTabName (tabIndex, newName);
  45933. }
  45934. void TabbedComponent::removeTab (const int tabIndex)
  45935. {
  45936. Component* const c = contentComponents [tabIndex];
  45937. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  45938. {
  45939. if (c == panelComponent)
  45940. panelComponent = 0;
  45941. delete c;
  45942. }
  45943. contentComponents.remove (tabIndex);
  45944. tabs->removeTab (tabIndex);
  45945. }
  45946. int TabbedComponent::getNumTabs() const
  45947. {
  45948. return tabs->getNumTabs();
  45949. }
  45950. const StringArray TabbedComponent::getTabNames() const
  45951. {
  45952. return tabs->getTabNames();
  45953. }
  45954. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  45955. {
  45956. return contentComponents [tabIndex];
  45957. }
  45958. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  45959. {
  45960. return tabs->getTabBackgroundColour (tabIndex);
  45961. }
  45962. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  45963. {
  45964. tabs->setTabBackgroundColour (tabIndex, newColour);
  45965. if (getCurrentTabIndex() == tabIndex)
  45966. repaint();
  45967. }
  45968. void TabbedComponent::setCurrentTabIndex (const int newTabIndex)
  45969. {
  45970. tabs->setCurrentTabIndex (newTabIndex);
  45971. }
  45972. int TabbedComponent::getCurrentTabIndex() const
  45973. {
  45974. return tabs->getCurrentTabIndex();
  45975. }
  45976. const String& TabbedComponent::getCurrentTabName() const
  45977. {
  45978. return tabs->getCurrentTabName();
  45979. }
  45980. void TabbedComponent::setOutline (const Colour& colour, int thickness)
  45981. {
  45982. outlineColour = colour;
  45983. outlineThickness = thickness;
  45984. repaint();
  45985. }
  45986. void TabbedComponent::setIndent (const int indentThickness)
  45987. {
  45988. edgeIndent = indentThickness;
  45989. }
  45990. void TabbedComponent::paint (Graphics& g)
  45991. {
  45992. const TabbedButtonBar::Orientation o = getOrientation();
  45993. int x = 0;
  45994. int y = 0;
  45995. int r = getWidth();
  45996. int b = getHeight();
  45997. if (o == TabbedButtonBar::TabsAtTop)
  45998. y += tabDepth;
  45999. else if (o == TabbedButtonBar::TabsAtBottom)
  46000. b -= tabDepth;
  46001. else if (o == TabbedButtonBar::TabsAtLeft)
  46002. x += tabDepth;
  46003. else if (o == TabbedButtonBar::TabsAtRight)
  46004. r -= tabDepth;
  46005. g.reduceClipRegion (x, y, r - x, b - y);
  46006. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  46007. if (outlineThickness > 0)
  46008. {
  46009. if (o == TabbedButtonBar::TabsAtTop)
  46010. --y;
  46011. else if (o == TabbedButtonBar::TabsAtBottom)
  46012. ++b;
  46013. else if (o == TabbedButtonBar::TabsAtLeft)
  46014. --x;
  46015. else if (o == TabbedButtonBar::TabsAtRight)
  46016. ++r;
  46017. g.setColour (outlineColour);
  46018. g.drawRect (x, y, r - x, b - y, outlineThickness);
  46019. }
  46020. }
  46021. void TabbedComponent::resized()
  46022. {
  46023. const TabbedButtonBar::Orientation o = getOrientation();
  46024. const int indent = edgeIndent + outlineThickness;
  46025. BorderSize indents (indent);
  46026. if (o == TabbedButtonBar::TabsAtTop)
  46027. {
  46028. tabs->setBounds (0, 0, getWidth(), tabDepth);
  46029. indents.setTop (tabDepth + edgeIndent);
  46030. }
  46031. else if (o == TabbedButtonBar::TabsAtBottom)
  46032. {
  46033. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  46034. indents.setBottom (tabDepth + edgeIndent);
  46035. }
  46036. else if (o == TabbedButtonBar::TabsAtLeft)
  46037. {
  46038. tabs->setBounds (0, 0, tabDepth, getHeight());
  46039. indents.setLeft (tabDepth + edgeIndent);
  46040. }
  46041. else if (o == TabbedButtonBar::TabsAtRight)
  46042. {
  46043. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  46044. indents.setRight (tabDepth + edgeIndent);
  46045. }
  46046. const Rectangle bounds (indents.subtractedFrom (Rectangle (0, 0, getWidth(), getHeight())));
  46047. for (int i = contentComponents.size(); --i >= 0;)
  46048. if (contentComponents.getUnchecked (i) != 0)
  46049. contentComponents.getUnchecked (i)->setBounds (bounds);
  46050. }
  46051. void TabbedComponent::lookAndFeelChanged()
  46052. {
  46053. for (int i = contentComponents.size(); --i >= 0;)
  46054. if (contentComponents.getUnchecked (i) != 0)
  46055. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  46056. }
  46057. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  46058. const String& newTabName)
  46059. {
  46060. if (panelComponent != 0)
  46061. {
  46062. panelComponent->setVisible (false);
  46063. removeChildComponent (panelComponent);
  46064. panelComponent = 0;
  46065. }
  46066. if (getCurrentTabIndex() >= 0)
  46067. {
  46068. panelComponent = contentComponents [getCurrentTabIndex()];
  46069. if (panelComponent != 0)
  46070. {
  46071. // do these ops as two stages instead of addAndMakeVisible() so that the
  46072. // component has always got a parent when it gets the visibilityChanged() callback
  46073. addChildComponent (panelComponent);
  46074. panelComponent->setVisible (true);
  46075. panelComponent->toFront (true);
  46076. }
  46077. repaint();
  46078. }
  46079. resized();
  46080. currentTabChanged (newCurrentTabIndex, newTabName);
  46081. }
  46082. void TabbedComponent::currentTabChanged (const int, const String&)
  46083. {
  46084. }
  46085. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  46086. {
  46087. }
  46088. END_JUCE_NAMESPACE
  46089. /********* End of inlined file: juce_TabbedComponent.cpp *********/
  46090. /********* Start of inlined file: juce_Viewport.cpp *********/
  46091. BEGIN_JUCE_NAMESPACE
  46092. Viewport::Viewport (const String& componentName)
  46093. : Component (componentName),
  46094. contentComp (0),
  46095. lastVX (0),
  46096. lastVY (0),
  46097. lastVW (0),
  46098. lastVH (0),
  46099. scrollBarThickness (0),
  46100. singleStepX (16),
  46101. singleStepY (16),
  46102. showHScrollbar (true),
  46103. showVScrollbar (true)
  46104. {
  46105. // content holder is used to clip the contents so they don't overlap the scrollbars
  46106. addAndMakeVisible (contentHolder = new Component());
  46107. contentHolder->setInterceptsMouseClicks (false, true);
  46108. verticalScrollBar = new ScrollBar (true);
  46109. horizontalScrollBar = new ScrollBar (false);
  46110. addChildComponent (verticalScrollBar);
  46111. addChildComponent (horizontalScrollBar);
  46112. verticalScrollBar->addListener (this);
  46113. horizontalScrollBar->addListener (this);
  46114. setInterceptsMouseClicks (false, true);
  46115. setWantsKeyboardFocus (true);
  46116. }
  46117. Viewport::~Viewport()
  46118. {
  46119. contentHolder->deleteAllChildren();
  46120. deleteAllChildren();
  46121. }
  46122. void Viewport::visibleAreaChanged (int, int, int, int)
  46123. {
  46124. }
  46125. void Viewport::setViewedComponent (Component* const newViewedComponent)
  46126. {
  46127. if (contentComp != newViewedComponent)
  46128. {
  46129. if (contentComp->isValidComponent())
  46130. {
  46131. Component* const oldComp = contentComp;
  46132. contentComp = 0;
  46133. delete oldComp;
  46134. }
  46135. contentComp = newViewedComponent;
  46136. if (contentComp != 0)
  46137. {
  46138. contentComp->setTopLeftPosition (0, 0);
  46139. contentHolder->addAndMakeVisible (contentComp);
  46140. contentComp->addComponentListener (this);
  46141. }
  46142. updateVisibleRegion();
  46143. }
  46144. }
  46145. int Viewport::getMaximumVisibleWidth() const throw()
  46146. {
  46147. return jmax (0, getWidth() - (verticalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  46148. }
  46149. int Viewport::getMaximumVisibleHeight() const throw()
  46150. {
  46151. return jmax (0, getHeight() - (horizontalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  46152. }
  46153. void Viewport::setViewPosition (const int xPixelsOffset,
  46154. const int yPixelsOffset)
  46155. {
  46156. if (contentComp != 0)
  46157. contentComp->setTopLeftPosition (-xPixelsOffset,
  46158. -yPixelsOffset);
  46159. }
  46160. void Viewport::setViewPositionProportionately (const double x,
  46161. const double y)
  46162. {
  46163. if (contentComp != 0)
  46164. setViewPosition (jmax (0, roundDoubleToInt (x * (contentComp->getWidth() - getWidth()))),
  46165. jmax (0, roundDoubleToInt (y * (contentComp->getHeight() - getHeight()))));
  46166. }
  46167. void Viewport::componentMovedOrResized (Component&, bool, bool)
  46168. {
  46169. updateVisibleRegion();
  46170. }
  46171. void Viewport::resized()
  46172. {
  46173. updateVisibleRegion();
  46174. }
  46175. void Viewport::updateVisibleRegion()
  46176. {
  46177. if (contentComp != 0)
  46178. {
  46179. const int newVX = -contentComp->getX();
  46180. const int newVY = -contentComp->getY();
  46181. if (newVX == 0 && newVY == 0
  46182. && contentComp->getWidth() <= getWidth()
  46183. && contentComp->getHeight() <= getHeight())
  46184. {
  46185. horizontalScrollBar->setVisible (false);
  46186. verticalScrollBar->setVisible (false);
  46187. }
  46188. if ((contentComp->getWidth() > 0) && showHScrollbar
  46189. && getHeight() > getScrollBarThickness())
  46190. {
  46191. horizontalScrollBar->setRangeLimits (0.0, contentComp->getWidth());
  46192. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  46193. horizontalScrollBar->setSingleStepSize (singleStepX);
  46194. }
  46195. else
  46196. {
  46197. horizontalScrollBar->setVisible (false);
  46198. }
  46199. if ((contentComp->getHeight() > 0) && showVScrollbar
  46200. && getWidth() > getScrollBarThickness())
  46201. {
  46202. verticalScrollBar->setRangeLimits (0.0, contentComp->getHeight());
  46203. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  46204. verticalScrollBar->setSingleStepSize (singleStepY);
  46205. }
  46206. else
  46207. {
  46208. verticalScrollBar->setVisible (false);
  46209. }
  46210. if (verticalScrollBar->isVisible())
  46211. {
  46212. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  46213. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  46214. verticalScrollBar
  46215. ->setBounds (getMaximumVisibleWidth(), 0,
  46216. getScrollBarThickness(), getMaximumVisibleHeight());
  46217. }
  46218. if (horizontalScrollBar->isVisible())
  46219. {
  46220. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  46221. horizontalScrollBar
  46222. ->setBounds (0, getMaximumVisibleHeight(),
  46223. getMaximumVisibleWidth(), getScrollBarThickness());
  46224. }
  46225. contentHolder->setSize (getMaximumVisibleWidth(),
  46226. getMaximumVisibleHeight());
  46227. const int newVW = jmin (contentComp->getRight(), getMaximumVisibleWidth());
  46228. const int newVH = jmin (contentComp->getBottom(), getMaximumVisibleHeight());
  46229. if (newVX != lastVX
  46230. || newVY != lastVY
  46231. || newVW != lastVW
  46232. || newVH != lastVH)
  46233. {
  46234. lastVX = newVX;
  46235. lastVY = newVY;
  46236. lastVW = newVW;
  46237. lastVH = newVH;
  46238. visibleAreaChanged (newVX, newVY, newVW, newVH);
  46239. }
  46240. horizontalScrollBar->handleUpdateNowIfNeeded();
  46241. verticalScrollBar->handleUpdateNowIfNeeded();
  46242. }
  46243. else
  46244. {
  46245. horizontalScrollBar->setVisible (false);
  46246. verticalScrollBar->setVisible (false);
  46247. }
  46248. }
  46249. void Viewport::setSingleStepSizes (const int stepX,
  46250. const int stepY)
  46251. {
  46252. singleStepX = stepX;
  46253. singleStepY = stepY;
  46254. updateVisibleRegion();
  46255. }
  46256. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  46257. const bool showHorizontalScrollbarIfNeeded)
  46258. {
  46259. showVScrollbar = showVerticalScrollbarIfNeeded;
  46260. showHScrollbar = showHorizontalScrollbarIfNeeded;
  46261. updateVisibleRegion();
  46262. }
  46263. void Viewport::setScrollBarThickness (const int thickness)
  46264. {
  46265. scrollBarThickness = thickness;
  46266. updateVisibleRegion();
  46267. }
  46268. int Viewport::getScrollBarThickness() const throw()
  46269. {
  46270. return (scrollBarThickness > 0) ? scrollBarThickness
  46271. : getLookAndFeel().getDefaultScrollbarWidth();
  46272. }
  46273. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  46274. {
  46275. verticalScrollBar->setButtonVisibility (buttonsVisible);
  46276. horizontalScrollBar->setButtonVisibility (buttonsVisible);
  46277. }
  46278. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart)
  46279. {
  46280. if (scrollBarThatHasMoved == horizontalScrollBar)
  46281. {
  46282. setViewPosition (roundDoubleToInt (newRangeStart), getViewPositionY());
  46283. }
  46284. else if (scrollBarThatHasMoved == verticalScrollBar)
  46285. {
  46286. setViewPosition (getViewPositionX(), roundDoubleToInt (newRangeStart));
  46287. }
  46288. }
  46289. void Viewport::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  46290. {
  46291. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  46292. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  46293. }
  46294. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  46295. {
  46296. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  46297. {
  46298. const bool hasVertBar = verticalScrollBar->isVisible();
  46299. const bool hasHorzBar = horizontalScrollBar->isVisible();
  46300. if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  46301. {
  46302. horizontalScrollBar->mouseWheelMove (e.getEventRelativeTo (horizontalScrollBar),
  46303. wheelIncrementX, wheelIncrementY);
  46304. return true;
  46305. }
  46306. else if (hasVertBar && wheelIncrementY != 0)
  46307. {
  46308. verticalScrollBar->mouseWheelMove (e.getEventRelativeTo (verticalScrollBar),
  46309. wheelIncrementX, wheelIncrementY);
  46310. return true;
  46311. }
  46312. }
  46313. return false;
  46314. }
  46315. bool Viewport::keyPressed (const KeyPress& key)
  46316. {
  46317. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  46318. || key.isKeyCode (KeyPress::downKey)
  46319. || key.isKeyCode (KeyPress::pageUpKey)
  46320. || key.isKeyCode (KeyPress::pageDownKey)
  46321. || key.isKeyCode (KeyPress::homeKey)
  46322. || key.isKeyCode (KeyPress::endKey);
  46323. if (verticalScrollBar->isVisible() && isUpDownKey)
  46324. return verticalScrollBar->keyPressed (key);
  46325. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  46326. || key.isKeyCode (KeyPress::rightKey);
  46327. if (horizontalScrollBar->isVisible() && (isUpDownKey || isLeftRightKey))
  46328. return horizontalScrollBar->keyPressed (key);
  46329. return false;
  46330. }
  46331. END_JUCE_NAMESPACE
  46332. /********* End of inlined file: juce_Viewport.cpp *********/
  46333. /********* Start of inlined file: juce_LookAndFeel.cpp *********/
  46334. BEGIN_JUCE_NAMESPACE
  46335. static const Colour createBaseColour (const Colour& buttonColour,
  46336. const bool hasKeyboardFocus,
  46337. const bool isMouseOverButton,
  46338. const bool isButtonDown) throw()
  46339. {
  46340. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  46341. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  46342. if (isButtonDown)
  46343. return baseColour.contrasting (0.2f);
  46344. else if (isMouseOverButton)
  46345. return baseColour.contrasting (0.1f);
  46346. return baseColour;
  46347. }
  46348. LookAndFeel::LookAndFeel()
  46349. {
  46350. /* if this fails it means you're trying to create a LookAndFeel object before
  46351. the static Colours have been initialised. That ain't gonna work. It probably
  46352. means that you're using a static LookAndFeel object and that your compiler has
  46353. decided to intialise it before the Colours class.
  46354. */
  46355. jassert (Colours::white == Colour (0xffffffff));
  46356. // set up the standard set of colours..
  46357. #define textButtonColour 0xffbbbbff
  46358. #define textHighlightColour 0x401111ee
  46359. #define standardOutlineColour 0xb2808080
  46360. static const int standardColours[] =
  46361. {
  46362. TextButton::buttonColourId, textButtonColour,
  46363. TextButton::buttonOnColourId, 0xff4444ff,
  46364. TextButton::textColourId, 0xff000000,
  46365. ComboBox::buttonColourId, 0xffbbbbff,
  46366. ComboBox::outlineColourId, standardOutlineColour,
  46367. ToggleButton::textColourId, 0xff000000,
  46368. TextEditor::backgroundColourId, 0xffffffff,
  46369. TextEditor::textColourId, 0xff000000,
  46370. TextEditor::highlightColourId, textHighlightColour,
  46371. TextEditor::highlightedTextColourId, 0xff000000,
  46372. TextEditor::caretColourId, 0xff000000,
  46373. TextEditor::outlineColourId, 0x00000000,
  46374. TextEditor::focusedOutlineColourId, textButtonColour,
  46375. TextEditor::shadowColourId, 0x38000000,
  46376. Label::backgroundColourId, 0x00000000,
  46377. Label::textColourId, 0xff000000,
  46378. Label::outlineColourId, 0x00000000,
  46379. ScrollBar::backgroundColourId, 0x00000000,
  46380. ScrollBar::thumbColourId, 0xffffffff,
  46381. ScrollBar::trackColourId, 0xffffffff,
  46382. TreeView::linesColourId, 0x4c000000,
  46383. TreeView::backgroundColourId, 0x00000000,
  46384. PopupMenu::backgroundColourId, 0xffffffff,
  46385. PopupMenu::textColourId, 0xff000000,
  46386. PopupMenu::headerTextColourId, 0xff000000,
  46387. PopupMenu::highlightedTextColourId, 0xffffffff,
  46388. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  46389. ComboBox::textColourId, 0xff000000,
  46390. ComboBox::backgroundColourId, 0xffffffff,
  46391. ComboBox::arrowColourId, 0x99000000,
  46392. ListBox::backgroundColourId, 0xffffffff,
  46393. ListBox::outlineColourId, standardOutlineColour,
  46394. ListBox::textColourId, 0xff000000,
  46395. Slider::backgroundColourId, 0x00000000,
  46396. Slider::thumbColourId, textButtonColour,
  46397. Slider::trackColourId, 0x7fffffff,
  46398. Slider::rotarySliderFillColourId, 0x7f0000ff,
  46399. Slider::rotarySliderOutlineColourId, 0x66000000,
  46400. Slider::textBoxTextColourId, 0xff000000,
  46401. Slider::textBoxBackgroundColourId, 0xffffffff,
  46402. Slider::textBoxHighlightColourId, textHighlightColour,
  46403. Slider::textBoxOutlineColourId, standardOutlineColour,
  46404. AlertWindow::backgroundColourId, 0xffededed,
  46405. AlertWindow::textColourId, 0xff000000,
  46406. AlertWindow::outlineColourId, 0xff666666,
  46407. ProgressBar::backgroundColourId, 0xffeeeeee,
  46408. ProgressBar::foregroundColourId, 0xffaaaaee,
  46409. TooltipWindow::backgroundColourId, 0xffeeeebb,
  46410. TooltipWindow::textColourId, 0xff000000,
  46411. TooltipWindow::outlineColourId, 0x4c000000,
  46412. Toolbar::backgroundColourId, 0xfff6f8f9,
  46413. Toolbar::separatorColourId, 0x4c000000,
  46414. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  46415. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  46416. Toolbar::labelTextColourId, 0xff000000,
  46417. Toolbar::editingModeOutlineColourId, 0xffff0000,
  46418. HyperlinkButton::textColourId, 0xcc1111ee,
  46419. GroupComponent::outlineColourId, 0x66000000,
  46420. GroupComponent::textColourId, 0xff000000,
  46421. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  46422. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  46423. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  46424. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  46425. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  46426. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  46427. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  46428. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  46429. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  46430. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  46431. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  46432. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  46433. ColourSelector::backgroundColourId, 0xffe5e5e5,
  46434. ColourSelector::labelTextColourId, 0xff000000,
  46435. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  46436. };
  46437. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  46438. setColour (standardColours [i], Colour (standardColours [i + 1]));
  46439. }
  46440. LookAndFeel::~LookAndFeel()
  46441. {
  46442. }
  46443. const Colour LookAndFeel::findColour (const int colourId) const throw()
  46444. {
  46445. const int index = colourIds.indexOf (colourId);
  46446. if (index >= 0)
  46447. return colours [index];
  46448. jassertfalse
  46449. return Colours::black;
  46450. }
  46451. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  46452. {
  46453. const int index = colourIds.indexOf (colourId);
  46454. if (index >= 0)
  46455. colours.set (index, colour);
  46456. colourIds.add (colourId);
  46457. colours.add (colour);
  46458. }
  46459. static LookAndFeel* defaultLF = 0;
  46460. static LookAndFeel* currentDefaultLF = 0;
  46461. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  46462. {
  46463. // if this happens, your app hasn't initialised itself properly.. if you're
  46464. // trying to hack your own main() function, have a look at
  46465. // JUCEApplication::initialiseForGUI()
  46466. jassert (currentDefaultLF != 0);
  46467. return *currentDefaultLF;
  46468. }
  46469. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  46470. {
  46471. if (newDefaultLookAndFeel == 0)
  46472. {
  46473. if (defaultLF == 0)
  46474. defaultLF = new LookAndFeel();
  46475. newDefaultLookAndFeel = defaultLF;
  46476. }
  46477. currentDefaultLF = newDefaultLookAndFeel;
  46478. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  46479. {
  46480. Component* const c = Desktop::getInstance().getComponent (i);
  46481. if (c != 0)
  46482. c->sendLookAndFeelChange();
  46483. }
  46484. }
  46485. void LookAndFeel::clearDefaultLookAndFeel() throw()
  46486. {
  46487. if (currentDefaultLF == defaultLF)
  46488. currentDefaultLF = 0;
  46489. deleteAndZero (defaultLF);
  46490. }
  46491. void LookAndFeel::drawButtonBackground (Graphics& g,
  46492. Button& button,
  46493. const Colour& backgroundColour,
  46494. bool isMouseOverButton,
  46495. bool isButtonDown)
  46496. {
  46497. const int width = button.getWidth();
  46498. const int height = button.getHeight();
  46499. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  46500. const float halfThickness = outlineThickness * 0.5f;
  46501. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  46502. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  46503. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  46504. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  46505. const Colour baseColour (createBaseColour (backgroundColour,
  46506. button.hasKeyboardFocus (true),
  46507. isMouseOverButton, isButtonDown)
  46508. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  46509. drawGlassLozenge (g,
  46510. indentL,
  46511. indentT,
  46512. width - indentL - indentR,
  46513. height - indentT - indentB,
  46514. baseColour, outlineThickness, -1.0f,
  46515. button.isConnectedOnLeft(),
  46516. button.isConnectedOnRight(),
  46517. button.isConnectedOnTop(),
  46518. button.isConnectedOnBottom());
  46519. }
  46520. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  46521. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  46522. {
  46523. g.setFont (button.getFont());
  46524. g.setColour (button.findColour (TextButton::textColourId)
  46525. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  46526. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  46527. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  46528. const int fontHeight = roundFloatToInt (g.getCurrentFont().getHeight() * 0.6f);
  46529. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  46530. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  46531. g.drawFittedText (button.getButtonText(),
  46532. leftIndent,
  46533. yIndent,
  46534. button.getWidth() - leftIndent - rightIndent,
  46535. button.getHeight() - yIndent * 2,
  46536. Justification::centred, 2);
  46537. }
  46538. void LookAndFeel::drawTickBox (Graphics& g,
  46539. Component& component,
  46540. int x, int y, int w, int h,
  46541. const bool ticked,
  46542. const bool isEnabled,
  46543. const bool isMouseOverButton,
  46544. const bool isButtonDown)
  46545. {
  46546. const float boxSize = w * 0.7f;
  46547. drawGlassSphere (g, (float) x, y + (h - boxSize) * 0.5f, boxSize,
  46548. createBaseColour (component.findColour (TextButton::buttonColourId)
  46549. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  46550. true,
  46551. isMouseOverButton,
  46552. isButtonDown),
  46553. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  46554. if (ticked)
  46555. {
  46556. Path tick;
  46557. tick.startNewSubPath (1.5f, 3.0f);
  46558. tick.lineTo (3.0f, 6.0f);
  46559. tick.lineTo (6.0f, 0.0f);
  46560. g.setColour (isEnabled ? Colours::black : Colours::grey);
  46561. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  46562. .translated ((float) x, (float) y));
  46563. g.strokePath (tick, PathStrokeType (2.5f), trans);
  46564. }
  46565. }
  46566. void LookAndFeel::drawToggleButton (Graphics& g,
  46567. ToggleButton& button,
  46568. bool isMouseOverButton,
  46569. bool isButtonDown)
  46570. {
  46571. if (button.hasKeyboardFocus (true))
  46572. {
  46573. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  46574. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  46575. }
  46576. const int tickWidth = jmin (20, button.getHeight() - 4);
  46577. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  46578. tickWidth, tickWidth,
  46579. button.getToggleState(),
  46580. button.isEnabled(),
  46581. isMouseOverButton,
  46582. isButtonDown);
  46583. g.setColour (button.findColour (ToggleButton::textColourId));
  46584. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  46585. if (! button.isEnabled())
  46586. g.setOpacity (0.5f);
  46587. const int textX = tickWidth + 5;
  46588. g.drawFittedText (button.getButtonText(),
  46589. textX, 4,
  46590. button.getWidth() - textX - 2, button.getHeight() - 8,
  46591. Justification::centredLeft, 10);
  46592. }
  46593. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  46594. {
  46595. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  46596. const int tickWidth = jmin (24, button.getHeight());
  46597. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  46598. button.getHeight());
  46599. }
  46600. void LookAndFeel::drawAlertBox (Graphics& g,
  46601. AlertWindow& alert,
  46602. const Rectangle& textArea,
  46603. TextLayout& textLayout)
  46604. {
  46605. const int iconWidth = 80;
  46606. const Colour background (alert.findColour (AlertWindow::backgroundColourId));
  46607. g.fillAll (background);
  46608. int iconSpaceUsed = 0;
  46609. Justification alignment (Justification::horizontallyCentred);
  46610. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  46611. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  46612. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  46613. const Rectangle iconRect (iconSize / -10,
  46614. iconSize / -10,
  46615. iconSize,
  46616. iconSize);
  46617. if (alert.getAlertType() == AlertWindow::QuestionIcon
  46618. || alert.getAlertType() == AlertWindow::InfoIcon)
  46619. {
  46620. if (alert.getAlertType() == AlertWindow::InfoIcon)
  46621. g.setColour (background.overlaidWith (Colour (0x280000ff)));
  46622. else
  46623. g.setColour (background.overlaidWith (Colours::gold.darker().withAlpha (0.25f)));
  46624. g.fillEllipse ((float) iconRect.getX(),
  46625. (float) iconRect.getY(),
  46626. (float) iconRect.getWidth(),
  46627. (float) iconRect.getHeight());
  46628. g.setColour (background);
  46629. g.setFont (iconRect.getHeight() * 0.9f, Font::bold);
  46630. g.drawText ((alert.getAlertType() == AlertWindow::InfoIcon) ? "i"
  46631. : "?",
  46632. iconRect.getX(),
  46633. iconRect.getY(),
  46634. iconRect.getWidth(),
  46635. iconRect.getHeight(),
  46636. Justification::centred, false);
  46637. iconSpaceUsed = iconWidth;
  46638. alignment = Justification::left;
  46639. }
  46640. else if (alert.getAlertType() == AlertWindow::WarningIcon)
  46641. {
  46642. Path p;
  46643. p.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f,
  46644. (float) iconRect.getY(),
  46645. (float) iconRect.getRight(),
  46646. (float) iconRect.getBottom(),
  46647. (float) iconRect.getX(),
  46648. (float) iconRect.getBottom());
  46649. g.setColour (background.overlaidWith (Colour (0x33ff0000)));
  46650. g.fillPath (p.createPathWithRoundedCorners (5.0f));
  46651. g.setColour (background);
  46652. g.setFont (iconRect.getHeight() * 0.9f, Font::bold);
  46653. g.drawText (T("!"),
  46654. iconRect.getX(),
  46655. iconRect.getY(),
  46656. iconRect.getWidth(),
  46657. iconRect.getHeight() + iconRect.getHeight() / 8,
  46658. Justification::centred, false);
  46659. iconSpaceUsed = iconWidth;
  46660. alignment = Justification::left;
  46661. }
  46662. g.setColour (alert.findColour (AlertWindow::textColourId));
  46663. textLayout.drawWithin (g,
  46664. textArea.getX() + iconSpaceUsed,
  46665. textArea.getY(),
  46666. textArea.getWidth() - iconSpaceUsed,
  46667. textArea.getHeight(),
  46668. alignment.getFlags() | Justification::top);
  46669. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  46670. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  46671. }
  46672. int LookAndFeel::getAlertBoxWindowFlags()
  46673. {
  46674. return ComponentPeer::windowAppearsOnTaskbar
  46675. | ComponentPeer::windowHasDropShadow;
  46676. }
  46677. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  46678. int width, int height,
  46679. double progress, const String& textToShow)
  46680. {
  46681. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  46682. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  46683. g.fillAll (background);
  46684. if (progress >= 0.0f && progress < 1.0f)
  46685. {
  46686. drawGlassLozenge (g, 1.0f, 1.0f,
  46687. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  46688. (float) (height - 2),
  46689. foreground,
  46690. 0.5f, 0.0f,
  46691. true, true, true, true);
  46692. }
  46693. else
  46694. {
  46695. // spinning bar..
  46696. g.setColour (foreground);
  46697. const int stripeWidth = height * 2;
  46698. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  46699. Path p;
  46700. for (float x = (float) (-stripeWidth - position); x < width + stripeWidth; x += stripeWidth)
  46701. p.addQuadrilateral (x, 0.0f,
  46702. x + stripeWidth * 0.5f, 0.0f,
  46703. x, (float) height,
  46704. x - stripeWidth * 0.5f, (float) height);
  46705. Image im (Image::ARGB, width, height, true);
  46706. {
  46707. Graphics g (im);
  46708. drawGlassLozenge (g, 1.0f, 1.0f,
  46709. (float) (width - 2),
  46710. (float) (height - 2),
  46711. foreground,
  46712. 0.5f, 0.0f,
  46713. true, true, true, true);
  46714. }
  46715. ImageBrush ib (&im, 0, 0, 0.85f);
  46716. g.setBrush (&ib);
  46717. g.fillPath (p);
  46718. }
  46719. if (textToShow.isNotEmpty())
  46720. {
  46721. g.setColour (Colour::contrasting (background, foreground));
  46722. g.setFont (height * 0.6f);
  46723. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  46724. }
  46725. }
  46726. void LookAndFeel::drawScrollbarButton (Graphics& g,
  46727. ScrollBar& scrollbar,
  46728. int width, int height,
  46729. int buttonDirection,
  46730. bool /*isScrollbarVertical*/,
  46731. bool /*isMouseOverButton*/,
  46732. bool isButtonDown)
  46733. {
  46734. Path p;
  46735. if (buttonDirection == 0)
  46736. p.addTriangle (width * 0.5f, height * 0.2f,
  46737. width * 0.1f, height * 0.7f,
  46738. width * 0.9f, height * 0.7f);
  46739. else if (buttonDirection == 1)
  46740. p.addTriangle (width * 0.8f, height * 0.5f,
  46741. width * 0.3f, height * 0.1f,
  46742. width * 0.3f, height * 0.9f);
  46743. else if (buttonDirection == 2)
  46744. p.addTriangle (width * 0.5f, height * 0.8f,
  46745. width * 0.1f, height * 0.3f,
  46746. width * 0.9f, height * 0.3f);
  46747. else if (buttonDirection == 3)
  46748. p.addTriangle (width * 0.2f, height * 0.5f,
  46749. width * 0.7f, height * 0.1f,
  46750. width * 0.7f, height * 0.9f);
  46751. if (isButtonDown)
  46752. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  46753. else
  46754. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  46755. g.fillPath (p);
  46756. g.setColour (Colour (0x80000000));
  46757. g.strokePath (p, PathStrokeType (0.5f));
  46758. }
  46759. void LookAndFeel::drawScrollbar (Graphics& g,
  46760. ScrollBar& scrollbar,
  46761. int x, int y,
  46762. int width, int height,
  46763. bool isScrollbarVertical,
  46764. int thumbStartPosition,
  46765. int thumbSize,
  46766. bool /*isMouseOver*/,
  46767. bool /*isMouseDown*/)
  46768. {
  46769. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  46770. Path slotPath, thumbPath;
  46771. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  46772. const float slotIndentx2 = slotIndent * 2.0f;
  46773. const float thumbIndent = slotIndent + 1.0f;
  46774. const float thumbIndentx2 = thumbIndent * 2.0f;
  46775. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  46776. if (isScrollbarVertical)
  46777. {
  46778. slotPath.addRoundedRectangle (x + slotIndent,
  46779. y + slotIndent,
  46780. width - slotIndentx2,
  46781. height - slotIndentx2,
  46782. (width - slotIndentx2) * 0.5f);
  46783. if (thumbSize > 0)
  46784. thumbPath.addRoundedRectangle (x + thumbIndent,
  46785. thumbStartPosition + thumbIndent,
  46786. width - thumbIndentx2,
  46787. thumbSize - thumbIndentx2,
  46788. (width - thumbIndentx2) * 0.5f);
  46789. gx1 = (float) x;
  46790. gx2 = x + width * 0.7f;
  46791. }
  46792. else
  46793. {
  46794. slotPath.addRoundedRectangle (x + slotIndent,
  46795. y + slotIndent,
  46796. width - slotIndentx2,
  46797. height - slotIndentx2,
  46798. (height - slotIndentx2) * 0.5f);
  46799. if (thumbSize > 0)
  46800. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  46801. y + thumbIndent,
  46802. thumbSize - thumbIndentx2,
  46803. height - thumbIndentx2,
  46804. (height - thumbIndentx2) * 0.5f);
  46805. gy1 = (float) y;
  46806. gy2 = y + height * 0.7f;
  46807. }
  46808. const Colour thumbColour (scrollbar.findColour (ScrollBar::trackColourId));
  46809. GradientBrush gb (thumbColour.overlaidWith (Colour (0x44000000)),
  46810. gx1, gy1,
  46811. thumbColour.overlaidWith (Colour (0x19000000)),
  46812. gx2, gy2, false);
  46813. g.setBrush (&gb);
  46814. g.fillPath (slotPath);
  46815. if (isScrollbarVertical)
  46816. {
  46817. gx1 = x + width * 0.6f;
  46818. gx2 = (float) x + width;
  46819. }
  46820. else
  46821. {
  46822. gy1 = y + height * 0.6f;
  46823. gy2 = (float) y + height;
  46824. }
  46825. GradientBrush gb2 (Colours::transparentBlack,
  46826. gx1, gy1,
  46827. Colour (0x19000000),
  46828. gx2, gy2, false);
  46829. g.setBrush (&gb2);
  46830. g.fillPath (slotPath);
  46831. g.setColour (thumbColour);
  46832. g.fillPath (thumbPath);
  46833. GradientBrush gb3 (Colour (0x10000000),
  46834. gx1, gy1,
  46835. Colours::transparentBlack,
  46836. gx2, gy2, false);
  46837. g.saveState();
  46838. g.setBrush (&gb3);
  46839. if (isScrollbarVertical)
  46840. g.reduceClipRegion (x + width / 2, y, width, height);
  46841. else
  46842. g.reduceClipRegion (x, y + height / 2, width, height);
  46843. g.fillPath (thumbPath);
  46844. g.restoreState();
  46845. g.setColour (Colour (0x4c000000));
  46846. g.strokePath (thumbPath, PathStrokeType (0.4f));
  46847. }
  46848. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  46849. {
  46850. return 0;
  46851. }
  46852. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  46853. {
  46854. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  46855. }
  46856. int LookAndFeel::getDefaultScrollbarWidth()
  46857. {
  46858. return 18;
  46859. }
  46860. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  46861. {
  46862. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  46863. : scrollbar.getHeight());
  46864. }
  46865. const Path LookAndFeel::getTickShape (const float height)
  46866. {
  46867. static const unsigned char tickShapeData[] =
  46868. {
  46869. 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,
  46870. 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,
  46871. 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,
  46872. 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,
  46873. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  46874. };
  46875. Path p;
  46876. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  46877. p.scaleToFit (0, 0, height * 2.0f, height, true);
  46878. return p;
  46879. }
  46880. const Path LookAndFeel::getCrossShape (const float height)
  46881. {
  46882. static const unsigned char crossShapeData[] =
  46883. {
  46884. 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,
  46885. 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,
  46886. 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,
  46887. 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,
  46888. 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,
  46889. 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,
  46890. 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
  46891. };
  46892. Path p;
  46893. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  46894. p.scaleToFit (0, 0, height * 2.0f, height, true);
  46895. return p;
  46896. }
  46897. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus)
  46898. {
  46899. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  46900. x += (w - boxSize) >> 1;
  46901. y += (h - boxSize) >> 1;
  46902. w = boxSize;
  46903. h = boxSize;
  46904. g.setColour (Colour (0xe5ffffff));
  46905. g.fillRect (x, y, w, h);
  46906. g.setColour (Colour (0x80000000));
  46907. g.drawRect (x, y, w, h);
  46908. const float size = boxSize / 2 + 1.0f;
  46909. const float centre = (float) (boxSize / 2);
  46910. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  46911. if (isPlus)
  46912. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  46913. }
  46914. void LookAndFeel::drawBubble (Graphics& g,
  46915. float tipX, float tipY,
  46916. float boxX, float boxY,
  46917. float boxW, float boxH)
  46918. {
  46919. int side = 0;
  46920. if (tipX < boxX)
  46921. side = 1;
  46922. else if (tipX > boxX + boxW)
  46923. side = 3;
  46924. else if (tipY > boxY + boxH)
  46925. side = 2;
  46926. const float indent = 2.0f;
  46927. Path p;
  46928. p.addBubble (boxX + indent,
  46929. boxY + indent,
  46930. boxW - indent * 2.0f,
  46931. boxH - indent * 2.0f,
  46932. 5.0f,
  46933. tipX, tipY,
  46934. side,
  46935. 0.5f,
  46936. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  46937. //xxx need to take comp as param for colour
  46938. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  46939. g.fillPath (p);
  46940. //xxx as above
  46941. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  46942. g.strokePath (p, PathStrokeType (1.33f));
  46943. }
  46944. const Font LookAndFeel::getPopupMenuFont()
  46945. {
  46946. return Font (17.0f);
  46947. }
  46948. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  46949. const bool isSeparator,
  46950. int standardMenuItemHeight,
  46951. int& idealWidth,
  46952. int& idealHeight)
  46953. {
  46954. if (isSeparator)
  46955. {
  46956. idealWidth = 50;
  46957. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  46958. }
  46959. else
  46960. {
  46961. Font font (getPopupMenuFont());
  46962. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  46963. font.setHeight (standardMenuItemHeight / 1.3f);
  46964. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundFloatToInt (font.getHeight() * 1.3f);
  46965. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  46966. }
  46967. }
  46968. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  46969. {
  46970. const Colour background (findColour (PopupMenu::backgroundColourId));
  46971. g.fillAll (background);
  46972. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  46973. for (int i = 0; i < height; i += 3)
  46974. g.fillRect (0, i, width, 1);
  46975. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  46976. g.drawRect (0, 0, width, height);
  46977. }
  46978. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  46979. int width, int height,
  46980. bool isScrollUpArrow)
  46981. {
  46982. const Colour background (findColour (PopupMenu::backgroundColourId));
  46983. GradientBrush gb (background,
  46984. 0.0f, height * 0.5f,
  46985. background.withAlpha (0.0f),
  46986. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  46987. false);
  46988. g.setBrush (&gb);
  46989. g.fillRect (1, 1, width - 2, height - 2);
  46990. const float hw = width * 0.5f;
  46991. const float arrowW = height * 0.3f;
  46992. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  46993. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  46994. Path p;
  46995. p.addTriangle (hw - arrowW, y1,
  46996. hw + arrowW, y1,
  46997. hw, y2);
  46998. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  46999. g.fillPath (p);
  47000. }
  47001. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  47002. int width, int height,
  47003. const bool isSeparator,
  47004. const bool isActive,
  47005. const bool isHighlighted,
  47006. const bool isTicked,
  47007. const bool hasSubMenu,
  47008. const String& text,
  47009. const String& shortcutKeyText,
  47010. Image* image,
  47011. const Colour* const textColourToUse)
  47012. {
  47013. const float halfH = height * 0.5f;
  47014. if (isSeparator)
  47015. {
  47016. const float separatorIndent = 5.5f;
  47017. g.setColour (Colour (0x33000000));
  47018. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  47019. g.setColour (Colour (0x66ffffff));
  47020. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  47021. }
  47022. else
  47023. {
  47024. Colour textColour (findColour (PopupMenu::textColourId));
  47025. if (textColourToUse != 0)
  47026. textColour = *textColourToUse;
  47027. if (isHighlighted)
  47028. {
  47029. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  47030. g.fillRect (1, 1, width - 2, height - 2);
  47031. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  47032. }
  47033. else
  47034. {
  47035. g.setColour (textColour);
  47036. }
  47037. if (! isActive)
  47038. g.setOpacity (0.3f);
  47039. Font font (getPopupMenuFont());
  47040. if (font.getHeight() > height / 1.3f)
  47041. font.setHeight (height / 1.3f);
  47042. g.setFont (font);
  47043. const int leftBorder = (height * 5) / 4;
  47044. const int rightBorder = 4;
  47045. if (image != 0)
  47046. {
  47047. g.drawImageWithin (image,
  47048. 2, 1, leftBorder - 4, height - 2,
  47049. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  47050. }
  47051. else if (isTicked)
  47052. {
  47053. const Path tick (getTickShape (1.0f));
  47054. const float th = font.getAscent();
  47055. const float ty = halfH - th * 0.5f;
  47056. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  47057. th, true));
  47058. }
  47059. g.drawFittedText (text,
  47060. leftBorder, 0,
  47061. width - (leftBorder + rightBorder), height,
  47062. Justification::centredLeft, 1);
  47063. if (shortcutKeyText.isNotEmpty())
  47064. {
  47065. Font f2 (g.getCurrentFont());
  47066. f2.setHeight (f2.getHeight() * 0.75f);
  47067. f2.setHorizontalScale (0.95f);
  47068. g.setFont (f2);
  47069. g.drawText (shortcutKeyText,
  47070. leftBorder,
  47071. 0,
  47072. width - (leftBorder + rightBorder + 4),
  47073. height,
  47074. Justification::centredRight,
  47075. true);
  47076. }
  47077. if (hasSubMenu)
  47078. {
  47079. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  47080. const float x = width - height * 0.6f;
  47081. Path p;
  47082. p.addTriangle (x, halfH - arrowH * 0.5f,
  47083. x, halfH + arrowH * 0.5f,
  47084. x + arrowH * 0.6f, halfH);
  47085. g.fillPath (p);
  47086. }
  47087. }
  47088. }
  47089. int LookAndFeel::getMenuWindowFlags()
  47090. {
  47091. return ComponentPeer::windowHasDropShadow;
  47092. }
  47093. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  47094. bool, MenuBarComponent& menuBar)
  47095. {
  47096. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  47097. if (menuBar.isEnabled())
  47098. {
  47099. drawShinyButtonShape (g,
  47100. -4.0f, 0.0f,
  47101. width + 8.0f, (float) height,
  47102. 0.0f,
  47103. baseColour,
  47104. 0.4f,
  47105. true, true, true, true);
  47106. }
  47107. else
  47108. {
  47109. g.fillAll (baseColour);
  47110. }
  47111. }
  47112. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  47113. {
  47114. return Font (menuBar.getHeight() * 0.7f);
  47115. }
  47116. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  47117. {
  47118. return getMenuBarFont (menuBar, itemIndex, itemText)
  47119. .getStringWidth (itemText) + menuBar.getHeight();
  47120. }
  47121. void LookAndFeel::drawMenuBarItem (Graphics& g,
  47122. int width, int height,
  47123. int itemIndex,
  47124. const String& itemText,
  47125. bool isMouseOverItem,
  47126. bool isMenuOpen,
  47127. bool /*isMouseOverBar*/,
  47128. MenuBarComponent& menuBar)
  47129. {
  47130. if (! menuBar.isEnabled())
  47131. {
  47132. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  47133. .withMultipliedAlpha (0.5f));
  47134. }
  47135. else if (isMenuOpen || isMouseOverItem)
  47136. {
  47137. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  47138. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  47139. }
  47140. else
  47141. {
  47142. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  47143. }
  47144. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  47145. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  47146. }
  47147. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  47148. TextEditor& textEditor)
  47149. {
  47150. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  47151. }
  47152. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  47153. {
  47154. if (textEditor.isEnabled())
  47155. {
  47156. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  47157. {
  47158. const int border = 2;
  47159. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  47160. g.drawRect (0, 0, width, height, border);
  47161. g.setOpacity (1.0f);
  47162. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  47163. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  47164. }
  47165. else
  47166. {
  47167. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  47168. g.drawRect (0, 0, width, height);
  47169. g.setOpacity (1.0f);
  47170. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  47171. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  47172. }
  47173. }
  47174. }
  47175. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  47176. const bool isButtonDown,
  47177. int buttonX, int buttonY,
  47178. int buttonW, int buttonH,
  47179. ComboBox& box)
  47180. {
  47181. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  47182. if (box.isEnabled() && box.hasKeyboardFocus (false))
  47183. {
  47184. g.setColour (box.findColour (TextButton::buttonColourId));
  47185. g.drawRect (0, 0, width, height, 2);
  47186. }
  47187. else
  47188. {
  47189. g.setColour (box.findColour (ComboBox::outlineColourId));
  47190. g.drawRect (0, 0, width, height);
  47191. }
  47192. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  47193. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  47194. box.hasKeyboardFocus (true),
  47195. false, isButtonDown)
  47196. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  47197. drawGlassLozenge (g,
  47198. buttonX + outlineThickness, buttonY + outlineThickness,
  47199. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  47200. baseColour, outlineThickness, -1.0f,
  47201. true, true, true, true);
  47202. if (box.isEnabled())
  47203. {
  47204. const float arrowX = 0.3f;
  47205. const float arrowH = 0.2f;
  47206. Path p;
  47207. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  47208. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  47209. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  47210. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  47211. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  47212. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  47213. g.setColour (box.findColour (ComboBox::arrowColourId));
  47214. g.fillPath (p);
  47215. }
  47216. }
  47217. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  47218. {
  47219. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  47220. }
  47221. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  47222. {
  47223. return new Label (String::empty, String::empty);
  47224. }
  47225. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  47226. {
  47227. label.setBounds (1, 1,
  47228. box.getWidth() + 3 - box.getHeight(),
  47229. box.getHeight() - 2);
  47230. label.setFont (getComboBoxFont (box));
  47231. }
  47232. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  47233. int x, int y,
  47234. int width, int height,
  47235. float /*sliderPos*/,
  47236. float /*minSliderPos*/,
  47237. float /*maxSliderPos*/,
  47238. const Slider::SliderStyle /*style*/,
  47239. Slider& slider)
  47240. {
  47241. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  47242. const Colour trackColour (slider.findColour (Slider::trackColourId));
  47243. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  47244. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  47245. Path indent;
  47246. if (slider.isHorizontal())
  47247. {
  47248. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  47249. const float ih = sliderRadius;
  47250. GradientBrush gb (gradCol1, 0.0f, iy,
  47251. gradCol2, 0.0f, iy + ih, false);
  47252. g.setBrush (&gb);
  47253. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  47254. width + sliderRadius, ih,
  47255. 5.0f);
  47256. g.fillPath (indent);
  47257. }
  47258. else
  47259. {
  47260. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  47261. const float iw = sliderRadius;
  47262. GradientBrush gb (gradCol1, ix, 0.0f,
  47263. gradCol2, ix + iw, 0.0f, false);
  47264. g.setBrush (&gb);
  47265. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  47266. iw, height + sliderRadius,
  47267. 5.0f);
  47268. g.fillPath (indent);
  47269. }
  47270. g.setColour (Colour (0x4c000000));
  47271. g.strokePath (indent, PathStrokeType (0.5f));
  47272. }
  47273. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  47274. int x, int y,
  47275. int width, int height,
  47276. float sliderPos,
  47277. float minSliderPos,
  47278. float maxSliderPos,
  47279. const Slider::SliderStyle style,
  47280. Slider& slider)
  47281. {
  47282. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  47283. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  47284. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  47285. slider.isMouseOverOrDragging() && slider.isEnabled(),
  47286. slider.isMouseButtonDown() && slider.isEnabled()));
  47287. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  47288. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  47289. {
  47290. float kx, ky;
  47291. if (style == Slider::LinearVertical)
  47292. {
  47293. kx = x + width * 0.5f;
  47294. ky = sliderPos;
  47295. }
  47296. else
  47297. {
  47298. kx = sliderPos;
  47299. ky = y + height * 0.5f;
  47300. }
  47301. drawGlassSphere (g,
  47302. kx - sliderRadius,
  47303. ky - sliderRadius,
  47304. sliderRadius * 2.0f,
  47305. knobColour, outlineThickness);
  47306. }
  47307. else
  47308. {
  47309. if (style == Slider::ThreeValueVertical)
  47310. {
  47311. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  47312. sliderPos - sliderRadius,
  47313. sliderRadius * 2.0f,
  47314. knobColour, outlineThickness);
  47315. }
  47316. else if (style == Slider::ThreeValueHorizontal)
  47317. {
  47318. drawGlassSphere (g,sliderPos - sliderRadius,
  47319. y + height * 0.5f - sliderRadius,
  47320. sliderRadius * 2.0f,
  47321. knobColour, outlineThickness);
  47322. }
  47323. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  47324. {
  47325. const float sr = jmin (sliderRadius, width * 0.4f);
  47326. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  47327. minSliderPos - sliderRadius,
  47328. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  47329. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  47330. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  47331. }
  47332. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  47333. {
  47334. const float sr = jmin (sliderRadius, height * 0.4f);
  47335. drawGlassPointer (g, minSliderPos - sr,
  47336. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  47337. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  47338. drawGlassPointer (g, maxSliderPos - sliderRadius,
  47339. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  47340. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  47341. }
  47342. }
  47343. }
  47344. void LookAndFeel::drawLinearSlider (Graphics& g,
  47345. int x, int y,
  47346. int width, int height,
  47347. float sliderPos,
  47348. float minSliderPos,
  47349. float maxSliderPos,
  47350. const Slider::SliderStyle style,
  47351. Slider& slider)
  47352. {
  47353. g.fillAll (slider.findColour (Slider::backgroundColourId));
  47354. if (style == Slider::LinearBar)
  47355. {
  47356. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  47357. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  47358. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  47359. false,
  47360. isMouseOver,
  47361. isMouseOver || slider.isMouseButtonDown()));
  47362. drawShinyButtonShape (g,
  47363. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  47364. baseColour,
  47365. slider.isEnabled() ? 0.9f : 0.3f,
  47366. true, true, true, true);
  47367. }
  47368. else
  47369. {
  47370. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  47371. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  47372. }
  47373. }
  47374. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  47375. {
  47376. return jmin (7,
  47377. slider.getHeight() / 2,
  47378. slider.getWidth() / 2) + 2;
  47379. }
  47380. void LookAndFeel::drawRotarySlider (Graphics& g,
  47381. int x, int y,
  47382. int width, int height,
  47383. float sliderPos,
  47384. const float rotaryStartAngle,
  47385. const float rotaryEndAngle,
  47386. Slider& slider)
  47387. {
  47388. const float radius = jmin (width / 2, height / 2) - 2.0f;
  47389. const float centreX = x + width * 0.5f;
  47390. const float centreY = y + height * 0.5f;
  47391. const float rx = centreX - radius;
  47392. const float ry = centreY - radius;
  47393. const float rw = radius * 2.0f;
  47394. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  47395. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  47396. if (radius > 12.0f)
  47397. {
  47398. if (slider.isEnabled())
  47399. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  47400. else
  47401. g.setColour (Colour (0x80808080));
  47402. const float thickness = 0.7f;
  47403. {
  47404. Path filledArc;
  47405. filledArc.addPieSegment (rx, ry, rw, rw,
  47406. rotaryStartAngle,
  47407. angle,
  47408. thickness);
  47409. g.fillPath (filledArc);
  47410. }
  47411. if (thickness > 0)
  47412. {
  47413. const float innerRadius = radius * 0.2f;
  47414. Path p;
  47415. p.addTriangle (-innerRadius, 0.0f,
  47416. 0.0f, -radius * thickness * 1.1f,
  47417. innerRadius, 0.0f);
  47418. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  47419. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  47420. }
  47421. if (slider.isEnabled())
  47422. {
  47423. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  47424. Path outlineArc;
  47425. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  47426. outlineArc.closeSubPath();
  47427. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  47428. }
  47429. }
  47430. else
  47431. {
  47432. if (slider.isEnabled())
  47433. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  47434. else
  47435. g.setColour (Colour (0x80808080));
  47436. Path p;
  47437. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  47438. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  47439. p.addLineSegment (0.0f, 0.0f, 0.0f, -radius, rw * 0.2f);
  47440. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  47441. }
  47442. }
  47443. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  47444. {
  47445. return new TextButton (isIncrement ? "+" : "-", String::empty);
  47446. }
  47447. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  47448. {
  47449. Label* const l = new Label (T("n"), String::empty);
  47450. l->setJustificationType (Justification::centred);
  47451. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  47452. l->setColour (Label::backgroundColourId,
  47453. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  47454. : slider.findColour (Slider::textBoxBackgroundColourId));
  47455. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  47456. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  47457. l->setColour (TextEditor::backgroundColourId,
  47458. slider.findColour (Slider::textBoxBackgroundColourId)
  47459. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  47460. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  47461. return l;
  47462. }
  47463. ImageEffectFilter* LookAndFeel::getSliderEffect()
  47464. {
  47465. return 0;
  47466. }
  47467. static const TextLayout layoutTooltipText (const String& text) throw()
  47468. {
  47469. const float tooltipFontSize = 15.0f;
  47470. const int maxToolTipWidth = 400;
  47471. const Font f (tooltipFontSize, Font::bold);
  47472. TextLayout tl (text, f);
  47473. tl.layout (maxToolTipWidth, Justification::left, true);
  47474. return tl;
  47475. }
  47476. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  47477. {
  47478. const TextLayout tl (layoutTooltipText (tipText));
  47479. width = tl.getWidth() + 14;
  47480. height = tl.getHeight() + 10;
  47481. }
  47482. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  47483. {
  47484. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  47485. const Colour textCol (findColour (TooltipWindow::textColourId));
  47486. g.setColour (findColour (TooltipWindow::outlineColourId));
  47487. g.drawRect (0, 0, width, height);
  47488. const TextLayout tl (layoutTooltipText (text));
  47489. g.setColour (findColour (TooltipWindow::textColourId));
  47490. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  47491. }
  47492. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  47493. {
  47494. return new TextButton (text, TRANS("click to browse for a different file"));
  47495. }
  47496. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  47497. ComboBox* filenameBox,
  47498. Button* browseButton)
  47499. {
  47500. browseButton->setSize (80, filenameComp.getHeight());
  47501. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  47502. if (tb != 0)
  47503. tb->changeWidthToFitText();
  47504. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  47505. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  47506. }
  47507. void LookAndFeel::drawCornerResizer (Graphics& g,
  47508. int w, int h,
  47509. bool /*isMouseOver*/,
  47510. bool /*isMouseDragging*/)
  47511. {
  47512. const float lineThickness = jmin (w, h) * 0.075f;
  47513. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  47514. {
  47515. g.setColour (Colours::lightgrey);
  47516. g.drawLine (w * i,
  47517. h + 1.0f,
  47518. w + 1.0f,
  47519. h * i,
  47520. lineThickness);
  47521. g.setColour (Colours::darkgrey);
  47522. g.drawLine (w * i + lineThickness,
  47523. h + 1.0f,
  47524. w + 1.0f,
  47525. h * i + lineThickness,
  47526. lineThickness);
  47527. }
  47528. }
  47529. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  47530. const BorderSize& /*borders*/)
  47531. {
  47532. }
  47533. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  47534. const BorderSize& border, ResizableWindow&)
  47535. {
  47536. g.setColour (Colour (0x80000000));
  47537. g.drawRect (0, 0, w, h);
  47538. g.setColour (Colour (0x19000000));
  47539. g.drawRect (border.getLeft() - 1,
  47540. border.getTop() - 1,
  47541. w + 2 - border.getLeftAndRight(),
  47542. h + 2 - border.getTopAndBottom());
  47543. }
  47544. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  47545. Graphics& g, int w, int h,
  47546. int titleSpaceX, int titleSpaceW,
  47547. const Image* icon,
  47548. bool drawTitleTextOnLeft)
  47549. {
  47550. const bool isActive = window.isActiveWindow();
  47551. GradientBrush gb (window.getBackgroundColour(),
  47552. 0.0f, 0.0f,
  47553. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  47554. 0.0f, (float) h, false);
  47555. g.setBrush (&gb);
  47556. g.fillAll();
  47557. g.setFont (h * 0.65f, Font::bold);
  47558. int textW = g.getCurrentFont().getStringWidth (window.getName());
  47559. int iconW = 0;
  47560. int iconH = 0;
  47561. if (icon != 0)
  47562. {
  47563. iconH = (int) g.getCurrentFont().getHeight();
  47564. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  47565. }
  47566. textW = jmin (titleSpaceW, textW + iconW);
  47567. int textX = drawTitleTextOnLeft ? titleSpaceX
  47568. : jmax (titleSpaceX, (w - textW) / 2);
  47569. if (textX + textW > titleSpaceX + titleSpaceW)
  47570. textX = titleSpaceX + titleSpaceW - textW;
  47571. if (icon != 0)
  47572. {
  47573. g.setOpacity (isActive ? 1.0f : 0.6f);
  47574. g.drawImageWithin (icon, textX, (h - iconH) / 2, iconW, iconH,
  47575. RectanglePlacement::centred, false);
  47576. textX += iconW;
  47577. textW -= iconW;
  47578. }
  47579. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  47580. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  47581. }
  47582. class GlassWindowButton : public Button
  47583. {
  47584. public:
  47585. GlassWindowButton (const String& name, const Colour& col,
  47586. const Path& normalShape_,
  47587. const Path& toggledShape_) throw()
  47588. : Button (name),
  47589. colour (col),
  47590. normalShape (normalShape_),
  47591. toggledShape (toggledShape_)
  47592. {
  47593. }
  47594. ~GlassWindowButton()
  47595. {
  47596. }
  47597. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  47598. {
  47599. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  47600. if (! isEnabled())
  47601. alpha *= 0.5f;
  47602. float x = 0, y = 0, diam;
  47603. if (getWidth() < getHeight())
  47604. {
  47605. diam = (float) getWidth();
  47606. y = (getHeight() - getWidth()) * 0.5f;
  47607. }
  47608. else
  47609. {
  47610. diam = (float) getHeight();
  47611. y = (getWidth() - getHeight()) * 0.5f;
  47612. }
  47613. x += diam * 0.05f;
  47614. y += diam * 0.05f;
  47615. diam *= 0.9f;
  47616. GradientBrush gb1 (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  47617. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false);
  47618. g.setBrush (&gb1);
  47619. g.fillEllipse (x, y, diam, diam);
  47620. x += 2.0f;
  47621. y += 2.0f;
  47622. diam -= 4.0f;
  47623. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  47624. Path& p = getToggleState() ? toggledShape : normalShape;
  47625. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  47626. diam * 0.4f, diam * 0.4f, true));
  47627. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  47628. g.fillPath (p, t);
  47629. }
  47630. juce_UseDebuggingNewOperator
  47631. private:
  47632. Colour colour;
  47633. Path normalShape, toggledShape;
  47634. GlassWindowButton (const GlassWindowButton&);
  47635. const GlassWindowButton& operator= (const GlassWindowButton&);
  47636. };
  47637. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  47638. {
  47639. Path shape;
  47640. const float crossThickness = 0.25f;
  47641. if (buttonType == DocumentWindow::closeButton)
  47642. {
  47643. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, crossThickness * 1.4f);
  47644. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, crossThickness * 1.4f);
  47645. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  47646. }
  47647. else if (buttonType == DocumentWindow::minimiseButton)
  47648. {
  47649. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  47650. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  47651. }
  47652. else if (buttonType == DocumentWindow::maximiseButton)
  47653. {
  47654. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, crossThickness);
  47655. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  47656. Path fullscreenShape;
  47657. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  47658. fullscreenShape.lineTo (0.0f, 100.0f);
  47659. fullscreenShape.lineTo (0.0f, 0.0f);
  47660. fullscreenShape.lineTo (100.0f, 0.0f);
  47661. fullscreenShape.lineTo (100.0f, 45.0f);
  47662. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  47663. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  47664. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  47665. }
  47666. jassertfalse
  47667. return 0;
  47668. }
  47669. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  47670. int titleBarX,
  47671. int titleBarY,
  47672. int titleBarW,
  47673. int titleBarH,
  47674. Button* minimiseButton,
  47675. Button* maximiseButton,
  47676. Button* closeButton,
  47677. bool positionTitleBarButtonsOnLeft)
  47678. {
  47679. const int buttonW = titleBarH - titleBarH / 8;
  47680. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  47681. : titleBarX + titleBarW - buttonW - buttonW / 4;
  47682. if (closeButton != 0)
  47683. {
  47684. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  47685. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  47686. }
  47687. if (positionTitleBarButtonsOnLeft)
  47688. swapVariables (minimiseButton, maximiseButton);
  47689. if (maximiseButton != 0)
  47690. {
  47691. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  47692. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  47693. }
  47694. if (minimiseButton != 0)
  47695. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  47696. }
  47697. int LookAndFeel::getDefaultMenuBarHeight()
  47698. {
  47699. return 24;
  47700. }
  47701. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  47702. {
  47703. return new DropShadower (0.4f, 1, 5, 10);
  47704. }
  47705. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  47706. int w, int h,
  47707. bool /*isVerticalBar*/,
  47708. bool isMouseOver,
  47709. bool isMouseDragging)
  47710. {
  47711. float alpha = 0.5f;
  47712. if (isMouseOver || isMouseDragging)
  47713. {
  47714. g.fillAll (Colour (0x190000ff));
  47715. alpha = 1.0f;
  47716. }
  47717. const float cx = w * 0.5f;
  47718. const float cy = h * 0.5f;
  47719. const float cr = jmin (w, h) * 0.4f;
  47720. GradientBrush gb (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  47721. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  47722. true);
  47723. g.setBrush (&gb);
  47724. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  47725. }
  47726. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  47727. const String& text,
  47728. const Justification& position,
  47729. GroupComponent& group)
  47730. {
  47731. const float textH = 15.0f;
  47732. const float indent = 3.0f;
  47733. const float textEdgeGap = 4.0f;
  47734. float cs = 5.0f;
  47735. Font f (textH);
  47736. Path p;
  47737. float x = indent;
  47738. float y = f.getAscent() - 3.0f;
  47739. float w = jmax (0.0f, width - x * 2.0f);
  47740. float h = jmax (0.0f, height - y - indent);
  47741. cs = jmin (cs, w * 0.5f, h * 0.5f);
  47742. const float cs2 = 2.0f * cs;
  47743. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  47744. float textX = cs + textEdgeGap;
  47745. if (position.testFlags (Justification::horizontallyCentred))
  47746. textX = cs + (w - cs2 - textW) * 0.5f;
  47747. else if (position.testFlags (Justification::right))
  47748. textX = w - cs - textW - textEdgeGap;
  47749. p.startNewSubPath (x + textX + textW, y);
  47750. p.lineTo (x + w - cs, y);
  47751. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  47752. p.lineTo (x + w, y + h - cs);
  47753. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  47754. p.lineTo (x + cs, y + h);
  47755. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  47756. p.lineTo (x, y + cs);
  47757. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  47758. p.lineTo (x + textX, y);
  47759. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  47760. g.setColour (group.findColour (GroupComponent::outlineColourId)
  47761. .withMultipliedAlpha (alpha));
  47762. g.strokePath (p, PathStrokeType (2.0f));
  47763. g.setColour (group.findColour (GroupComponent::textColourId)
  47764. .withMultipliedAlpha (alpha));
  47765. g.setFont (f);
  47766. g.drawText (text,
  47767. roundFloatToInt (x + textX), 0,
  47768. roundFloatToInt (textW),
  47769. roundFloatToInt (textH),
  47770. Justification::centred, true);
  47771. }
  47772. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  47773. {
  47774. return 1 + tabDepth / 3;
  47775. }
  47776. int LookAndFeel::getTabButtonSpaceAroundImage()
  47777. {
  47778. return 4;
  47779. }
  47780. void LookAndFeel::createTabButtonShape (Path& p,
  47781. int width, int height,
  47782. int /*tabIndex*/,
  47783. const String& /*text*/,
  47784. Button& /*button*/,
  47785. TabbedButtonBar::Orientation orientation,
  47786. const bool /*isMouseOver*/,
  47787. const bool /*isMouseDown*/,
  47788. const bool /*isFrontTab*/)
  47789. {
  47790. const float w = (float) width;
  47791. const float h = (float) height;
  47792. float length = w;
  47793. float depth = h;
  47794. if (orientation == TabbedButtonBar::TabsAtLeft
  47795. || orientation == TabbedButtonBar::TabsAtRight)
  47796. {
  47797. swapVariables (length, depth);
  47798. }
  47799. const float indent = (float) getTabButtonOverlap ((int) depth);
  47800. const float overhang = 4.0f;
  47801. if (orientation == TabbedButtonBar::TabsAtLeft)
  47802. {
  47803. p.startNewSubPath (w, 0.0f);
  47804. p.lineTo (0.0f, indent);
  47805. p.lineTo (0.0f, h - indent);
  47806. p.lineTo (w, h);
  47807. p.lineTo (w + overhang, h + overhang);
  47808. p.lineTo (w + overhang, -overhang);
  47809. }
  47810. else if (orientation == TabbedButtonBar::TabsAtRight)
  47811. {
  47812. p.startNewSubPath (0.0f, 0.0f);
  47813. p.lineTo (w, indent);
  47814. p.lineTo (w, h - indent);
  47815. p.lineTo (0.0f, h);
  47816. p.lineTo (-overhang, h + overhang);
  47817. p.lineTo (-overhang, -overhang);
  47818. }
  47819. else if (orientation == TabbedButtonBar::TabsAtBottom)
  47820. {
  47821. p.startNewSubPath (0.0f, 0.0f);
  47822. p.lineTo (indent, h);
  47823. p.lineTo (w - indent, h);
  47824. p.lineTo (w, 0.0f);
  47825. p.lineTo (w + overhang, -overhang);
  47826. p.lineTo (-overhang, -overhang);
  47827. }
  47828. else
  47829. {
  47830. p.startNewSubPath (0.0f, h);
  47831. p.lineTo (indent, 0.0f);
  47832. p.lineTo (w - indent, 0.0f);
  47833. p.lineTo (w, h);
  47834. p.lineTo (w + overhang, h + overhang);
  47835. p.lineTo (-overhang, h + overhang);
  47836. }
  47837. p.closeSubPath();
  47838. p = p.createPathWithRoundedCorners (3.0f);
  47839. }
  47840. void LookAndFeel::fillTabButtonShape (Graphics& g,
  47841. const Path& path,
  47842. const Colour& preferredColour,
  47843. int /*tabIndex*/,
  47844. const String& /*text*/,
  47845. Button& button,
  47846. TabbedButtonBar::Orientation /*orientation*/,
  47847. const bool /*isMouseOver*/,
  47848. const bool /*isMouseDown*/,
  47849. const bool isFrontTab)
  47850. {
  47851. g.setColour (isFrontTab ? preferredColour
  47852. : preferredColour.withMultipliedAlpha (0.9f));
  47853. g.fillPath (path);
  47854. g.setColour (Colours::black.withAlpha (button.isEnabled() ? 0.5f : 0.25f));
  47855. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  47856. }
  47857. void LookAndFeel::drawTabButtonText (Graphics& g,
  47858. int x, int y, int w, int h,
  47859. const Colour& preferredBackgroundColour,
  47860. int /*tabIndex*/,
  47861. const String& text,
  47862. Button& button,
  47863. TabbedButtonBar::Orientation orientation,
  47864. const bool isMouseOver,
  47865. const bool isMouseDown,
  47866. const bool /*isFrontTab*/)
  47867. {
  47868. int length = w;
  47869. int depth = h;
  47870. if (orientation == TabbedButtonBar::TabsAtLeft
  47871. || orientation == TabbedButtonBar::TabsAtRight)
  47872. {
  47873. swapVariables (length, depth);
  47874. }
  47875. Font font (depth * 0.6f);
  47876. font.setUnderline (button.hasKeyboardFocus (false));
  47877. GlyphArrangement textLayout;
  47878. textLayout.addFittedText (font, text.trim(),
  47879. 0.0f, 0.0f, (float) length, (float) depth,
  47880. Justification::centred,
  47881. jmax (1, depth / 12));
  47882. AffineTransform transform;
  47883. if (orientation == TabbedButtonBar::TabsAtLeft)
  47884. {
  47885. transform = transform.rotated (float_Pi * -0.5f)
  47886. .translated ((float) x, (float) (y + h));
  47887. }
  47888. else if (orientation == TabbedButtonBar::TabsAtRight)
  47889. {
  47890. transform = transform.rotated (float_Pi * 0.5f)
  47891. .translated ((float) (x + w), (float) y);
  47892. }
  47893. else
  47894. {
  47895. transform = transform.translated ((float) x, (float) y);
  47896. }
  47897. g.setColour (preferredBackgroundColour.contrasting());
  47898. if (! (isMouseOver || isMouseDown))
  47899. g.setOpacity (0.8f);
  47900. if (! button.isEnabled())
  47901. g.setOpacity (0.3f);
  47902. textLayout.draw (g, transform);
  47903. }
  47904. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  47905. const String& text,
  47906. int tabDepth,
  47907. Button&)
  47908. {
  47909. Font f (tabDepth * 0.6f);
  47910. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  47911. }
  47912. void LookAndFeel::drawTabButton (Graphics& g,
  47913. int w, int h,
  47914. const Colour& preferredColour,
  47915. int tabIndex,
  47916. const String& text,
  47917. Button& button,
  47918. TabbedButtonBar::Orientation orientation,
  47919. const bool isMouseOver,
  47920. const bool isMouseDown,
  47921. const bool isFrontTab)
  47922. {
  47923. int length = w;
  47924. int depth = h;
  47925. if (orientation == TabbedButtonBar::TabsAtLeft
  47926. || orientation == TabbedButtonBar::TabsAtRight)
  47927. {
  47928. swapVariables (length, depth);
  47929. }
  47930. Path tabShape;
  47931. createTabButtonShape (tabShape, w, h,
  47932. tabIndex, text, button, orientation,
  47933. isMouseOver, isMouseDown, isFrontTab);
  47934. fillTabButtonShape (g, tabShape, preferredColour,
  47935. tabIndex, text, button, orientation,
  47936. isMouseOver, isMouseDown, isFrontTab);
  47937. const int indent = getTabButtonOverlap (depth);
  47938. int x = 0, y = 0;
  47939. if (orientation == TabbedButtonBar::TabsAtLeft
  47940. || orientation == TabbedButtonBar::TabsAtRight)
  47941. {
  47942. y += indent;
  47943. h -= indent * 2;
  47944. }
  47945. else
  47946. {
  47947. x += indent;
  47948. w -= indent * 2;
  47949. }
  47950. drawTabButtonText (g, x, y, w, h, preferredColour,
  47951. tabIndex, text, button, orientation,
  47952. isMouseOver, isMouseDown, isFrontTab);
  47953. }
  47954. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  47955. int w, int h,
  47956. TabbedButtonBar& tabBar,
  47957. TabbedButtonBar::Orientation orientation)
  47958. {
  47959. const float shadowSize = 0.2f;
  47960. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  47961. Rectangle shadowRect;
  47962. if (orientation == TabbedButtonBar::TabsAtLeft)
  47963. {
  47964. x1 = (float) w;
  47965. x2 = w * (1.0f - shadowSize);
  47966. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  47967. }
  47968. else if (orientation == TabbedButtonBar::TabsAtRight)
  47969. {
  47970. x2 = w * shadowSize;
  47971. shadowRect.setBounds (0, 0, (int) x2, h);
  47972. }
  47973. else if (orientation == TabbedButtonBar::TabsAtBottom)
  47974. {
  47975. y2 = h * shadowSize;
  47976. shadowRect.setBounds (0, 0, w, (int) y2);
  47977. }
  47978. else
  47979. {
  47980. y1 = (float) h;
  47981. y2 = h * (1.0f - shadowSize);
  47982. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  47983. }
  47984. GradientBrush gb (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  47985. Colours::transparentBlack, x2, y2,
  47986. false);
  47987. g.setBrush (&gb);
  47988. shadowRect.expand (2, 2);
  47989. g.fillRect (shadowRect);
  47990. g.setColour (Colour (0x80000000));
  47991. if (orientation == TabbedButtonBar::TabsAtLeft)
  47992. {
  47993. g.fillRect (w - 1, 0, 1, h);
  47994. }
  47995. else if (orientation == TabbedButtonBar::TabsAtRight)
  47996. {
  47997. g.fillRect (0, 0, 1, h);
  47998. }
  47999. else if (orientation == TabbedButtonBar::TabsAtBottom)
  48000. {
  48001. g.fillRect (0, 0, w, 1);
  48002. }
  48003. else
  48004. {
  48005. g.fillRect (0, h - 1, w, 1);
  48006. }
  48007. }
  48008. Button* LookAndFeel::createTabBarExtrasButton()
  48009. {
  48010. const float thickness = 7.0f;
  48011. const float indent = 22.0f;
  48012. Path p;
  48013. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  48014. DrawablePath ellipse;
  48015. ellipse.setPath (p);
  48016. ellipse.setSolidFill (Colour (0x99ffffff));
  48017. p.clear();
  48018. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  48019. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  48020. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  48021. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  48022. p.setUsingNonZeroWinding (false);
  48023. DrawablePath dp;
  48024. dp.setPath (p);
  48025. dp.setSolidFill (Colour (0x59000000));
  48026. DrawableComposite normalImage;
  48027. normalImage.insertDrawable (ellipse);
  48028. normalImage.insertDrawable (dp);
  48029. dp.setSolidFill (Colour (0xcc000000));
  48030. DrawableComposite overImage;
  48031. overImage.insertDrawable (ellipse);
  48032. overImage.insertDrawable (dp);
  48033. DrawableButton* db = new DrawableButton (T("tabs"), DrawableButton::ImageFitted);
  48034. db->setImages (&normalImage, &overImage, 0);
  48035. return db;
  48036. }
  48037. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  48038. {
  48039. g.fillAll (Colours::white);
  48040. const int w = header.getWidth();
  48041. const int h = header.getHeight();
  48042. GradientBrush gb (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  48043. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  48044. false);
  48045. g.setBrush (&gb);
  48046. g.fillRect (0, h / 2, w, h);
  48047. g.setColour (Colour (0x33000000));
  48048. g.fillRect (0, h - 1, w, 1);
  48049. for (int i = header.getNumColumns (true); --i >= 0;)
  48050. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  48051. }
  48052. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  48053. int width, int height,
  48054. bool isMouseOver, bool isMouseDown,
  48055. int columnFlags)
  48056. {
  48057. if (isMouseDown)
  48058. g.fillAll (Colour (0x8899aadd));
  48059. else if (isMouseOver)
  48060. g.fillAll (Colour (0x5599aadd));
  48061. int rightOfText = width - 4;
  48062. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  48063. {
  48064. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  48065. const float bottom = height - top;
  48066. const float w = height * 0.5f;
  48067. const float x = rightOfText - (w * 1.25f);
  48068. rightOfText = (int) x;
  48069. Path sortArrow;
  48070. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  48071. g.setColour (Colour (0x99000000));
  48072. g.fillPath (sortArrow);
  48073. }
  48074. g.setColour (Colours::black);
  48075. g.setFont (height * 0.5f, Font::bold);
  48076. const int textX = 4;
  48077. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  48078. }
  48079. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  48080. {
  48081. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  48082. GradientBrush gb (background, 0.0f, 0.0f,
  48083. background.darker (0.1f),
  48084. toolbar.isVertical() ? w - 1.0f : 0.0f,
  48085. toolbar.isVertical() ? 0.0f : h - 1.0f,
  48086. false);
  48087. g.setBrush (&gb);
  48088. g.fillAll();
  48089. }
  48090. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  48091. {
  48092. return createTabBarExtrasButton();
  48093. }
  48094. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  48095. bool isMouseOver, bool isMouseDown,
  48096. ToolbarItemComponent& component)
  48097. {
  48098. if (isMouseDown)
  48099. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  48100. else if (isMouseOver)
  48101. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  48102. }
  48103. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  48104. const String& text, ToolbarItemComponent& component)
  48105. {
  48106. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  48107. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  48108. const float fontHeight = jmin (14.0f, height * 0.85f);
  48109. g.setFont (fontHeight);
  48110. g.drawFittedText (text,
  48111. x, y, width, height,
  48112. Justification::centred,
  48113. jmax (1, height / (int) fontHeight));
  48114. }
  48115. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  48116. bool isOpen, int width, int height)
  48117. {
  48118. const int buttonSize = (height * 3) / 4;
  48119. const int buttonIndent = (height - buttonSize) / 2;
  48120. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen);
  48121. const int textX = buttonIndent * 2 + buttonSize + 2;
  48122. g.setColour (Colours::black);
  48123. g.setFont (height * 0.7f, Font::bold);
  48124. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  48125. }
  48126. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  48127. PropertyComponent&)
  48128. {
  48129. g.setColour (Colour (0x66ffffff));
  48130. g.fillRect (0, 0, width, height - 1);
  48131. }
  48132. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  48133. PropertyComponent& component)
  48134. {
  48135. g.setColour (Colours::black);
  48136. if (! component.isEnabled())
  48137. g.setOpacity (g.getCurrentColour().getAlpha() * 0.6f);
  48138. g.setFont (jmin (height, 24) * 0.65f);
  48139. const Rectangle r (getPropertyComponentContentPosition (component));
  48140. g.drawFittedText (component.getName(),
  48141. 3, r.getY(), r.getX() - 5, r.getHeight(),
  48142. Justification::centredLeft, 2);
  48143. }
  48144. const Rectangle LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  48145. {
  48146. return Rectangle (component.getWidth() / 3, 1,
  48147. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  48148. }
  48149. void LookAndFeel::createFileChooserHeaderText (const String& title,
  48150. const String& instructions,
  48151. GlyphArrangement& text,
  48152. int width)
  48153. {
  48154. text.clear();
  48155. text.addJustifiedText (Font (17.0f, Font::bold), title,
  48156. 8.0f, 22.0f, width - 16.0f,
  48157. Justification::centred);
  48158. text.addJustifiedText (Font (14.0f), instructions,
  48159. 8.0f, 24.0f + 16.0f, width - 16.0f,
  48160. Justification::centred);
  48161. }
  48162. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  48163. const String& filename, Image* icon,
  48164. const String& fileSizeDescription,
  48165. const String& fileTimeDescription,
  48166. const bool isDirectory,
  48167. const bool isItemSelected,
  48168. const int /*itemIndex*/)
  48169. {
  48170. if (isItemSelected)
  48171. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  48172. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  48173. g.setFont (height * 0.7f);
  48174. Image* im = icon;
  48175. Image* toRelease = 0;
  48176. if (im == 0)
  48177. {
  48178. toRelease = im = (isDirectory ? getDefaultFolderImage()
  48179. : getDefaultDocumentFileImage());
  48180. }
  48181. const int x = 32;
  48182. if (im != 0)
  48183. {
  48184. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  48185. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48186. false);
  48187. ImageCache::release (toRelease);
  48188. }
  48189. if (width > 450 && ! isDirectory)
  48190. {
  48191. const int sizeX = roundFloatToInt (width * 0.7f);
  48192. const int dateX = roundFloatToInt (width * 0.8f);
  48193. g.drawFittedText (filename,
  48194. x, 0, sizeX - x, height,
  48195. Justification::centredLeft, 1);
  48196. g.setFont (height * 0.5f);
  48197. g.setColour (Colours::darkgrey);
  48198. if (! isDirectory)
  48199. {
  48200. g.drawFittedText (fileSizeDescription,
  48201. sizeX, 0, dateX - sizeX - 8, height,
  48202. Justification::centredRight, 1);
  48203. g.drawFittedText (fileTimeDescription,
  48204. dateX, 0, width - 8 - dateX, height,
  48205. Justification::centredRight, 1);
  48206. }
  48207. }
  48208. else
  48209. {
  48210. g.drawFittedText (filename,
  48211. x, 0, width - x, height,
  48212. Justification::centredLeft, 1);
  48213. }
  48214. }
  48215. Button* LookAndFeel::createFileBrowserGoUpButton()
  48216. {
  48217. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  48218. Path arrowPath;
  48219. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  48220. DrawablePath arrowImage;
  48221. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  48222. arrowImage.setPath (arrowPath);
  48223. goUpButton->setImages (&arrowImage);
  48224. return goUpButton;
  48225. }
  48226. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  48227. DirectoryContentsDisplayComponent* fileListComponent,
  48228. FilePreviewComponent* previewComp,
  48229. ComboBox* currentPathBox,
  48230. TextEditor* filenameBox,
  48231. Button* goUpButton)
  48232. {
  48233. const int x = 8;
  48234. int w = browserComp.getWidth() - x - x;
  48235. if (previewComp != 0)
  48236. {
  48237. const int previewWidth = w / 3;
  48238. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  48239. w -= previewWidth + 4;
  48240. }
  48241. int y = 4;
  48242. const int controlsHeight = 22;
  48243. const int bottomSectionHeight = controlsHeight + 8;
  48244. const int upButtonWidth = 50;
  48245. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  48246. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  48247. y += controlsHeight + 4;
  48248. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  48249. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  48250. y = listAsComp->getBottom() + 4;
  48251. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  48252. }
  48253. Image* LookAndFeel::getDefaultFolderImage()
  48254. {
  48255. 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,
  48256. 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,
  48257. 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,
  48258. 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,
  48259. 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,
  48260. 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,
  48261. 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,
  48262. 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,
  48263. 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,
  48264. 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,
  48265. 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,
  48266. 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,
  48267. 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,
  48268. 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,
  48269. 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,
  48270. 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,
  48271. 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,
  48272. 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,
  48273. 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,
  48274. 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,
  48275. 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,
  48276. 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,
  48277. 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,
  48278. 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,
  48279. 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,
  48280. 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,
  48281. 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,
  48282. 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,
  48283. 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,
  48284. 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,
  48285. 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,
  48286. 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,
  48287. 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,
  48288. 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,
  48289. 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,
  48290. 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,
  48291. 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,
  48292. 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,
  48293. 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,
  48294. 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,
  48295. 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,
  48296. 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,
  48297. 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,
  48298. 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};
  48299. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  48300. }
  48301. Image* LookAndFeel::getDefaultDocumentFileImage()
  48302. {
  48303. 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,
  48304. 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,
  48305. 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,
  48306. 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,
  48307. 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,
  48308. 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,
  48309. 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,
  48310. 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,
  48311. 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,
  48312. 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,
  48313. 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,
  48314. 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,
  48315. 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,
  48316. 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,
  48317. 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,
  48318. 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,
  48319. 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,
  48320. 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,
  48321. 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,
  48322. 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,
  48323. 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,
  48324. 174,66,96,130,0,0};
  48325. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  48326. }
  48327. void LookAndFeel::playAlertSound()
  48328. {
  48329. PlatformUtilities::beep();
  48330. }
  48331. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  48332. {
  48333. g.setColour (Colours::white.withAlpha (0.7f));
  48334. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  48335. g.setColour (Colours::black.withAlpha (0.2f));
  48336. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  48337. const int totalBlocks = 7;
  48338. const int numBlocks = roundDoubleToInt (totalBlocks * level);
  48339. const float w = (width - 6.0f) / (float) totalBlocks;
  48340. for (int i = 0; i < totalBlocks; ++i)
  48341. {
  48342. if (i >= numBlocks)
  48343. g.setColour (Colours::lightblue.withAlpha (0.6f));
  48344. else
  48345. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  48346. : Colours::red);
  48347. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  48348. }
  48349. }
  48350. static void createRoundedPath (Path& p,
  48351. const float x, const float y,
  48352. const float w, const float h,
  48353. const float cs,
  48354. const bool curveTopLeft, const bool curveTopRight,
  48355. const bool curveBottomLeft, const bool curveBottomRight) throw()
  48356. {
  48357. const float cs2 = 2.0f * cs;
  48358. if (curveTopLeft)
  48359. {
  48360. p.startNewSubPath (x, y + cs);
  48361. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  48362. }
  48363. else
  48364. {
  48365. p.startNewSubPath (x, y);
  48366. }
  48367. if (curveTopRight)
  48368. {
  48369. p.lineTo (x + w - cs, y);
  48370. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  48371. }
  48372. else
  48373. {
  48374. p.lineTo (x + w, y);
  48375. }
  48376. if (curveBottomRight)
  48377. {
  48378. p.lineTo (x + w, y + h - cs);
  48379. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  48380. }
  48381. else
  48382. {
  48383. p.lineTo (x + w, y + h);
  48384. }
  48385. if (curveBottomLeft)
  48386. {
  48387. p.lineTo (x + cs, y + h);
  48388. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  48389. }
  48390. else
  48391. {
  48392. p.lineTo (x, y + h);
  48393. }
  48394. p.closeSubPath();
  48395. }
  48396. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  48397. float x, float y, float w, float h,
  48398. float maxCornerSize,
  48399. const Colour& baseColour,
  48400. const float strokeWidth,
  48401. const bool flatOnLeft,
  48402. const bool flatOnRight,
  48403. const bool flatOnTop,
  48404. const bool flatOnBottom) throw()
  48405. {
  48406. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  48407. return;
  48408. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  48409. Path outline;
  48410. createRoundedPath (outline, x, y, w, h, cs,
  48411. ! (flatOnLeft || flatOnTop),
  48412. ! (flatOnRight || flatOnTop),
  48413. ! (flatOnLeft || flatOnBottom),
  48414. ! (flatOnRight || flatOnBottom));
  48415. ColourGradient cg (baseColour, 0.0f, y,
  48416. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  48417. false);
  48418. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  48419. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  48420. GradientBrush gb (cg);
  48421. g.setBrush (&gb);
  48422. g.fillPath (outline);
  48423. g.setColour (Colour (0x80000000));
  48424. g.strokePath (outline, PathStrokeType (strokeWidth));
  48425. }
  48426. void LookAndFeel::drawGlassSphere (Graphics& g,
  48427. const float x, const float y,
  48428. const float diameter,
  48429. const Colour& colour,
  48430. const float outlineThickness) throw()
  48431. {
  48432. if (diameter <= outlineThickness)
  48433. return;
  48434. Path p;
  48435. p.addEllipse (x, y, diameter, diameter);
  48436. {
  48437. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  48438. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  48439. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  48440. GradientBrush gb (cg);
  48441. g.setBrush (&gb);
  48442. g.fillPath (p);
  48443. }
  48444. {
  48445. GradientBrush gb (Colours::white, 0, y + diameter * 0.06f,
  48446. Colours::transparentWhite, 0, y + diameter * 0.3f, false);
  48447. g.setBrush (&gb);
  48448. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  48449. }
  48450. {
  48451. ColourGradient cg (Colours::transparentBlack,
  48452. x + diameter * 0.5f, y + diameter * 0.5f,
  48453. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  48454. x, y + diameter * 0.5f, true);
  48455. cg.addColour (0.7, Colours::transparentBlack);
  48456. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  48457. GradientBrush gb (cg);
  48458. g.setBrush (&gb);
  48459. g.fillPath (p);
  48460. }
  48461. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  48462. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  48463. }
  48464. void LookAndFeel::drawGlassPointer (Graphics& g,
  48465. const float x, const float y,
  48466. const float diameter,
  48467. const Colour& colour, const float outlineThickness,
  48468. const int direction) throw()
  48469. {
  48470. if (diameter <= outlineThickness)
  48471. return;
  48472. Path p;
  48473. p.startNewSubPath (x + diameter * 0.5f, y);
  48474. p.lineTo (x + diameter, y + diameter * 0.6f);
  48475. p.lineTo (x + diameter, y + diameter);
  48476. p.lineTo (x, y + diameter);
  48477. p.lineTo (x, y + diameter * 0.6f);
  48478. p.closeSubPath();
  48479. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  48480. {
  48481. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  48482. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  48483. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  48484. GradientBrush gb (cg);
  48485. g.setBrush (&gb);
  48486. g.fillPath (p);
  48487. }
  48488. {
  48489. ColourGradient cg (Colours::transparentBlack,
  48490. x + diameter * 0.5f, y + diameter * 0.5f,
  48491. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  48492. x - diameter * 0.2f, y + diameter * 0.5f, true);
  48493. cg.addColour (0.5, Colours::transparentBlack);
  48494. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  48495. GradientBrush gb (cg);
  48496. g.setBrush (&gb);
  48497. g.fillPath (p);
  48498. }
  48499. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  48500. g.strokePath (p, PathStrokeType (outlineThickness));
  48501. }
  48502. void LookAndFeel::drawGlassLozenge (Graphics& g,
  48503. const float x, const float y,
  48504. const float width, const float height,
  48505. const Colour& colour,
  48506. const float outlineThickness,
  48507. const float cornerSize,
  48508. const bool flatOnLeft,
  48509. const bool flatOnRight,
  48510. const bool flatOnTop,
  48511. const bool flatOnBottom) throw()
  48512. {
  48513. if (width <= outlineThickness || height <= outlineThickness)
  48514. return;
  48515. const int intX = (int) x;
  48516. const int intY = (int) y;
  48517. const int intW = (int) width;
  48518. const int intH = (int) height;
  48519. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  48520. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  48521. const int intEdge = (int) edgeBlurRadius;
  48522. Path outline;
  48523. createRoundedPath (outline, x, y, width, height, cs,
  48524. ! (flatOnLeft || flatOnTop),
  48525. ! (flatOnRight || flatOnTop),
  48526. ! (flatOnLeft || flatOnBottom),
  48527. ! (flatOnRight || flatOnBottom));
  48528. {
  48529. ColourGradient cg (colour.darker (0.2f), 0, y,
  48530. colour.darker (0.2f), 0, y + height, false);
  48531. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  48532. cg.addColour (0.4, colour);
  48533. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  48534. GradientBrush gb (cg);
  48535. g.setBrush (&gb);
  48536. g.fillPath (outline);
  48537. }
  48538. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  48539. colour.darker (0.2f), x, y + height * 0.5f, true);
  48540. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  48541. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  48542. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  48543. {
  48544. GradientBrush gb (cg);
  48545. g.saveState();
  48546. g.setBrush (&gb);
  48547. g.reduceClipRegion (intX, intY, intEdge, intH);
  48548. g.fillPath (outline);
  48549. g.restoreState();
  48550. }
  48551. if (! (flatOnRight || flatOnTop || flatOnBottom))
  48552. {
  48553. cg.x1 = x + width - edgeBlurRadius;
  48554. cg.x2 = x + width;
  48555. GradientBrush gb (cg);
  48556. g.saveState();
  48557. g.setBrush (&gb);
  48558. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  48559. g.fillPath (outline);
  48560. g.restoreState();
  48561. }
  48562. {
  48563. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  48564. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  48565. Path highlight;
  48566. createRoundedPath (highlight,
  48567. x + leftIndent,
  48568. y + cs * 0.1f,
  48569. width - (leftIndent + rightIndent),
  48570. height * 0.4f, cs * 0.4f,
  48571. ! (flatOnLeft || flatOnTop),
  48572. ! (flatOnRight || flatOnTop),
  48573. ! (flatOnLeft || flatOnBottom),
  48574. ! (flatOnRight || flatOnBottom));
  48575. GradientBrush gb (colour.brighter (10.0f), 0, y + height * 0.06f,
  48576. Colours::transparentWhite, 0, y + height * 0.4f, false);
  48577. g.setBrush (&gb);
  48578. g.fillPath (highlight);
  48579. }
  48580. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  48581. g.strokePath (outline, PathStrokeType (outlineThickness));
  48582. }
  48583. END_JUCE_NAMESPACE
  48584. /********* End of inlined file: juce_LookAndFeel.cpp *********/
  48585. /********* Start of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  48586. BEGIN_JUCE_NAMESPACE
  48587. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  48588. {
  48589. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  48590. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  48591. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  48592. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  48593. setColour (Slider::thumbColourId, Colours::white);
  48594. setColour (Slider::trackColourId, Colour (0x7f000000));
  48595. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  48596. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  48597. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  48598. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  48599. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  48600. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  48601. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  48602. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  48603. }
  48604. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  48605. {
  48606. }
  48607. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  48608. Button& button,
  48609. const Colour& backgroundColour,
  48610. bool isMouseOverButton,
  48611. bool isButtonDown)
  48612. {
  48613. const int width = button.getWidth();
  48614. const int height = button.getHeight();
  48615. const float indent = 2.0f;
  48616. const int cornerSize = jmin (roundFloatToInt (width * 0.4f),
  48617. roundFloatToInt (height * 0.4f));
  48618. Path p;
  48619. p.addRoundedRectangle (indent, indent,
  48620. width - indent * 2.0f,
  48621. height - indent * 2.0f,
  48622. (float) cornerSize);
  48623. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  48624. if (isMouseOverButton)
  48625. {
  48626. if (isButtonDown)
  48627. bc = bc.brighter();
  48628. else if (bc.getBrightness() > 0.5f)
  48629. bc = bc.darker (0.1f);
  48630. else
  48631. bc = bc.brighter (0.1f);
  48632. }
  48633. g.setColour (bc);
  48634. g.fillPath (p);
  48635. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  48636. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  48637. }
  48638. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  48639. Component& /*component*/,
  48640. int x, int y, int w, int h,
  48641. const bool ticked,
  48642. const bool isEnabled,
  48643. const bool /*isMouseOverButton*/,
  48644. const bool isButtonDown)
  48645. {
  48646. Path box;
  48647. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  48648. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  48649. : Colours::lightgrey.withAlpha (0.1f));
  48650. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  48651. .translated ((float) x, (float) y));
  48652. g.fillPath (box, trans);
  48653. g.setColour (Colours::black.withAlpha (0.6f));
  48654. g.strokePath (box, PathStrokeType (0.9f), trans);
  48655. if (ticked)
  48656. {
  48657. Path tick;
  48658. tick.startNewSubPath (1.5f, 3.0f);
  48659. tick.lineTo (3.0f, 6.0f);
  48660. tick.lineTo (6.0f, 0.0f);
  48661. g.setColour (isEnabled ? Colours::black : Colours::grey);
  48662. g.strokePath (tick, PathStrokeType (2.5f), trans);
  48663. }
  48664. }
  48665. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  48666. ToggleButton& button,
  48667. bool isMouseOverButton,
  48668. bool isButtonDown)
  48669. {
  48670. if (button.hasKeyboardFocus (true))
  48671. {
  48672. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  48673. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  48674. }
  48675. const int tickWidth = jmin (20, button.getHeight() - 4);
  48676. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  48677. tickWidth, tickWidth,
  48678. button.getToggleState(),
  48679. button.isEnabled(),
  48680. isMouseOverButton,
  48681. isButtonDown);
  48682. g.setColour (button.findColour (ToggleButton::textColourId));
  48683. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  48684. if (! button.isEnabled())
  48685. g.setOpacity (0.5f);
  48686. const int textX = tickWidth + 5;
  48687. g.drawFittedText (button.getButtonText(),
  48688. textX, 4,
  48689. button.getWidth() - textX - 2, button.getHeight() - 8,
  48690. Justification::centredLeft, 10);
  48691. }
  48692. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  48693. int width, int height,
  48694. double progress, const String& textToShow)
  48695. {
  48696. if (progress < 0 || progress >= 1.0)
  48697. {
  48698. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  48699. }
  48700. else
  48701. {
  48702. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  48703. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  48704. g.fillAll (background);
  48705. g.setColour (foreground);
  48706. g.fillRect (1, 1,
  48707. jlimit (0, width - 2, roundDoubleToInt (progress * (width - 2))),
  48708. height - 2);
  48709. if (textToShow.isNotEmpty())
  48710. {
  48711. g.setColour (Colour::contrasting (background, foreground));
  48712. g.setFont (height * 0.6f);
  48713. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  48714. }
  48715. }
  48716. }
  48717. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  48718. ScrollBar& bar,
  48719. int width, int height,
  48720. int buttonDirection,
  48721. bool isScrollbarVertical,
  48722. bool isMouseOverButton,
  48723. bool isButtonDown)
  48724. {
  48725. if (isScrollbarVertical)
  48726. width -= 2;
  48727. else
  48728. height -= 2;
  48729. Path p;
  48730. if (buttonDirection == 0)
  48731. p.addTriangle (width * 0.5f, height * 0.2f,
  48732. width * 0.1f, height * 0.7f,
  48733. width * 0.9f, height * 0.7f);
  48734. else if (buttonDirection == 1)
  48735. p.addTriangle (width * 0.8f, height * 0.5f,
  48736. width * 0.3f, height * 0.1f,
  48737. width * 0.3f, height * 0.9f);
  48738. else if (buttonDirection == 2)
  48739. p.addTriangle (width * 0.5f, height * 0.8f,
  48740. width * 0.1f, height * 0.3f,
  48741. width * 0.9f, height * 0.3f);
  48742. else if (buttonDirection == 3)
  48743. p.addTriangle (width * 0.2f, height * 0.5f,
  48744. width * 0.7f, height * 0.1f,
  48745. width * 0.7f, height * 0.9f);
  48746. if (isButtonDown)
  48747. g.setColour (Colours::white);
  48748. else if (isMouseOverButton)
  48749. g.setColour (Colours::white.withAlpha (0.7f));
  48750. else
  48751. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  48752. g.fillPath (p);
  48753. g.setColour (Colours::black.withAlpha (0.5f));
  48754. g.strokePath (p, PathStrokeType (0.5f));
  48755. }
  48756. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  48757. ScrollBar& bar,
  48758. int x, int y,
  48759. int width, int height,
  48760. bool isScrollbarVertical,
  48761. int thumbStartPosition,
  48762. int thumbSize,
  48763. bool isMouseOver,
  48764. bool isMouseDown)
  48765. {
  48766. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  48767. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  48768. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  48769. if (thumbSize > 0.0f)
  48770. {
  48771. Rectangle thumb;
  48772. if (isScrollbarVertical)
  48773. {
  48774. width -= 2;
  48775. g.fillRect (x + roundFloatToInt (width * 0.35f), y,
  48776. roundFloatToInt (width * 0.3f), height);
  48777. thumb.setBounds (x + 1, thumbStartPosition,
  48778. width - 2, thumbSize);
  48779. }
  48780. else
  48781. {
  48782. height -= 2;
  48783. g.fillRect (x, y + roundFloatToInt (height * 0.35f),
  48784. width, roundFloatToInt (height * 0.3f));
  48785. thumb.setBounds (thumbStartPosition, y + 1,
  48786. thumbSize, height - 2);
  48787. }
  48788. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  48789. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  48790. g.fillRect (thumb);
  48791. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  48792. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  48793. if (thumbSize > 16)
  48794. {
  48795. for (int i = 3; --i >= 0;)
  48796. {
  48797. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  48798. g.setColour (Colours::black.withAlpha (0.15f));
  48799. if (isScrollbarVertical)
  48800. {
  48801. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  48802. g.setColour (Colours::white.withAlpha (0.15f));
  48803. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  48804. }
  48805. else
  48806. {
  48807. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  48808. g.setColour (Colours::white.withAlpha (0.15f));
  48809. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  48810. }
  48811. }
  48812. }
  48813. }
  48814. }
  48815. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  48816. {
  48817. return &scrollbarShadow;
  48818. }
  48819. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  48820. {
  48821. g.fillAll (findColour (PopupMenu::backgroundColourId));
  48822. g.setColour (Colours::black.withAlpha (0.6f));
  48823. g.drawRect (0, 0, width, height);
  48824. }
  48825. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  48826. bool, MenuBarComponent& menuBar)
  48827. {
  48828. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  48829. }
  48830. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  48831. {
  48832. if (textEditor.isEnabled())
  48833. {
  48834. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  48835. g.drawRect (0, 0, width, height);
  48836. }
  48837. }
  48838. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  48839. const bool isButtonDown,
  48840. int buttonX, int buttonY,
  48841. int buttonW, int buttonH,
  48842. ComboBox& box)
  48843. {
  48844. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  48845. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  48846. : ComboBox::backgroundColourId));
  48847. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  48848. g.setColour (box.findColour (ComboBox::outlineColourId));
  48849. g.drawRect (0, 0, width, height);
  48850. const float arrowX = 0.2f;
  48851. const float arrowH = 0.3f;
  48852. if (box.isEnabled())
  48853. {
  48854. Path p;
  48855. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  48856. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  48857. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  48858. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  48859. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  48860. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  48861. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  48862. : ComboBox::buttonColourId));
  48863. g.fillPath (p);
  48864. }
  48865. }
  48866. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  48867. {
  48868. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  48869. f.setHorizontalScale (0.9f);
  48870. return f;
  48871. }
  48872. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  48873. {
  48874. Path p;
  48875. p.addTriangle (x1, y1, x2, y2, x3, y3);
  48876. g.setColour (fill);
  48877. g.fillPath (p);
  48878. g.setColour (outline);
  48879. g.strokePath (p, PathStrokeType (0.3f));
  48880. }
  48881. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  48882. int x, int y,
  48883. int w, int h,
  48884. float sliderPos,
  48885. float minSliderPos,
  48886. float maxSliderPos,
  48887. const Slider::SliderStyle style,
  48888. Slider& slider)
  48889. {
  48890. g.fillAll (slider.findColour (Slider::backgroundColourId));
  48891. if (style == Slider::LinearBar)
  48892. {
  48893. g.setColour (slider.findColour (Slider::thumbColourId));
  48894. g.fillRect (x, y, (int) sliderPos - x, h);
  48895. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  48896. g.drawRect (x, y, (int) sliderPos - x, h);
  48897. }
  48898. else
  48899. {
  48900. g.setColour (slider.findColour (Slider::trackColourId)
  48901. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  48902. if (slider.isHorizontal())
  48903. {
  48904. g.fillRect (x, y + roundFloatToInt (h * 0.6f),
  48905. w, roundFloatToInt (h * 0.2f));
  48906. }
  48907. else
  48908. {
  48909. g.fillRect (x + roundFloatToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  48910. jmin (4, roundFloatToInt (w * 0.2f)), h);
  48911. }
  48912. float alpha = 0.35f;
  48913. if (slider.isEnabled())
  48914. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  48915. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  48916. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  48917. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  48918. {
  48919. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  48920. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  48921. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  48922. fill, outline);
  48923. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  48924. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  48925. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  48926. fill, outline);
  48927. }
  48928. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  48929. {
  48930. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  48931. minSliderPos - 7.0f, y + h * 0.9f ,
  48932. minSliderPos, y + h * 0.9f,
  48933. fill, outline);
  48934. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  48935. maxSliderPos, y + h * 0.9f,
  48936. maxSliderPos + 7.0f, y + h * 0.9f,
  48937. fill, outline);
  48938. }
  48939. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  48940. {
  48941. drawTriangle (g, sliderPos, y + h * 0.9f,
  48942. sliderPos - 7.0f, y + h * 0.2f,
  48943. sliderPos + 7.0f, y + h * 0.2f,
  48944. fill, outline);
  48945. }
  48946. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  48947. {
  48948. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  48949. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  48950. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  48951. fill, outline);
  48952. }
  48953. }
  48954. }
  48955. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  48956. {
  48957. if (isIncrement)
  48958. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  48959. else
  48960. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  48961. }
  48962. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  48963. {
  48964. return &scrollbarShadow;
  48965. }
  48966. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  48967. {
  48968. return 8;
  48969. }
  48970. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  48971. int w, int h,
  48972. bool isMouseOver,
  48973. bool isMouseDragging)
  48974. {
  48975. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  48976. : Colours::darkgrey);
  48977. const float lineThickness = jmin (w, h) * 0.1f;
  48978. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  48979. {
  48980. g.drawLine (w * i,
  48981. h + 1.0f,
  48982. w + 1.0f,
  48983. h * i,
  48984. lineThickness);
  48985. }
  48986. }
  48987. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  48988. {
  48989. Path shape;
  48990. if (buttonType == DocumentWindow::closeButton)
  48991. {
  48992. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, 0.35f);
  48993. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, 0.35f);
  48994. ShapeButton* const b = new ShapeButton ("close",
  48995. Colour (0x7fff3333),
  48996. Colour (0xd7ff3333),
  48997. Colour (0xf7ff3333));
  48998. b->setShape (shape, true, true, true);
  48999. return b;
  49000. }
  49001. else if (buttonType == DocumentWindow::minimiseButton)
  49002. {
  49003. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  49004. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  49005. DrawablePath dp;
  49006. dp.setPath (shape);
  49007. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  49008. b->setImages (&dp);
  49009. return b;
  49010. }
  49011. else if (buttonType == DocumentWindow::maximiseButton)
  49012. {
  49013. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, 0.25f);
  49014. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  49015. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  49016. DrawablePath dp;
  49017. dp.setPath (shape);
  49018. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  49019. b->setImages (&dp);
  49020. return b;
  49021. }
  49022. jassertfalse
  49023. return 0;
  49024. }
  49025. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  49026. int titleBarX,
  49027. int titleBarY,
  49028. int titleBarW,
  49029. int titleBarH,
  49030. Button* minimiseButton,
  49031. Button* maximiseButton,
  49032. Button* closeButton,
  49033. bool positionTitleBarButtonsOnLeft)
  49034. {
  49035. titleBarY += titleBarH / 8;
  49036. titleBarH -= titleBarH / 4;
  49037. const int buttonW = titleBarH;
  49038. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  49039. : titleBarX + titleBarW - buttonW - 4;
  49040. if (closeButton != 0)
  49041. {
  49042. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  49043. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  49044. : -(buttonW + buttonW / 5);
  49045. }
  49046. if (positionTitleBarButtonsOnLeft)
  49047. swapVariables (minimiseButton, maximiseButton);
  49048. if (maximiseButton != 0)
  49049. {
  49050. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  49051. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  49052. }
  49053. if (minimiseButton != 0)
  49054. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  49055. }
  49056. END_JUCE_NAMESPACE
  49057. /********* End of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  49058. /********* Start of inlined file: juce_MenuBarComponent.cpp *********/
  49059. BEGIN_JUCE_NAMESPACE
  49060. class DummyMenuComponent : public Component
  49061. {
  49062. DummyMenuComponent (const DummyMenuComponent&);
  49063. const DummyMenuComponent& operator= (const DummyMenuComponent&);
  49064. public:
  49065. DummyMenuComponent() {}
  49066. ~DummyMenuComponent() {}
  49067. void inputAttemptWhenModal()
  49068. {
  49069. exitModalState (0);
  49070. }
  49071. };
  49072. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  49073. : model (0),
  49074. itemUnderMouse (-1),
  49075. currentPopupIndex (-1),
  49076. indexToShowAgain (-1),
  49077. lastMouseX (0),
  49078. lastMouseY (0),
  49079. inModalState (false),
  49080. currentPopup (0)
  49081. {
  49082. setRepaintsOnMouseActivity (true);
  49083. setWantsKeyboardFocus (false);
  49084. setMouseClickGrabsKeyboardFocus (false);
  49085. setModel (model_);
  49086. }
  49087. MenuBarComponent::~MenuBarComponent()
  49088. {
  49089. setModel (0);
  49090. Desktop::getInstance().removeGlobalMouseListener (this);
  49091. deleteAndZero (currentPopup);
  49092. }
  49093. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  49094. {
  49095. if (model != newModel)
  49096. {
  49097. if (model != 0)
  49098. model->removeListener (this);
  49099. model = newModel;
  49100. if (model != 0)
  49101. model->addListener (this);
  49102. repaint();
  49103. menuBarItemsChanged (0);
  49104. }
  49105. }
  49106. void MenuBarComponent::paint (Graphics& g)
  49107. {
  49108. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  49109. getLookAndFeel().drawMenuBarBackground (g,
  49110. getWidth(),
  49111. getHeight(),
  49112. isMouseOverBar,
  49113. *this);
  49114. if (model != 0)
  49115. {
  49116. for (int i = 0; i < menuNames.size(); ++i)
  49117. {
  49118. g.saveState();
  49119. g.setOrigin (xPositions [i], 0);
  49120. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  49121. getLookAndFeel().drawMenuBarItem (g,
  49122. xPositions[i + 1] - xPositions[i],
  49123. getHeight(),
  49124. i,
  49125. menuNames[i],
  49126. i == itemUnderMouse,
  49127. i == currentPopupIndex,
  49128. isMouseOverBar,
  49129. *this);
  49130. g.restoreState();
  49131. }
  49132. }
  49133. }
  49134. void MenuBarComponent::resized()
  49135. {
  49136. xPositions.clear();
  49137. int x = 2;
  49138. xPositions.add (x);
  49139. for (int i = 0; i < menuNames.size(); ++i)
  49140. {
  49141. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  49142. xPositions.add (x);
  49143. }
  49144. }
  49145. int MenuBarComponent::getItemAt (const int x, const int y)
  49146. {
  49147. for (int i = 0; i < xPositions.size(); ++i)
  49148. if (x >= xPositions[i] && x < xPositions[i + 1])
  49149. return reallyContains (x, y, true) ? i : -1;
  49150. return -1;
  49151. }
  49152. void MenuBarComponent::repaintMenuItem (int index)
  49153. {
  49154. if (((unsigned int) index) < (unsigned int) xPositions.size())
  49155. {
  49156. const int x1 = xPositions [index];
  49157. const int x2 = xPositions [index + 1];
  49158. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  49159. }
  49160. }
  49161. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  49162. {
  49163. const int newItem = getItemAt (x, y);
  49164. if (itemUnderMouse != newItem)
  49165. {
  49166. repaintMenuItem (itemUnderMouse);
  49167. itemUnderMouse = newItem;
  49168. repaintMenuItem (itemUnderMouse);
  49169. }
  49170. }
  49171. void MenuBarComponent::hideCurrentMenu()
  49172. {
  49173. deleteAndZero (currentPopup);
  49174. repaint();
  49175. }
  49176. void MenuBarComponent::showMenu (int index)
  49177. {
  49178. if (index != currentPopupIndex)
  49179. {
  49180. if (inModalState)
  49181. {
  49182. hideCurrentMenu();
  49183. indexToShowAgain = index;
  49184. return;
  49185. }
  49186. indexToShowAgain = -1;
  49187. currentPopupIndex = -1;
  49188. deleteAndZero (currentPopup);
  49189. menuBarItemsChanged (0);
  49190. Component* const prevFocused = getCurrentlyFocusedComponent();
  49191. ComponentDeletionWatcher* prevCompDeletionChecker = 0;
  49192. if (prevFocused != 0)
  49193. prevCompDeletionChecker = new ComponentDeletionWatcher (prevFocused);
  49194. ComponentDeletionWatcher deletionChecker (this);
  49195. enterModalState (false);
  49196. inModalState = true;
  49197. int result = 0;
  49198. ApplicationCommandManager* managerOfChosenCommand = 0;
  49199. Desktop::getInstance().addGlobalMouseListener (this);
  49200. for (;;)
  49201. {
  49202. const int x = getScreenX() + xPositions [itemUnderMouse];
  49203. const int w = xPositions [itemUnderMouse + 1] - xPositions [itemUnderMouse];
  49204. currentPopupIndex = itemUnderMouse;
  49205. indexToShowAgain = -1;
  49206. repaint();
  49207. if (((unsigned int) itemUnderMouse) < (unsigned int) menuNames.size())
  49208. {
  49209. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  49210. menuNames [itemUnderMouse]));
  49211. currentPopup = m.createMenuComponent (x, getScreenY(),
  49212. w, getHeight(),
  49213. 0, w, 0, 0,
  49214. true, this,
  49215. &managerOfChosenCommand,
  49216. this);
  49217. }
  49218. if (currentPopup == 0)
  49219. {
  49220. currentPopup = new DummyMenuComponent();
  49221. addAndMakeVisible (currentPopup);
  49222. }
  49223. currentPopup->enterModalState (false);
  49224. currentPopup->toFront (false); // need to do this after making it modal, or it could
  49225. // be stuck behind other comps that are already modal..
  49226. result = currentPopup->runModalLoop();
  49227. if (deletionChecker.hasBeenDeleted())
  49228. {
  49229. delete prevCompDeletionChecker;
  49230. return;
  49231. }
  49232. const int lastPopupIndex = currentPopupIndex;
  49233. deleteAndZero (currentPopup);
  49234. currentPopupIndex = -1;
  49235. if (result != 0)
  49236. {
  49237. topLevelIndexClicked = lastPopupIndex;
  49238. break;
  49239. }
  49240. else if (indexToShowAgain >= 0)
  49241. {
  49242. menuBarItemsChanged (0);
  49243. repaint();
  49244. itemUnderMouse = indexToShowAgain;
  49245. if (((unsigned int) itemUnderMouse) >= (unsigned int) menuNames.size())
  49246. break;
  49247. }
  49248. else
  49249. {
  49250. break;
  49251. }
  49252. }
  49253. Desktop::getInstance().removeGlobalMouseListener (this);
  49254. inModalState = false;
  49255. exitModalState (0);
  49256. if (prevCompDeletionChecker != 0)
  49257. {
  49258. if (! prevCompDeletionChecker->hasBeenDeleted())
  49259. prevFocused->grabKeyboardFocus();
  49260. delete prevCompDeletionChecker;
  49261. }
  49262. int mx, my;
  49263. getMouseXYRelative (mx, my);
  49264. updateItemUnderMouse (mx, my);
  49265. repaint();
  49266. if (result != 0)
  49267. {
  49268. if (managerOfChosenCommand != 0)
  49269. {
  49270. ApplicationCommandTarget::InvocationInfo info (result);
  49271. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  49272. managerOfChosenCommand->invoke (info, true);
  49273. }
  49274. postCommandMessage (result);
  49275. }
  49276. }
  49277. }
  49278. void MenuBarComponent::handleCommandMessage (int commandId)
  49279. {
  49280. if (model != 0)
  49281. model->menuItemSelected (commandId, topLevelIndexClicked);
  49282. }
  49283. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  49284. {
  49285. if (e.eventComponent == this)
  49286. updateItemUnderMouse (e.x, e.y);
  49287. }
  49288. void MenuBarComponent::mouseExit (const MouseEvent& e)
  49289. {
  49290. if (e.eventComponent == this)
  49291. updateItemUnderMouse (e.x, e.y);
  49292. }
  49293. void MenuBarComponent::mouseDown (const MouseEvent& e)
  49294. {
  49295. const MouseEvent e2 (e.getEventRelativeTo (this));
  49296. if (currentPopupIndex < 0)
  49297. {
  49298. updateItemUnderMouse (e2.x, e2.y);
  49299. currentPopupIndex = -2;
  49300. showMenu (itemUnderMouse);
  49301. }
  49302. }
  49303. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  49304. {
  49305. const MouseEvent e2 (e.getEventRelativeTo (this));
  49306. const int item = getItemAt (e2.x, e2.y);
  49307. if (item >= 0)
  49308. showMenu (item);
  49309. }
  49310. void MenuBarComponent::mouseUp (const MouseEvent& e)
  49311. {
  49312. const MouseEvent e2 (e.getEventRelativeTo (this));
  49313. updateItemUnderMouse (e2.x, e2.y);
  49314. if (itemUnderMouse < 0 && dynamic_cast <DummyMenuComponent*> (currentPopup) != 0)
  49315. hideCurrentMenu();
  49316. }
  49317. void MenuBarComponent::mouseMove (const MouseEvent& e)
  49318. {
  49319. const MouseEvent e2 (e.getEventRelativeTo (this));
  49320. if (lastMouseX != e2.x || lastMouseY != e2.y)
  49321. {
  49322. if (currentPopupIndex >= 0)
  49323. {
  49324. const int item = getItemAt (e2.x, e2.y);
  49325. if (item >= 0)
  49326. showMenu (item);
  49327. }
  49328. else
  49329. {
  49330. updateItemUnderMouse (e2.x, e2.y);
  49331. }
  49332. lastMouseX = e2.x;
  49333. lastMouseY = e2.y;
  49334. }
  49335. }
  49336. bool MenuBarComponent::keyPressed (const KeyPress& key)
  49337. {
  49338. bool used = false;
  49339. const int numMenus = menuNames.size();
  49340. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  49341. if (key.isKeyCode (KeyPress::leftKey))
  49342. {
  49343. showMenu ((currentIndex + numMenus - 1) % numMenus);
  49344. used = true;
  49345. }
  49346. else if (key.isKeyCode (KeyPress::rightKey))
  49347. {
  49348. showMenu ((currentIndex + 1) % numMenus);
  49349. used = true;
  49350. }
  49351. return used;
  49352. }
  49353. void MenuBarComponent::inputAttemptWhenModal()
  49354. {
  49355. hideCurrentMenu();
  49356. }
  49357. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  49358. {
  49359. StringArray newNames;
  49360. if (model != 0)
  49361. newNames = model->getMenuBarNames();
  49362. if (newNames != menuNames)
  49363. {
  49364. menuNames = newNames;
  49365. repaint();
  49366. resized();
  49367. }
  49368. }
  49369. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  49370. const ApplicationCommandTarget::InvocationInfo& info)
  49371. {
  49372. if (model == 0
  49373. || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  49374. return;
  49375. for (int i = 0; i < menuNames.size(); ++i)
  49376. {
  49377. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  49378. if (menu.containsCommandItem (info.commandID))
  49379. {
  49380. itemUnderMouse = i;
  49381. repaintMenuItem (i);
  49382. startTimer (200);
  49383. break;
  49384. }
  49385. }
  49386. }
  49387. void MenuBarComponent::timerCallback()
  49388. {
  49389. stopTimer();
  49390. int mx, my;
  49391. getMouseXYRelative (mx, my);
  49392. updateItemUnderMouse (mx, my);
  49393. }
  49394. END_JUCE_NAMESPACE
  49395. /********* End of inlined file: juce_MenuBarComponent.cpp *********/
  49396. /********* Start of inlined file: juce_MenuBarModel.cpp *********/
  49397. BEGIN_JUCE_NAMESPACE
  49398. MenuBarModel::MenuBarModel() throw()
  49399. : manager (0)
  49400. {
  49401. }
  49402. MenuBarModel::~MenuBarModel()
  49403. {
  49404. setApplicationCommandManagerToWatch (0);
  49405. }
  49406. void MenuBarModel::menuItemsChanged()
  49407. {
  49408. triggerAsyncUpdate();
  49409. }
  49410. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  49411. {
  49412. if (manager != newManager)
  49413. {
  49414. if (manager != 0)
  49415. manager->removeListener (this);
  49416. manager = newManager;
  49417. if (manager != 0)
  49418. manager->addListener (this);
  49419. }
  49420. }
  49421. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  49422. {
  49423. jassert (newListener != 0);
  49424. jassert (! listeners.contains (newListener)); // trying to add a listener to the list twice!
  49425. if (newListener != 0)
  49426. listeners.add (newListener);
  49427. }
  49428. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  49429. {
  49430. // Trying to remove a listener that isn't on the list!
  49431. // If this assertion happens because this object is a dangling pointer, make sure you've not
  49432. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  49433. jassert (listeners.contains (listenerToRemove));
  49434. listeners.removeValue (listenerToRemove);
  49435. }
  49436. void MenuBarModel::handleAsyncUpdate()
  49437. {
  49438. for (int i = listeners.size(); --i >= 0;)
  49439. {
  49440. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuBarItemsChanged (this);
  49441. i = jmin (i, listeners.size());
  49442. }
  49443. }
  49444. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  49445. {
  49446. for (int i = listeners.size(); --i >= 0;)
  49447. {
  49448. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuCommandInvoked (this, info);
  49449. i = jmin (i, listeners.size());
  49450. }
  49451. }
  49452. void MenuBarModel::applicationCommandListChanged()
  49453. {
  49454. menuItemsChanged();
  49455. }
  49456. END_JUCE_NAMESPACE
  49457. /********* End of inlined file: juce_MenuBarModel.cpp *********/
  49458. /********* Start of inlined file: juce_PopupMenu.cpp *********/
  49459. BEGIN_JUCE_NAMESPACE
  49460. static VoidArray activeMenuWindows;
  49461. class MenuItemInfo
  49462. {
  49463. public:
  49464. const int itemId;
  49465. String text;
  49466. const Colour textColour;
  49467. const bool active, isSeparator, isTicked, usesColour;
  49468. Image* image;
  49469. PopupMenuCustomComponent* const customComp;
  49470. PopupMenu* subMenu;
  49471. ApplicationCommandManager* const commandManager;
  49472. MenuItemInfo() throw()
  49473. : itemId (0),
  49474. active (true),
  49475. isSeparator (true),
  49476. isTicked (false),
  49477. usesColour (false),
  49478. image (0),
  49479. customComp (0),
  49480. subMenu (0),
  49481. commandManager (0)
  49482. {
  49483. }
  49484. MenuItemInfo (const int itemId_,
  49485. const String& text_,
  49486. const bool active_,
  49487. const bool isTicked_,
  49488. const Image* im,
  49489. const Colour& textColour_,
  49490. const bool usesColour_,
  49491. PopupMenuCustomComponent* const customComp_,
  49492. const PopupMenu* const subMenu_,
  49493. ApplicationCommandManager* const commandManager_) throw()
  49494. : itemId (itemId_),
  49495. text (text_),
  49496. textColour (textColour_),
  49497. active (active_),
  49498. isSeparator (false),
  49499. isTicked (isTicked_),
  49500. usesColour (usesColour_),
  49501. image (0),
  49502. customComp (customComp_),
  49503. commandManager (commandManager_)
  49504. {
  49505. subMenu = (subMenu_ != 0) ? new PopupMenu (*subMenu_) : 0;
  49506. if (customComp != 0)
  49507. customComp->refCount_++;
  49508. if (im != 0)
  49509. image = im->createCopy();
  49510. if (commandManager_ != 0 && itemId_ != 0)
  49511. {
  49512. String shortcutKey;
  49513. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  49514. ->getKeyPressesAssignedToCommand (itemId_));
  49515. for (int i = 0; i < keyPresses.size(); ++i)
  49516. {
  49517. const String key (keyPresses.getReference(i).getTextDescription());
  49518. if (shortcutKey.isNotEmpty())
  49519. shortcutKey << ", ";
  49520. if (key.length() == 1)
  49521. shortcutKey << "shortcut: '" << key << '\'';
  49522. else
  49523. shortcutKey << key;
  49524. }
  49525. shortcutKey = shortcutKey.trim();
  49526. if (shortcutKey.isNotEmpty())
  49527. text << "<end>" << shortcutKey;
  49528. }
  49529. }
  49530. MenuItemInfo (const MenuItemInfo& other) throw()
  49531. : itemId (other.itemId),
  49532. text (other.text),
  49533. textColour (other.textColour),
  49534. active (other.active),
  49535. isSeparator (other.isSeparator),
  49536. isTicked (other.isTicked),
  49537. usesColour (other.usesColour),
  49538. customComp (other.customComp),
  49539. commandManager (other.commandManager)
  49540. {
  49541. if (other.subMenu != 0)
  49542. subMenu = new PopupMenu (*(other.subMenu));
  49543. else
  49544. subMenu = 0;
  49545. if (other.image != 0)
  49546. image = other.image->createCopy();
  49547. else
  49548. image = 0;
  49549. if (customComp != 0)
  49550. customComp->refCount_++;
  49551. }
  49552. ~MenuItemInfo() throw()
  49553. {
  49554. delete subMenu;
  49555. delete image;
  49556. if (customComp != 0 && --(customComp->refCount_) == 0)
  49557. delete customComp;
  49558. }
  49559. bool canBeTriggered() const throw()
  49560. {
  49561. return active && ! (isSeparator || (subMenu != 0));
  49562. }
  49563. bool hasActiveSubMenu() const throw()
  49564. {
  49565. return active && (subMenu != 0);
  49566. }
  49567. juce_UseDebuggingNewOperator
  49568. private:
  49569. const MenuItemInfo& operator= (const MenuItemInfo&);
  49570. };
  49571. class MenuItemComponent : public Component
  49572. {
  49573. bool isHighlighted;
  49574. public:
  49575. MenuItemInfo itemInfo;
  49576. MenuItemComponent (const MenuItemInfo& itemInfo_)
  49577. : isHighlighted (false),
  49578. itemInfo (itemInfo_)
  49579. {
  49580. if (itemInfo.customComp != 0)
  49581. addAndMakeVisible (itemInfo.customComp);
  49582. }
  49583. ~MenuItemComponent()
  49584. {
  49585. if (itemInfo.customComp != 0)
  49586. removeChildComponent (itemInfo.customComp);
  49587. }
  49588. void getIdealSize (int& idealWidth,
  49589. int& idealHeight,
  49590. const int standardItemHeight)
  49591. {
  49592. if (itemInfo.customComp != 0)
  49593. {
  49594. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  49595. }
  49596. else
  49597. {
  49598. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  49599. itemInfo.isSeparator,
  49600. standardItemHeight,
  49601. idealWidth,
  49602. idealHeight);
  49603. }
  49604. }
  49605. void paint (Graphics& g)
  49606. {
  49607. if (itemInfo.customComp == 0)
  49608. {
  49609. String mainText (itemInfo.text);
  49610. String endText;
  49611. const int endIndex = mainText.indexOf (T("<end>"));
  49612. if (endIndex >= 0)
  49613. {
  49614. endText = mainText.substring (endIndex + 5).trim();
  49615. mainText = mainText.substring (0, endIndex);
  49616. }
  49617. getLookAndFeel()
  49618. .drawPopupMenuItem (g, getWidth(), getHeight(),
  49619. itemInfo.isSeparator,
  49620. itemInfo.active,
  49621. isHighlighted,
  49622. itemInfo.isTicked,
  49623. itemInfo.subMenu != 0,
  49624. mainText, endText,
  49625. itemInfo.image,
  49626. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  49627. }
  49628. }
  49629. void resized()
  49630. {
  49631. if (getNumChildComponents() > 0)
  49632. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  49633. }
  49634. void setHighlighted (bool shouldBeHighlighted)
  49635. {
  49636. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  49637. if (isHighlighted != shouldBeHighlighted)
  49638. {
  49639. isHighlighted = shouldBeHighlighted;
  49640. if (itemInfo.customComp != 0)
  49641. {
  49642. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  49643. itemInfo.customComp->repaint();
  49644. }
  49645. repaint();
  49646. }
  49647. }
  49648. private:
  49649. MenuItemComponent (const MenuItemComponent&);
  49650. const MenuItemComponent& operator= (const MenuItemComponent&);
  49651. };
  49652. static const int scrollZone = 24;
  49653. static const int borderSize = 2;
  49654. static const int timerInterval = 50;
  49655. static const int dismissCommandId = 0x6287345f;
  49656. static bool wasHiddenBecauseOfAppChange = false;
  49657. class PopupMenuWindow : public Component,
  49658. private Timer
  49659. {
  49660. public:
  49661. PopupMenuWindow() throw()
  49662. : Component (T("menu")),
  49663. owner (0),
  49664. currentChild (0),
  49665. activeSubMenu (0),
  49666. menuBarComponent (0),
  49667. managerOfChosenCommand (0),
  49668. componentAttachedTo (0),
  49669. attachedCompWatcher (0),
  49670. lastMouseX (0),
  49671. lastMouseY (0),
  49672. minimumWidth (0),
  49673. maximumNumColumns (7),
  49674. standardItemHeight (0),
  49675. isOver (false),
  49676. hasBeenOver (false),
  49677. isDown (false),
  49678. needsToScroll (false),
  49679. hideOnExit (false),
  49680. disableMouseMoves (false),
  49681. hasAnyJuceCompHadFocus (false),
  49682. numColumns (0),
  49683. contentHeight (0),
  49684. childYOffset (0),
  49685. timeEnteredCurrentChildComp (0),
  49686. scrollAcceleration (1.0)
  49687. {
  49688. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  49689. setWantsKeyboardFocus (true);
  49690. setOpaque (true);
  49691. setAlwaysOnTop (true);
  49692. Desktop::getInstance().addGlobalMouseListener (this);
  49693. activeMenuWindows.add (this);
  49694. }
  49695. ~PopupMenuWindow()
  49696. {
  49697. activeMenuWindows.removeValue (this);
  49698. Desktop::getInstance().removeGlobalMouseListener (this);
  49699. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  49700. delete activeSubMenu;
  49701. deleteAllChildren();
  49702. delete attachedCompWatcher;
  49703. }
  49704. static PopupMenuWindow* create (const PopupMenu& menu,
  49705. const bool dismissOnMouseUp,
  49706. PopupMenuWindow* const owner_,
  49707. const int minX, const int maxX,
  49708. const int minY, const int maxY,
  49709. const int minimumWidth,
  49710. const int maximumNumColumns,
  49711. const int standardItemHeight,
  49712. const bool alignToRectangle,
  49713. const int itemIdThatMustBeVisible,
  49714. Component* const menuBarComponent,
  49715. ApplicationCommandManager** managerOfChosenCommand,
  49716. Component* const componentAttachedTo) throw()
  49717. {
  49718. if (menu.items.size() > 0)
  49719. {
  49720. int totalItems = 0;
  49721. PopupMenuWindow* const mw = new PopupMenuWindow();
  49722. mw->setLookAndFeel (menu.lookAndFeel);
  49723. mw->setWantsKeyboardFocus (false);
  49724. mw->minimumWidth = minimumWidth;
  49725. mw->maximumNumColumns = maximumNumColumns;
  49726. mw->standardItemHeight = standardItemHeight;
  49727. mw->dismissOnMouseUp = dismissOnMouseUp;
  49728. for (int i = 0; i < menu.items.size(); ++i)
  49729. {
  49730. MenuItemInfo* const item = (MenuItemInfo*) menu.items.getUnchecked(i);
  49731. mw->addItem (*item);
  49732. ++totalItems;
  49733. }
  49734. if (totalItems == 0)
  49735. {
  49736. delete mw;
  49737. }
  49738. else
  49739. {
  49740. mw->owner = owner_;
  49741. mw->menuBarComponent = menuBarComponent;
  49742. mw->managerOfChosenCommand = managerOfChosenCommand;
  49743. mw->componentAttachedTo = componentAttachedTo;
  49744. delete mw->attachedCompWatcher;
  49745. mw->attachedCompWatcher = componentAttachedTo != 0 ? new ComponentDeletionWatcher (componentAttachedTo) : 0;
  49746. mw->calculateWindowPos (minX, maxX, minY, maxY, alignToRectangle);
  49747. mw->setTopLeftPosition (mw->windowPos.getX(),
  49748. mw->windowPos.getY());
  49749. mw->updateYPositions();
  49750. if (itemIdThatMustBeVisible != 0)
  49751. {
  49752. const int y = minY - mw->windowPos.getY();
  49753. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  49754. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  49755. }
  49756. mw->resizeToBestWindowPos();
  49757. mw->addToDesktop (ComponentPeer::windowIsTemporary
  49758. | mw->getLookAndFeel().getMenuWindowFlags());
  49759. return mw;
  49760. }
  49761. }
  49762. return 0;
  49763. }
  49764. void paint (Graphics& g)
  49765. {
  49766. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  49767. }
  49768. void paintOverChildren (Graphics& g)
  49769. {
  49770. if (isScrolling())
  49771. {
  49772. LookAndFeel& lf = getLookAndFeel();
  49773. if (isScrollZoneActive (false))
  49774. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, true);
  49775. if (isScrollZoneActive (true))
  49776. {
  49777. g.setOrigin (0, getHeight() - scrollZone);
  49778. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, false);
  49779. }
  49780. }
  49781. }
  49782. bool isScrollZoneActive (bool bottomOne) const
  49783. {
  49784. return isScrolling()
  49785. && (bottomOne
  49786. ? childYOffset < contentHeight - windowPos.getHeight()
  49787. : childYOffset > 0);
  49788. }
  49789. void addItem (const MenuItemInfo& item) throw()
  49790. {
  49791. MenuItemComponent* const mic = new MenuItemComponent (item);
  49792. addAndMakeVisible (mic);
  49793. int itemW = 80;
  49794. int itemH = 16;
  49795. mic->getIdealSize (itemW, itemH, standardItemHeight);
  49796. mic->setSize (itemW, jlimit (10, 600, itemH));
  49797. mic->addMouseListener (this, false);
  49798. }
  49799. // hide this and all sub-comps
  49800. void hide (const MenuItemInfo* const item) throw()
  49801. {
  49802. if (isVisible())
  49803. {
  49804. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  49805. deleteAndZero (activeSubMenu);
  49806. currentChild = 0;
  49807. exitModalState (item != 0 ? item->itemId : 0);
  49808. setVisible (false);
  49809. if (item != 0
  49810. && item->commandManager != 0
  49811. && item->itemId != 0)
  49812. {
  49813. *managerOfChosenCommand = item->commandManager;
  49814. }
  49815. }
  49816. }
  49817. void dismissMenu (const MenuItemInfo* const item) throw()
  49818. {
  49819. if (owner != 0)
  49820. {
  49821. owner->dismissMenu (item);
  49822. }
  49823. else
  49824. {
  49825. if (item != 0)
  49826. {
  49827. // need a copy of this on the stack as the one passed in will get deleted during this call
  49828. const MenuItemInfo mi (*item);
  49829. hide (&mi);
  49830. }
  49831. else
  49832. {
  49833. hide (0);
  49834. }
  49835. }
  49836. }
  49837. void mouseMove (const MouseEvent&)
  49838. {
  49839. timerCallback();
  49840. }
  49841. void mouseDown (const MouseEvent&)
  49842. {
  49843. timerCallback();
  49844. }
  49845. void mouseDrag (const MouseEvent&)
  49846. {
  49847. timerCallback();
  49848. }
  49849. void mouseUp (const MouseEvent&)
  49850. {
  49851. timerCallback();
  49852. }
  49853. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  49854. {
  49855. alterChildYPos (roundFloatToInt (-10.0f * amountY * scrollZone));
  49856. lastMouseX = -1;
  49857. }
  49858. bool keyPressed (const KeyPress& key)
  49859. {
  49860. if (key.isKeyCode (KeyPress::downKey))
  49861. {
  49862. selectNextItem (1);
  49863. }
  49864. else if (key.isKeyCode (KeyPress::upKey))
  49865. {
  49866. selectNextItem (-1);
  49867. }
  49868. else if (key.isKeyCode (KeyPress::leftKey))
  49869. {
  49870. PopupMenuWindow* parentWindow = owner;
  49871. if (parentWindow != 0)
  49872. {
  49873. MenuItemComponent* currentChildOfParent
  49874. = (parentWindow != 0) ? parentWindow->currentChild : 0;
  49875. hide (0);
  49876. if (parentWindow->isValidComponent())
  49877. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  49878. disableTimerUntilMouseMoves();
  49879. }
  49880. else if (menuBarComponent != 0)
  49881. {
  49882. menuBarComponent->keyPressed (key);
  49883. }
  49884. }
  49885. else if (key.isKeyCode (KeyPress::rightKey))
  49886. {
  49887. disableTimerUntilMouseMoves();
  49888. if (showSubMenuFor (currentChild))
  49889. {
  49890. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  49891. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  49892. activeSubMenu->selectNextItem (1);
  49893. }
  49894. else if (menuBarComponent != 0)
  49895. {
  49896. menuBarComponent->keyPressed (key);
  49897. }
  49898. }
  49899. else if (key.isKeyCode (KeyPress::returnKey))
  49900. {
  49901. triggerCurrentlyHighlightedItem();
  49902. }
  49903. else if (key.isKeyCode (KeyPress::escapeKey))
  49904. {
  49905. dismissMenu (0);
  49906. }
  49907. else
  49908. {
  49909. return false;
  49910. }
  49911. return true;
  49912. }
  49913. void inputAttemptWhenModal()
  49914. {
  49915. timerCallback();
  49916. if (! isOverAnyMenu())
  49917. {
  49918. if (componentAttachedTo != 0 && ! attachedCompWatcher->hasBeenDeleted())
  49919. {
  49920. // we want to dismiss the menu, but if we do it synchronously, then
  49921. // the mouse-click will be allowed to pass through. That's good, except
  49922. // when the user clicks on the button that orginally popped the menu up,
  49923. // as they'll expect the menu to go away, and in fact it'll just
  49924. // come back. So only dismiss synchronously if they're not on the original
  49925. // comp that we're attached to.
  49926. int mx, my;
  49927. componentAttachedTo->getMouseXYRelative (mx, my);
  49928. if (componentAttachedTo->reallyContains (mx, my, true))
  49929. {
  49930. postCommandMessage (dismissCommandId); // dismiss asynchrounously
  49931. return;
  49932. }
  49933. }
  49934. dismissMenu (0);
  49935. }
  49936. }
  49937. void handleCommandMessage (int commandId)
  49938. {
  49939. Component::handleCommandMessage (commandId);
  49940. if (commandId == dismissCommandId)
  49941. dismissMenu (0);
  49942. }
  49943. void timerCallback()
  49944. {
  49945. if (! isVisible())
  49946. return;
  49947. if (attachedCompWatcher != 0 && attachedCompWatcher->hasBeenDeleted())
  49948. {
  49949. dismissMenu (0);
  49950. return;
  49951. }
  49952. PopupMenuWindow* currentlyModalWindow = dynamic_cast <PopupMenuWindow*> (Component::getCurrentlyModalComponent());
  49953. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  49954. return;
  49955. startTimer (timerInterval); // do this in case it was called from a mouse
  49956. // move rather than a real timer callback
  49957. int mx, my;
  49958. Desktop::getMousePosition (mx, my);
  49959. int x = mx, y = my;
  49960. globalPositionToRelative (x, y);
  49961. const uint32 now = Time::getMillisecondCounter();
  49962. if (now > timeEnteredCurrentChildComp + 100
  49963. && reallyContains (x, y, true)
  49964. && currentChild->isValidComponent()
  49965. && (! disableMouseMoves)
  49966. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  49967. {
  49968. showSubMenuFor (currentChild);
  49969. }
  49970. if (mx != lastMouseX || my != lastMouseY || now > lastMouseMoveTime + 350)
  49971. {
  49972. highlightItemUnderMouse (mx, my, x, y);
  49973. }
  49974. bool overScrollArea = false;
  49975. if (isScrolling()
  49976. && (isOver || (isDown && ((unsigned int) x) < (unsigned int) getWidth()))
  49977. && ((isScrollZoneActive (false) && y < scrollZone)
  49978. || (isScrollZoneActive (true) && y > getHeight() - scrollZone)))
  49979. {
  49980. if (now > lastScroll + 20)
  49981. {
  49982. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  49983. int amount = 0;
  49984. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  49985. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  49986. alterChildYPos (y < scrollZone ? -amount : amount);
  49987. lastScroll = now;
  49988. }
  49989. overScrollArea = true;
  49990. lastMouseX = -1; // trigger a mouse-move
  49991. }
  49992. else
  49993. {
  49994. scrollAcceleration = 1.0;
  49995. }
  49996. const bool wasDown = isDown;
  49997. bool isOverAny = isOverAnyMenu();
  49998. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  49999. {
  50000. activeSubMenu->updateMouseOverStatus (mx, my);
  50001. isOverAny = isOverAnyMenu();
  50002. }
  50003. if (hideOnExit && hasBeenOver && ! isOverAny)
  50004. {
  50005. hide (0);
  50006. }
  50007. else
  50008. {
  50009. isDown = hasBeenOver
  50010. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  50011. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  50012. bool anyFocused = Process::isForegroundProcess();
  50013. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  50014. {
  50015. // because no component at all may have focus, our test here will
  50016. // only be triggered when something has focus and then loses it.
  50017. anyFocused = ! hasAnyJuceCompHadFocus;
  50018. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  50019. {
  50020. if (ComponentPeer::getPeer (i)->isFocused())
  50021. {
  50022. anyFocused = true;
  50023. hasAnyJuceCompHadFocus = true;
  50024. break;
  50025. }
  50026. }
  50027. }
  50028. if (! anyFocused)
  50029. {
  50030. if (now > lastFocused + 10)
  50031. {
  50032. wasHiddenBecauseOfAppChange = true;
  50033. dismissMenu (0);
  50034. return; // may have been deleted by the previous call..
  50035. }
  50036. }
  50037. else if (wasDown && now > menuCreationTime + 250
  50038. && ! (isDown || overScrollArea))
  50039. {
  50040. isOver = reallyContains (x, y, true);
  50041. if (isOver)
  50042. {
  50043. triggerCurrentlyHighlightedItem();
  50044. }
  50045. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  50046. {
  50047. dismissMenu (0);
  50048. }
  50049. return; // may have been deleted by the previous calls..
  50050. }
  50051. else
  50052. {
  50053. lastFocused = now;
  50054. }
  50055. }
  50056. }
  50057. juce_UseDebuggingNewOperator
  50058. private:
  50059. PopupMenuWindow* owner;
  50060. MenuItemComponent* currentChild;
  50061. PopupMenuWindow* activeSubMenu;
  50062. Component* menuBarComponent;
  50063. ApplicationCommandManager** managerOfChosenCommand;
  50064. Component* componentAttachedTo;
  50065. ComponentDeletionWatcher* attachedCompWatcher;
  50066. Rectangle windowPos;
  50067. int lastMouseX, lastMouseY;
  50068. int minimumWidth, maximumNumColumns, standardItemHeight;
  50069. bool isOver, hasBeenOver, isDown, needsToScroll;
  50070. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  50071. int numColumns, contentHeight, childYOffset;
  50072. Array <int> columnWidths;
  50073. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  50074. double scrollAcceleration;
  50075. bool overlaps (const Rectangle& r) const throw()
  50076. {
  50077. return r.intersects (getBounds())
  50078. || (owner != 0 && owner->overlaps (r));
  50079. }
  50080. bool isOverAnyMenu() const throw()
  50081. {
  50082. return (owner != 0) ? owner->isOverAnyMenu()
  50083. : isOverChildren();
  50084. }
  50085. bool isOverChildren() const throw()
  50086. {
  50087. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  50088. return isVisible()
  50089. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  50090. }
  50091. void updateMouseOverStatus (const int mx, const int my) throw()
  50092. {
  50093. int rx = mx, ry = my;
  50094. globalPositionToRelative (rx, ry);
  50095. isOver = reallyContains (rx, ry, true);
  50096. if (activeSubMenu != 0)
  50097. activeSubMenu->updateMouseOverStatus (mx, my);
  50098. }
  50099. bool treeContains (const PopupMenuWindow* const window) const throw()
  50100. {
  50101. const PopupMenuWindow* mw = this;
  50102. while (mw->owner != 0)
  50103. mw = mw->owner;
  50104. while (mw != 0)
  50105. {
  50106. if (mw == window)
  50107. return true;
  50108. mw = mw->activeSubMenu;
  50109. }
  50110. return false;
  50111. }
  50112. void calculateWindowPos (const int minX, const int maxX,
  50113. const int minY, const int maxY,
  50114. const bool alignToRectangle)
  50115. {
  50116. const Rectangle mon (Desktop::getInstance()
  50117. .getMonitorAreaContaining ((minX + maxX) / 2,
  50118. (minY + maxY) / 2,
  50119. true));
  50120. int x, y, widthToUse, heightToUse;
  50121. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  50122. if (alignToRectangle)
  50123. {
  50124. x = minX;
  50125. const int spaceUnder = mon.getHeight() - (maxY - mon.getY());
  50126. const int spaceOver = minY - mon.getY();
  50127. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  50128. y = maxY;
  50129. else
  50130. y = minY - heightToUse;
  50131. }
  50132. else
  50133. {
  50134. bool tendTowardsRight = (minX + maxX) / 2 < mon.getCentreX();
  50135. if (owner != 0)
  50136. {
  50137. if (owner->owner != 0)
  50138. {
  50139. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  50140. > owner->owner->getX() + owner->owner->getWidth() / 2);
  50141. if (ownerGoingRight && maxX + widthToUse < mon.getRight() - 4)
  50142. tendTowardsRight = true;
  50143. else if ((! ownerGoingRight) && minX > widthToUse + 4)
  50144. tendTowardsRight = false;
  50145. }
  50146. else if (maxX + widthToUse < mon.getRight() - 32)
  50147. {
  50148. tendTowardsRight = true;
  50149. }
  50150. }
  50151. const int biggestSpace = jmax (mon.getRight() - maxX,
  50152. minX - mon.getX()) - 32;
  50153. if (biggestSpace < widthToUse)
  50154. {
  50155. layoutMenuItems (biggestSpace + (maxX - minX) / 3, widthToUse, heightToUse);
  50156. if (numColumns > 1)
  50157. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  50158. tendTowardsRight = (mon.getRight() - maxX) >= (minX - mon.getX());
  50159. }
  50160. if (tendTowardsRight)
  50161. x = jmin (mon.getRight() - widthToUse - 4, maxX);
  50162. else
  50163. x = jmax (mon.getX() + 4, minX - widthToUse);
  50164. y = minY;
  50165. if ((minY + maxY) / 2 > mon.getCentreY())
  50166. y = jmax (mon.getY(), maxY - heightToUse);
  50167. }
  50168. x = jlimit (mon.getX() + 1, mon.getRight() - (widthToUse + 6), x);
  50169. y = jlimit (mon.getY() + 1, mon.getBottom() - (heightToUse + 6), y);
  50170. windowPos.setBounds (x, y, widthToUse, heightToUse);
  50171. // sets this flag if it's big enough to obscure any of its parent menus
  50172. hideOnExit = (owner != 0)
  50173. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  50174. }
  50175. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  50176. {
  50177. numColumns = 0;
  50178. contentHeight = 0;
  50179. const int maxMenuH = getParentHeight() - 24;
  50180. int totalW;
  50181. do
  50182. {
  50183. ++numColumns;
  50184. totalW = workOutBestSize (numColumns, maxMenuW);
  50185. if (totalW > maxMenuW)
  50186. {
  50187. numColumns = jmax (1, numColumns - 1);
  50188. totalW = workOutBestSize (numColumns, maxMenuW); // to update col widths
  50189. break;
  50190. }
  50191. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  50192. {
  50193. break;
  50194. }
  50195. } while (numColumns < maximumNumColumns);
  50196. const int actualH = jmin (contentHeight, maxMenuH);
  50197. needsToScroll = contentHeight > actualH;
  50198. width = updateYPositions();
  50199. height = actualH + borderSize * 2;
  50200. }
  50201. int workOutBestSize (const int numColumns, const int maxMenuW)
  50202. {
  50203. int totalW = 0;
  50204. contentHeight = 0;
  50205. int childNum = 0;
  50206. for (int col = 0; col < numColumns; ++col)
  50207. {
  50208. int i, colW = 50, colH = 0;
  50209. const int numChildren = jmin (getNumChildComponents() - childNum,
  50210. (getNumChildComponents() + numColumns - 1) / numColumns);
  50211. for (i = numChildren; --i >= 0;)
  50212. {
  50213. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  50214. colH += getChildComponent (childNum + i)->getHeight();
  50215. }
  50216. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + borderSize * 2);
  50217. columnWidths.set (col, colW);
  50218. totalW += colW;
  50219. contentHeight = jmax (contentHeight, colH);
  50220. childNum += numChildren;
  50221. }
  50222. if (totalW < minimumWidth)
  50223. {
  50224. totalW = minimumWidth;
  50225. for (int col = 0; col < numColumns; ++col)
  50226. columnWidths.set (0, totalW / numColumns);
  50227. }
  50228. return totalW;
  50229. }
  50230. void ensureItemIsVisible (const int itemId, int wantedY)
  50231. {
  50232. jassert (itemId != 0)
  50233. for (int i = getNumChildComponents(); --i >= 0;)
  50234. {
  50235. MenuItemComponent* const m = (MenuItemComponent*) getChildComponent (i);
  50236. if (m != 0
  50237. && m->itemInfo.itemId == itemId
  50238. && windowPos.getHeight() > scrollZone * 4)
  50239. {
  50240. const int currentY = m->getY();
  50241. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  50242. {
  50243. if (wantedY < 0)
  50244. wantedY = jlimit (scrollZone,
  50245. jmax (scrollZone, windowPos.getHeight() - (scrollZone + m->getHeight())),
  50246. currentY);
  50247. const Rectangle mon (Desktop::getInstance()
  50248. .getMonitorAreaContaining (windowPos.getX(),
  50249. windowPos.getY(),
  50250. true));
  50251. int deltaY = wantedY - currentY;
  50252. const int newY = jlimit (mon.getY(),
  50253. mon.getBottom() - windowPos.getHeight(),
  50254. windowPos.getY() + deltaY);
  50255. deltaY -= newY - windowPos.getY();
  50256. childYOffset -= deltaY;
  50257. windowPos.setPosition (windowPos.getX(), newY);
  50258. updateYPositions();
  50259. }
  50260. break;
  50261. }
  50262. }
  50263. }
  50264. void resizeToBestWindowPos()
  50265. {
  50266. Rectangle r (windowPos);
  50267. if (childYOffset < 0)
  50268. {
  50269. r.setBounds (r.getX(), r.getY() - childYOffset,
  50270. r.getWidth(), r.getHeight() + childYOffset);
  50271. }
  50272. else if (childYOffset > 0)
  50273. {
  50274. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  50275. if (spaceAtBottom > 0)
  50276. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  50277. }
  50278. setBounds (r);
  50279. updateYPositions();
  50280. }
  50281. void alterChildYPos (const int delta)
  50282. {
  50283. if (isScrolling())
  50284. {
  50285. childYOffset += delta;
  50286. if (delta < 0)
  50287. {
  50288. childYOffset = jmax (childYOffset, 0);
  50289. }
  50290. else if (delta > 0)
  50291. {
  50292. childYOffset = jmin (childYOffset,
  50293. contentHeight - windowPos.getHeight() + borderSize);
  50294. }
  50295. updateYPositions();
  50296. }
  50297. else
  50298. {
  50299. childYOffset = 0;
  50300. }
  50301. resizeToBestWindowPos();
  50302. repaint();
  50303. }
  50304. int updateYPositions()
  50305. {
  50306. int x = 0;
  50307. int childNum = 0;
  50308. for (int col = 0; col < numColumns; ++col)
  50309. {
  50310. const int numChildren = jmin (getNumChildComponents() - childNum,
  50311. (getNumChildComponents() + numColumns - 1) / numColumns);
  50312. const int colW = columnWidths [col];
  50313. int y = borderSize - (childYOffset + (getY() - windowPos.getY()));
  50314. for (int i = 0; i < numChildren; ++i)
  50315. {
  50316. Component* const c = getChildComponent (childNum + i);
  50317. c->setBounds (x, y, colW, c->getHeight());
  50318. y += c->getHeight();
  50319. }
  50320. x += colW;
  50321. childNum += numChildren;
  50322. }
  50323. return x;
  50324. }
  50325. bool isScrolling() const throw()
  50326. {
  50327. return childYOffset != 0 || needsToScroll;
  50328. }
  50329. void setCurrentlyHighlightedChild (MenuItemComponent* const child) throw()
  50330. {
  50331. if (currentChild->isValidComponent())
  50332. currentChild->setHighlighted (false);
  50333. currentChild = child;
  50334. if (currentChild != 0)
  50335. {
  50336. currentChild->setHighlighted (true);
  50337. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  50338. }
  50339. }
  50340. bool showSubMenuFor (MenuItemComponent* const childComp)
  50341. {
  50342. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  50343. deleteAndZero (activeSubMenu);
  50344. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  50345. {
  50346. int left = 0, top = 0;
  50347. childComp->relativePositionToGlobal (left, top);
  50348. int right = childComp->getWidth(), bottom = childComp->getHeight();
  50349. childComp->relativePositionToGlobal (right, bottom);
  50350. activeSubMenu = PopupMenuWindow::create (*(childComp->itemInfo.subMenu),
  50351. dismissOnMouseUp,
  50352. this,
  50353. left, right, top, bottom,
  50354. 0, maximumNumColumns,
  50355. standardItemHeight,
  50356. false, 0, menuBarComponent,
  50357. managerOfChosenCommand,
  50358. componentAttachedTo);
  50359. if (activeSubMenu != 0)
  50360. {
  50361. activeSubMenu->setVisible (true);
  50362. activeSubMenu->enterModalState (false);
  50363. activeSubMenu->toFront (false);
  50364. return true;
  50365. }
  50366. }
  50367. return false;
  50368. }
  50369. void highlightItemUnderMouse (const int mx, const int my, const int x, const int y)
  50370. {
  50371. isOver = reallyContains (x, y, true);
  50372. if (isOver)
  50373. hasBeenOver = true;
  50374. if (abs (lastMouseX - mx) > 2 || abs (lastMouseY - my) > 2)
  50375. {
  50376. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  50377. if (disableMouseMoves && isOver)
  50378. disableMouseMoves = false;
  50379. }
  50380. if (disableMouseMoves)
  50381. return;
  50382. bool isMovingTowardsMenu = false;
  50383. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  50384. if (isOver && (activeSubMenu != 0) && (mx != lastMouseX || my != lastMouseY))
  50385. {
  50386. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  50387. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  50388. // extends from the last mouse pos to the submenu's rectangle..
  50389. float subX = (float) activeSubMenu->getScreenX();
  50390. if (activeSubMenu->getX() > getX())
  50391. {
  50392. lastMouseX -= 2; // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  50393. }
  50394. else
  50395. {
  50396. lastMouseX += 2;
  50397. subX += activeSubMenu->getWidth();
  50398. }
  50399. Path areaTowardsSubMenu;
  50400. areaTowardsSubMenu.addTriangle ((float) lastMouseX,
  50401. (float) lastMouseY,
  50402. subX,
  50403. (float) activeSubMenu->getScreenY(),
  50404. subX,
  50405. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  50406. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) mx, (float) my);
  50407. }
  50408. lastMouseX = mx;
  50409. lastMouseY = my;
  50410. if (! isMovingTowardsMenu)
  50411. {
  50412. Component* c = getComponentAt (x, y);
  50413. if (c == this)
  50414. c = 0;
  50415. MenuItemComponent* mic = dynamic_cast <MenuItemComponent*> (c);
  50416. if (mic == 0 && c != 0)
  50417. mic = c->findParentComponentOfClass ((MenuItemComponent*) 0);
  50418. if (mic != currentChild
  50419. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  50420. {
  50421. if (isOver && (c != 0) && (activeSubMenu != 0))
  50422. {
  50423. activeSubMenu->hide (0);
  50424. }
  50425. if (! isOver)
  50426. mic = 0;
  50427. setCurrentlyHighlightedChild (mic);
  50428. }
  50429. }
  50430. }
  50431. void triggerCurrentlyHighlightedItem()
  50432. {
  50433. if (currentChild->isValidComponent()
  50434. && currentChild->itemInfo.canBeTriggered()
  50435. && (currentChild->itemInfo.customComp == 0
  50436. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  50437. {
  50438. dismissMenu (&currentChild->itemInfo);
  50439. }
  50440. }
  50441. void selectNextItem (const int delta)
  50442. {
  50443. disableTimerUntilMouseMoves();
  50444. MenuItemComponent* mic = 0;
  50445. bool wasLastOne = (currentChild == 0);
  50446. const int numItems = getNumChildComponents();
  50447. for (int i = 0; i < numItems + 1; ++i)
  50448. {
  50449. int index = (delta > 0) ? i : (numItems - 1 - i);
  50450. index = (index + numItems) % numItems;
  50451. mic = dynamic_cast <MenuItemComponent*> (getChildComponent (index));
  50452. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  50453. && wasLastOne)
  50454. break;
  50455. if (mic == currentChild)
  50456. wasLastOne = true;
  50457. }
  50458. setCurrentlyHighlightedChild (mic);
  50459. }
  50460. void disableTimerUntilMouseMoves() throw()
  50461. {
  50462. disableMouseMoves = true;
  50463. if (owner != 0)
  50464. owner->disableTimerUntilMouseMoves();
  50465. }
  50466. PopupMenuWindow (const PopupMenuWindow&);
  50467. const PopupMenuWindow& operator= (const PopupMenuWindow&);
  50468. };
  50469. PopupMenu::PopupMenu() throw()
  50470. : items (8),
  50471. lookAndFeel (0),
  50472. separatorPending (false)
  50473. {
  50474. }
  50475. PopupMenu::PopupMenu (const PopupMenu& other) throw()
  50476. : items (8),
  50477. lookAndFeel (other.lookAndFeel),
  50478. separatorPending (false)
  50479. {
  50480. items.ensureStorageAllocated (other.items.size());
  50481. for (int i = 0; i < other.items.size(); ++i)
  50482. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  50483. }
  50484. const PopupMenu& PopupMenu::operator= (const PopupMenu& other) throw()
  50485. {
  50486. if (this != &other)
  50487. {
  50488. lookAndFeel = other.lookAndFeel;
  50489. clear();
  50490. items.ensureStorageAllocated (other.items.size());
  50491. for (int i = 0; i < other.items.size(); ++i)
  50492. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  50493. }
  50494. return *this;
  50495. }
  50496. PopupMenu::~PopupMenu() throw()
  50497. {
  50498. clear();
  50499. }
  50500. void PopupMenu::clear() throw()
  50501. {
  50502. for (int i = items.size(); --i >= 0;)
  50503. {
  50504. MenuItemInfo* const mi = (MenuItemInfo*) items.getUnchecked(i);
  50505. delete mi;
  50506. }
  50507. items.clear();
  50508. separatorPending = false;
  50509. }
  50510. void PopupMenu::addSeparatorIfPending()
  50511. {
  50512. if (separatorPending)
  50513. {
  50514. separatorPending = false;
  50515. if (items.size() > 0)
  50516. items.add (new MenuItemInfo());
  50517. }
  50518. }
  50519. void PopupMenu::addItem (const int itemResultId,
  50520. const String& itemText,
  50521. const bool isActive,
  50522. const bool isTicked,
  50523. const Image* const iconToUse) throw()
  50524. {
  50525. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  50526. // didn't pick anything, so you shouldn't use it as the id
  50527. // for an item..
  50528. addSeparatorIfPending();
  50529. items.add (new MenuItemInfo (itemResultId,
  50530. itemText,
  50531. isActive,
  50532. isTicked,
  50533. iconToUse,
  50534. Colours::black,
  50535. false,
  50536. 0, 0, 0));
  50537. }
  50538. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  50539. const int commandID,
  50540. const String& displayName) throw()
  50541. {
  50542. jassert (commandManager != 0 && commandID != 0);
  50543. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  50544. if (registeredInfo != 0)
  50545. {
  50546. ApplicationCommandInfo info (*registeredInfo);
  50547. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  50548. addSeparatorIfPending();
  50549. items.add (new MenuItemInfo (commandID,
  50550. displayName.isNotEmpty() ? displayName
  50551. : info.shortName,
  50552. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  50553. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  50554. 0,
  50555. Colours::black,
  50556. false,
  50557. 0, 0,
  50558. commandManager));
  50559. }
  50560. }
  50561. void PopupMenu::addColouredItem (const int itemResultId,
  50562. const String& itemText,
  50563. const Colour& itemTextColour,
  50564. const bool isActive,
  50565. const bool isTicked,
  50566. const Image* const iconToUse) throw()
  50567. {
  50568. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  50569. // didn't pick anything, so you shouldn't use it as the id
  50570. // for an item..
  50571. addSeparatorIfPending();
  50572. items.add (new MenuItemInfo (itemResultId,
  50573. itemText,
  50574. isActive,
  50575. isTicked,
  50576. iconToUse,
  50577. itemTextColour,
  50578. true,
  50579. 0, 0, 0));
  50580. }
  50581. void PopupMenu::addCustomItem (const int itemResultId,
  50582. PopupMenuCustomComponent* const customComponent) throw()
  50583. {
  50584. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  50585. // didn't pick anything, so you shouldn't use it as the id
  50586. // for an item..
  50587. addSeparatorIfPending();
  50588. items.add (new MenuItemInfo (itemResultId,
  50589. String::empty,
  50590. true,
  50591. false,
  50592. 0,
  50593. Colours::black,
  50594. false,
  50595. customComponent,
  50596. 0, 0));
  50597. }
  50598. class NormalComponentWrapper : public PopupMenuCustomComponent
  50599. {
  50600. public:
  50601. NormalComponentWrapper (Component* const comp,
  50602. const int w, const int h,
  50603. const bool triggerMenuItemAutomaticallyWhenClicked)
  50604. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  50605. width (w),
  50606. height (h)
  50607. {
  50608. addAndMakeVisible (comp);
  50609. }
  50610. ~NormalComponentWrapper() {}
  50611. void getIdealSize (int& idealWidth, int& idealHeight)
  50612. {
  50613. idealWidth = width;
  50614. idealHeight = height;
  50615. }
  50616. void resized()
  50617. {
  50618. if (getChildComponent(0) != 0)
  50619. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  50620. }
  50621. juce_UseDebuggingNewOperator
  50622. private:
  50623. const int width, height;
  50624. NormalComponentWrapper (const NormalComponentWrapper&);
  50625. const NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  50626. };
  50627. void PopupMenu::addCustomItem (const int itemResultId,
  50628. Component* customComponent,
  50629. int idealWidth, int idealHeight,
  50630. const bool triggerMenuItemAutomaticallyWhenClicked) throw()
  50631. {
  50632. addCustomItem (itemResultId,
  50633. new NormalComponentWrapper (customComponent,
  50634. idealWidth, idealHeight,
  50635. triggerMenuItemAutomaticallyWhenClicked));
  50636. }
  50637. void PopupMenu::addSubMenu (const String& subMenuName,
  50638. const PopupMenu& subMenu,
  50639. const bool isActive,
  50640. Image* const iconToUse) throw()
  50641. {
  50642. addSeparatorIfPending();
  50643. items.add (new MenuItemInfo (0,
  50644. subMenuName,
  50645. isActive && (subMenu.getNumItems() > 0),
  50646. false,
  50647. iconToUse,
  50648. Colours::black,
  50649. false,
  50650. 0,
  50651. &subMenu,
  50652. 0));
  50653. }
  50654. void PopupMenu::addSeparator() throw()
  50655. {
  50656. separatorPending = true;
  50657. }
  50658. class HeaderItemComponent : public PopupMenuCustomComponent
  50659. {
  50660. public:
  50661. HeaderItemComponent (const String& name)
  50662. : PopupMenuCustomComponent (false)
  50663. {
  50664. setName (name);
  50665. }
  50666. ~HeaderItemComponent()
  50667. {
  50668. }
  50669. void paint (Graphics& g)
  50670. {
  50671. Font f (getLookAndFeel().getPopupMenuFont());
  50672. f.setBold (true);
  50673. g.setFont (f);
  50674. g.setColour (findColour (PopupMenu::headerTextColourId));
  50675. g.drawFittedText (getName(),
  50676. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  50677. Justification::bottomLeft, 1);
  50678. }
  50679. void getIdealSize (int& idealWidth,
  50680. int& idealHeight)
  50681. {
  50682. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  50683. idealHeight += idealHeight / 2;
  50684. idealWidth += idealWidth / 4;
  50685. }
  50686. juce_UseDebuggingNewOperator
  50687. };
  50688. void PopupMenu::addSectionHeader (const String& title) throw()
  50689. {
  50690. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  50691. }
  50692. Component* PopupMenu::createMenuComponent (const int x, const int y, const int w, const int h,
  50693. const int itemIdThatMustBeVisible,
  50694. const int minimumWidth,
  50695. const int maximumNumColumns,
  50696. const int standardItemHeight,
  50697. const bool alignToRectangle,
  50698. Component* menuBarComponent,
  50699. ApplicationCommandManager** managerOfChosenCommand,
  50700. Component* const componentAttachedTo) throw()
  50701. {
  50702. PopupMenuWindow* const pw
  50703. = PopupMenuWindow::create (*this,
  50704. ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  50705. 0,
  50706. x, x + w,
  50707. y, y + h,
  50708. minimumWidth,
  50709. maximumNumColumns,
  50710. standardItemHeight,
  50711. alignToRectangle,
  50712. itemIdThatMustBeVisible,
  50713. menuBarComponent,
  50714. managerOfChosenCommand,
  50715. componentAttachedTo);
  50716. if (pw != 0)
  50717. pw->setVisible (true);
  50718. return pw;
  50719. }
  50720. int PopupMenu::showMenu (const int x, const int y, const int w, const int h,
  50721. const int itemIdThatMustBeVisible,
  50722. const int minimumWidth,
  50723. const int maximumNumColumns,
  50724. const int standardItemHeight,
  50725. const bool alignToRectangle,
  50726. Component* const componentAttachedTo) throw()
  50727. {
  50728. Component* const prevFocused = Component::getCurrentlyFocusedComponent();
  50729. ComponentDeletionWatcher* deletionChecker1 = 0;
  50730. if (prevFocused != 0)
  50731. deletionChecker1 = new ComponentDeletionWatcher (prevFocused);
  50732. Component* const prevTopLevel = (prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0;
  50733. ComponentDeletionWatcher* deletionChecker2 = 0;
  50734. if (prevTopLevel != 0)
  50735. deletionChecker2 = new ComponentDeletionWatcher (prevTopLevel);
  50736. wasHiddenBecauseOfAppChange = false;
  50737. int result = 0;
  50738. ApplicationCommandManager* managerOfChosenCommand = 0;
  50739. Component* const popupComp = createMenuComponent (x, y, w, h,
  50740. itemIdThatMustBeVisible,
  50741. minimumWidth,
  50742. maximumNumColumns > 0 ? maximumNumColumns : 7,
  50743. standardItemHeight,
  50744. alignToRectangle, 0,
  50745. &managerOfChosenCommand,
  50746. componentAttachedTo);
  50747. if (popupComp != 0)
  50748. {
  50749. popupComp->enterModalState (false);
  50750. popupComp->toFront (false); // need to do this after making it modal, or it could
  50751. // be stuck behind other comps that are already modal..
  50752. result = popupComp->runModalLoop();
  50753. delete popupComp;
  50754. if (! wasHiddenBecauseOfAppChange)
  50755. {
  50756. if (deletionChecker2 != 0 && ! deletionChecker2->hasBeenDeleted())
  50757. prevTopLevel->toFront (true);
  50758. if (deletionChecker1 != 0 && ! deletionChecker1->hasBeenDeleted())
  50759. prevFocused->grabKeyboardFocus();
  50760. }
  50761. }
  50762. delete deletionChecker1;
  50763. delete deletionChecker2;
  50764. if (managerOfChosenCommand != 0 && result != 0)
  50765. {
  50766. ApplicationCommandTarget::InvocationInfo info (result);
  50767. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  50768. managerOfChosenCommand->invoke (info, true);
  50769. }
  50770. return result;
  50771. }
  50772. int PopupMenu::show (const int itemIdThatMustBeVisible,
  50773. const int minimumWidth,
  50774. const int maximumNumColumns,
  50775. const int standardItemHeight)
  50776. {
  50777. int x, y;
  50778. Desktop::getMousePosition (x, y);
  50779. return showAt (x, y,
  50780. itemIdThatMustBeVisible,
  50781. minimumWidth,
  50782. maximumNumColumns,
  50783. standardItemHeight);
  50784. }
  50785. int PopupMenu::showAt (const int screenX,
  50786. const int screenY,
  50787. const int itemIdThatMustBeVisible,
  50788. const int minimumWidth,
  50789. const int maximumNumColumns,
  50790. const int standardItemHeight)
  50791. {
  50792. return showMenu (screenX, screenY, 1, 1,
  50793. itemIdThatMustBeVisible,
  50794. minimumWidth, maximumNumColumns,
  50795. standardItemHeight,
  50796. false, 0);
  50797. }
  50798. int PopupMenu::showAt (Component* componentToAttachTo,
  50799. const int itemIdThatMustBeVisible,
  50800. const int minimumWidth,
  50801. const int maximumNumColumns,
  50802. const int standardItemHeight)
  50803. {
  50804. if (componentToAttachTo != 0)
  50805. {
  50806. return showMenu (componentToAttachTo->getScreenX(),
  50807. componentToAttachTo->getScreenY(),
  50808. componentToAttachTo->getWidth(),
  50809. componentToAttachTo->getHeight(),
  50810. itemIdThatMustBeVisible,
  50811. minimumWidth,
  50812. maximumNumColumns,
  50813. standardItemHeight,
  50814. true, componentToAttachTo);
  50815. }
  50816. else
  50817. {
  50818. return show (itemIdThatMustBeVisible,
  50819. minimumWidth,
  50820. maximumNumColumns,
  50821. standardItemHeight);
  50822. }
  50823. }
  50824. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus() throw()
  50825. {
  50826. for (int i = activeMenuWindows.size(); --i >= 0;)
  50827. {
  50828. PopupMenuWindow* const pmw = (PopupMenuWindow*) activeMenuWindows[i];
  50829. if (pmw != 0)
  50830. pmw->dismissMenu (0);
  50831. }
  50832. }
  50833. int PopupMenu::getNumItems() const throw()
  50834. {
  50835. int num = 0;
  50836. for (int i = items.size(); --i >= 0;)
  50837. if (! ((MenuItemInfo*) items.getUnchecked(i))->isSeparator)
  50838. ++num;
  50839. return num;
  50840. }
  50841. bool PopupMenu::containsCommandItem (const int commandID) const throw()
  50842. {
  50843. for (int i = items.size(); --i >= 0;)
  50844. {
  50845. const MenuItemInfo* mi = (const MenuItemInfo*) items.getUnchecked (i);
  50846. if ((mi->itemId == commandID && mi->commandManager != 0)
  50847. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  50848. {
  50849. return true;
  50850. }
  50851. }
  50852. return false;
  50853. }
  50854. bool PopupMenu::containsAnyActiveItems() const throw()
  50855. {
  50856. for (int i = items.size(); --i >= 0;)
  50857. {
  50858. const MenuItemInfo* const mi = (const MenuItemInfo*) items.getUnchecked (i);
  50859. if (mi->subMenu != 0)
  50860. {
  50861. if (mi->subMenu->containsAnyActiveItems())
  50862. return true;
  50863. }
  50864. else if (mi->active)
  50865. {
  50866. return true;
  50867. }
  50868. }
  50869. return false;
  50870. }
  50871. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel) throw()
  50872. {
  50873. lookAndFeel = newLookAndFeel;
  50874. }
  50875. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  50876. : refCount_ (0),
  50877. isHighlighted (false),
  50878. isTriggeredAutomatically (isTriggeredAutomatically_)
  50879. {
  50880. }
  50881. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  50882. {
  50883. jassert (refCount_ == 0); // should be deleted only by the menu component, as they keep a ref-count.
  50884. }
  50885. void PopupMenuCustomComponent::triggerMenuItem()
  50886. {
  50887. MenuItemComponent* const mic = dynamic_cast<MenuItemComponent*> (getParentComponent());
  50888. if (mic != 0)
  50889. {
  50890. PopupMenuWindow* const pmw = dynamic_cast<PopupMenuWindow*> (mic->getParentComponent());
  50891. if (pmw != 0)
  50892. {
  50893. pmw->dismissMenu (&mic->itemInfo);
  50894. }
  50895. else
  50896. {
  50897. // something must have gone wrong with the component hierarchy if this happens..
  50898. jassertfalse
  50899. }
  50900. }
  50901. else
  50902. {
  50903. // why isn't this component inside a menu? Not much point triggering the item if
  50904. // there's no menu.
  50905. jassertfalse
  50906. }
  50907. }
  50908. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_) throw()
  50909. : subMenu (0),
  50910. itemId (0),
  50911. isSeparator (false),
  50912. isTicked (false),
  50913. isEnabled (false),
  50914. isCustomComponent (false),
  50915. isSectionHeader (false),
  50916. customColour (0),
  50917. customImage (0),
  50918. menu (menu_),
  50919. index (0)
  50920. {
  50921. }
  50922. PopupMenu::MenuItemIterator::~MenuItemIterator() throw()
  50923. {
  50924. }
  50925. bool PopupMenu::MenuItemIterator::next() throw()
  50926. {
  50927. if (index >= menu.items.size())
  50928. return false;
  50929. const MenuItemInfo* const item = (const MenuItemInfo*) menu.items.getUnchecked (index);
  50930. ++index;
  50931. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  50932. subMenu = item->subMenu;
  50933. itemId = item->itemId;
  50934. isSeparator = item->isSeparator;
  50935. isTicked = item->isTicked;
  50936. isEnabled = item->active;
  50937. isSectionHeader = dynamic_cast <HeaderItemComponent*> (item->customComp) != 0;
  50938. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  50939. customColour = item->usesColour ? &(item->textColour) : 0;
  50940. customImage = item->image;
  50941. commandManager = item->commandManager;
  50942. return true;
  50943. }
  50944. END_JUCE_NAMESPACE
  50945. /********* End of inlined file: juce_PopupMenu.cpp *********/
  50946. /********* Start of inlined file: juce_ComponentDragger.cpp *********/
  50947. BEGIN_JUCE_NAMESPACE
  50948. ComponentDragger::ComponentDragger()
  50949. : constrainer (0),
  50950. originalX (0),
  50951. originalY (0)
  50952. {
  50953. }
  50954. ComponentDragger::~ComponentDragger()
  50955. {
  50956. }
  50957. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  50958. ComponentBoundsConstrainer* const constrainer_)
  50959. {
  50960. jassert (componentToDrag->isValidComponent());
  50961. if (componentToDrag->isValidComponent())
  50962. {
  50963. constrainer = constrainer_;
  50964. originalX = 0;
  50965. originalY = 0;
  50966. componentToDrag->relativePositionToGlobal (originalX, originalY);
  50967. }
  50968. }
  50969. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  50970. {
  50971. jassert (componentToDrag->isValidComponent());
  50972. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  50973. if (componentToDrag->isValidComponent())
  50974. {
  50975. int x = originalX + e.getDistanceFromDragStartX();
  50976. int y = originalY + e.getDistanceFromDragStartY();
  50977. int w = componentToDrag->getWidth();
  50978. int h = componentToDrag->getHeight();
  50979. const Component* const parentComp = componentToDrag->getParentComponent();
  50980. if (parentComp != 0)
  50981. parentComp->globalPositionToRelative (x, y);
  50982. if (constrainer != 0)
  50983. constrainer->setBoundsForComponent (componentToDrag, x, y, w, h,
  50984. false, false, false, false);
  50985. else
  50986. componentToDrag->setBounds (x, y, w, h);
  50987. }
  50988. }
  50989. END_JUCE_NAMESPACE
  50990. /********* End of inlined file: juce_ComponentDragger.cpp *********/
  50991. /********* Start of inlined file: juce_DragAndDropContainer.cpp *********/
  50992. BEGIN_JUCE_NAMESPACE
  50993. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  50994. bool juce_performDragDropText (const String& text, bool& shouldStop);
  50995. class DragImageComponent : public Component,
  50996. public Timer
  50997. {
  50998. private:
  50999. Image* image;
  51000. Component* const source;
  51001. DragAndDropContainer* const owner;
  51002. ComponentDeletionWatcher* sourceWatcher;
  51003. Component* mouseDragSource;
  51004. ComponentDeletionWatcher* mouseDragSourceWatcher;
  51005. DragAndDropTarget* currentlyOver;
  51006. String dragDesc;
  51007. int xOff, yOff;
  51008. bool hasCheckedForExternalDrag, drawImage;
  51009. DragImageComponent (const DragImageComponent&);
  51010. const DragImageComponent& operator= (const DragImageComponent&);
  51011. public:
  51012. DragImageComponent (Image* const im,
  51013. const String& desc,
  51014. Component* const s,
  51015. DragAndDropContainer* const o)
  51016. : image (im),
  51017. source (s),
  51018. owner (o),
  51019. currentlyOver (0),
  51020. dragDesc (desc),
  51021. hasCheckedForExternalDrag (false),
  51022. drawImage (true)
  51023. {
  51024. setSize (im->getWidth(), im->getHeight());
  51025. sourceWatcher = new ComponentDeletionWatcher (source);
  51026. mouseDragSource = Component::getComponentUnderMouse();
  51027. if (mouseDragSource == 0)
  51028. mouseDragSource = source;
  51029. mouseDragSourceWatcher = new ComponentDeletionWatcher (mouseDragSource);
  51030. mouseDragSource->addMouseListener (this, false);
  51031. int mx, my;
  51032. Desktop::getLastMouseDownPosition (mx, my);
  51033. source->globalPositionToRelative (mx, my);
  51034. xOff = jlimit (0, im->getWidth(), mx);
  51035. yOff = jlimit (0, im->getHeight(), my);
  51036. startTimer (200);
  51037. setInterceptsMouseClicks (false, false);
  51038. setAlwaysOnTop (true);
  51039. }
  51040. ~DragImageComponent()
  51041. {
  51042. if (owner->dragImageComponent == this)
  51043. owner->dragImageComponent = 0;
  51044. if (((Component*) currentlyOver)->isValidComponent())
  51045. {
  51046. Component* const over = dynamic_cast <Component*> (currentlyOver);
  51047. if (over != 0
  51048. && over->isValidComponent()
  51049. && source->isValidComponent()
  51050. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  51051. {
  51052. currentlyOver->itemDragExit (dragDesc, source);
  51053. }
  51054. }
  51055. if (! mouseDragSourceWatcher->hasBeenDeleted())
  51056. mouseDragSource->removeMouseListener (this);
  51057. delete mouseDragSourceWatcher;
  51058. delete sourceWatcher;
  51059. delete image;
  51060. }
  51061. void paint (Graphics& g)
  51062. {
  51063. if (isOpaque())
  51064. g.fillAll (Colours::white);
  51065. if (drawImage)
  51066. {
  51067. g.setOpacity (1.0f);
  51068. g.drawImageAt (image, 0, 0);
  51069. }
  51070. }
  51071. DragAndDropTarget* findTarget (const int screenX, const int screenY,
  51072. int& relX, int& relY) const throw()
  51073. {
  51074. Component* hit = getParentComponent();
  51075. if (hit == 0)
  51076. {
  51077. hit = Desktop::getInstance().findComponentAt (screenX, screenY);
  51078. }
  51079. else
  51080. {
  51081. int rx = screenX, ry = screenY;
  51082. hit->globalPositionToRelative (rx, ry);
  51083. hit = hit->getComponentAt (rx, ry);
  51084. }
  51085. while (hit != 0)
  51086. {
  51087. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  51088. if (ddt != 0 && ddt->isInterestedInDragSource (dragDesc, source))
  51089. {
  51090. relX = screenX;
  51091. relY = screenY;
  51092. hit->globalPositionToRelative (relX, relY);
  51093. return ddt;
  51094. }
  51095. hit = hit->getParentComponent();
  51096. }
  51097. return 0;
  51098. }
  51099. void mouseUp (const MouseEvent& e)
  51100. {
  51101. if (e.originalComponent != this)
  51102. {
  51103. if (! mouseDragSourceWatcher->hasBeenDeleted())
  51104. mouseDragSource->removeMouseListener (this);
  51105. bool dropAccepted = false;
  51106. DragAndDropTarget* ddt = 0;
  51107. int relX = 0, relY = 0;
  51108. if (isVisible())
  51109. {
  51110. setVisible (false);
  51111. ddt = findTarget (e.getScreenX(),
  51112. e.getScreenY(),
  51113. relX, relY);
  51114. // fade this component and remove it - it'll be deleted later by the timer callback
  51115. dropAccepted = ddt != 0;
  51116. setVisible (true);
  51117. if (dropAccepted || sourceWatcher->hasBeenDeleted())
  51118. {
  51119. fadeOutComponent (120);
  51120. }
  51121. else
  51122. {
  51123. int targetX = source->getWidth() / 2;
  51124. int targetY = source->getHeight() / 2;
  51125. source->relativePositionToGlobal (targetX, targetY);
  51126. int ourCentreX = getWidth() / 2;
  51127. int ourCentreY = getHeight() / 2;
  51128. relativePositionToGlobal (ourCentreX, ourCentreY);
  51129. fadeOutComponent (120,
  51130. targetX - ourCentreX,
  51131. targetY - ourCentreY);
  51132. }
  51133. }
  51134. if (getParentComponent() != 0)
  51135. getParentComponent()->removeChildComponent (this);
  51136. if (dropAccepted && ddt != 0)
  51137. ddt->itemDropped (dragDesc, source, relX, relY);
  51138. // careful - this object could now be deleted..
  51139. }
  51140. }
  51141. void updateLocation (const bool canDoExternalDrag, int x, int y)
  51142. {
  51143. int newX = x - xOff;
  51144. int newY = y - yOff;
  51145. if (getParentComponent() != 0)
  51146. getParentComponent()->globalPositionToRelative (newX, newY);
  51147. if (newX != getX() || newY != getY())
  51148. {
  51149. setTopLeftPosition (newX, newY);
  51150. int relX = 0, relY = 0;
  51151. DragAndDropTarget* const ddt = findTarget (x, y, relX, relY);
  51152. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  51153. if (ddt != currentlyOver)
  51154. {
  51155. Component* const over = dynamic_cast <Component*> (currentlyOver);
  51156. if (over != 0
  51157. && over->isValidComponent()
  51158. && ! (sourceWatcher->hasBeenDeleted())
  51159. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  51160. {
  51161. currentlyOver->itemDragExit (dragDesc, source);
  51162. }
  51163. currentlyOver = ddt;
  51164. if (currentlyOver != 0
  51165. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  51166. currentlyOver->itemDragEnter (dragDesc, source, relX, relY);
  51167. }
  51168. if (currentlyOver != 0
  51169. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  51170. currentlyOver->itemDragMove (dragDesc, source, relX, relY);
  51171. if (currentlyOver == 0
  51172. && canDoExternalDrag
  51173. && ! hasCheckedForExternalDrag)
  51174. {
  51175. if (Desktop::getInstance().findComponentAt (x, y) == 0)
  51176. {
  51177. hasCheckedForExternalDrag = true;
  51178. StringArray files;
  51179. bool canMoveFiles = false;
  51180. if (owner->shouldDropFilesWhenDraggedExternally (dragDesc, source, files, canMoveFiles)
  51181. && files.size() > 0)
  51182. {
  51183. ComponentDeletionWatcher cdw (this);
  51184. setVisible (false);
  51185. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  51186. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  51187. if (! cdw.hasBeenDeleted())
  51188. delete this;
  51189. return;
  51190. }
  51191. }
  51192. }
  51193. }
  51194. }
  51195. void mouseDrag (const MouseEvent& e)
  51196. {
  51197. if (e.originalComponent != this)
  51198. updateLocation (true, e.getScreenX(), e.getScreenY());
  51199. }
  51200. void timerCallback()
  51201. {
  51202. if (sourceWatcher->hasBeenDeleted())
  51203. {
  51204. delete this;
  51205. }
  51206. else if (! isMouseButtonDownAnywhere())
  51207. {
  51208. if (! mouseDragSourceWatcher->hasBeenDeleted())
  51209. mouseDragSource->removeMouseListener (this);
  51210. delete this;
  51211. }
  51212. }
  51213. };
  51214. DragAndDropContainer::DragAndDropContainer()
  51215. : dragImageComponent (0)
  51216. {
  51217. }
  51218. DragAndDropContainer::~DragAndDropContainer()
  51219. {
  51220. if (dragImageComponent != 0)
  51221. delete dragImageComponent;
  51222. }
  51223. void DragAndDropContainer::startDragging (const String& sourceDescription,
  51224. Component* sourceComponent,
  51225. Image* im,
  51226. const bool allowDraggingToExternalWindows)
  51227. {
  51228. if (dragImageComponent != 0)
  51229. {
  51230. if (im != 0)
  51231. delete im;
  51232. }
  51233. else
  51234. {
  51235. Component* const thisComp = dynamic_cast <Component*> (this);
  51236. if (thisComp != 0)
  51237. {
  51238. int mx, my;
  51239. Desktop::getLastMouseDownPosition (mx, my);
  51240. if (im == 0)
  51241. {
  51242. im = sourceComponent->createComponentSnapshot (Rectangle (0, 0, sourceComponent->getWidth(), sourceComponent->getHeight()));
  51243. if (im->getFormat() != Image::ARGB)
  51244. {
  51245. Image* newIm = new Image (Image::ARGB, im->getWidth(), im->getHeight(), true);
  51246. Graphics g2 (*newIm);
  51247. g2.drawImageAt (im, 0, 0);
  51248. delete im;
  51249. im = newIm;
  51250. }
  51251. im->multiplyAllAlphas (0.6f);
  51252. const int lo = 150;
  51253. const int hi = 400;
  51254. int rx = mx, ry = my;
  51255. sourceComponent->globalPositionToRelative (rx, ry);
  51256. const int cx = jlimit (0, im->getWidth(), rx);
  51257. const int cy = jlimit (0, im->getHeight(), ry);
  51258. for (int y = im->getHeight(); --y >= 0;)
  51259. {
  51260. const double dy = (y - cy) * (y - cy);
  51261. for (int x = im->getWidth(); --x >= 0;)
  51262. {
  51263. const int dx = x - cx;
  51264. const int distance = roundDoubleToInt (sqrt (dx * dx + dy));
  51265. if (distance > lo)
  51266. {
  51267. const float alpha = (distance > hi) ? 0
  51268. : (hi - distance) / (float) (hi - lo)
  51269. + Random::getSystemRandom().nextFloat() * 0.008f;
  51270. im->multiplyAlphaAt (x, y, alpha);
  51271. }
  51272. }
  51273. }
  51274. }
  51275. DragImageComponent* const dic
  51276. = new DragImageComponent (im,
  51277. sourceDescription,
  51278. sourceComponent,
  51279. this);
  51280. dragImageComponent = dic;
  51281. currentDragDesc = sourceDescription;
  51282. if (allowDraggingToExternalWindows)
  51283. {
  51284. if (! Desktop::canUseSemiTransparentWindows())
  51285. dic->setOpaque (true);
  51286. dic->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  51287. | ComponentPeer::windowIsTemporary);
  51288. }
  51289. else
  51290. thisComp->addChildComponent (dic);
  51291. dic->updateLocation (false, mx, my);
  51292. dic->setVisible (true);
  51293. }
  51294. else
  51295. {
  51296. // this class must only be implemented by an object that
  51297. // is also a Component.
  51298. jassertfalse
  51299. if (im != 0)
  51300. delete im;
  51301. }
  51302. }
  51303. }
  51304. bool DragAndDropContainer::isDragAndDropActive() const
  51305. {
  51306. return dragImageComponent != 0;
  51307. }
  51308. const String DragAndDropContainer::getCurrentDragDescription() const
  51309. {
  51310. return (dragImageComponent != 0) ? currentDragDesc
  51311. : String::empty;
  51312. }
  51313. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  51314. {
  51315. if (c == 0)
  51316. return 0;
  51317. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  51318. return c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  51319. }
  51320. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  51321. {
  51322. return false;
  51323. }
  51324. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  51325. {
  51326. }
  51327. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  51328. {
  51329. }
  51330. void DragAndDropTarget::itemDragExit (const String&, Component*)
  51331. {
  51332. }
  51333. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  51334. {
  51335. return true;
  51336. }
  51337. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  51338. {
  51339. }
  51340. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  51341. {
  51342. }
  51343. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  51344. {
  51345. }
  51346. END_JUCE_NAMESPACE
  51347. /********* End of inlined file: juce_DragAndDropContainer.cpp *********/
  51348. /********* Start of inlined file: juce_MouseCursor.cpp *********/
  51349. BEGIN_JUCE_NAMESPACE
  51350. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw();
  51351. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw();
  51352. // isStandard set depending on which interface was used to create the cursor
  51353. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw();
  51354. static CriticalSection mouseCursorLock;
  51355. static VoidArray standardCursors (2);
  51356. class RefCountedMouseCursor
  51357. {
  51358. public:
  51359. RefCountedMouseCursor (const MouseCursor::StandardCursorType t) throw()
  51360. : refCount (1),
  51361. standardType (t),
  51362. isStandard (true)
  51363. {
  51364. handle = juce_createStandardMouseCursor (standardType);
  51365. standardCursors.add (this);
  51366. }
  51367. RefCountedMouseCursor (Image& image,
  51368. const int hotSpotX,
  51369. const int hotSpotY) throw()
  51370. : refCount (1),
  51371. standardType (MouseCursor::NormalCursor),
  51372. isStandard (false)
  51373. {
  51374. handle = juce_createMouseCursorFromImage (image, hotSpotX, hotSpotY);
  51375. }
  51376. ~RefCountedMouseCursor() throw()
  51377. {
  51378. juce_deleteMouseCursor (handle, isStandard);
  51379. standardCursors.removeValue (this);
  51380. }
  51381. void decRef() throw()
  51382. {
  51383. if (--refCount == 0)
  51384. delete this;
  51385. }
  51386. void incRef() throw()
  51387. {
  51388. ++refCount;
  51389. }
  51390. void* getHandle() const throw()
  51391. {
  51392. return handle;
  51393. }
  51394. static RefCountedMouseCursor* findInstance (MouseCursor::StandardCursorType type) throw()
  51395. {
  51396. const ScopedLock sl (mouseCursorLock);
  51397. for (int i = 0; i < standardCursors.size(); i++)
  51398. {
  51399. RefCountedMouseCursor* const r = (RefCountedMouseCursor*) standardCursors.getUnchecked(i);
  51400. if (r->standardType == type)
  51401. {
  51402. r->incRef();
  51403. return r;
  51404. }
  51405. }
  51406. return new RefCountedMouseCursor (type);
  51407. }
  51408. juce_UseDebuggingNewOperator
  51409. private:
  51410. void* handle;
  51411. int refCount;
  51412. const MouseCursor::StandardCursorType standardType;
  51413. const bool isStandard;
  51414. const RefCountedMouseCursor& operator= (const RefCountedMouseCursor&);
  51415. };
  51416. MouseCursor::MouseCursor() throw()
  51417. {
  51418. cursorHandle = RefCountedMouseCursor::findInstance (NormalCursor);
  51419. }
  51420. MouseCursor::MouseCursor (const StandardCursorType type) throw()
  51421. {
  51422. cursorHandle = RefCountedMouseCursor::findInstance (type);
  51423. }
  51424. MouseCursor::MouseCursor (Image& image,
  51425. const int hotSpotX,
  51426. const int hotSpotY) throw()
  51427. {
  51428. cursorHandle = new RefCountedMouseCursor (image, hotSpotX, hotSpotY);
  51429. }
  51430. MouseCursor::MouseCursor (const MouseCursor& other) throw()
  51431. : cursorHandle (other.cursorHandle)
  51432. {
  51433. const ScopedLock sl (mouseCursorLock);
  51434. cursorHandle->incRef();
  51435. }
  51436. MouseCursor::~MouseCursor() throw()
  51437. {
  51438. const ScopedLock sl (mouseCursorLock);
  51439. cursorHandle->decRef();
  51440. }
  51441. const MouseCursor& MouseCursor::operator= (const MouseCursor& other) throw()
  51442. {
  51443. if (this != &other)
  51444. {
  51445. const ScopedLock sl (mouseCursorLock);
  51446. cursorHandle->decRef();
  51447. cursorHandle = other.cursorHandle;
  51448. cursorHandle->incRef();
  51449. }
  51450. return *this;
  51451. }
  51452. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  51453. {
  51454. return cursorHandle == other.cursorHandle;
  51455. }
  51456. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  51457. {
  51458. return cursorHandle != other.cursorHandle;
  51459. }
  51460. void* MouseCursor::getHandle() const throw()
  51461. {
  51462. return cursorHandle->getHandle();
  51463. }
  51464. void MouseCursor::showWaitCursor() throw()
  51465. {
  51466. const MouseCursor mc (MouseCursor::WaitCursor);
  51467. mc.showInAllWindows();
  51468. }
  51469. void MouseCursor::hideWaitCursor() throw()
  51470. {
  51471. if (Component::getComponentUnderMouse()->isValidComponent())
  51472. {
  51473. Component::getComponentUnderMouse()->getMouseCursor().showInAllWindows();
  51474. }
  51475. else
  51476. {
  51477. const MouseCursor mc (MouseCursor::NormalCursor);
  51478. mc.showInAllWindows();
  51479. }
  51480. }
  51481. END_JUCE_NAMESPACE
  51482. /********* End of inlined file: juce_MouseCursor.cpp *********/
  51483. /********* Start of inlined file: juce_MouseEvent.cpp *********/
  51484. BEGIN_JUCE_NAMESPACE
  51485. MouseEvent::MouseEvent (const int x_,
  51486. const int y_,
  51487. const ModifierKeys& mods_,
  51488. Component* const originator,
  51489. const Time& eventTime_,
  51490. const int mouseDownX_,
  51491. const int mouseDownY_,
  51492. const Time& mouseDownTime_,
  51493. const int numberOfClicks_,
  51494. const bool mouseWasDragged) throw()
  51495. : x (x_),
  51496. y (y_),
  51497. mods (mods_),
  51498. eventComponent (originator),
  51499. originalComponent (originator),
  51500. eventTime (eventTime_),
  51501. mouseDownX (mouseDownX_),
  51502. mouseDownY (mouseDownY_),
  51503. mouseDownTime (mouseDownTime_),
  51504. numberOfClicks (numberOfClicks_),
  51505. wasMovedSinceMouseDown (mouseWasDragged)
  51506. {
  51507. }
  51508. MouseEvent::~MouseEvent() throw()
  51509. {
  51510. }
  51511. bool MouseEvent::mouseWasClicked() const throw()
  51512. {
  51513. return ! wasMovedSinceMouseDown;
  51514. }
  51515. int MouseEvent::getMouseDownX() const throw()
  51516. {
  51517. return mouseDownX;
  51518. }
  51519. int MouseEvent::getMouseDownY() const throw()
  51520. {
  51521. return mouseDownY;
  51522. }
  51523. int MouseEvent::getDistanceFromDragStartX() const throw()
  51524. {
  51525. return x - mouseDownX;
  51526. }
  51527. int MouseEvent::getDistanceFromDragStartY() const throw()
  51528. {
  51529. return y - mouseDownY;
  51530. }
  51531. int MouseEvent::getDistanceFromDragStart() const throw()
  51532. {
  51533. return roundDoubleToInt (juce_hypot (getDistanceFromDragStartX(),
  51534. getDistanceFromDragStartY()));
  51535. }
  51536. int MouseEvent::getLengthOfMousePress() const throw()
  51537. {
  51538. if (mouseDownTime.toMilliseconds() > 0)
  51539. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  51540. return 0;
  51541. }
  51542. int MouseEvent::getScreenX() const throw()
  51543. {
  51544. int sx = x, sy = y;
  51545. eventComponent->relativePositionToGlobal (sx, sy);
  51546. return sx;
  51547. }
  51548. int MouseEvent::getScreenY() const throw()
  51549. {
  51550. int sx = x, sy = y;
  51551. eventComponent->relativePositionToGlobal (sx, sy);
  51552. return sy;
  51553. }
  51554. int MouseEvent::getMouseDownScreenX() const throw()
  51555. {
  51556. int sx = mouseDownX, sy = mouseDownY;
  51557. eventComponent->relativePositionToGlobal (sx, sy);
  51558. return sx;
  51559. }
  51560. int MouseEvent::getMouseDownScreenY() const throw()
  51561. {
  51562. int sx = mouseDownX, sy = mouseDownY;
  51563. eventComponent->relativePositionToGlobal (sx, sy);
  51564. return sy;
  51565. }
  51566. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  51567. {
  51568. if (otherComponent == 0)
  51569. {
  51570. jassertfalse
  51571. return *this;
  51572. }
  51573. MouseEvent me (*this);
  51574. eventComponent->relativePositionToOtherComponent (otherComponent, me.x, me.y);
  51575. eventComponent->relativePositionToOtherComponent (otherComponent, me.mouseDownX, me.mouseDownY);
  51576. me.eventComponent = otherComponent;
  51577. return me;
  51578. }
  51579. static int doubleClickTimeOutMs = 400;
  51580. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  51581. {
  51582. doubleClickTimeOutMs = newTime;
  51583. }
  51584. int MouseEvent::getDoubleClickTimeout() throw()
  51585. {
  51586. return doubleClickTimeOutMs;
  51587. }
  51588. END_JUCE_NAMESPACE
  51589. /********* End of inlined file: juce_MouseEvent.cpp *********/
  51590. /********* Start of inlined file: juce_MouseHoverDetector.cpp *********/
  51591. BEGIN_JUCE_NAMESPACE
  51592. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  51593. : source (0),
  51594. hoverTimeMillisecs (hoverTimeMillisecs_),
  51595. hasJustHovered (false)
  51596. {
  51597. internalTimer.owner = this;
  51598. }
  51599. MouseHoverDetector::~MouseHoverDetector()
  51600. {
  51601. setHoverComponent (0);
  51602. }
  51603. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  51604. {
  51605. hoverTimeMillisecs = newTimeInMillisecs;
  51606. }
  51607. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  51608. {
  51609. if (source != newSourceComponent)
  51610. {
  51611. internalTimer.stopTimer();
  51612. hasJustHovered = false;
  51613. if (source != 0)
  51614. {
  51615. // ! you need to delete the hover detector before deleting its component
  51616. jassert (source->isValidComponent());
  51617. source->removeMouseListener (&internalTimer);
  51618. }
  51619. source = newSourceComponent;
  51620. if (newSourceComponent != 0)
  51621. newSourceComponent->addMouseListener (&internalTimer, false);
  51622. }
  51623. }
  51624. void MouseHoverDetector::hoverTimerCallback()
  51625. {
  51626. internalTimer.stopTimer();
  51627. if (source != 0)
  51628. {
  51629. int mx, my;
  51630. source->getMouseXYRelative (mx, my);
  51631. if (source->reallyContains (mx, my, false))
  51632. {
  51633. hasJustHovered = true;
  51634. mouseHovered (mx, my);
  51635. }
  51636. }
  51637. }
  51638. void MouseHoverDetector::checkJustHoveredCallback()
  51639. {
  51640. if (hasJustHovered)
  51641. {
  51642. hasJustHovered = false;
  51643. mouseMovedAfterHover();
  51644. }
  51645. }
  51646. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  51647. {
  51648. owner->hoverTimerCallback();
  51649. }
  51650. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  51651. {
  51652. stopTimer();
  51653. owner->checkJustHoveredCallback();
  51654. }
  51655. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  51656. {
  51657. stopTimer();
  51658. owner->checkJustHoveredCallback();
  51659. }
  51660. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  51661. {
  51662. stopTimer();
  51663. owner->checkJustHoveredCallback();
  51664. }
  51665. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  51666. {
  51667. stopTimer();
  51668. owner->checkJustHoveredCallback();
  51669. }
  51670. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  51671. {
  51672. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  51673. {
  51674. lastX = e.x;
  51675. lastY = e.y;
  51676. if (owner->source != 0)
  51677. startTimer (owner->hoverTimeMillisecs);
  51678. owner->checkJustHoveredCallback();
  51679. }
  51680. }
  51681. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  51682. {
  51683. stopTimer();
  51684. owner->checkJustHoveredCallback();
  51685. }
  51686. END_JUCE_NAMESPACE
  51687. /********* End of inlined file: juce_MouseHoverDetector.cpp *********/
  51688. /********* Start of inlined file: juce_MouseListener.cpp *********/
  51689. BEGIN_JUCE_NAMESPACE
  51690. void MouseListener::mouseEnter (const MouseEvent&)
  51691. {
  51692. }
  51693. void MouseListener::mouseExit (const MouseEvent&)
  51694. {
  51695. }
  51696. void MouseListener::mouseDown (const MouseEvent&)
  51697. {
  51698. }
  51699. void MouseListener::mouseUp (const MouseEvent&)
  51700. {
  51701. }
  51702. void MouseListener::mouseDrag (const MouseEvent&)
  51703. {
  51704. }
  51705. void MouseListener::mouseMove (const MouseEvent&)
  51706. {
  51707. }
  51708. void MouseListener::mouseDoubleClick (const MouseEvent&)
  51709. {
  51710. }
  51711. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  51712. {
  51713. }
  51714. END_JUCE_NAMESPACE
  51715. /********* End of inlined file: juce_MouseListener.cpp *********/
  51716. /********* Start of inlined file: juce_BooleanPropertyComponent.cpp *********/
  51717. BEGIN_JUCE_NAMESPACE
  51718. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  51719. const String& buttonTextWhenTrue,
  51720. const String& buttonTextWhenFalse)
  51721. : PropertyComponent (name),
  51722. onText (buttonTextWhenTrue),
  51723. offText (buttonTextWhenFalse)
  51724. {
  51725. addAndMakeVisible (button = new ToggleButton (String::empty));
  51726. button->setClickingTogglesState (false);
  51727. button->addButtonListener (this);
  51728. }
  51729. BooleanPropertyComponent::~BooleanPropertyComponent()
  51730. {
  51731. deleteAllChildren();
  51732. }
  51733. void BooleanPropertyComponent::paint (Graphics& g)
  51734. {
  51735. PropertyComponent::paint (g);
  51736. const Rectangle r (button->getBounds());
  51737. g.setColour (Colours::white);
  51738. g.fillRect (r);
  51739. g.setColour (findColour (ComboBox::outlineColourId));
  51740. g.drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  51741. }
  51742. void BooleanPropertyComponent::refresh()
  51743. {
  51744. button->setToggleState (getState(), false);
  51745. button->setButtonText (button->getToggleState() ? onText : offText);
  51746. }
  51747. void BooleanPropertyComponent::buttonClicked (Button*)
  51748. {
  51749. setState (! getState());
  51750. }
  51751. END_JUCE_NAMESPACE
  51752. /********* End of inlined file: juce_BooleanPropertyComponent.cpp *********/
  51753. /********* Start of inlined file: juce_ButtonPropertyComponent.cpp *********/
  51754. BEGIN_JUCE_NAMESPACE
  51755. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  51756. const bool triggerOnMouseDown)
  51757. : PropertyComponent (name)
  51758. {
  51759. addAndMakeVisible (button = new TextButton (String::empty));
  51760. button->setTriggeredOnMouseDown (triggerOnMouseDown);
  51761. button->addButtonListener (this);
  51762. }
  51763. ButtonPropertyComponent::~ButtonPropertyComponent()
  51764. {
  51765. deleteAllChildren();
  51766. }
  51767. void ButtonPropertyComponent::refresh()
  51768. {
  51769. button->setButtonText (getButtonText());
  51770. }
  51771. void ButtonPropertyComponent::buttonClicked (Button*)
  51772. {
  51773. buttonClicked();
  51774. }
  51775. END_JUCE_NAMESPACE
  51776. /********* End of inlined file: juce_ButtonPropertyComponent.cpp *********/
  51777. /********* Start of inlined file: juce_ChoicePropertyComponent.cpp *********/
  51778. BEGIN_JUCE_NAMESPACE
  51779. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  51780. : PropertyComponent (name),
  51781. comboBox (0)
  51782. {
  51783. }
  51784. ChoicePropertyComponent::~ChoicePropertyComponent()
  51785. {
  51786. deleteAllChildren();
  51787. }
  51788. const StringArray& ChoicePropertyComponent::getChoices() const throw()
  51789. {
  51790. return choices;
  51791. }
  51792. void ChoicePropertyComponent::refresh()
  51793. {
  51794. if (comboBox == 0)
  51795. {
  51796. addAndMakeVisible (comboBox = new ComboBox (String::empty));
  51797. for (int i = 0; i < choices.size(); ++i)
  51798. {
  51799. if (choices[i].isNotEmpty())
  51800. comboBox->addItem (choices[i], i + 1);
  51801. else
  51802. comboBox->addSeparator();
  51803. }
  51804. comboBox->setEditableText (false);
  51805. comboBox->addListener (this);
  51806. }
  51807. comboBox->setSelectedId (getIndex() + 1, true);
  51808. }
  51809. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  51810. {
  51811. const int newIndex = comboBox->getSelectedId() - 1;
  51812. if (newIndex != getIndex())
  51813. setIndex (newIndex);
  51814. }
  51815. END_JUCE_NAMESPACE
  51816. /********* End of inlined file: juce_ChoicePropertyComponent.cpp *********/
  51817. /********* Start of inlined file: juce_PropertyComponent.cpp *********/
  51818. BEGIN_JUCE_NAMESPACE
  51819. PropertyComponent::PropertyComponent (const String& name,
  51820. const int preferredHeight_)
  51821. : Component (name),
  51822. preferredHeight (preferredHeight_)
  51823. {
  51824. jassert (name.isNotEmpty());
  51825. }
  51826. PropertyComponent::~PropertyComponent()
  51827. {
  51828. }
  51829. void PropertyComponent::paint (Graphics& g)
  51830. {
  51831. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  51832. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  51833. }
  51834. void PropertyComponent::resized()
  51835. {
  51836. if (getNumChildComponents() > 0)
  51837. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  51838. }
  51839. void PropertyComponent::enablementChanged()
  51840. {
  51841. repaint();
  51842. }
  51843. END_JUCE_NAMESPACE
  51844. /********* End of inlined file: juce_PropertyComponent.cpp *********/
  51845. /********* Start of inlined file: juce_PropertyPanel.cpp *********/
  51846. BEGIN_JUCE_NAMESPACE
  51847. class PropertyHolderComponent : public Component
  51848. {
  51849. public:
  51850. PropertyHolderComponent()
  51851. {
  51852. }
  51853. ~PropertyHolderComponent()
  51854. {
  51855. deleteAllChildren();
  51856. }
  51857. void paint (Graphics&)
  51858. {
  51859. }
  51860. void updateLayout (const int width);
  51861. void refreshAll() const;
  51862. };
  51863. class PropertySectionComponent : public Component
  51864. {
  51865. public:
  51866. PropertySectionComponent (const String& sectionTitle,
  51867. const Array <PropertyComponent*>& newProperties,
  51868. const bool open)
  51869. : Component (sectionTitle),
  51870. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  51871. isOpen_ (open)
  51872. {
  51873. for (int i = newProperties.size(); --i >= 0;)
  51874. {
  51875. addAndMakeVisible (newProperties.getUnchecked(i));
  51876. newProperties.getUnchecked(i)->refresh();
  51877. }
  51878. }
  51879. ~PropertySectionComponent()
  51880. {
  51881. deleteAllChildren();
  51882. }
  51883. void paint (Graphics& g)
  51884. {
  51885. if (titleHeight > 0)
  51886. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  51887. }
  51888. void resized()
  51889. {
  51890. int y = titleHeight;
  51891. for (int i = getNumChildComponents(); --i >= 0;)
  51892. {
  51893. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51894. if (pec != 0)
  51895. {
  51896. const int prefH = pec->getPreferredHeight();
  51897. pec->setBounds (1, y, getWidth() - 2, prefH);
  51898. y += prefH;
  51899. }
  51900. }
  51901. }
  51902. int getPreferredHeight() const
  51903. {
  51904. int y = titleHeight;
  51905. if (isOpen())
  51906. {
  51907. for (int i = 0; i < getNumChildComponents(); ++i)
  51908. {
  51909. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51910. if (pec != 0)
  51911. y += pec->getPreferredHeight();
  51912. }
  51913. }
  51914. return y;
  51915. }
  51916. void setOpen (const bool open)
  51917. {
  51918. if (isOpen_ != open)
  51919. {
  51920. isOpen_ = open;
  51921. for (int i = 0; i < getNumChildComponents(); ++i)
  51922. {
  51923. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51924. if (pec != 0)
  51925. pec->setVisible (open);
  51926. }
  51927. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  51928. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  51929. if (pp != 0)
  51930. pp->resized();
  51931. }
  51932. }
  51933. bool isOpen() const throw()
  51934. {
  51935. return isOpen_;
  51936. }
  51937. void refreshAll() const
  51938. {
  51939. for (int i = 0; i < getNumChildComponents(); ++i)
  51940. {
  51941. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51942. if (pec != 0)
  51943. pec->refresh();
  51944. }
  51945. }
  51946. void mouseDown (const MouseEvent&)
  51947. {
  51948. }
  51949. void mouseUp (const MouseEvent& e)
  51950. {
  51951. if (e.getMouseDownX() < titleHeight
  51952. && e.x < titleHeight
  51953. && e.y < titleHeight
  51954. && e.getNumberOfClicks() != 2)
  51955. {
  51956. setOpen (! isOpen());
  51957. }
  51958. }
  51959. void mouseDoubleClick (const MouseEvent& e)
  51960. {
  51961. if (e.y < titleHeight)
  51962. setOpen (! isOpen());
  51963. }
  51964. private:
  51965. int titleHeight;
  51966. bool isOpen_;
  51967. };
  51968. void PropertyHolderComponent::updateLayout (const int width)
  51969. {
  51970. int y = 0;
  51971. for (int i = getNumChildComponents(); --i >= 0;)
  51972. {
  51973. PropertySectionComponent* const section
  51974. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  51975. if (section != 0)
  51976. {
  51977. const int prefH = section->getPreferredHeight();
  51978. section->setBounds (0, y, width, prefH);
  51979. y += prefH;
  51980. }
  51981. }
  51982. setSize (width, y);
  51983. repaint();
  51984. }
  51985. void PropertyHolderComponent::refreshAll() const
  51986. {
  51987. for (int i = getNumChildComponents(); --i >= 0;)
  51988. {
  51989. PropertySectionComponent* const section
  51990. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  51991. if (section != 0)
  51992. section->refreshAll();
  51993. }
  51994. }
  51995. PropertyPanel::PropertyPanel()
  51996. {
  51997. messageWhenEmpty = TRANS("(nothing selected)");
  51998. addAndMakeVisible (viewport = new Viewport());
  51999. viewport->setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  52000. viewport->setFocusContainer (true);
  52001. }
  52002. PropertyPanel::~PropertyPanel()
  52003. {
  52004. clear();
  52005. deleteAllChildren();
  52006. }
  52007. void PropertyPanel::paint (Graphics& g)
  52008. {
  52009. if (propertyHolderComponent->getNumChildComponents() == 0)
  52010. {
  52011. g.setColour (Colours::black.withAlpha (0.5f));
  52012. g.setFont (14.0f);
  52013. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  52014. Justification::centred, true);
  52015. }
  52016. }
  52017. void PropertyPanel::resized()
  52018. {
  52019. viewport->setBounds (0, 0, getWidth(), getHeight());
  52020. updatePropHolderLayout();
  52021. }
  52022. void PropertyPanel::clear()
  52023. {
  52024. if (propertyHolderComponent->getNumChildComponents() > 0)
  52025. {
  52026. propertyHolderComponent->deleteAllChildren();
  52027. repaint();
  52028. }
  52029. }
  52030. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  52031. {
  52032. if (propertyHolderComponent->getNumChildComponents() == 0)
  52033. repaint();
  52034. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  52035. newProperties,
  52036. true), 0);
  52037. updatePropHolderLayout();
  52038. }
  52039. void PropertyPanel::addSection (const String& sectionTitle,
  52040. const Array <PropertyComponent*>& newProperties,
  52041. const bool shouldBeOpen)
  52042. {
  52043. jassert (sectionTitle.isNotEmpty());
  52044. if (propertyHolderComponent->getNumChildComponents() == 0)
  52045. repaint();
  52046. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  52047. newProperties,
  52048. shouldBeOpen), 0);
  52049. updatePropHolderLayout();
  52050. }
  52051. void PropertyPanel::updatePropHolderLayout() const
  52052. {
  52053. const int maxWidth = viewport->getMaximumVisibleWidth();
  52054. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (maxWidth);
  52055. const int newMaxWidth = viewport->getMaximumVisibleWidth();
  52056. if (maxWidth != newMaxWidth)
  52057. {
  52058. // need to do this twice because of scrollbars changing the size, etc.
  52059. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (newMaxWidth);
  52060. }
  52061. }
  52062. void PropertyPanel::refreshAll() const
  52063. {
  52064. ((PropertyHolderComponent*) propertyHolderComponent)->refreshAll();
  52065. }
  52066. const StringArray PropertyPanel::getSectionNames() const
  52067. {
  52068. StringArray s;
  52069. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  52070. {
  52071. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  52072. if (section != 0 && section->getName().isNotEmpty())
  52073. s.add (section->getName());
  52074. }
  52075. return s;
  52076. }
  52077. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  52078. {
  52079. int index = 0;
  52080. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  52081. {
  52082. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  52083. if (section != 0 && section->getName().isNotEmpty())
  52084. {
  52085. if (index == sectionIndex)
  52086. return section->isOpen();
  52087. ++index;
  52088. }
  52089. }
  52090. return false;
  52091. }
  52092. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  52093. {
  52094. int index = 0;
  52095. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  52096. {
  52097. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  52098. if (section != 0 && section->getName().isNotEmpty())
  52099. {
  52100. if (index == sectionIndex)
  52101. {
  52102. section->setOpen (shouldBeOpen);
  52103. break;
  52104. }
  52105. ++index;
  52106. }
  52107. }
  52108. }
  52109. XmlElement* PropertyPanel::getOpennessState() const
  52110. {
  52111. XmlElement* const xml = new XmlElement (T("PROPERTYPANELSTATE"));
  52112. const StringArray sections (getSectionNames());
  52113. for (int i = 0; i < sections.size(); ++i)
  52114. {
  52115. if (sections[i].isNotEmpty())
  52116. {
  52117. XmlElement* const e = new XmlElement (T("SECTION"));
  52118. e->setAttribute (T("name"), sections[i]);
  52119. e->setAttribute (T("open"), isSectionOpen (i) ? 1 : 0);
  52120. xml->addChildElement (e);
  52121. }
  52122. }
  52123. return xml;
  52124. }
  52125. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  52126. {
  52127. if (xml.hasTagName (T("PROPERTYPANELSTATE")))
  52128. {
  52129. const StringArray sections (getSectionNames());
  52130. forEachXmlChildElementWithTagName (xml, e, T("SECTION"))
  52131. {
  52132. setSectionOpen (sections.indexOf (e->getStringAttribute (T("name"))),
  52133. e->getBoolAttribute (T("open")));
  52134. }
  52135. }
  52136. }
  52137. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  52138. {
  52139. if (messageWhenEmpty != newMessage)
  52140. {
  52141. messageWhenEmpty = newMessage;
  52142. repaint();
  52143. }
  52144. }
  52145. const String& PropertyPanel::getMessageWhenEmpty() const throw()
  52146. {
  52147. return messageWhenEmpty;
  52148. }
  52149. END_JUCE_NAMESPACE
  52150. /********* End of inlined file: juce_PropertyPanel.cpp *********/
  52151. /********* Start of inlined file: juce_SliderPropertyComponent.cpp *********/
  52152. BEGIN_JUCE_NAMESPACE
  52153. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  52154. const double rangeMin,
  52155. const double rangeMax,
  52156. const double interval,
  52157. const double skewFactor)
  52158. : PropertyComponent (name)
  52159. {
  52160. addAndMakeVisible (slider = new Slider (name));
  52161. slider->setRange (rangeMin, rangeMax, interval);
  52162. slider->setSkewFactor (skewFactor);
  52163. slider->setSliderStyle (Slider::LinearBar);
  52164. slider->addListener (this);
  52165. }
  52166. SliderPropertyComponent::~SliderPropertyComponent()
  52167. {
  52168. deleteAllChildren();
  52169. }
  52170. void SliderPropertyComponent::refresh()
  52171. {
  52172. slider->setValue (getValue(), false);
  52173. }
  52174. void SliderPropertyComponent::sliderValueChanged (Slider*)
  52175. {
  52176. if (getValue() != slider->getValue())
  52177. setValue (slider->getValue());
  52178. }
  52179. END_JUCE_NAMESPACE
  52180. /********* End of inlined file: juce_SliderPropertyComponent.cpp *********/
  52181. /********* Start of inlined file: juce_TextPropertyComponent.cpp *********/
  52182. BEGIN_JUCE_NAMESPACE
  52183. class TextPropLabel : public Label
  52184. {
  52185. TextPropertyComponent& owner;
  52186. int maxChars;
  52187. bool isMultiline;
  52188. public:
  52189. TextPropLabel (TextPropertyComponent& owner_,
  52190. const int maxChars_, const bool isMultiline_)
  52191. : Label (String::empty, String::empty),
  52192. owner (owner_),
  52193. maxChars (maxChars_),
  52194. isMultiline (isMultiline_)
  52195. {
  52196. setEditable (true, true, false);
  52197. setColour (backgroundColourId, Colours::white);
  52198. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  52199. }
  52200. ~TextPropLabel()
  52201. {
  52202. }
  52203. TextEditor* createEditorComponent()
  52204. {
  52205. TextEditor* const textEditor = Label::createEditorComponent();
  52206. textEditor->setInputRestrictions (maxChars);
  52207. if (isMultiline)
  52208. {
  52209. textEditor->setMultiLine (true, true);
  52210. textEditor->setReturnKeyStartsNewLine (true);
  52211. }
  52212. return textEditor;
  52213. }
  52214. void textWasEdited()
  52215. {
  52216. owner.textWasEdited();
  52217. }
  52218. };
  52219. TextPropertyComponent::TextPropertyComponent (const String& name,
  52220. const int maxNumChars,
  52221. const bool isMultiLine)
  52222. : PropertyComponent (name)
  52223. {
  52224. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  52225. if (isMultiLine)
  52226. {
  52227. textEditor->setJustificationType (Justification::topLeft);
  52228. preferredHeight = 120;
  52229. }
  52230. }
  52231. TextPropertyComponent::~TextPropertyComponent()
  52232. {
  52233. deleteAllChildren();
  52234. }
  52235. void TextPropertyComponent::refresh()
  52236. {
  52237. textEditor->setText (getText(), false);
  52238. }
  52239. void TextPropertyComponent::textWasEdited()
  52240. {
  52241. const String newText (textEditor->getText());
  52242. if (getText() != newText)
  52243. setText (newText);
  52244. }
  52245. END_JUCE_NAMESPACE
  52246. /********* End of inlined file: juce_TextPropertyComponent.cpp *********/
  52247. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  52248. BEGIN_JUCE_NAMESPACE
  52249. class SimpleDeviceManagerInputLevelMeter : public Component,
  52250. public Timer
  52251. {
  52252. public:
  52253. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  52254. : manager (manager_),
  52255. level (0)
  52256. {
  52257. startTimer (50);
  52258. manager->enableInputLevelMeasurement (true);
  52259. }
  52260. ~SimpleDeviceManagerInputLevelMeter()
  52261. {
  52262. manager->enableInputLevelMeasurement (false);
  52263. }
  52264. void timerCallback()
  52265. {
  52266. const float newLevel = (float) manager->getCurrentInputLevel();
  52267. if (fabsf (level - newLevel) > 0.005f)
  52268. {
  52269. level = newLevel;
  52270. repaint();
  52271. }
  52272. }
  52273. void paint (Graphics& g)
  52274. {
  52275. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(), level);
  52276. }
  52277. private:
  52278. AudioDeviceManager* const manager;
  52279. float level;
  52280. };
  52281. class MidiInputSelectorComponentListBox : public ListBox,
  52282. public ListBoxModel
  52283. {
  52284. public:
  52285. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  52286. const String& noItemsMessage_,
  52287. const int minNumber_,
  52288. const int maxNumber_)
  52289. : ListBox (String::empty, 0),
  52290. deviceManager (deviceManager_),
  52291. noItemsMessage (noItemsMessage_),
  52292. minNumber (minNumber_),
  52293. maxNumber (maxNumber_)
  52294. {
  52295. items = MidiInput::getDevices();
  52296. setModel (this);
  52297. setOutlineThickness (1);
  52298. }
  52299. ~MidiInputSelectorComponentListBox()
  52300. {
  52301. }
  52302. int getNumRows()
  52303. {
  52304. return items.size();
  52305. }
  52306. void paintListBoxItem (int row,
  52307. Graphics& g,
  52308. int width, int height,
  52309. bool rowIsSelected)
  52310. {
  52311. if (((unsigned int) row) < (unsigned int) items.size())
  52312. {
  52313. if (rowIsSelected)
  52314. g.fillAll (findColour (TextEditor::highlightColourId)
  52315. .withMultipliedAlpha (0.3f));
  52316. const String item (items [row]);
  52317. bool enabled = deviceManager.isMidiInputEnabled (item);
  52318. const int x = getTickX();
  52319. const int tickW = height - height / 4;
  52320. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  52321. enabled, true, true, false);
  52322. g.setFont (height * 0.6f);
  52323. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  52324. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  52325. }
  52326. }
  52327. void listBoxItemClicked (int row, const MouseEvent& e)
  52328. {
  52329. selectRow (row);
  52330. if (e.x < getTickX())
  52331. flipEnablement (row);
  52332. }
  52333. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  52334. {
  52335. flipEnablement (row);
  52336. }
  52337. void returnKeyPressed (int row)
  52338. {
  52339. flipEnablement (row);
  52340. }
  52341. void paint (Graphics& g)
  52342. {
  52343. ListBox::paint (g);
  52344. if (items.size() == 0)
  52345. {
  52346. g.setColour (Colours::grey);
  52347. g.setFont (13.0f);
  52348. g.drawText (noItemsMessage,
  52349. 0, 0, getWidth(), getHeight() / 2,
  52350. Justification::centred, true);
  52351. }
  52352. }
  52353. int getBestHeight (const int preferredHeight)
  52354. {
  52355. const int extra = getOutlineThickness() * 2;
  52356. return jmax (getRowHeight() * 2 + extra,
  52357. jmin (getRowHeight() * getNumRows() + extra,
  52358. preferredHeight));
  52359. }
  52360. juce_UseDebuggingNewOperator
  52361. private:
  52362. AudioDeviceManager& deviceManager;
  52363. const String noItemsMessage;
  52364. StringArray items;
  52365. int minNumber, maxNumber;
  52366. void flipEnablement (const int row)
  52367. {
  52368. if (((unsigned int) row) < (unsigned int) items.size())
  52369. {
  52370. const String item (items [row]);
  52371. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  52372. }
  52373. }
  52374. int getTickX() const throw()
  52375. {
  52376. return getRowHeight() + 5;
  52377. }
  52378. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  52379. const MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  52380. };
  52381. class AudioDeviceSettingsPanel : public Component,
  52382. public ComboBoxListener,
  52383. public ChangeListener,
  52384. public ButtonListener
  52385. {
  52386. public:
  52387. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  52388. AudioIODeviceType::DeviceSetupDetails& setup_,
  52389. const bool hideAdvancedOptionsWithButton)
  52390. : type (type_),
  52391. setup (setup_)
  52392. {
  52393. sampleRateDropDown = 0;
  52394. sampleRateLabel = 0;
  52395. bufferSizeDropDown = 0;
  52396. bufferSizeLabel = 0;
  52397. outputDeviceDropDown = 0;
  52398. outputDeviceLabel = 0;
  52399. inputDeviceDropDown = 0;
  52400. inputDeviceLabel = 0;
  52401. testButton = 0;
  52402. inputLevelMeter = 0;
  52403. showUIButton = 0;
  52404. inputChanList = 0;
  52405. outputChanList = 0;
  52406. inputChanLabel = 0;
  52407. outputChanLabel = 0;
  52408. showAdvancedSettingsButton = 0;
  52409. if (hideAdvancedOptionsWithButton)
  52410. {
  52411. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  52412. showAdvancedSettingsButton->addButtonListener (this);
  52413. }
  52414. type->scanForDevices();
  52415. setup.manager->addChangeListener (this);
  52416. changeListenerCallback (0);
  52417. }
  52418. ~AudioDeviceSettingsPanel()
  52419. {
  52420. setup.manager->removeChangeListener (this);
  52421. deleteAndZero (outputDeviceLabel);
  52422. deleteAndZero (inputDeviceLabel);
  52423. deleteAndZero (sampleRateLabel);
  52424. deleteAndZero (bufferSizeLabel);
  52425. deleteAndZero (showUIButton);
  52426. deleteAndZero (inputChanLabel);
  52427. deleteAndZero (outputChanLabel);
  52428. deleteAndZero (showAdvancedSettingsButton);
  52429. deleteAllChildren();
  52430. }
  52431. void resized()
  52432. {
  52433. const int lx = proportionOfWidth (0.35f);
  52434. const int w = proportionOfWidth (0.4f);
  52435. const int h = 24;
  52436. const int space = 6;
  52437. const int dh = h + space;
  52438. int y = 0;
  52439. if (outputDeviceDropDown != 0)
  52440. {
  52441. outputDeviceDropDown->setBounds (lx, y, w, h);
  52442. testButton->setBounds (proportionOfWidth (0.77f),
  52443. outputDeviceDropDown->getY(),
  52444. proportionOfWidth (0.18f),
  52445. h);
  52446. y += dh;
  52447. }
  52448. if (inputDeviceDropDown != 0)
  52449. {
  52450. inputDeviceDropDown->setBounds (lx, y, w, h);
  52451. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  52452. inputDeviceDropDown->getY(),
  52453. proportionOfWidth (0.18f),
  52454. h);
  52455. y += dh;
  52456. }
  52457. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  52458. if (outputChanList != 0)
  52459. {
  52460. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  52461. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  52462. y += bh + space;
  52463. }
  52464. if (inputChanList != 0)
  52465. {
  52466. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  52467. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  52468. y += bh + space;
  52469. }
  52470. y += space * 2;
  52471. if (showAdvancedSettingsButton != 0)
  52472. {
  52473. showAdvancedSettingsButton->changeWidthToFitText (h);
  52474. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  52475. }
  52476. if (sampleRateDropDown != 0)
  52477. {
  52478. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  52479. || ! showAdvancedSettingsButton->isVisible());
  52480. sampleRateDropDown->setBounds (lx, y, w, h);
  52481. y += dh;
  52482. }
  52483. if (bufferSizeDropDown != 0)
  52484. {
  52485. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  52486. || ! showAdvancedSettingsButton->isVisible());
  52487. bufferSizeDropDown->setBounds (lx, y, w, h);
  52488. y += dh;
  52489. }
  52490. if (showUIButton != 0)
  52491. {
  52492. showUIButton->setVisible (showAdvancedSettingsButton == 0
  52493. || ! showAdvancedSettingsButton->isVisible());
  52494. showUIButton->changeWidthToFitText (h);
  52495. showUIButton->setTopLeftPosition (lx, y);
  52496. }
  52497. }
  52498. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  52499. {
  52500. if (comboBoxThatHasChanged == 0)
  52501. return;
  52502. AudioDeviceManager::AudioDeviceSetup config;
  52503. setup.manager->getAudioDeviceSetup (config);
  52504. String error;
  52505. if (comboBoxThatHasChanged == outputDeviceDropDown
  52506. || comboBoxThatHasChanged == inputDeviceDropDown)
  52507. {
  52508. if (outputDeviceDropDown != 0)
  52509. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  52510. : outputDeviceDropDown->getText();
  52511. if (inputDeviceDropDown != 0)
  52512. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  52513. : inputDeviceDropDown->getText();
  52514. if (! type->hasSeparateInputsAndOutputs())
  52515. config.inputDeviceName = config.outputDeviceName;
  52516. if (comboBoxThatHasChanged == inputDeviceDropDown)
  52517. config.useDefaultInputChannels = true;
  52518. else
  52519. config.useDefaultOutputChannels = true;
  52520. error = setup.manager->setAudioDeviceSetup (config, true);
  52521. showCorrectDeviceName (inputDeviceDropDown, true);
  52522. showCorrectDeviceName (outputDeviceDropDown, false);
  52523. updateControlPanelButton();
  52524. resized();
  52525. }
  52526. else if (comboBoxThatHasChanged == sampleRateDropDown)
  52527. {
  52528. if (sampleRateDropDown->getSelectedId() > 0)
  52529. {
  52530. config.sampleRate = sampleRateDropDown->getSelectedId();
  52531. error = setup.manager->setAudioDeviceSetup (config, true);
  52532. }
  52533. }
  52534. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  52535. {
  52536. if (bufferSizeDropDown->getSelectedId() > 0)
  52537. {
  52538. config.bufferSize = bufferSizeDropDown->getSelectedId();
  52539. error = setup.manager->setAudioDeviceSetup (config, true);
  52540. }
  52541. }
  52542. if (error.isNotEmpty())
  52543. {
  52544. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  52545. T("Error when trying to open audio device!"),
  52546. error);
  52547. }
  52548. }
  52549. void buttonClicked (Button* button)
  52550. {
  52551. if (button == showAdvancedSettingsButton)
  52552. {
  52553. showAdvancedSettingsButton->setVisible (false);
  52554. resized();
  52555. }
  52556. else if (button == showUIButton)
  52557. {
  52558. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  52559. if (device != 0 && device->showControlPanel())
  52560. {
  52561. setup.manager->closeAudioDevice();
  52562. setup.manager->restartLastAudioDevice();
  52563. getTopLevelComponent()->toFront (true);
  52564. }
  52565. }
  52566. else if (button == testButton)
  52567. {
  52568. setup.manager->playTestSound();
  52569. }
  52570. }
  52571. void updateControlPanelButton()
  52572. {
  52573. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  52574. deleteAndZero (showUIButton);
  52575. if (currentDevice != 0 && currentDevice->hasControlPanel())
  52576. {
  52577. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  52578. TRANS ("opens the device's own control panel")));
  52579. showUIButton->addButtonListener (this);
  52580. }
  52581. resized();
  52582. }
  52583. void changeListenerCallback (void*)
  52584. {
  52585. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  52586. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  52587. {
  52588. if (outputDeviceDropDown == 0)
  52589. {
  52590. outputDeviceDropDown = new ComboBox (String::empty);
  52591. outputDeviceDropDown->addListener (this);
  52592. addAndMakeVisible (outputDeviceDropDown);
  52593. outputDeviceLabel = new Label (String::empty,
  52594. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  52595. : TRANS ("device:"));
  52596. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  52597. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  52598. testButton->addButtonListener (this);
  52599. }
  52600. addNamesToDeviceBox (*outputDeviceDropDown, false);
  52601. }
  52602. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  52603. {
  52604. if (inputDeviceDropDown == 0)
  52605. {
  52606. inputDeviceDropDown = new ComboBox (String::empty);
  52607. inputDeviceDropDown->addListener (this);
  52608. addAndMakeVisible (inputDeviceDropDown);
  52609. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  52610. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  52611. addAndMakeVisible (inputLevelMeter
  52612. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  52613. }
  52614. addNamesToDeviceBox (*inputDeviceDropDown, true);
  52615. }
  52616. updateControlPanelButton();
  52617. showCorrectDeviceName (inputDeviceDropDown, true);
  52618. showCorrectDeviceName (outputDeviceDropDown, false);
  52619. if (currentDevice != 0)
  52620. {
  52621. if (setup.maxNumOutputChannels > 0
  52622. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  52623. {
  52624. if (outputChanList == 0)
  52625. {
  52626. addAndMakeVisible (outputChanList
  52627. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  52628. TRANS ("(no audio output channels found)")));
  52629. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  52630. outputChanLabel->attachToComponent (outputChanList, true);
  52631. }
  52632. outputChanList->refresh();
  52633. }
  52634. else
  52635. {
  52636. deleteAndZero (outputChanLabel);
  52637. deleteAndZero (outputChanList);
  52638. }
  52639. if (setup.maxNumInputChannels > 0
  52640. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  52641. {
  52642. if (inputChanList == 0)
  52643. {
  52644. addAndMakeVisible (inputChanList
  52645. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  52646. TRANS ("(no audio input channels found)")));
  52647. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  52648. inputChanLabel->attachToComponent (inputChanList, true);
  52649. }
  52650. inputChanList->refresh();
  52651. }
  52652. else
  52653. {
  52654. deleteAndZero (inputChanLabel);
  52655. deleteAndZero (inputChanList);
  52656. }
  52657. // sample rate..
  52658. {
  52659. if (sampleRateDropDown == 0)
  52660. {
  52661. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  52662. sampleRateDropDown->addListener (this);
  52663. delete sampleRateLabel;
  52664. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  52665. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  52666. }
  52667. else
  52668. {
  52669. sampleRateDropDown->clear();
  52670. sampleRateDropDown->removeListener (this);
  52671. }
  52672. const int numRates = currentDevice->getNumSampleRates();
  52673. for (int i = 0; i < numRates; ++i)
  52674. {
  52675. const int rate = roundDoubleToInt (currentDevice->getSampleRate (i));
  52676. sampleRateDropDown->addItem (String (rate) + T(" Hz"), rate);
  52677. }
  52678. sampleRateDropDown->setSelectedId (roundDoubleToInt (currentDevice->getCurrentSampleRate()), true);
  52679. sampleRateDropDown->addListener (this);
  52680. }
  52681. // buffer size
  52682. {
  52683. if (bufferSizeDropDown == 0)
  52684. {
  52685. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  52686. bufferSizeDropDown->addListener (this);
  52687. delete bufferSizeLabel;
  52688. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  52689. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  52690. }
  52691. else
  52692. {
  52693. bufferSizeDropDown->clear();
  52694. }
  52695. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  52696. double currentRate = currentDevice->getCurrentSampleRate();
  52697. if (currentRate == 0)
  52698. currentRate = 48000.0;
  52699. for (int i = 0; i < numBufferSizes; ++i)
  52700. {
  52701. const int bs = currentDevice->getBufferSizeSamples (i);
  52702. bufferSizeDropDown->addItem (String (bs)
  52703. + T(" samples (")
  52704. + String (bs * 1000.0 / currentRate, 1)
  52705. + T(" ms)"),
  52706. bs);
  52707. }
  52708. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  52709. }
  52710. }
  52711. else
  52712. {
  52713. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  52714. deleteAndZero (sampleRateLabel);
  52715. deleteAndZero (bufferSizeLabel);
  52716. deleteAndZero (sampleRateDropDown);
  52717. deleteAndZero (bufferSizeDropDown);
  52718. if (outputDeviceDropDown != 0)
  52719. outputDeviceDropDown->setSelectedId (-1, true);
  52720. if (inputDeviceDropDown != 0)
  52721. inputDeviceDropDown->setSelectedId (-1, true);
  52722. }
  52723. resized();
  52724. setSize (getWidth(), getLowestY() + 4);
  52725. }
  52726. private:
  52727. AudioIODeviceType* const type;
  52728. const AudioIODeviceType::DeviceSetupDetails setup;
  52729. ComboBox* outputDeviceDropDown;
  52730. ComboBox* inputDeviceDropDown;
  52731. ComboBox* sampleRateDropDown;
  52732. ComboBox* bufferSizeDropDown;
  52733. Label* outputDeviceLabel;
  52734. Label* inputDeviceLabel;
  52735. Label* sampleRateLabel;
  52736. Label* bufferSizeLabel;
  52737. Label* inputChanLabel;
  52738. Label* outputChanLabel;
  52739. TextButton* testButton;
  52740. Component* inputLevelMeter;
  52741. TextButton* showUIButton;
  52742. TextButton* showAdvancedSettingsButton;
  52743. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  52744. {
  52745. if (box != 0)
  52746. {
  52747. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  52748. const int index = type->getIndexOfDevice (currentDevice, isInput);
  52749. box->setSelectedId (index + 1, true);
  52750. if (! isInput)
  52751. testButton->setEnabled (index >= 0);
  52752. }
  52753. }
  52754. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  52755. {
  52756. const StringArray devs (type->getDeviceNames (isInputs));
  52757. combo.clear (true);
  52758. for (int i = 0; i < devs.size(); ++i)
  52759. combo.addItem (devs[i], i + 1);
  52760. combo.addItem (TRANS("<< none >>"), -1);
  52761. combo.setSelectedId (-1, true);
  52762. }
  52763. int getLowestY() const
  52764. {
  52765. int y = 0;
  52766. for (int i = getNumChildComponents(); --i >= 0;)
  52767. y = jmax (y, getChildComponent (i)->getBottom());
  52768. return y;
  52769. }
  52770. class ChannelSelectorListBox : public ListBox,
  52771. public ListBoxModel
  52772. {
  52773. public:
  52774. enum BoxType
  52775. {
  52776. audioInputType,
  52777. audioOutputType
  52778. };
  52779. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  52780. const BoxType type_,
  52781. const String& noItemsMessage_)
  52782. : ListBox (String::empty, 0),
  52783. setup (setup_),
  52784. type (type_),
  52785. noItemsMessage (noItemsMessage_)
  52786. {
  52787. refresh();
  52788. setModel (this);
  52789. setOutlineThickness (1);
  52790. }
  52791. ~ChannelSelectorListBox()
  52792. {
  52793. }
  52794. void refresh()
  52795. {
  52796. items.clear();
  52797. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  52798. if (currentDevice != 0)
  52799. {
  52800. if (type == audioInputType)
  52801. items = currentDevice->getInputChannelNames();
  52802. else if (type == audioOutputType)
  52803. items = currentDevice->getOutputChannelNames();
  52804. if (setup.useStereoPairs)
  52805. {
  52806. StringArray pairs;
  52807. for (int i = 0; i < items.size(); i += 2)
  52808. {
  52809. String name (items[i]);
  52810. String name2 (items[i + 1]);
  52811. String commonBit;
  52812. for (int j = 0; j < name.length(); ++j)
  52813. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  52814. commonBit = name.substring (0, j);
  52815. pairs.add (name.trim()
  52816. + " + "
  52817. + name2.substring (commonBit.length()).trim());
  52818. }
  52819. items = pairs;
  52820. }
  52821. }
  52822. updateContent();
  52823. repaint();
  52824. }
  52825. int getNumRows()
  52826. {
  52827. return items.size();
  52828. }
  52829. void paintListBoxItem (int row,
  52830. Graphics& g,
  52831. int width, int height,
  52832. bool rowIsSelected)
  52833. {
  52834. if (((unsigned int) row) < (unsigned int) items.size())
  52835. {
  52836. if (rowIsSelected)
  52837. g.fillAll (findColour (TextEditor::highlightColourId)
  52838. .withMultipliedAlpha (0.3f));
  52839. const String item (items [row]);
  52840. bool enabled = false;
  52841. AudioDeviceManager::AudioDeviceSetup config;
  52842. setup.manager->getAudioDeviceSetup (config);
  52843. if (setup.useStereoPairs)
  52844. {
  52845. if (type == audioInputType)
  52846. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  52847. else if (type == audioOutputType)
  52848. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  52849. }
  52850. else
  52851. {
  52852. if (type == audioInputType)
  52853. enabled = config.inputChannels [row];
  52854. else if (type == audioOutputType)
  52855. enabled = config.outputChannels [row];
  52856. }
  52857. const int x = getTickX();
  52858. const int tickW = height - height / 4;
  52859. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  52860. enabled, true, true, false);
  52861. g.setFont (height * 0.6f);
  52862. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  52863. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  52864. }
  52865. }
  52866. void listBoxItemClicked (int row, const MouseEvent& e)
  52867. {
  52868. selectRow (row);
  52869. if (e.x < getTickX())
  52870. flipEnablement (row);
  52871. }
  52872. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  52873. {
  52874. flipEnablement (row);
  52875. }
  52876. void returnKeyPressed (int row)
  52877. {
  52878. flipEnablement (row);
  52879. }
  52880. void paint (Graphics& g)
  52881. {
  52882. ListBox::paint (g);
  52883. if (items.size() == 0)
  52884. {
  52885. g.setColour (Colours::grey);
  52886. g.setFont (13.0f);
  52887. g.drawText (noItemsMessage,
  52888. 0, 0, getWidth(), getHeight() / 2,
  52889. Justification::centred, true);
  52890. }
  52891. }
  52892. int getBestHeight (int maxHeight)
  52893. {
  52894. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  52895. getNumRows())
  52896. + getOutlineThickness() * 2;
  52897. }
  52898. juce_UseDebuggingNewOperator
  52899. private:
  52900. const AudioIODeviceType::DeviceSetupDetails setup;
  52901. const BoxType type;
  52902. const String noItemsMessage;
  52903. StringArray items;
  52904. void flipEnablement (const int row)
  52905. {
  52906. jassert (type == audioInputType || type == audioOutputType);
  52907. if (((unsigned int) row) < (unsigned int) items.size())
  52908. {
  52909. AudioDeviceManager::AudioDeviceSetup config;
  52910. setup.manager->getAudioDeviceSetup (config);
  52911. if (setup.useStereoPairs)
  52912. {
  52913. BitArray bits;
  52914. BitArray& original = (type == audioInputType ? config.inputChannels
  52915. : config.outputChannels);
  52916. int i;
  52917. for (i = 0; i < 256; i += 2)
  52918. bits.setBit (i / 2, original [i] || original [i + 1]);
  52919. if (type == audioInputType)
  52920. {
  52921. config.useDefaultInputChannels = false;
  52922. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  52923. }
  52924. else
  52925. {
  52926. config.useDefaultOutputChannels = false;
  52927. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  52928. }
  52929. for (i = 0; i < 256; ++i)
  52930. original.setBit (i, bits [i / 2]);
  52931. }
  52932. else
  52933. {
  52934. if (type == audioInputType)
  52935. {
  52936. config.useDefaultInputChannels = false;
  52937. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  52938. }
  52939. else
  52940. {
  52941. config.useDefaultOutputChannels = false;
  52942. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  52943. }
  52944. }
  52945. String error (setup.manager->setAudioDeviceSetup (config, true));
  52946. if (! error.isEmpty())
  52947. {
  52948. //xxx
  52949. }
  52950. }
  52951. }
  52952. static void flipBit (BitArray& chans, int index, int minNumber, int maxNumber)
  52953. {
  52954. const int numActive = chans.countNumberOfSetBits();
  52955. if (chans [index])
  52956. {
  52957. if (numActive > minNumber)
  52958. chans.setBit (index, false);
  52959. }
  52960. else
  52961. {
  52962. if (numActive >= maxNumber)
  52963. {
  52964. const int firstActiveChan = chans.findNextSetBit();
  52965. chans.setBit (index > firstActiveChan
  52966. ? firstActiveChan : chans.getHighestBit(),
  52967. false);
  52968. }
  52969. chans.setBit (index, true);
  52970. }
  52971. }
  52972. int getTickX() const throw()
  52973. {
  52974. return getRowHeight() + 5;
  52975. }
  52976. ChannelSelectorListBox (const ChannelSelectorListBox&);
  52977. const ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  52978. };
  52979. ChannelSelectorListBox* inputChanList;
  52980. ChannelSelectorListBox* outputChanList;
  52981. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  52982. const AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  52983. };
  52984. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  52985. const int minInputChannels_,
  52986. const int maxInputChannels_,
  52987. const int minOutputChannels_,
  52988. const int maxOutputChannels_,
  52989. const bool showMidiInputOptions,
  52990. const bool showMidiOutputSelector,
  52991. const bool showChannelsAsStereoPairs_,
  52992. const bool hideAdvancedOptionsWithButton_)
  52993. : deviceManager (deviceManager_),
  52994. minOutputChannels (minOutputChannels_),
  52995. maxOutputChannels (maxOutputChannels_),
  52996. minInputChannels (minInputChannels_),
  52997. maxInputChannels (maxInputChannels_),
  52998. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  52999. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_),
  53000. deviceTypeDropDown (0),
  53001. deviceTypeDropDownLabel (0),
  53002. audioDeviceSettingsComp (0)
  53003. {
  53004. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  53005. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  53006. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  53007. {
  53008. deviceTypeDropDown = new ComboBox (String::empty);
  53009. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  53010. {
  53011. deviceTypeDropDown
  53012. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  53013. i + 1);
  53014. }
  53015. addAndMakeVisible (deviceTypeDropDown);
  53016. deviceTypeDropDown->addListener (this);
  53017. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  53018. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  53019. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  53020. }
  53021. if (showMidiInputOptions)
  53022. {
  53023. addAndMakeVisible (midiInputsList
  53024. = new MidiInputSelectorComponentListBox (deviceManager,
  53025. TRANS("(no midi inputs available)"),
  53026. 0, 0));
  53027. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  53028. midiInputsLabel->setJustificationType (Justification::topRight);
  53029. midiInputsLabel->attachToComponent (midiInputsList, true);
  53030. }
  53031. else
  53032. {
  53033. midiInputsList = 0;
  53034. midiInputsLabel = 0;
  53035. }
  53036. if (showMidiOutputSelector)
  53037. {
  53038. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  53039. midiOutputSelector->addListener (this);
  53040. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  53041. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  53042. }
  53043. else
  53044. {
  53045. midiOutputSelector = 0;
  53046. midiOutputLabel = 0;
  53047. }
  53048. deviceManager_.addChangeListener (this);
  53049. changeListenerCallback (0);
  53050. }
  53051. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  53052. {
  53053. deviceManager.removeChangeListener (this);
  53054. deleteAllChildren();
  53055. }
  53056. void AudioDeviceSelectorComponent::resized()
  53057. {
  53058. const int lx = proportionOfWidth (0.35f);
  53059. const int w = proportionOfWidth (0.4f);
  53060. const int h = 24;
  53061. const int space = 6;
  53062. const int dh = h + space;
  53063. int y = 15;
  53064. if (deviceTypeDropDown != 0)
  53065. {
  53066. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  53067. y += dh + space * 2;
  53068. }
  53069. if (audioDeviceSettingsComp != 0)
  53070. {
  53071. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  53072. y += audioDeviceSettingsComp->getHeight() + space;
  53073. }
  53074. if (midiInputsList != 0)
  53075. {
  53076. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space));
  53077. midiInputsList->setBounds (lx, y, w, bh);
  53078. y += bh + space;
  53079. }
  53080. if (midiOutputSelector != 0)
  53081. midiOutputSelector->setBounds (lx, y, w, h);
  53082. }
  53083. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  53084. {
  53085. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  53086. if (device != 0 && device->hasControlPanel())
  53087. {
  53088. if (device->showControlPanel())
  53089. deviceManager.restartLastAudioDevice();
  53090. getTopLevelComponent()->toFront (true);
  53091. }
  53092. }
  53093. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  53094. {
  53095. if (comboBoxThatHasChanged == deviceTypeDropDown)
  53096. {
  53097. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  53098. if (type != 0)
  53099. {
  53100. deleteAndZero (audioDeviceSettingsComp);
  53101. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  53102. changeListenerCallback (0); // needed in case the type hasn't actally changed
  53103. }
  53104. }
  53105. else if (comboBoxThatHasChanged == midiOutputSelector)
  53106. {
  53107. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  53108. }
  53109. }
  53110. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  53111. {
  53112. if (deviceTypeDropDown != 0)
  53113. {
  53114. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  53115. }
  53116. if (audioDeviceSettingsComp == 0
  53117. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  53118. {
  53119. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  53120. deleteAndZero (audioDeviceSettingsComp);
  53121. AudioIODeviceType* const type
  53122. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  53123. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  53124. if (type != 0)
  53125. {
  53126. AudioIODeviceType::DeviceSetupDetails details;
  53127. details.manager = &deviceManager;
  53128. details.minNumInputChannels = minInputChannels;
  53129. details.maxNumInputChannels = maxInputChannels;
  53130. details.minNumOutputChannels = minOutputChannels;
  53131. details.maxNumOutputChannels = maxOutputChannels;
  53132. details.useStereoPairs = showChannelsAsStereoPairs;
  53133. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  53134. if (audioDeviceSettingsComp != 0)
  53135. {
  53136. addAndMakeVisible (audioDeviceSettingsComp);
  53137. audioDeviceSettingsComp->resized();
  53138. }
  53139. }
  53140. }
  53141. if (midiInputsList != 0)
  53142. {
  53143. midiInputsList->updateContent();
  53144. midiInputsList->repaint();
  53145. }
  53146. if (midiOutputSelector != 0)
  53147. {
  53148. midiOutputSelector->clear();
  53149. const StringArray midiOuts (MidiOutput::getDevices());
  53150. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  53151. midiOutputSelector->addSeparator();
  53152. for (int i = 0; i < midiOuts.size(); ++i)
  53153. midiOutputSelector->addItem (midiOuts[i], i + 1);
  53154. int current = -1;
  53155. if (deviceManager.getDefaultMidiOutput() != 0)
  53156. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  53157. midiOutputSelector->setSelectedId (current, true);
  53158. }
  53159. resized();
  53160. }
  53161. END_JUCE_NAMESPACE
  53162. /********* End of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  53163. /********* Start of inlined file: juce_BubbleComponent.cpp *********/
  53164. BEGIN_JUCE_NAMESPACE
  53165. BubbleComponent::BubbleComponent()
  53166. : side (0),
  53167. allowablePlacements (above | below | left | right),
  53168. arrowTipX (0.0f),
  53169. arrowTipY (0.0f)
  53170. {
  53171. setInterceptsMouseClicks (false, false);
  53172. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  53173. setComponentEffect (&shadow);
  53174. }
  53175. BubbleComponent::~BubbleComponent()
  53176. {
  53177. }
  53178. void BubbleComponent::paint (Graphics& g)
  53179. {
  53180. int x = content.getX();
  53181. int y = content.getY();
  53182. int w = content.getWidth();
  53183. int h = content.getHeight();
  53184. int cw, ch;
  53185. getContentSize (cw, ch);
  53186. if (side == 3)
  53187. x += w - cw;
  53188. else if (side != 1)
  53189. x += (w - cw) / 2;
  53190. w = cw;
  53191. if (side == 2)
  53192. y += h - ch;
  53193. else if (side != 0)
  53194. y += (h - ch) / 2;
  53195. h = ch;
  53196. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  53197. (float) x, (float) y,
  53198. (float) w, (float) h);
  53199. const int cx = x + (w - cw) / 2;
  53200. const int cy = y + (h - ch) / 2;
  53201. const int indent = 3;
  53202. g.setOrigin (cx + indent, cy + indent);
  53203. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  53204. paintContent (g, cw - indent * 2, ch - indent * 2);
  53205. }
  53206. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  53207. {
  53208. allowablePlacements = newPlacement;
  53209. }
  53210. void BubbleComponent::setPosition (Component* componentToPointTo)
  53211. {
  53212. jassert (componentToPointTo->isValidComponent());
  53213. int tx = 0;
  53214. int ty = 0;
  53215. if (getParentComponent() != 0)
  53216. componentToPointTo->relativePositionToOtherComponent (getParentComponent(), tx, ty);
  53217. else
  53218. componentToPointTo->relativePositionToGlobal (tx, ty);
  53219. setPosition (Rectangle (tx, ty, componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  53220. }
  53221. void BubbleComponent::setPosition (const int arrowTipX,
  53222. const int arrowTipY)
  53223. {
  53224. setPosition (Rectangle (arrowTipX, arrowTipY, 1, 1));
  53225. }
  53226. void BubbleComponent::setPosition (const Rectangle& rectangleToPointTo)
  53227. {
  53228. Rectangle availableSpace;
  53229. if (getParentComponent() != 0)
  53230. {
  53231. availableSpace.setSize (getParentComponent()->getWidth(),
  53232. getParentComponent()->getHeight());
  53233. }
  53234. else
  53235. {
  53236. availableSpace = getParentMonitorArea();
  53237. }
  53238. int x = 0;
  53239. int y = 0;
  53240. int w = 150;
  53241. int h = 30;
  53242. getContentSize (w, h);
  53243. w += 30;
  53244. h += 30;
  53245. const float edgeIndent = 2.0f;
  53246. const int arrowLength = jmin (10, h / 3, w / 3);
  53247. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  53248. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  53249. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  53250. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  53251. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  53252. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  53253. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  53254. {
  53255. spaceLeft = spaceRight = 0;
  53256. }
  53257. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  53258. && (spaceLeft > w + 20 || spaceRight > w + 20))
  53259. {
  53260. spaceAbove = spaceBelow = 0;
  53261. }
  53262. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  53263. {
  53264. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  53265. arrowTipX = w * 0.5f;
  53266. content.setSize (w, h - arrowLength);
  53267. if (spaceAbove >= spaceBelow)
  53268. {
  53269. // above
  53270. y = rectangleToPointTo.getY() - h;
  53271. content.setPosition (0, 0);
  53272. arrowTipY = h - edgeIndent;
  53273. side = 2;
  53274. }
  53275. else
  53276. {
  53277. // below
  53278. y = rectangleToPointTo.getBottom();
  53279. content.setPosition (0, arrowLength);
  53280. arrowTipY = edgeIndent;
  53281. side = 0;
  53282. }
  53283. }
  53284. else
  53285. {
  53286. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  53287. arrowTipY = h * 0.5f;
  53288. content.setSize (w - arrowLength, h);
  53289. if (spaceLeft > spaceRight)
  53290. {
  53291. // on the left
  53292. x = rectangleToPointTo.getX() - w;
  53293. content.setPosition (0, 0);
  53294. arrowTipX = w - edgeIndent;
  53295. side = 3;
  53296. }
  53297. else
  53298. {
  53299. // on the right
  53300. x = rectangleToPointTo.getRight();
  53301. content.setPosition (arrowLength, 0);
  53302. arrowTipX = edgeIndent;
  53303. side = 1;
  53304. }
  53305. }
  53306. setBounds (x, y, w, h);
  53307. }
  53308. END_JUCE_NAMESPACE
  53309. /********* End of inlined file: juce_BubbleComponent.cpp *********/
  53310. /********* Start of inlined file: juce_BubbleMessageComponent.cpp *********/
  53311. BEGIN_JUCE_NAMESPACE
  53312. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  53313. : fadeOutLength (fadeOutLengthMs),
  53314. deleteAfterUse (false)
  53315. {
  53316. }
  53317. BubbleMessageComponent::~BubbleMessageComponent()
  53318. {
  53319. fadeOutComponent (fadeOutLength);
  53320. }
  53321. void BubbleMessageComponent::showAt (int x, int y,
  53322. const String& text,
  53323. const int numMillisecondsBeforeRemoving,
  53324. const bool removeWhenMouseClicked,
  53325. const bool deleteSelfAfterUse)
  53326. {
  53327. textLayout.clear();
  53328. textLayout.setText (text, Font (14.0f));
  53329. textLayout.layout (256, Justification::centredLeft, true);
  53330. setPosition (x, y);
  53331. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  53332. }
  53333. void BubbleMessageComponent::showAt (Component* const component,
  53334. const String& text,
  53335. const int numMillisecondsBeforeRemoving,
  53336. const bool removeWhenMouseClicked,
  53337. const bool deleteSelfAfterUse)
  53338. {
  53339. textLayout.clear();
  53340. textLayout.setText (text, Font (14.0f));
  53341. textLayout.layout (256, Justification::centredLeft, true);
  53342. setPosition (component);
  53343. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  53344. }
  53345. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  53346. const bool removeWhenMouseClicked,
  53347. const bool deleteSelfAfterUse)
  53348. {
  53349. setVisible (true);
  53350. deleteAfterUse = deleteSelfAfterUse;
  53351. if (numMillisecondsBeforeRemoving > 0)
  53352. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  53353. else
  53354. expiryTime = 0;
  53355. startTimer (77);
  53356. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  53357. if (! (removeWhenMouseClicked && isShowing()))
  53358. mouseClickCounter += 0xfffff;
  53359. repaint();
  53360. }
  53361. void BubbleMessageComponent::getContentSize (int& w, int& h)
  53362. {
  53363. w = textLayout.getWidth() + 16;
  53364. h = textLayout.getHeight() + 16;
  53365. }
  53366. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  53367. {
  53368. g.setColour (findColour (TooltipWindow::textColourId));
  53369. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  53370. }
  53371. void BubbleMessageComponent::timerCallback()
  53372. {
  53373. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  53374. {
  53375. stopTimer();
  53376. setVisible (false);
  53377. if (deleteAfterUse)
  53378. delete this;
  53379. }
  53380. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  53381. {
  53382. stopTimer();
  53383. fadeOutComponent (fadeOutLength);
  53384. if (deleteAfterUse)
  53385. delete this;
  53386. }
  53387. }
  53388. END_JUCE_NAMESPACE
  53389. /********* End of inlined file: juce_BubbleMessageComponent.cpp *********/
  53390. /********* Start of inlined file: juce_ColourSelector.cpp *********/
  53391. BEGIN_JUCE_NAMESPACE
  53392. static const int swatchesPerRow = 8;
  53393. static const int swatchHeight = 22;
  53394. class ColourComponentSlider : public Slider
  53395. {
  53396. public:
  53397. ColourComponentSlider (const String& name)
  53398. : Slider (name)
  53399. {
  53400. setRange (0.0, 255.0, 1.0);
  53401. }
  53402. ~ColourComponentSlider()
  53403. {
  53404. }
  53405. const String getTextFromValue (double currentValue)
  53406. {
  53407. return String::formatted (T("%02X"), (int)currentValue);
  53408. }
  53409. double getValueFromText (const String& text)
  53410. {
  53411. return (double) text.getHexValue32();
  53412. }
  53413. private:
  53414. ColourComponentSlider (const ColourComponentSlider&);
  53415. const ColourComponentSlider& operator= (const ColourComponentSlider&);
  53416. };
  53417. class ColourSpaceMarker : public Component
  53418. {
  53419. public:
  53420. ColourSpaceMarker()
  53421. {
  53422. setInterceptsMouseClicks (false, false);
  53423. }
  53424. ~ColourSpaceMarker()
  53425. {
  53426. }
  53427. void paint (Graphics& g)
  53428. {
  53429. g.setColour (Colour::greyLevel (0.1f));
  53430. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  53431. g.setColour (Colour::greyLevel (0.9f));
  53432. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  53433. }
  53434. private:
  53435. ColourSpaceMarker (const ColourSpaceMarker&);
  53436. const ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  53437. };
  53438. class ColourSpaceView : public Component
  53439. {
  53440. ColourSelector* const owner;
  53441. float& h;
  53442. float& s;
  53443. float& v;
  53444. float lastHue;
  53445. ColourSpaceMarker* marker;
  53446. const int edge;
  53447. public:
  53448. ColourSpaceView (ColourSelector* owner_,
  53449. float& h_, float& s_, float& v_,
  53450. const int edgeSize)
  53451. : owner (owner_),
  53452. h (h_), s (s_), v (v_),
  53453. lastHue (0.0f),
  53454. edge (edgeSize)
  53455. {
  53456. addAndMakeVisible (marker = new ColourSpaceMarker());
  53457. setMouseCursor (MouseCursor::CrosshairCursor);
  53458. }
  53459. ~ColourSpaceView()
  53460. {
  53461. deleteAllChildren();
  53462. }
  53463. void paint (Graphics& g)
  53464. {
  53465. const float hue = h;
  53466. const float xScale = 1.0f / (getWidth() - edge * 2);
  53467. const float yScale = 1.0f / (getHeight() - edge * 2);
  53468. const Rectangle clip (g.getClipBounds());
  53469. const int x1 = jmax (clip.getX(), edge) & ~1;
  53470. const int x2 = jmin (clip.getRight(), getWidth() - edge) | 1;
  53471. const int y1 = jmax (clip.getY(), edge) & ~1;
  53472. const int y2 = jmin (clip.getBottom(), getHeight() - edge) | 1;
  53473. for (int y = y1; y < y2; y += 2)
  53474. {
  53475. const float v = jlimit (0.0f, 1.0f, 1.0f - (y - edge) * yScale);
  53476. for (int x = x1; x < x2; x += 2)
  53477. {
  53478. const float s = jlimit (0.0f, 1.0f, (x - edge) * xScale);
  53479. g.setColour (Colour (hue, s, v, 1.0f));
  53480. g.fillRect (x, y, 2, 2);
  53481. }
  53482. }
  53483. }
  53484. void mouseDown (const MouseEvent& e)
  53485. {
  53486. mouseDrag (e);
  53487. }
  53488. void mouseDrag (const MouseEvent& e)
  53489. {
  53490. const float s = (e.x - edge) / (float) (getWidth() - edge * 2);
  53491. const float v = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  53492. owner->setSV (s, v);
  53493. }
  53494. void updateIfNeeded()
  53495. {
  53496. if (lastHue != h)
  53497. {
  53498. lastHue = h;
  53499. repaint();
  53500. }
  53501. resized();
  53502. }
  53503. void resized()
  53504. {
  53505. marker->setBounds (roundFloatToInt ((getWidth() - edge * 2) * s),
  53506. roundFloatToInt ((getHeight() - edge * 2) * (1.0f - v)),
  53507. edge * 2, edge * 2);
  53508. }
  53509. private:
  53510. ColourSpaceView (const ColourSpaceView&);
  53511. const ColourSpaceView& operator= (const ColourSpaceView&);
  53512. };
  53513. class HueSelectorMarker : public Component
  53514. {
  53515. public:
  53516. HueSelectorMarker()
  53517. {
  53518. setInterceptsMouseClicks (false, false);
  53519. }
  53520. ~HueSelectorMarker()
  53521. {
  53522. }
  53523. void paint (Graphics& g)
  53524. {
  53525. Path p;
  53526. p.addTriangle (1.0f, 1.0f,
  53527. getWidth() * 0.3f, getHeight() * 0.5f,
  53528. 1.0f, getHeight() - 1.0f);
  53529. p.addTriangle (getWidth() - 1.0f, 1.0f,
  53530. getWidth() * 0.7f, getHeight() * 0.5f,
  53531. getWidth() - 1.0f, getHeight() - 1.0f);
  53532. g.setColour (Colours::white.withAlpha (0.75f));
  53533. g.fillPath (p);
  53534. g.setColour (Colours::black.withAlpha (0.75f));
  53535. g.strokePath (p, PathStrokeType (1.2f));
  53536. }
  53537. private:
  53538. HueSelectorMarker (const HueSelectorMarker&);
  53539. const HueSelectorMarker& operator= (const HueSelectorMarker&);
  53540. };
  53541. class HueSelectorComp : public Component
  53542. {
  53543. public:
  53544. HueSelectorComp (ColourSelector* owner_,
  53545. float& h_, float& s_, float& v_,
  53546. const int edgeSize)
  53547. : owner (owner_),
  53548. h (h_), s (s_), v (v_),
  53549. lastHue (0.0f),
  53550. edge (edgeSize)
  53551. {
  53552. addAndMakeVisible (marker = new HueSelectorMarker());
  53553. }
  53554. ~HueSelectorComp()
  53555. {
  53556. deleteAllChildren();
  53557. }
  53558. void paint (Graphics& g)
  53559. {
  53560. const float yScale = 1.0f / (getHeight() - edge * 2);
  53561. const Rectangle clip (g.getClipBounds());
  53562. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  53563. {
  53564. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  53565. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  53566. }
  53567. }
  53568. void resized()
  53569. {
  53570. marker->setBounds (0, roundFloatToInt ((getHeight() - edge * 2) * h),
  53571. getWidth(), edge * 2);
  53572. }
  53573. void mouseDown (const MouseEvent& e)
  53574. {
  53575. mouseDrag (e);
  53576. }
  53577. void mouseDrag (const MouseEvent& e)
  53578. {
  53579. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  53580. owner->setHue (hue);
  53581. }
  53582. void updateIfNeeded()
  53583. {
  53584. resized();
  53585. }
  53586. private:
  53587. ColourSelector* const owner;
  53588. float& h;
  53589. float& s;
  53590. float& v;
  53591. float lastHue;
  53592. HueSelectorMarker* marker;
  53593. const int edge;
  53594. HueSelectorComp (const HueSelectorComp&);
  53595. const HueSelectorComp& operator= (const HueSelectorComp&);
  53596. };
  53597. class SwatchComponent : public Component
  53598. {
  53599. public:
  53600. SwatchComponent (ColourSelector* owner_, int index_)
  53601. : owner (owner_),
  53602. index (index_)
  53603. {
  53604. }
  53605. ~SwatchComponent()
  53606. {
  53607. }
  53608. void paint (Graphics& g)
  53609. {
  53610. const Colour colour (owner->getSwatchColour (index));
  53611. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  53612. 6, 6,
  53613. Colour (0xffdddddd).overlaidWith (colour),
  53614. Colour (0xffffffff).overlaidWith (colour));
  53615. }
  53616. void mouseDown (const MouseEvent&)
  53617. {
  53618. PopupMenu m;
  53619. m.addItem (1, TRANS("Use this swatch as the current colour"));
  53620. m.addSeparator();
  53621. m.addItem (2, TRANS("Set this swatch to the current colour"));
  53622. const int r = m.showAt (this);
  53623. if (r == 1)
  53624. {
  53625. owner->setCurrentColour (owner->getSwatchColour (index));
  53626. }
  53627. else if (r == 2)
  53628. {
  53629. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  53630. {
  53631. owner->setSwatchColour (index, owner->getCurrentColour());
  53632. repaint();
  53633. }
  53634. }
  53635. }
  53636. private:
  53637. ColourSelector* const owner;
  53638. const int index;
  53639. SwatchComponent (const SwatchComponent&);
  53640. const SwatchComponent& operator= (const SwatchComponent&);
  53641. };
  53642. ColourSelector::ColourSelector (const int flags_,
  53643. const int edgeGap_,
  53644. const int gapAroundColourSpaceComponent)
  53645. : colour (Colours::white),
  53646. flags (flags_),
  53647. topSpace (0),
  53648. edgeGap (edgeGap_)
  53649. {
  53650. // not much point having a selector with no components in it!
  53651. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  53652. updateHSV();
  53653. if ((flags & showSliders) != 0)
  53654. {
  53655. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  53656. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  53657. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  53658. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  53659. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  53660. for (int i = 4; --i >= 0;)
  53661. sliders[i]->addListener (this);
  53662. }
  53663. else
  53664. {
  53665. zeromem (sliders, sizeof (sliders));
  53666. }
  53667. if ((flags & showColourspace) != 0)
  53668. {
  53669. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  53670. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  53671. }
  53672. else
  53673. {
  53674. colourSpace = 0;
  53675. hueSelector = 0;
  53676. }
  53677. update();
  53678. }
  53679. ColourSelector::~ColourSelector()
  53680. {
  53681. dispatchPendingMessages();
  53682. deleteAllChildren();
  53683. }
  53684. const Colour ColourSelector::getCurrentColour() const
  53685. {
  53686. return ((flags & showAlphaChannel) != 0) ? colour
  53687. : colour.withAlpha ((uint8) 0xff);
  53688. }
  53689. void ColourSelector::setCurrentColour (const Colour& c)
  53690. {
  53691. if (c != colour)
  53692. {
  53693. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  53694. updateHSV();
  53695. update();
  53696. }
  53697. }
  53698. void ColourSelector::setHue (float newH)
  53699. {
  53700. newH = jlimit (0.0f, 1.0f, newH);
  53701. if (h != newH)
  53702. {
  53703. h = newH;
  53704. colour = Colour (h, s, v, colour.getFloatAlpha());
  53705. update();
  53706. }
  53707. }
  53708. void ColourSelector::setSV (float newS, float newV)
  53709. {
  53710. newS = jlimit (0.0f, 1.0f, newS);
  53711. newV = jlimit (0.0f, 1.0f, newV);
  53712. if (s != newS || v != newV)
  53713. {
  53714. s = newS;
  53715. v = newV;
  53716. colour = Colour (h, s, v, colour.getFloatAlpha());
  53717. update();
  53718. }
  53719. }
  53720. void ColourSelector::updateHSV()
  53721. {
  53722. colour.getHSB (h, s, v);
  53723. }
  53724. void ColourSelector::update()
  53725. {
  53726. if (sliders[0] != 0)
  53727. {
  53728. sliders[0]->setValue ((int) colour.getRed());
  53729. sliders[1]->setValue ((int) colour.getGreen());
  53730. sliders[2]->setValue ((int) colour.getBlue());
  53731. sliders[3]->setValue ((int) colour.getAlpha());
  53732. }
  53733. if (colourSpace != 0)
  53734. {
  53735. ((ColourSpaceView*) colourSpace)->updateIfNeeded();
  53736. ((HueSelectorComp*) hueSelector)->updateIfNeeded();
  53737. }
  53738. if ((flags & showColourAtTop) != 0)
  53739. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  53740. sendChangeMessage (this);
  53741. }
  53742. void ColourSelector::paint (Graphics& g)
  53743. {
  53744. g.fillAll (findColour (backgroundColourId));
  53745. if ((flags & showColourAtTop) != 0)
  53746. {
  53747. const Colour colour (getCurrentColour());
  53748. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  53749. 10, 10,
  53750. Colour (0xffdddddd).overlaidWith (colour),
  53751. Colour (0xffffffff).overlaidWith (colour));
  53752. g.setColour (Colours::white.overlaidWith (colour).contrasting());
  53753. g.setFont (14.0f, true);
  53754. g.drawText (((flags & showAlphaChannel) != 0)
  53755. ? String::formatted (T("#%02X%02X%02X%02X"),
  53756. (int) colour.getAlpha(),
  53757. (int) colour.getRed(),
  53758. (int) colour.getGreen(),
  53759. (int) colour.getBlue())
  53760. : String::formatted (T("#%02X%02X%02X"),
  53761. (int) colour.getRed(),
  53762. (int) colour.getGreen(),
  53763. (int) colour.getBlue()),
  53764. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  53765. Justification::centred, false);
  53766. }
  53767. if ((flags & showSliders) != 0)
  53768. {
  53769. g.setColour (findColour (labelTextColourId));
  53770. g.setFont (11.0f);
  53771. for (int i = 4; --i >= 0;)
  53772. {
  53773. if (sliders[i]->isVisible())
  53774. g.drawText (sliders[i]->getName() + T(":"),
  53775. 0, sliders[i]->getY(),
  53776. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  53777. Justification::centredRight, false);
  53778. }
  53779. }
  53780. }
  53781. void ColourSelector::resized()
  53782. {
  53783. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  53784. const int numSwatches = getNumSwatches();
  53785. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  53786. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  53787. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  53788. int y = topSpace;
  53789. if ((flags & showColourspace) != 0)
  53790. {
  53791. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  53792. colourSpace->setBounds (edgeGap, y,
  53793. getWidth() - hueWidth - edgeGap - 4,
  53794. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  53795. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  53796. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  53797. colourSpace->getHeight());
  53798. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  53799. }
  53800. if ((flags & showSliders) != 0)
  53801. {
  53802. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  53803. for (int i = 0; i < numSliders; ++i)
  53804. {
  53805. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  53806. proportionOfWidth (0.72f), sliderHeight - 2);
  53807. y += sliderHeight;
  53808. }
  53809. }
  53810. if (numSwatches > 0)
  53811. {
  53812. const int startX = 8;
  53813. const int xGap = 4;
  53814. const int yGap = 4;
  53815. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  53816. y += edgeGap;
  53817. if (swatchComponents.size() != numSwatches)
  53818. {
  53819. int i;
  53820. for (i = swatchComponents.size(); --i >= 0;)
  53821. {
  53822. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  53823. delete sc;
  53824. }
  53825. for (i = 0; i < numSwatches; ++i)
  53826. {
  53827. SwatchComponent* const sc = new SwatchComponent (this, i);
  53828. swatchComponents.add (sc);
  53829. addAndMakeVisible (sc);
  53830. }
  53831. }
  53832. int x = startX;
  53833. for (int i = 0; i < swatchComponents.size(); ++i)
  53834. {
  53835. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  53836. sc->setBounds (x + xGap / 2,
  53837. y + yGap / 2,
  53838. swatchWidth - xGap,
  53839. swatchHeight - yGap);
  53840. if (((i + 1) % swatchesPerRow) == 0)
  53841. {
  53842. x = startX;
  53843. y += swatchHeight;
  53844. }
  53845. else
  53846. {
  53847. x += swatchWidth;
  53848. }
  53849. }
  53850. }
  53851. }
  53852. void ColourSelector::sliderValueChanged (Slider*)
  53853. {
  53854. if (sliders[0] != 0)
  53855. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  53856. (uint8) sliders[1]->getValue(),
  53857. (uint8) sliders[2]->getValue(),
  53858. (uint8) sliders[3]->getValue()));
  53859. }
  53860. int ColourSelector::getNumSwatches() const
  53861. {
  53862. return 0;
  53863. }
  53864. const Colour ColourSelector::getSwatchColour (const int) const
  53865. {
  53866. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  53867. return Colours::black;
  53868. }
  53869. void ColourSelector::setSwatchColour (const int, const Colour&) const
  53870. {
  53871. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  53872. }
  53873. END_JUCE_NAMESPACE
  53874. /********* End of inlined file: juce_ColourSelector.cpp *********/
  53875. /********* Start of inlined file: juce_DropShadower.cpp *********/
  53876. BEGIN_JUCE_NAMESPACE
  53877. class ShadowWindow : public Component
  53878. {
  53879. Component* owner;
  53880. Image** shadowImageSections;
  53881. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  53882. public:
  53883. ShadowWindow (Component* const owner_,
  53884. const int type_,
  53885. Image** const shadowImageSections_)
  53886. : owner (owner_),
  53887. shadowImageSections (shadowImageSections_),
  53888. type (type_)
  53889. {
  53890. setInterceptsMouseClicks (false, false);
  53891. if (owner_->isOnDesktop())
  53892. {
  53893. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  53894. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  53895. | ComponentPeer::windowIsTemporary);
  53896. }
  53897. else if (owner_->getParentComponent() != 0)
  53898. {
  53899. owner_->getParentComponent()->addChildComponent (this);
  53900. }
  53901. }
  53902. ~ShadowWindow()
  53903. {
  53904. }
  53905. void paint (Graphics& g)
  53906. {
  53907. Image* const topLeft = shadowImageSections [type * 3];
  53908. Image* const bottomRight = shadowImageSections [type * 3 + 1];
  53909. Image* const filler = shadowImageSections [type * 3 + 2];
  53910. ImageBrush fillBrush (filler, 0, 0, 1.0f);
  53911. g.setOpacity (1.0f);
  53912. if (type < 2)
  53913. {
  53914. int imH = jmin (topLeft->getHeight(), getHeight() / 2);
  53915. g.drawImage (topLeft,
  53916. 0, 0, topLeft->getWidth(), imH,
  53917. 0, 0, topLeft->getWidth(), imH);
  53918. imH = jmin (bottomRight->getHeight(), getHeight() - getHeight() / 2);
  53919. g.drawImage (bottomRight,
  53920. 0, getHeight() - imH, bottomRight->getWidth(), imH,
  53921. 0, bottomRight->getHeight() - imH, bottomRight->getWidth(), imH);
  53922. g.setBrush (&fillBrush);
  53923. g.fillRect (0, topLeft->getHeight(), getWidth(), getHeight() - (topLeft->getHeight() + bottomRight->getHeight()));
  53924. }
  53925. else
  53926. {
  53927. int imW = jmin (topLeft->getWidth(), getWidth() / 2);
  53928. g.drawImage (topLeft,
  53929. 0, 0, imW, topLeft->getHeight(),
  53930. 0, 0, imW, topLeft->getHeight());
  53931. imW = jmin (bottomRight->getWidth(), getWidth() - getWidth() / 2);
  53932. g.drawImage (bottomRight,
  53933. getWidth() - imW, 0, imW, bottomRight->getHeight(),
  53934. bottomRight->getWidth() - imW, 0, imW, bottomRight->getHeight());
  53935. g.setBrush (&fillBrush);
  53936. g.fillRect (topLeft->getWidth(), 0, getWidth() - (topLeft->getWidth() + bottomRight->getWidth()), getHeight());
  53937. }
  53938. }
  53939. void resized()
  53940. {
  53941. repaint(); // (needed for correct repainting)
  53942. }
  53943. private:
  53944. ShadowWindow (const ShadowWindow&);
  53945. const ShadowWindow& operator= (const ShadowWindow&);
  53946. };
  53947. DropShadower::DropShadower (const float alpha_,
  53948. const int xOffset_,
  53949. const int yOffset_,
  53950. const float blurRadius_)
  53951. : owner (0),
  53952. numShadows (0),
  53953. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  53954. xOffset (xOffset_),
  53955. yOffset (yOffset_),
  53956. alpha (alpha_),
  53957. blurRadius (blurRadius_),
  53958. inDestructor (false),
  53959. reentrant (false)
  53960. {
  53961. }
  53962. DropShadower::~DropShadower()
  53963. {
  53964. if (owner != 0)
  53965. owner->removeComponentListener (this);
  53966. inDestructor = true;
  53967. deleteShadowWindows();
  53968. }
  53969. void DropShadower::deleteShadowWindows()
  53970. {
  53971. if (numShadows > 0)
  53972. {
  53973. int i;
  53974. for (i = numShadows; --i >= 0;)
  53975. delete shadowWindows[i];
  53976. for (i = 12; --i >= 0;)
  53977. delete shadowImageSections[i];
  53978. numShadows = 0;
  53979. }
  53980. }
  53981. void DropShadower::setOwner (Component* componentToFollow)
  53982. {
  53983. if (componentToFollow != owner)
  53984. {
  53985. if (owner != 0)
  53986. owner->removeComponentListener (this);
  53987. // (the component can't be null)
  53988. jassert (componentToFollow != 0);
  53989. owner = componentToFollow;
  53990. jassert (owner != 0);
  53991. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  53992. owner->addComponentListener (this);
  53993. updateShadows();
  53994. }
  53995. }
  53996. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  53997. {
  53998. updateShadows();
  53999. }
  54000. void DropShadower::componentBroughtToFront (Component&)
  54001. {
  54002. bringShadowWindowsToFront();
  54003. }
  54004. void DropShadower::componentChildrenChanged (Component&)
  54005. {
  54006. }
  54007. void DropShadower::componentParentHierarchyChanged (Component&)
  54008. {
  54009. deleteShadowWindows();
  54010. updateShadows();
  54011. }
  54012. void DropShadower::componentVisibilityChanged (Component&)
  54013. {
  54014. updateShadows();
  54015. }
  54016. void DropShadower::updateShadows()
  54017. {
  54018. if (reentrant || inDestructor || (owner == 0))
  54019. return;
  54020. reentrant = true;
  54021. ComponentPeer* const nw = owner->getPeer();
  54022. const bool isOwnerVisible = owner->isVisible()
  54023. && (nw == 0 || ! nw->isMinimised());
  54024. const bool createShadowWindows = numShadows == 0
  54025. && owner->getWidth() > 0
  54026. && owner->getHeight() > 0
  54027. && isOwnerVisible
  54028. && (Desktop::canUseSemiTransparentWindows()
  54029. || owner->getParentComponent() != 0);
  54030. if (createShadowWindows)
  54031. {
  54032. // keep a cached version of the image to save doing the gaussian too often
  54033. String imageId;
  54034. imageId << shadowEdge << T(',')
  54035. << xOffset << T(',')
  54036. << yOffset << T(',')
  54037. << alpha;
  54038. const int hash = imageId.hashCode();
  54039. Image* bigIm = ImageCache::getFromHashCode (hash);
  54040. if (bigIm == 0)
  54041. {
  54042. bigIm = new Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true);
  54043. Graphics bigG (*bigIm);
  54044. bigG.setColour (Colours::black.withAlpha (alpha));
  54045. bigG.fillRect (shadowEdge + xOffset,
  54046. shadowEdge + yOffset,
  54047. bigIm->getWidth() - (shadowEdge * 2),
  54048. bigIm->getHeight() - (shadowEdge * 2));
  54049. ImageConvolutionKernel blurKernel (roundFloatToInt (blurRadius * 2.0f));
  54050. blurKernel.createGaussianBlur (blurRadius);
  54051. blurKernel.applyToImage (*bigIm, 0,
  54052. xOffset,
  54053. yOffset,
  54054. bigIm->getWidth(),
  54055. bigIm->getHeight());
  54056. ImageCache::addImageToCache (bigIm, hash);
  54057. }
  54058. const int iw = bigIm->getWidth();
  54059. const int ih = bigIm->getHeight();
  54060. const int shadowEdge2 = shadowEdge * 2;
  54061. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  54062. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  54063. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  54064. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  54065. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  54066. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  54067. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  54068. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  54069. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  54070. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  54071. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  54072. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  54073. ImageCache::release (bigIm);
  54074. for (int i = 0; i < 4; ++i)
  54075. {
  54076. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  54077. ++numShadows;
  54078. }
  54079. }
  54080. if (numShadows > 0)
  54081. {
  54082. for (int i = numShadows; --i >= 0;)
  54083. {
  54084. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  54085. shadowWindows[i]->setVisible (isOwnerVisible);
  54086. }
  54087. const int x = owner->getX();
  54088. const int y = owner->getY() - shadowEdge;
  54089. const int w = owner->getWidth();
  54090. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  54091. shadowWindows[0]->setBounds (x - shadowEdge,
  54092. y,
  54093. shadowEdge,
  54094. h);
  54095. shadowWindows[1]->setBounds (x + w,
  54096. y,
  54097. shadowEdge,
  54098. h);
  54099. shadowWindows[2]->setBounds (x,
  54100. y,
  54101. w,
  54102. shadowEdge);
  54103. shadowWindows[3]->setBounds (x,
  54104. owner->getBottom(),
  54105. w,
  54106. shadowEdge);
  54107. }
  54108. reentrant = false;
  54109. if (createShadowWindows)
  54110. bringShadowWindowsToFront();
  54111. }
  54112. void DropShadower::setShadowImage (Image* const src,
  54113. const int num,
  54114. const int w,
  54115. const int h,
  54116. const int sx,
  54117. const int sy) throw()
  54118. {
  54119. shadowImageSections[num] = new Image (Image::ARGB, w, h, true);
  54120. Graphics g (*shadowImageSections[num]);
  54121. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  54122. }
  54123. void DropShadower::bringShadowWindowsToFront()
  54124. {
  54125. if (! (inDestructor || reentrant))
  54126. {
  54127. updateShadows();
  54128. reentrant = true;
  54129. for (int i = numShadows; --i >= 0;)
  54130. shadowWindows[i]->toBehind (owner);
  54131. reentrant = false;
  54132. }
  54133. }
  54134. END_JUCE_NAMESPACE
  54135. /********* End of inlined file: juce_DropShadower.cpp *********/
  54136. /********* Start of inlined file: juce_MagnifierComponent.cpp *********/
  54137. BEGIN_JUCE_NAMESPACE
  54138. class MagnifyingPeer : public ComponentPeer
  54139. {
  54140. public:
  54141. MagnifyingPeer (Component* const component,
  54142. MagnifierComponent* const magnifierComp_)
  54143. : ComponentPeer (component, 0),
  54144. magnifierComp (magnifierComp_)
  54145. {
  54146. }
  54147. ~MagnifyingPeer()
  54148. {
  54149. }
  54150. void* getNativeHandle() const { return 0; }
  54151. void setVisible (bool) {}
  54152. void setTitle (const String&) {}
  54153. void setPosition (int, int) {}
  54154. void setSize (int, int) {}
  54155. void setBounds (int, int, int, int, const bool) {}
  54156. void setMinimised (bool) {}
  54157. bool isMinimised() const { return false; }
  54158. void setFullScreen (bool) {}
  54159. bool isFullScreen() const { return false; }
  54160. const BorderSize getFrameSize() const { return BorderSize (0); }
  54161. bool setAlwaysOnTop (bool) { return true; }
  54162. void toFront (bool) {}
  54163. void toBehind (ComponentPeer*) {}
  54164. void setIcon (const Image&) {}
  54165. bool isFocused() const
  54166. {
  54167. return magnifierComp->hasKeyboardFocus (true);
  54168. }
  54169. void grabFocus()
  54170. {
  54171. ComponentPeer* peer = magnifierComp->getPeer();
  54172. if (peer != 0)
  54173. peer->grabFocus();
  54174. }
  54175. void textInputRequired (int x, int y)
  54176. {
  54177. ComponentPeer* peer = magnifierComp->getPeer();
  54178. if (peer != 0)
  54179. peer->textInputRequired (x, y);
  54180. }
  54181. void getBounds (int& x, int& y, int& w, int& h) const
  54182. {
  54183. x = magnifierComp->getScreenX();
  54184. y = magnifierComp->getScreenY();
  54185. w = component->getWidth();
  54186. h = component->getHeight();
  54187. }
  54188. int getScreenX() const { return magnifierComp->getScreenX(); }
  54189. int getScreenY() const { return magnifierComp->getScreenY(); }
  54190. void relativePositionToGlobal (int& x, int& y)
  54191. {
  54192. const double zoom = magnifierComp->getScaleFactor();
  54193. x = roundDoubleToInt (x * zoom);
  54194. y = roundDoubleToInt (y * zoom);
  54195. magnifierComp->relativePositionToGlobal (x, y);
  54196. }
  54197. void globalPositionToRelative (int& x, int& y)
  54198. {
  54199. magnifierComp->globalPositionToRelative (x, y);
  54200. const double zoom = magnifierComp->getScaleFactor();
  54201. x = roundDoubleToInt (x / zoom);
  54202. y = roundDoubleToInt (y / zoom);
  54203. }
  54204. bool contains (int x, int y, bool) const
  54205. {
  54206. return ((unsigned int) x) < (unsigned int) magnifierComp->getWidth()
  54207. && ((unsigned int) y) < (unsigned int) magnifierComp->getHeight();
  54208. }
  54209. void repaint (int x, int y, int w, int h)
  54210. {
  54211. const double zoom = magnifierComp->getScaleFactor();
  54212. magnifierComp->repaint ((int) (x * zoom),
  54213. (int) (y * zoom),
  54214. roundDoubleToInt (w * zoom) + 1,
  54215. roundDoubleToInt (h * zoom) + 1);
  54216. }
  54217. void performAnyPendingRepaintsNow()
  54218. {
  54219. }
  54220. juce_UseDebuggingNewOperator
  54221. private:
  54222. MagnifierComponent* const magnifierComp;
  54223. MagnifyingPeer (const MagnifyingPeer&);
  54224. const MagnifyingPeer& operator= (const MagnifyingPeer&);
  54225. };
  54226. class PeerHolderComp : public Component
  54227. {
  54228. public:
  54229. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  54230. : magnifierComp (magnifierComp_)
  54231. {
  54232. setVisible (true);
  54233. }
  54234. ~PeerHolderComp()
  54235. {
  54236. }
  54237. ComponentPeer* createNewPeer (int, void*)
  54238. {
  54239. return new MagnifyingPeer (this, magnifierComp);
  54240. }
  54241. void childBoundsChanged (Component* c)
  54242. {
  54243. if (c != 0)
  54244. {
  54245. setSize (c->getWidth(), c->getHeight());
  54246. magnifierComp->childBoundsChanged (this);
  54247. }
  54248. }
  54249. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  54250. {
  54251. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  54252. Component* const p = magnifierComp->getParentComponent();
  54253. if (p != 0)
  54254. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  54255. }
  54256. private:
  54257. MagnifierComponent* const magnifierComp;
  54258. PeerHolderComp (const PeerHolderComp&);
  54259. const PeerHolderComp& operator= (const PeerHolderComp&);
  54260. };
  54261. MagnifierComponent::MagnifierComponent (Component* const content_,
  54262. const bool deleteContentCompWhenNoLongerNeeded)
  54263. : content (content_),
  54264. scaleFactor (0.0),
  54265. peer (0),
  54266. deleteContent (deleteContentCompWhenNoLongerNeeded)
  54267. {
  54268. holderComp = new PeerHolderComp (this);
  54269. setScaleFactor (1.0);
  54270. }
  54271. MagnifierComponent::~MagnifierComponent()
  54272. {
  54273. delete holderComp;
  54274. if (deleteContent)
  54275. delete content;
  54276. }
  54277. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  54278. {
  54279. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  54280. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  54281. if (scaleFactor != newScaleFactor)
  54282. {
  54283. scaleFactor = newScaleFactor;
  54284. if (scaleFactor == 1.0)
  54285. {
  54286. holderComp->removeFromDesktop();
  54287. peer = 0;
  54288. addChildComponent (content);
  54289. childBoundsChanged (content);
  54290. }
  54291. else
  54292. {
  54293. holderComp->addAndMakeVisible (content);
  54294. holderComp->childBoundsChanged (content);
  54295. childBoundsChanged (holderComp);
  54296. holderComp->addToDesktop (0);
  54297. peer = holderComp->getPeer();
  54298. }
  54299. repaint();
  54300. }
  54301. }
  54302. void MagnifierComponent::paint (Graphics& g)
  54303. {
  54304. const int w = holderComp->getWidth();
  54305. const int h = holderComp->getHeight();
  54306. if (w == 0 || h == 0)
  54307. return;
  54308. const Rectangle r (g.getClipBounds());
  54309. const int srcX = (int) (r.getX() / scaleFactor);
  54310. const int srcY = (int) (r.getY() / scaleFactor);
  54311. int srcW = roundDoubleToInt (r.getRight() / scaleFactor) - srcX;
  54312. int srcH = roundDoubleToInt (r.getBottom() / scaleFactor) - srcY;
  54313. if (scaleFactor >= 1.0)
  54314. {
  54315. ++srcW;
  54316. ++srcH;
  54317. }
  54318. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  54319. temp.clear (srcX, srcY, srcW, srcH);
  54320. Graphics g2 (temp);
  54321. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  54322. holderComp->paintEntireComponent (g2);
  54323. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  54324. g.drawImage (&temp,
  54325. 0, 0, (int) (w * scaleFactor), (int) (h * scaleFactor),
  54326. 0, 0, w, h,
  54327. false);
  54328. }
  54329. void MagnifierComponent::childBoundsChanged (Component* c)
  54330. {
  54331. if (c != 0)
  54332. setSize (roundDoubleToInt (c->getWidth() * scaleFactor),
  54333. roundDoubleToInt (c->getHeight() * scaleFactor));
  54334. }
  54335. void MagnifierComponent::mouseDown (const MouseEvent& e)
  54336. {
  54337. if (peer != 0)
  54338. peer->handleMouseDown (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  54339. }
  54340. void MagnifierComponent::mouseUp (const MouseEvent& e)
  54341. {
  54342. if (peer != 0)
  54343. peer->handleMouseUp (e.mods.getRawFlags(), scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  54344. }
  54345. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  54346. {
  54347. if (peer != 0)
  54348. peer->handleMouseDrag (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  54349. }
  54350. void MagnifierComponent::mouseMove (const MouseEvent& e)
  54351. {
  54352. if (peer != 0)
  54353. peer->handleMouseMove (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  54354. }
  54355. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  54356. {
  54357. if (peer != 0)
  54358. peer->handleMouseEnter (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  54359. }
  54360. void MagnifierComponent::mouseExit (const MouseEvent& e)
  54361. {
  54362. if (peer != 0)
  54363. peer->handleMouseExit (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  54364. }
  54365. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  54366. {
  54367. if (peer != 0)
  54368. peer->handleMouseWheel (roundFloatToInt (ix * 256.0f),
  54369. roundFloatToInt (iy * 256.0f),
  54370. e.eventTime.toMilliseconds());
  54371. else
  54372. Component::mouseWheelMove (e, ix, iy);
  54373. }
  54374. int MagnifierComponent::scaleInt (const int n) const throw()
  54375. {
  54376. return roundDoubleToInt (n / scaleFactor);
  54377. }
  54378. END_JUCE_NAMESPACE
  54379. /********* End of inlined file: juce_MagnifierComponent.cpp *********/
  54380. /********* Start of inlined file: juce_MidiKeyboardComponent.cpp *********/
  54381. BEGIN_JUCE_NAMESPACE
  54382. class MidiKeyboardUpDownButton : public Button
  54383. {
  54384. public:
  54385. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  54386. const int delta_)
  54387. : Button (String::empty),
  54388. owner (owner_),
  54389. delta (delta_)
  54390. {
  54391. setOpaque (true);
  54392. }
  54393. ~MidiKeyboardUpDownButton()
  54394. {
  54395. }
  54396. void clicked()
  54397. {
  54398. int note = owner->getLowestVisibleKey();
  54399. if (delta < 0)
  54400. note = (note - 1) / 12;
  54401. else
  54402. note = note / 12 + 1;
  54403. owner->setLowestVisibleKey (note * 12);
  54404. }
  54405. void paintButton (Graphics& g,
  54406. bool isMouseOverButton,
  54407. bool isButtonDown)
  54408. {
  54409. owner->drawUpDownButton (g, getWidth(), getHeight(),
  54410. isMouseOverButton, isButtonDown,
  54411. delta > 0);
  54412. }
  54413. private:
  54414. MidiKeyboardComponent* const owner;
  54415. const int delta;
  54416. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  54417. const MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  54418. };
  54419. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  54420. const Orientation orientation_)
  54421. : state (state_),
  54422. xOffset (0),
  54423. blackNoteLength (1),
  54424. keyWidth (16.0f),
  54425. orientation (orientation_),
  54426. midiChannel (1),
  54427. midiInChannelMask (0xffff),
  54428. velocity (1.0f),
  54429. noteUnderMouse (-1),
  54430. mouseDownNote (-1),
  54431. rangeStart (0),
  54432. rangeEnd (127),
  54433. firstKey (12 * 4),
  54434. canScroll (true),
  54435. mouseDragging (false),
  54436. keyPresses (4),
  54437. keyPressNotes (16),
  54438. keyMappingOctave (6),
  54439. octaveNumForMiddleC (3)
  54440. {
  54441. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  54442. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  54443. // initialise with a default set of querty key-mappings..
  54444. const char* const keymap = "awsedftgyhujkolp;";
  54445. for (int i = String (keymap).length(); --i >= 0;)
  54446. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  54447. setOpaque (true);
  54448. setWantsKeyboardFocus (true);
  54449. state.addListener (this);
  54450. }
  54451. MidiKeyboardComponent::~MidiKeyboardComponent()
  54452. {
  54453. state.removeListener (this);
  54454. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  54455. deleteAllChildren();
  54456. }
  54457. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  54458. {
  54459. keyWidth = widthInPixels;
  54460. resized();
  54461. }
  54462. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  54463. {
  54464. if (orientation != newOrientation)
  54465. {
  54466. orientation = newOrientation;
  54467. resized();
  54468. }
  54469. }
  54470. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  54471. const int highestNote)
  54472. {
  54473. jassert (lowestNote >= 0 && lowestNote <= 127);
  54474. jassert (highestNote >= 0 && highestNote <= 127);
  54475. jassert (lowestNote <= highestNote);
  54476. if (rangeStart != lowestNote || rangeEnd != highestNote)
  54477. {
  54478. rangeStart = jlimit (0, 127, lowestNote);
  54479. rangeEnd = jlimit (0, 127, highestNote);
  54480. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  54481. resized();
  54482. }
  54483. }
  54484. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  54485. {
  54486. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  54487. if (noteNumber != firstKey)
  54488. {
  54489. firstKey = noteNumber;
  54490. sendChangeMessage (this);
  54491. resized();
  54492. }
  54493. }
  54494. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  54495. {
  54496. if (canScroll != canScroll_)
  54497. {
  54498. canScroll = canScroll_;
  54499. resized();
  54500. }
  54501. }
  54502. void MidiKeyboardComponent::colourChanged()
  54503. {
  54504. repaint();
  54505. }
  54506. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  54507. {
  54508. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  54509. if (midiChannel != midiChannelNumber)
  54510. {
  54511. resetAnyKeysInUse();
  54512. midiChannel = jlimit (1, 16, midiChannelNumber);
  54513. }
  54514. }
  54515. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  54516. {
  54517. midiInChannelMask = midiChannelMask;
  54518. triggerAsyncUpdate();
  54519. }
  54520. void MidiKeyboardComponent::setVelocity (const float velocity_)
  54521. {
  54522. velocity = jlimit (0.0f, 1.0f, velocity_);
  54523. }
  54524. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth, int& x, int& w) const
  54525. {
  54526. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  54527. static const float blackNoteWidth = 0.7f;
  54528. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  54529. 1.0f, 2 - blackNoteWidth * 0.4f,
  54530. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  54531. 4.0f, 5 - blackNoteWidth * 0.5f,
  54532. 5.0f, 6 - blackNoteWidth * 0.3f,
  54533. 6.0f };
  54534. static const float widths[] = { 1.0f, blackNoteWidth,
  54535. 1.0f, blackNoteWidth,
  54536. 1.0f, 1.0f, blackNoteWidth,
  54537. 1.0f, blackNoteWidth,
  54538. 1.0f, blackNoteWidth,
  54539. 1.0f };
  54540. const int octave = midiNoteNumber / 12;
  54541. const int note = midiNoteNumber % 12;
  54542. x = roundFloatToInt (octave * 7.0f * keyWidth + notePos [note] * keyWidth);
  54543. w = roundFloatToInt (widths [note] * keyWidth);
  54544. }
  54545. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  54546. {
  54547. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  54548. int rx, rw;
  54549. getKeyPosition (rangeStart, keyWidth, rx, rw);
  54550. x -= xOffset + rx;
  54551. }
  54552. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  54553. {
  54554. int x, y;
  54555. getKeyPos (midiNoteNumber, x, y);
  54556. return x;
  54557. }
  54558. static const uint8 whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  54559. static const uint8 blackNotes[] = { 1, 3, 6, 8, 10 };
  54560. int MidiKeyboardComponent::xyToNote (int x, int y)
  54561. {
  54562. if (! reallyContains (x, y, false))
  54563. return -1;
  54564. if (orientation != horizontalKeyboard)
  54565. {
  54566. swapVariables (x, y);
  54567. if (orientation == verticalKeyboardFacingLeft)
  54568. y = getWidth() - y;
  54569. else
  54570. x = getHeight() - x;
  54571. }
  54572. return remappedXYToNote (x + xOffset, y);
  54573. }
  54574. int MidiKeyboardComponent::remappedXYToNote (int x, int y) const
  54575. {
  54576. if (y < blackNoteLength)
  54577. {
  54578. for (int octaveStart = 12 * (rangeStart / 12); octaveStart < rangeEnd; octaveStart += 12)
  54579. {
  54580. for (int i = 0; i < 5; ++i)
  54581. {
  54582. const int note = octaveStart + blackNotes [i];
  54583. if (note >= rangeStart && note <= rangeEnd)
  54584. {
  54585. int kx, kw;
  54586. getKeyPos (note, kx, kw);
  54587. kx += xOffset;
  54588. if (x >= kx && x < kx + kw)
  54589. return note;
  54590. }
  54591. }
  54592. }
  54593. }
  54594. for (int octaveStart = 12 * (rangeStart / 12); octaveStart < rangeEnd; octaveStart += 12)
  54595. {
  54596. for (int i = 0; i < 7; ++i)
  54597. {
  54598. const int note = octaveStart + whiteNotes [i];
  54599. if (note >= rangeStart && note <= rangeEnd)
  54600. {
  54601. int kx, kw;
  54602. getKeyPos (note, kx, kw);
  54603. kx += xOffset;
  54604. if (x >= kx && x < kx + kw)
  54605. return note;
  54606. }
  54607. }
  54608. }
  54609. return -1;
  54610. }
  54611. void MidiKeyboardComponent::repaintNote (const int noteNum)
  54612. {
  54613. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  54614. {
  54615. int x, w;
  54616. getKeyPos (noteNum, x, w);
  54617. if (orientation == horizontalKeyboard)
  54618. repaint (x, 0, w, getHeight());
  54619. else if (orientation == verticalKeyboardFacingLeft)
  54620. repaint (0, x, getWidth(), w);
  54621. else if (orientation == verticalKeyboardFacingRight)
  54622. repaint (0, getHeight() - x - w, getWidth(), w);
  54623. }
  54624. }
  54625. void MidiKeyboardComponent::paint (Graphics& g)
  54626. {
  54627. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  54628. const Colour lineColour (findColour (keySeparatorLineColourId));
  54629. const Colour textColour (findColour (textLabelColourId));
  54630. int x, w, octave;
  54631. for (octave = 0; octave < 128; octave += 12)
  54632. {
  54633. for (int white = 0; white < 7; ++white)
  54634. {
  54635. const int noteNum = octave + whiteNotes [white];
  54636. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  54637. {
  54638. getKeyPos (noteNum, x, w);
  54639. if (orientation == horizontalKeyboard)
  54640. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  54641. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54642. noteUnderMouse == noteNum,
  54643. lineColour, textColour);
  54644. else if (orientation == verticalKeyboardFacingLeft)
  54645. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  54646. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54647. noteUnderMouse == noteNum,
  54648. lineColour, textColour);
  54649. else if (orientation == verticalKeyboardFacingRight)
  54650. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  54651. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54652. noteUnderMouse == noteNum,
  54653. lineColour, textColour);
  54654. }
  54655. }
  54656. }
  54657. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54658. if (orientation == verticalKeyboardFacingLeft)
  54659. {
  54660. x1 = getWidth() - 1.0f;
  54661. x2 = getWidth() - 5.0f;
  54662. }
  54663. else if (orientation == verticalKeyboardFacingRight)
  54664. x2 = 5.0f;
  54665. else
  54666. y2 = 5.0f;
  54667. GradientBrush gb (Colours::black.withAlpha (0.3f), x1, y1,
  54668. Colours::transparentBlack, x2, y2, false);
  54669. g.setBrush (&gb);
  54670. getKeyPos (rangeEnd, x, w);
  54671. x += w;
  54672. if (orientation == verticalKeyboardFacingLeft)
  54673. g.fillRect (getWidth() - 5, 0, 5, x);
  54674. else if (orientation == verticalKeyboardFacingRight)
  54675. g.fillRect (0, 0, 5, x);
  54676. else
  54677. g.fillRect (0, 0, x, 5);
  54678. g.setColour (lineColour);
  54679. if (orientation == verticalKeyboardFacingLeft)
  54680. g.fillRect (0, 0, 1, x);
  54681. else if (orientation == verticalKeyboardFacingRight)
  54682. g.fillRect (getWidth() - 1, 0, 1, x);
  54683. else
  54684. g.fillRect (0, getHeight() - 1, x, 1);
  54685. const Colour blackNoteColour (findColour (blackNoteColourId));
  54686. for (octave = 0; octave < 128; octave += 12)
  54687. {
  54688. for (int black = 0; black < 5; ++black)
  54689. {
  54690. const int noteNum = octave + blackNotes [black];
  54691. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  54692. {
  54693. getKeyPos (noteNum, x, w);
  54694. if (orientation == horizontalKeyboard)
  54695. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  54696. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54697. noteUnderMouse == noteNum,
  54698. blackNoteColour);
  54699. else if (orientation == verticalKeyboardFacingLeft)
  54700. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  54701. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54702. noteUnderMouse == noteNum,
  54703. blackNoteColour);
  54704. else if (orientation == verticalKeyboardFacingRight)
  54705. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  54706. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54707. noteUnderMouse == noteNum,
  54708. blackNoteColour);
  54709. }
  54710. }
  54711. }
  54712. }
  54713. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  54714. Graphics& g, int x, int y, int w, int h,
  54715. bool isDown, bool isOver,
  54716. const Colour& lineColour,
  54717. const Colour& textColour)
  54718. {
  54719. Colour c (Colours::transparentWhite);
  54720. if (isDown)
  54721. c = findColour (keyDownOverlayColourId);
  54722. if (isOver)
  54723. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  54724. g.setColour (c);
  54725. g.fillRect (x, y, w, h);
  54726. const String text (getWhiteNoteText (midiNoteNumber));
  54727. if (! text.isEmpty())
  54728. {
  54729. g.setColour (textColour);
  54730. Font f (jmin (12.0f, keyWidth * 0.9f));
  54731. f.setHorizontalScale (0.8f);
  54732. g.setFont (f);
  54733. Justification justification (Justification::centredBottom);
  54734. if (orientation == verticalKeyboardFacingLeft)
  54735. justification = Justification::centredLeft;
  54736. else if (orientation == verticalKeyboardFacingRight)
  54737. justification = Justification::centredRight;
  54738. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  54739. }
  54740. g.setColour (lineColour);
  54741. if (orientation == horizontalKeyboard)
  54742. g.fillRect (x, y, 1, h);
  54743. else if (orientation == verticalKeyboardFacingLeft)
  54744. g.fillRect (x, y, w, 1);
  54745. else if (orientation == verticalKeyboardFacingRight)
  54746. g.fillRect (x, y + h - 1, w, 1);
  54747. if (midiNoteNumber == rangeEnd)
  54748. {
  54749. if (orientation == horizontalKeyboard)
  54750. g.fillRect (x + w, y, 1, h);
  54751. else if (orientation == verticalKeyboardFacingLeft)
  54752. g.fillRect (x, y + h, w, 1);
  54753. else if (orientation == verticalKeyboardFacingRight)
  54754. g.fillRect (x, y - 1, w, 1);
  54755. }
  54756. }
  54757. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  54758. Graphics& g, int x, int y, int w, int h,
  54759. bool isDown, bool isOver,
  54760. const Colour& noteFillColour)
  54761. {
  54762. Colour c (noteFillColour);
  54763. if (isDown)
  54764. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  54765. if (isOver)
  54766. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  54767. g.setColour (c);
  54768. g.fillRect (x, y, w, h);
  54769. if (isDown)
  54770. {
  54771. g.setColour (noteFillColour);
  54772. g.drawRect (x, y, w, h);
  54773. }
  54774. else
  54775. {
  54776. const int xIndent = jmax (1, jmin (w, h) / 8);
  54777. g.setColour (c.brighter());
  54778. if (orientation == horizontalKeyboard)
  54779. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  54780. else if (orientation == verticalKeyboardFacingLeft)
  54781. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  54782. else if (orientation == verticalKeyboardFacingRight)
  54783. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  54784. }
  54785. }
  54786. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_) throw()
  54787. {
  54788. octaveNumForMiddleC = octaveNumForMiddleC_;
  54789. repaint();
  54790. }
  54791. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  54792. {
  54793. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  54794. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  54795. return String::empty;
  54796. }
  54797. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  54798. const bool isMouseOver,
  54799. const bool isButtonDown,
  54800. const bool movesOctavesUp)
  54801. {
  54802. g.fillAll (findColour (upDownButtonBackgroundColourId));
  54803. float angle;
  54804. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  54805. angle = movesOctavesUp ? 0.0f : 0.5f;
  54806. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  54807. angle = movesOctavesUp ? 0.25f : 0.75f;
  54808. else
  54809. angle = movesOctavesUp ? 0.75f : 0.25f;
  54810. Path path;
  54811. path.lineTo (0.0f, 1.0f);
  54812. path.lineTo (1.0f, 0.5f);
  54813. path.closeSubPath();
  54814. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  54815. g.setColour (findColour (upDownButtonArrowColourId)
  54816. .withAlpha (isButtonDown ? 1.0f : (isMouseOver ? 0.6f : 0.4f)));
  54817. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  54818. w - 2.0f,
  54819. h - 2.0f,
  54820. true));
  54821. }
  54822. void MidiKeyboardComponent::resized()
  54823. {
  54824. int w = getWidth();
  54825. int h = getHeight();
  54826. if (w > 0 && h > 0)
  54827. {
  54828. if (orientation != horizontalKeyboard)
  54829. swapVariables (w, h);
  54830. blackNoteLength = roundFloatToInt (h * 0.7f);
  54831. int kx2, kw2;
  54832. getKeyPos (rangeEnd, kx2, kw2);
  54833. kx2 += kw2;
  54834. if (firstKey != rangeStart)
  54835. {
  54836. int kx1, kw1;
  54837. getKeyPos (rangeStart, kx1, kw1);
  54838. if (kx2 - kx1 <= w)
  54839. {
  54840. firstKey = rangeStart;
  54841. sendChangeMessage (this);
  54842. repaint();
  54843. }
  54844. }
  54845. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  54846. scrollDown->setVisible (showScrollButtons);
  54847. scrollUp->setVisible (showScrollButtons);
  54848. xOffset = 0;
  54849. if (showScrollButtons)
  54850. {
  54851. const int scrollButtonW = jmin (12, w / 2);
  54852. if (orientation == horizontalKeyboard)
  54853. {
  54854. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  54855. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  54856. }
  54857. else if (orientation == verticalKeyboardFacingLeft)
  54858. {
  54859. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  54860. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  54861. }
  54862. else if (orientation == verticalKeyboardFacingRight)
  54863. {
  54864. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  54865. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  54866. }
  54867. int endOfLastKey, kw;
  54868. getKeyPos (rangeEnd, endOfLastKey, kw);
  54869. endOfLastKey += kw;
  54870. const int spaceAvailable = w - scrollButtonW * 2;
  54871. const int lastStartKey = remappedXYToNote (endOfLastKey - spaceAvailable, 0) + 1;
  54872. if (lastStartKey >= 0 && firstKey > lastStartKey)
  54873. {
  54874. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  54875. sendChangeMessage (this);
  54876. }
  54877. int newOffset = 0;
  54878. getKeyPos (firstKey, newOffset, kw);
  54879. xOffset = newOffset - scrollButtonW;
  54880. }
  54881. else
  54882. {
  54883. firstKey = rangeStart;
  54884. }
  54885. timerCallback();
  54886. repaint();
  54887. }
  54888. }
  54889. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  54890. {
  54891. triggerAsyncUpdate();
  54892. }
  54893. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  54894. {
  54895. triggerAsyncUpdate();
  54896. }
  54897. void MidiKeyboardComponent::handleAsyncUpdate()
  54898. {
  54899. for (int i = rangeStart; i <= rangeEnd; ++i)
  54900. {
  54901. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  54902. {
  54903. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  54904. repaintNote (i);
  54905. }
  54906. }
  54907. }
  54908. void MidiKeyboardComponent::resetAnyKeysInUse()
  54909. {
  54910. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  54911. {
  54912. state.allNotesOff (midiChannel);
  54913. keysPressed.clear();
  54914. mouseDownNote = -1;
  54915. }
  54916. }
  54917. void MidiKeyboardComponent::updateNoteUnderMouse (int x, int y)
  54918. {
  54919. const int newNote = (mouseDragging || isMouseOver())
  54920. ? xyToNote (x, y) : -1;
  54921. if (noteUnderMouse != newNote)
  54922. {
  54923. if (mouseDownNote >= 0)
  54924. {
  54925. state.noteOff (midiChannel, mouseDownNote);
  54926. mouseDownNote = -1;
  54927. }
  54928. if (mouseDragging && newNote >= 0)
  54929. {
  54930. state.noteOn (midiChannel, newNote, velocity);
  54931. mouseDownNote = newNote;
  54932. }
  54933. repaintNote (noteUnderMouse);
  54934. noteUnderMouse = newNote;
  54935. repaintNote (noteUnderMouse);
  54936. }
  54937. else if (mouseDownNote >= 0 && ! mouseDragging)
  54938. {
  54939. state.noteOff (midiChannel, mouseDownNote);
  54940. mouseDownNote = -1;
  54941. }
  54942. }
  54943. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  54944. {
  54945. updateNoteUnderMouse (e.x, e.y);
  54946. stopTimer();
  54947. }
  54948. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  54949. {
  54950. const int newNote = xyToNote (e.x, e.y);
  54951. if (newNote >= 0)
  54952. mouseDraggedToKey (newNote, e);
  54953. updateNoteUnderMouse (e.x, e.y);
  54954. }
  54955. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  54956. {
  54957. return true;
  54958. }
  54959. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  54960. {
  54961. }
  54962. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  54963. {
  54964. const int newNote = xyToNote (e.x, e.y);
  54965. mouseDragging = false;
  54966. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  54967. {
  54968. repaintNote (noteUnderMouse);
  54969. noteUnderMouse = -1;
  54970. mouseDragging = true;
  54971. updateNoteUnderMouse (e.x, e.y);
  54972. startTimer (500);
  54973. }
  54974. }
  54975. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  54976. {
  54977. mouseDragging = false;
  54978. updateNoteUnderMouse (e.x, e.y);
  54979. stopTimer();
  54980. }
  54981. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  54982. {
  54983. updateNoteUnderMouse (e.x, e.y);
  54984. }
  54985. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  54986. {
  54987. updateNoteUnderMouse (e.x, e.y);
  54988. }
  54989. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  54990. {
  54991. setLowestVisibleKey (getLowestVisibleKey() + roundFloatToInt ((ix != 0 ? ix : iy) * 5.0f));
  54992. }
  54993. void MidiKeyboardComponent::timerCallback()
  54994. {
  54995. int mx, my;
  54996. getMouseXYRelative (mx, my);
  54997. updateNoteUnderMouse (mx, my);
  54998. }
  54999. void MidiKeyboardComponent::clearKeyMappings()
  55000. {
  55001. resetAnyKeysInUse();
  55002. keyPressNotes.clear();
  55003. keyPresses.clear();
  55004. }
  55005. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  55006. const int midiNoteOffsetFromC)
  55007. {
  55008. removeKeyPressForNote (midiNoteOffsetFromC);
  55009. keyPressNotes.add (midiNoteOffsetFromC);
  55010. keyPresses.add (key);
  55011. }
  55012. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  55013. {
  55014. for (int i = keyPressNotes.size(); --i >= 0;)
  55015. {
  55016. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  55017. {
  55018. keyPressNotes.remove (i);
  55019. keyPresses.remove (i);
  55020. }
  55021. }
  55022. }
  55023. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  55024. {
  55025. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  55026. keyMappingOctave = newOctaveNumber;
  55027. }
  55028. bool MidiKeyboardComponent::keyStateChanged()
  55029. {
  55030. bool keyPressUsed = false;
  55031. for (int i = keyPresses.size(); --i >= 0;)
  55032. {
  55033. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  55034. if (keyPresses.getReference(i).isCurrentlyDown())
  55035. {
  55036. if (! keysPressed [note])
  55037. {
  55038. keysPressed.setBit (note);
  55039. state.noteOn (midiChannel, note, velocity);
  55040. keyPressUsed = true;
  55041. }
  55042. }
  55043. else
  55044. {
  55045. if (keysPressed [note])
  55046. {
  55047. keysPressed.clearBit (note);
  55048. state.noteOff (midiChannel, note);
  55049. keyPressUsed = true;
  55050. }
  55051. }
  55052. }
  55053. return keyPressUsed;
  55054. }
  55055. void MidiKeyboardComponent::focusLost (FocusChangeType)
  55056. {
  55057. resetAnyKeysInUse();
  55058. }
  55059. END_JUCE_NAMESPACE
  55060. /********* End of inlined file: juce_MidiKeyboardComponent.cpp *********/
  55061. /********* Start of inlined file: juce_OpenGLComponent.cpp *********/
  55062. #if JUCE_OPENGL
  55063. BEGIN_JUCE_NAMESPACE
  55064. extern void juce_glViewport (const int w, const int h);
  55065. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  55066. const int alphaBits_,
  55067. const int depthBufferBits_,
  55068. const int stencilBufferBits_) throw()
  55069. : redBits (bitsPerRGBComponent),
  55070. greenBits (bitsPerRGBComponent),
  55071. blueBits (bitsPerRGBComponent),
  55072. alphaBits (alphaBits_),
  55073. depthBufferBits (depthBufferBits_),
  55074. stencilBufferBits (stencilBufferBits_),
  55075. accumulationBufferRedBits (0),
  55076. accumulationBufferGreenBits (0),
  55077. accumulationBufferBlueBits (0),
  55078. accumulationBufferAlphaBits (0),
  55079. fullSceneAntiAliasingNumSamples (0)
  55080. {
  55081. }
  55082. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const throw()
  55083. {
  55084. return memcmp (this, &other, sizeof (other)) == 0;
  55085. }
  55086. static VoidArray knownContexts;
  55087. OpenGLContext::OpenGLContext() throw()
  55088. {
  55089. knownContexts.add (this);
  55090. }
  55091. OpenGLContext::~OpenGLContext()
  55092. {
  55093. knownContexts.removeValue (this);
  55094. }
  55095. OpenGLContext* OpenGLContext::getCurrentContext()
  55096. {
  55097. for (int i = knownContexts.size(); --i >= 0;)
  55098. {
  55099. OpenGLContext* const oglc = (OpenGLContext*) knownContexts.getUnchecked(i);
  55100. if (oglc->isActive())
  55101. return oglc;
  55102. }
  55103. return 0;
  55104. }
  55105. class OpenGLComponentWatcher : public ComponentMovementWatcher
  55106. {
  55107. public:
  55108. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  55109. : ComponentMovementWatcher (owner_),
  55110. owner (owner_),
  55111. wasShowing (false)
  55112. {
  55113. }
  55114. ~OpenGLComponentWatcher() {}
  55115. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  55116. {
  55117. owner->updateContextPosition();
  55118. }
  55119. void componentPeerChanged()
  55120. {
  55121. const ScopedLock sl (owner->getContextLock());
  55122. owner->deleteContext();
  55123. }
  55124. void componentVisibilityChanged (Component&)
  55125. {
  55126. const bool isShowingNow = owner->isShowing();
  55127. if (wasShowing != isShowingNow)
  55128. {
  55129. wasShowing = isShowingNow;
  55130. owner->updateContextPosition();
  55131. }
  55132. }
  55133. juce_UseDebuggingNewOperator
  55134. private:
  55135. OpenGLComponent* const owner;
  55136. bool wasShowing;
  55137. };
  55138. OpenGLComponent::OpenGLComponent()
  55139. : context (0),
  55140. contextToShareListsWith (0),
  55141. needToUpdateViewport (true)
  55142. {
  55143. setOpaque (true);
  55144. componentWatcher = new OpenGLComponentWatcher (this);
  55145. }
  55146. OpenGLComponent::~OpenGLComponent()
  55147. {
  55148. deleteContext();
  55149. delete componentWatcher;
  55150. }
  55151. void OpenGLComponent::deleteContext()
  55152. {
  55153. const ScopedLock sl (contextLock);
  55154. deleteAndZero (context);
  55155. }
  55156. void OpenGLComponent::updateContextPosition()
  55157. {
  55158. needToUpdateViewport = true;
  55159. if (getWidth() > 0 && getHeight() > 0)
  55160. {
  55161. Component* const topComp = getTopLevelComponent();
  55162. if (topComp->getPeer() != 0)
  55163. {
  55164. const ScopedLock sl (contextLock);
  55165. if (context != 0)
  55166. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  55167. getScreenY() - topComp->getScreenY(),
  55168. getWidth(),
  55169. getHeight(),
  55170. topComp->getHeight());
  55171. }
  55172. }
  55173. }
  55174. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  55175. {
  55176. OpenGLPixelFormat pf;
  55177. const ScopedLock sl (contextLock);
  55178. if (context != 0)
  55179. pf = context->getPixelFormat();
  55180. return pf;
  55181. }
  55182. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  55183. {
  55184. if (! (preferredPixelFormat == formatToUse))
  55185. {
  55186. const ScopedLock sl (contextLock);
  55187. deleteContext();
  55188. preferredPixelFormat = formatToUse;
  55189. }
  55190. }
  55191. void OpenGLComponent::shareWith (OpenGLContext* context)
  55192. {
  55193. if (contextToShareListsWith != context)
  55194. {
  55195. const ScopedLock sl (contextLock);
  55196. deleteContext();
  55197. contextToShareListsWith = context;
  55198. }
  55199. }
  55200. bool OpenGLComponent::makeCurrentContextActive()
  55201. {
  55202. if (context == 0)
  55203. {
  55204. const ScopedLock sl (contextLock);
  55205. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  55206. {
  55207. context = OpenGLContext::createContextForWindow (this,
  55208. preferredPixelFormat,
  55209. contextToShareListsWith);
  55210. if (context != 0)
  55211. {
  55212. updateContextPosition();
  55213. if (context->makeActive())
  55214. newOpenGLContextCreated();
  55215. }
  55216. }
  55217. }
  55218. return context != 0 && context->makeActive();
  55219. }
  55220. void OpenGLComponent::makeCurrentContextInactive()
  55221. {
  55222. if (context != 0)
  55223. context->makeInactive();
  55224. }
  55225. bool OpenGLComponent::isActiveContext() const throw()
  55226. {
  55227. return context != 0 && context->isActive();
  55228. }
  55229. void OpenGLComponent::swapBuffers()
  55230. {
  55231. if (context != 0)
  55232. context->swapBuffers();
  55233. }
  55234. void OpenGLComponent::paint (Graphics&)
  55235. {
  55236. if (renderAndSwapBuffers())
  55237. {
  55238. ComponentPeer* const peer = getPeer();
  55239. if (peer != 0)
  55240. {
  55241. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  55242. getScreenY() - peer->getScreenY(),
  55243. getWidth(), getHeight());
  55244. }
  55245. }
  55246. }
  55247. bool OpenGLComponent::renderAndSwapBuffers()
  55248. {
  55249. const ScopedLock sl (contextLock);
  55250. if (! makeCurrentContextActive())
  55251. return false;
  55252. if (needToUpdateViewport)
  55253. {
  55254. needToUpdateViewport = false;
  55255. juce_glViewport (getWidth(), getHeight());
  55256. }
  55257. renderOpenGL();
  55258. swapBuffers();
  55259. return true;
  55260. }
  55261. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  55262. {
  55263. Component::internalRepaint (x, y, w, h);
  55264. if (context != 0)
  55265. context->repaint();
  55266. }
  55267. END_JUCE_NAMESPACE
  55268. #endif
  55269. /********* End of inlined file: juce_OpenGLComponent.cpp *********/
  55270. /********* Start of inlined file: juce_PreferencesPanel.cpp *********/
  55271. BEGIN_JUCE_NAMESPACE
  55272. PreferencesPanel::PreferencesPanel()
  55273. : currentPage (0),
  55274. buttonSize (70)
  55275. {
  55276. }
  55277. PreferencesPanel::~PreferencesPanel()
  55278. {
  55279. deleteAllChildren();
  55280. }
  55281. void PreferencesPanel::addSettingsPage (const String& title,
  55282. const Drawable* icon,
  55283. const Drawable* overIcon,
  55284. const Drawable* downIcon)
  55285. {
  55286. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  55287. button->setImages (icon, overIcon, downIcon);
  55288. button->setRadioGroupId (1);
  55289. button->addButtonListener (this);
  55290. button->setClickingTogglesState (true);
  55291. button->setWantsKeyboardFocus (false);
  55292. addAndMakeVisible (button);
  55293. resized();
  55294. }
  55295. void PreferencesPanel::addSettingsPage (const String& title,
  55296. const char* imageData,
  55297. const int imageDataSize)
  55298. {
  55299. DrawableImage icon, iconOver, iconDown;
  55300. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  55301. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  55302. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  55303. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  55304. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  55305. addSettingsPage (title, &icon, &iconOver, &iconDown);
  55306. if (currentPage == 0)
  55307. setCurrentPage (title);
  55308. }
  55309. class PrefsDialogWindow : public DialogWindow
  55310. {
  55311. public:
  55312. PrefsDialogWindow (const String& dialogtitle,
  55313. const Colour& backgroundColour)
  55314. : DialogWindow (dialogtitle, backgroundColour, true)
  55315. {
  55316. }
  55317. ~PrefsDialogWindow()
  55318. {
  55319. }
  55320. void closeButtonPressed()
  55321. {
  55322. exitModalState (0);
  55323. }
  55324. private:
  55325. PrefsDialogWindow (const PrefsDialogWindow&);
  55326. const PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  55327. };
  55328. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  55329. int dialogWidth,
  55330. int dialogHeight,
  55331. const Colour& backgroundColour)
  55332. {
  55333. setSize (dialogWidth, dialogHeight);
  55334. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  55335. dw.setContentComponent (this, true, true);
  55336. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  55337. dw.runModalLoop();
  55338. }
  55339. void PreferencesPanel::resized()
  55340. {
  55341. int x = 0;
  55342. for (int i = 0; i < getNumChildComponents(); ++i)
  55343. {
  55344. Component* c = getChildComponent (i);
  55345. if (dynamic_cast <DrawableButton*> (c) == 0)
  55346. {
  55347. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  55348. }
  55349. else
  55350. {
  55351. c->setBounds (x, 0, buttonSize, buttonSize);
  55352. x += buttonSize;
  55353. }
  55354. }
  55355. }
  55356. void PreferencesPanel::paint (Graphics& g)
  55357. {
  55358. g.setColour (Colours::grey);
  55359. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  55360. }
  55361. void PreferencesPanel::setCurrentPage (const String& pageName)
  55362. {
  55363. if (currentPageName != pageName)
  55364. {
  55365. currentPageName = pageName;
  55366. deleteAndZero (currentPage);
  55367. currentPage = createComponentForPage (pageName);
  55368. if (currentPage != 0)
  55369. {
  55370. addAndMakeVisible (currentPage);
  55371. currentPage->toBack();
  55372. resized();
  55373. }
  55374. for (int i = 0; i < getNumChildComponents(); ++i)
  55375. {
  55376. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  55377. if (db != 0 && db->getName() == pageName)
  55378. {
  55379. db->setToggleState (true, false);
  55380. break;
  55381. }
  55382. }
  55383. }
  55384. }
  55385. void PreferencesPanel::buttonClicked (Button*)
  55386. {
  55387. for (int i = 0; i < getNumChildComponents(); ++i)
  55388. {
  55389. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  55390. if (db != 0 && db->getToggleState())
  55391. {
  55392. setCurrentPage (db->getName());
  55393. break;
  55394. }
  55395. }
  55396. }
  55397. END_JUCE_NAMESPACE
  55398. /********* End of inlined file: juce_PreferencesPanel.cpp *********/
  55399. /********* Start of inlined file: juce_QuickTimeMovieComponent.cpp *********/
  55400. #if JUCE_QUICKTIME
  55401. #ifdef _MSC_VER
  55402. #pragma warning (disable: 4514)
  55403. #endif
  55404. #ifdef _WIN32
  55405. #include <windows.h>
  55406. #ifdef _MSC_VER
  55407. #pragma warning (push)
  55408. #pragma warning (disable : 4100)
  55409. #endif
  55410. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  55411. add its header directory to your include path.
  55412. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  55413. flag in juce_Config.h
  55414. */
  55415. #include <Movies.h>
  55416. #include <QTML.h>
  55417. #include <QuickTimeComponents.h>
  55418. #include <MediaHandlers.h>
  55419. #include <ImageCodec.h>
  55420. #ifdef _MSC_VER
  55421. #pragma warning (pop)
  55422. #endif
  55423. // If you've got QuickTime 7 installed, then these COM objects should be found in
  55424. // the "\Program Files\Quicktime" directory. You'll need to add this directory to
  55425. // your include search path to make these import statements work.
  55426. #import <QTOLibrary.dll>
  55427. #import <QTOControl.dll>
  55428. using namespace QTOLibrary;
  55429. using namespace QTOControlLib;
  55430. #else
  55431. #include <Carbon/Carbon.h>
  55432. #include <QuickTime/Movies.h>
  55433. #include <QuickTime/QuickTimeComponents.h>
  55434. #include <QuickTime/MediaHandlers.h>
  55435. #endif
  55436. BEGIN_JUCE_NAMESPACE
  55437. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  55438. static bool hasLoadedQT = false;
  55439. static bool isQTAvailable = false;
  55440. struct QTMovieCompInternal
  55441. {
  55442. QTMovieCompInternal()
  55443. : dataHandle (0)
  55444. {
  55445. #if JUCE_MAC
  55446. movie = 0;
  55447. controller = 0;
  55448. #endif
  55449. }
  55450. ~QTMovieCompInternal()
  55451. {
  55452. clearHandle();
  55453. }
  55454. #if JUCE_MAC
  55455. Movie movie;
  55456. MovieController controller;
  55457. #else
  55458. IQTControlPtr qtControlInternal;
  55459. IQTMoviePtr qtMovieInternal;
  55460. #endif
  55461. Handle dataHandle;
  55462. void clearHandle()
  55463. {
  55464. if (dataHandle != 0)
  55465. {
  55466. DisposeHandle (dataHandle);
  55467. dataHandle = 0;
  55468. }
  55469. }
  55470. };
  55471. #if JUCE_WIN32
  55472. #define qtControl (((QTMovieCompInternal*) internal)->qtControlInternal)
  55473. #define qtMovie (((QTMovieCompInternal*) internal)->qtMovieInternal)
  55474. QuickTimeMovieComponent::QuickTimeMovieComponent()
  55475. : movieLoaded (false),
  55476. controllerVisible (true)
  55477. {
  55478. internal = new QTMovieCompInternal();
  55479. setMouseEventsAllowed (false);
  55480. }
  55481. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  55482. {
  55483. closeMovie();
  55484. qtControl = 0;
  55485. deleteControl();
  55486. delete internal;
  55487. internal = 0;
  55488. }
  55489. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  55490. {
  55491. if (! hasLoadedQT)
  55492. {
  55493. hasLoadedQT = true;
  55494. isQTAvailable = (InitializeQTML (0) == noErr)
  55495. && (EnterMovies() == noErr);
  55496. }
  55497. return isQTAvailable;
  55498. }
  55499. void QuickTimeMovieComponent::createControlIfNeeded()
  55500. {
  55501. if (isShowing() && ! isControlCreated())
  55502. {
  55503. const IID qtIID = __uuidof (QTControl);
  55504. if (createControl (&qtIID))
  55505. {
  55506. const IID qtInterfaceIID = __uuidof (IQTControl);
  55507. qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  55508. if (qtControl != 0)
  55509. {
  55510. qtControl->Release(); // it has one ref too many at this point
  55511. qtControl->QuickTimeInitialize();
  55512. qtControl->PutSizing (qtMovieFitsControl);
  55513. if (movieFile != File::nonexistent)
  55514. loadMovie (movieFile, controllerVisible);
  55515. }
  55516. }
  55517. }
  55518. }
  55519. bool QuickTimeMovieComponent::isControlCreated() const
  55520. {
  55521. return isControlOpen();
  55522. }
  55523. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  55524. const bool isControllerVisible)
  55525. {
  55526. movieFile = File::nonexistent;
  55527. movieLoaded = false;
  55528. qtMovie = 0;
  55529. controllerVisible = isControllerVisible;
  55530. createControlIfNeeded();
  55531. if (isControlCreated())
  55532. {
  55533. if (qtControl != 0)
  55534. {
  55535. qtControl->Put_MovieHandle (0);
  55536. ((QTMovieCompInternal*) internal)->clearHandle();
  55537. Movie movie;
  55538. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, ((QTMovieCompInternal*) internal)->dataHandle))
  55539. {
  55540. qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  55541. qtMovie = qtControl->GetMovie();
  55542. if (qtMovie != 0)
  55543. qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  55544. : qtMovieControllerTypeNone);
  55545. }
  55546. if (movie == 0)
  55547. ((QTMovieCompInternal*) internal)->clearHandle();
  55548. }
  55549. movieLoaded = (qtMovie != 0);
  55550. }
  55551. else
  55552. {
  55553. // You're trying to open a movie when the control hasn't yet been created, probably because
  55554. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  55555. jassertfalse
  55556. }
  55557. delete movieStream;
  55558. return movieLoaded;
  55559. }
  55560. void QuickTimeMovieComponent::closeMovie()
  55561. {
  55562. stop();
  55563. movieFile = File::nonexistent;
  55564. movieLoaded = false;
  55565. qtMovie = 0;
  55566. if (qtControl != 0)
  55567. qtControl->Put_MovieHandle (0);
  55568. ((QTMovieCompInternal*) internal)->clearHandle();
  55569. }
  55570. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  55571. {
  55572. return movieFile;
  55573. }
  55574. bool QuickTimeMovieComponent::isMovieOpen() const
  55575. {
  55576. return movieLoaded;
  55577. }
  55578. double QuickTimeMovieComponent::getMovieDuration() const
  55579. {
  55580. if (qtMovie != 0)
  55581. return qtMovie->GetDuration() / (double) qtMovie->GetTimeScale();
  55582. return 0.0;
  55583. }
  55584. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  55585. {
  55586. if (qtMovie != 0)
  55587. {
  55588. struct QTRECT r = qtMovie->GetNaturalRect();
  55589. width = r.right - r.left;
  55590. height = r.bottom - r.top;
  55591. }
  55592. else
  55593. {
  55594. width = height = 0;
  55595. }
  55596. }
  55597. void QuickTimeMovieComponent::play()
  55598. {
  55599. if (qtMovie != 0)
  55600. qtMovie->Play();
  55601. }
  55602. void QuickTimeMovieComponent::stop()
  55603. {
  55604. if (qtMovie != 0)
  55605. qtMovie->Stop();
  55606. }
  55607. bool QuickTimeMovieComponent::isPlaying() const
  55608. {
  55609. return qtMovie != 0 && qtMovie->GetRate() != 0.0f;
  55610. }
  55611. void QuickTimeMovieComponent::setPosition (const double seconds)
  55612. {
  55613. if (qtMovie != 0)
  55614. qtMovie->PutTime ((long) (seconds * qtMovie->GetTimeScale()));
  55615. }
  55616. double QuickTimeMovieComponent::getPosition() const
  55617. {
  55618. if (qtMovie != 0)
  55619. return qtMovie->GetTime() / (double) qtMovie->GetTimeScale();
  55620. return 0.0;
  55621. }
  55622. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  55623. {
  55624. if (qtMovie != 0)
  55625. qtMovie->PutRate (newSpeed);
  55626. }
  55627. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  55628. {
  55629. if (qtMovie != 0)
  55630. {
  55631. qtMovie->PutAudioVolume (newVolume);
  55632. qtMovie->PutAudioMute (newVolume <= 0);
  55633. }
  55634. }
  55635. float QuickTimeMovieComponent::getMovieVolume() const
  55636. {
  55637. if (qtMovie != 0)
  55638. return qtMovie->GetAudioVolume();
  55639. return 0.0f;
  55640. }
  55641. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  55642. {
  55643. if (qtMovie != 0)
  55644. qtMovie->PutLoop (shouldLoop);
  55645. }
  55646. bool QuickTimeMovieComponent::isLooping() const
  55647. {
  55648. return qtMovie != 0 && qtMovie->GetLoop();
  55649. }
  55650. bool QuickTimeMovieComponent::isControllerVisible() const
  55651. {
  55652. return controllerVisible;
  55653. }
  55654. void QuickTimeMovieComponent::parentHierarchyChanged()
  55655. {
  55656. createControlIfNeeded();
  55657. QTWinBaseClass::parentHierarchyChanged();
  55658. }
  55659. void QuickTimeMovieComponent::visibilityChanged()
  55660. {
  55661. createControlIfNeeded();
  55662. QTWinBaseClass::visibilityChanged();
  55663. }
  55664. void QuickTimeMovieComponent::paint (Graphics& g)
  55665. {
  55666. if (! isControlCreated())
  55667. g.fillAll (Colours::black);
  55668. }
  55669. #endif
  55670. #if JUCE_MAC
  55671. static VoidArray activeQTWindows (2);
  55672. struct MacClickEventData
  55673. {
  55674. ::Point where;
  55675. long when;
  55676. long modifiers;
  55677. };
  55678. void OfferMouseClickToQuickTime (WindowRef window,
  55679. ::Point where, long when, long modifiers,
  55680. Component* topLevelComp)
  55681. {
  55682. if (hasLoadedQT)
  55683. {
  55684. for (int i = activeQTWindows.size(); --i >= 0;)
  55685. {
  55686. QuickTimeMovieComponent* const qtw = (QuickTimeMovieComponent*) activeQTWindows[i];
  55687. if (qtw->isVisible() && topLevelComp->isParentOf (qtw))
  55688. {
  55689. MacClickEventData data;
  55690. data.where = where;
  55691. data.when = when;
  55692. data.modifiers = modifiers;
  55693. qtw->handleMCEvent (&data);
  55694. }
  55695. }
  55696. }
  55697. }
  55698. QuickTimeMovieComponent::QuickTimeMovieComponent()
  55699. : internal (new QTMovieCompInternal()),
  55700. associatedWindow (0),
  55701. controllerVisible (false),
  55702. controllerAssignedToWindow (false),
  55703. reentrant (false)
  55704. {
  55705. if (! hasLoadedQT)
  55706. {
  55707. hasLoadedQT = true;
  55708. isQTAvailable = EnterMovies() == noErr;
  55709. }
  55710. setOpaque (true);
  55711. setVisible (true);
  55712. activeQTWindows.add (this);
  55713. }
  55714. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  55715. {
  55716. closeMovie();
  55717. activeQTWindows.removeValue ((void*) this);
  55718. QTMovieCompInternal* const i = (QTMovieCompInternal*) internal;
  55719. delete i;
  55720. if (activeQTWindows.size() == 0 && isQTAvailable)
  55721. {
  55722. isQTAvailable = false;
  55723. hasLoadedQT = false;
  55724. ExitMovies();
  55725. }
  55726. }
  55727. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  55728. {
  55729. if (! hasLoadedQT)
  55730. {
  55731. hasLoadedQT = true;
  55732. isQTAvailable = EnterMovies() == noErr;
  55733. }
  55734. return isQTAvailable;
  55735. }
  55736. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  55737. const bool controllerVisible_)
  55738. {
  55739. if (! isQTAvailable)
  55740. return false;
  55741. closeMovie();
  55742. movieFile = File::nonexistent;
  55743. if (getPeer() == 0)
  55744. {
  55745. // To open a movie, this component must be visible inside a functioning window, so that
  55746. // the QT control can be assigned to the window.
  55747. jassertfalse
  55748. return false;
  55749. }
  55750. controllerVisible = controllerVisible_;
  55751. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55752. GrafPtr savedPort;
  55753. GetPort (&savedPort);
  55754. bool result = false;
  55755. if (juce_OpenQuickTimeMovieFromStream (movieStream, qmci->movie, qmci->dataHandle))
  55756. {
  55757. qmci->controller = 0;
  55758. void* window = getWindowHandle();
  55759. if (window != associatedWindow && window != 0)
  55760. associatedWindow = window;
  55761. assignMovieToWindow();
  55762. SetMovieActive (qmci->movie, true);
  55763. SetMovieProgressProc (qmci->movie, (MovieProgressUPP) -1, 0);
  55764. startTimer (1000 / 50); // this needs to be quite a high frequency for smooth playback
  55765. result = true;
  55766. repaint();
  55767. }
  55768. MacSetPort (savedPort);
  55769. return result;
  55770. }
  55771. void QuickTimeMovieComponent::closeMovie()
  55772. {
  55773. stop();
  55774. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55775. if (qmci->controller != 0)
  55776. {
  55777. DisposeMovieController (qmci->controller);
  55778. qmci->controller = 0;
  55779. }
  55780. if (qmci->movie != 0)
  55781. {
  55782. DisposeMovie (qmci->movie);
  55783. qmci->movie = 0;
  55784. }
  55785. qmci->clearHandle();
  55786. stopTimer();
  55787. movieFile = File::nonexistent;
  55788. }
  55789. bool QuickTimeMovieComponent::isMovieOpen() const
  55790. {
  55791. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55792. return qmci->movie != 0 && qmci->controller != 0;
  55793. }
  55794. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  55795. {
  55796. return movieFile;
  55797. }
  55798. static GrafPtr getPortForWindow (void* window)
  55799. {
  55800. if (window == 0)
  55801. return 0;
  55802. return (GrafPtr) GetWindowPort ((WindowRef) window);
  55803. }
  55804. void QuickTimeMovieComponent::assignMovieToWindow()
  55805. {
  55806. if (reentrant)
  55807. return;
  55808. reentrant = true;
  55809. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55810. if (qmci->controller != 0)
  55811. {
  55812. DisposeMovieController (qmci->controller);
  55813. qmci->controller = 0;
  55814. }
  55815. controllerAssignedToWindow = false;
  55816. void* window = getWindowHandle();
  55817. GrafPtr port = getPortForWindow (window);
  55818. if (port != 0)
  55819. {
  55820. GrafPtr savedPort;
  55821. GetPort (&savedPort);
  55822. SetMovieGWorld (qmci->movie, (CGrafPtr) port, 0);
  55823. MacSetPort (port);
  55824. Rect r;
  55825. r.top = 0;
  55826. r.left = 0;
  55827. r.right = (short) jmax (1, getWidth());
  55828. r.bottom = (short) jmax (1, getHeight());
  55829. SetMovieBox (qmci->movie, &r);
  55830. // create the movie controller
  55831. qmci->controller = NewMovieController (qmci->movie, &r,
  55832. controllerVisible ? mcTopLeftMovie
  55833. : mcNotVisible);
  55834. if (qmci->controller != 0)
  55835. {
  55836. MCEnableEditing (qmci->controller, true);
  55837. MCDoAction (qmci->controller, mcActionSetUseBadge, (void*) false);
  55838. MCDoAction (qmci->controller, mcActionSetLoopIsPalindrome, (void*) false);
  55839. setLooping (looping);
  55840. MCDoAction (qmci->controller, mcActionSetFlags,
  55841. (void*) (pointer_sized_int) (mcFlagSuppressMovieFrame | (controllerVisible ? 0 : (mcFlagSuppressStepButtons | mcFlagSuppressSpeakerButton))));
  55842. MCSetControllerBoundsRect (qmci->controller, &r);
  55843. controllerAssignedToWindow = true;
  55844. resized();
  55845. }
  55846. MacSetPort (savedPort);
  55847. }
  55848. else
  55849. {
  55850. SetMovieGWorld (qmci->movie, 0, 0);
  55851. }
  55852. reentrant = false;
  55853. }
  55854. void QuickTimeMovieComponent::play()
  55855. {
  55856. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55857. if (qmci->movie != 0)
  55858. StartMovie (qmci->movie);
  55859. }
  55860. void QuickTimeMovieComponent::stop()
  55861. {
  55862. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55863. if (qmci->movie != 0)
  55864. StopMovie (qmci->movie);
  55865. }
  55866. bool QuickTimeMovieComponent::isPlaying() const
  55867. {
  55868. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55869. return qmci->movie != 0 && GetMovieRate (qmci->movie) != 0;
  55870. }
  55871. void QuickTimeMovieComponent::setPosition (const double seconds)
  55872. {
  55873. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55874. if (qmci->controller != 0)
  55875. {
  55876. TimeRecord time;
  55877. time.base = GetMovieTimeBase (qmci->movie);
  55878. time.scale = 100000;
  55879. const uint64 t = (uint64) (100000.0 * seconds);
  55880. time.value.lo = (UInt32) (t & 0xffffffff);
  55881. time.value.hi = (UInt32) (t >> 32);
  55882. SetMovieTime (qmci->movie, &time);
  55883. timerCallback(); // to call MCIdle
  55884. }
  55885. else
  55886. {
  55887. jassertfalse // no movie is open, so can't set the position.
  55888. }
  55889. }
  55890. double QuickTimeMovieComponent::getPosition() const
  55891. {
  55892. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55893. if (qmci->movie != 0)
  55894. {
  55895. TimeRecord time;
  55896. GetMovieTime (qmci->movie, &time);
  55897. return ((int64) (((uint64) time.value.hi << 32) | (uint64) time.value.lo))
  55898. / (double) time.scale;
  55899. }
  55900. return 0.0;
  55901. }
  55902. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  55903. {
  55904. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55905. if (qmci->movie != 0)
  55906. SetMovieRate (qmci->movie, (Fixed) (newSpeed * (Fixed) 0x00010000L));
  55907. }
  55908. double QuickTimeMovieComponent::getMovieDuration() const
  55909. {
  55910. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55911. if (qmci->movie != 0)
  55912. return GetMovieDuration (qmci->movie) / (double) GetMovieTimeScale (qmci->movie);
  55913. return 0.0;
  55914. }
  55915. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  55916. {
  55917. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55918. looping = shouldLoop;
  55919. if (qmci->controller != 0)
  55920. MCDoAction (qmci->controller, mcActionSetLooping, (void*) shouldLoop);
  55921. }
  55922. bool QuickTimeMovieComponent::isLooping() const
  55923. {
  55924. return looping;
  55925. }
  55926. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  55927. {
  55928. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55929. if (qmci->movie != 0)
  55930. SetMovieVolume (qmci->movie, jlimit ((short) 0, (short) 0x100, (short) (newVolume * 0x0100)));
  55931. }
  55932. float QuickTimeMovieComponent::getMovieVolume() const
  55933. {
  55934. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55935. if (qmci->movie != 0)
  55936. return jmax (0.0f, GetMovieVolume (qmci->movie) / (float) 0x0100);
  55937. return 0.0f;
  55938. }
  55939. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  55940. {
  55941. width = 0;
  55942. height = 0;
  55943. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55944. if (qmci->movie != 0)
  55945. {
  55946. Rect r;
  55947. GetMovieNaturalBoundsRect (qmci->movie, &r);
  55948. width = r.right - r.left;
  55949. height = r.bottom - r.top;
  55950. }
  55951. }
  55952. void QuickTimeMovieComponent::paint (Graphics& g)
  55953. {
  55954. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55955. if (qmci->movie == 0 || qmci->controller == 0)
  55956. {
  55957. g.fillAll (Colours::black);
  55958. return;
  55959. }
  55960. GrafPtr savedPort;
  55961. GetPort (&savedPort);
  55962. MacSetPort (getPortForWindow (getWindowHandle()));
  55963. MCDraw (qmci->controller, (WindowRef) getWindowHandle());
  55964. MacSetPort (savedPort);
  55965. ComponentPeer* const peer = getPeer();
  55966. if (peer != 0)
  55967. {
  55968. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  55969. getScreenY() - peer->getScreenY(),
  55970. getWidth(), getHeight());
  55971. }
  55972. timerCallback();
  55973. }
  55974. static const Rectangle getMoviePos (Component* const c)
  55975. {
  55976. return Rectangle (c->getScreenX() - c->getTopLevelComponent()->getScreenX(),
  55977. c->getScreenY() - c->getTopLevelComponent()->getScreenY(),
  55978. jmax (1, c->getWidth()),
  55979. jmax (1, c->getHeight()));
  55980. }
  55981. void QuickTimeMovieComponent::moved()
  55982. {
  55983. resized();
  55984. }
  55985. void QuickTimeMovieComponent::resized()
  55986. {
  55987. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55988. if (qmci->controller != 0 && isShowing())
  55989. {
  55990. checkWindowAssociation();
  55991. GrafPtr port = getPortForWindow (getWindowHandle());
  55992. if (port != 0)
  55993. {
  55994. GrafPtr savedPort;
  55995. GetPort (&savedPort);
  55996. SetMovieGWorld (qmci->movie, (CGrafPtr) port, 0);
  55997. MacSetPort (port);
  55998. lastPositionApplied = getMoviePos (this);
  55999. Rect r;
  56000. r.left = (short) lastPositionApplied.getX();
  56001. r.top = (short) lastPositionApplied.getY();
  56002. r.right = (short) lastPositionApplied.getRight();
  56003. r.bottom = (short) lastPositionApplied.getBottom();
  56004. if (MCGetVisible (qmci->controller))
  56005. MCSetControllerBoundsRect (qmci->controller, &r);
  56006. else
  56007. SetMovieBox (qmci->movie, &r);
  56008. if (! isPlaying())
  56009. timerCallback();
  56010. MacSetPort (savedPort);
  56011. repaint();
  56012. }
  56013. }
  56014. }
  56015. void QuickTimeMovieComponent::visibilityChanged()
  56016. {
  56017. checkWindowAssociation();
  56018. QTWinBaseClass::visibilityChanged();
  56019. }
  56020. void QuickTimeMovieComponent::timerCallback()
  56021. {
  56022. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  56023. if (qmci->controller != 0)
  56024. {
  56025. if (isTimerRunning())
  56026. startTimer (getTimerInterval());
  56027. MCIdle (qmci->controller);
  56028. if (lastPositionApplied != getMoviePos (this))
  56029. resized();
  56030. }
  56031. }
  56032. void QuickTimeMovieComponent::checkWindowAssociation()
  56033. {
  56034. void* const window = getWindowHandle();
  56035. if (window != associatedWindow
  56036. || (window != 0 && ! controllerAssignedToWindow))
  56037. {
  56038. associatedWindow = window;
  56039. assignMovieToWindow();
  56040. }
  56041. }
  56042. void QuickTimeMovieComponent::parentHierarchyChanged()
  56043. {
  56044. checkWindowAssociation();
  56045. }
  56046. void QuickTimeMovieComponent::handleMCEvent (void* ev)
  56047. {
  56048. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  56049. if (qmci->controller != 0 && isShowing())
  56050. {
  56051. MacClickEventData* data = (MacClickEventData*) ev;
  56052. data->where.h -= getTopLevelComponent()->getScreenX();
  56053. data->where.v -= getTopLevelComponent()->getScreenY();
  56054. Boolean b = false;
  56055. MCPtInController (qmci->controller, data->where, &b);
  56056. if (b)
  56057. {
  56058. const int oldTimeBeforeWaitCursor = MessageManager::getInstance()->getTimeBeforeShowingWaitCursor();
  56059. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (0);
  56060. MCClick (qmci->controller,
  56061. (WindowRef) getWindowHandle(),
  56062. data->where,
  56063. data->when,
  56064. data->modifiers);
  56065. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (oldTimeBeforeWaitCursor);
  56066. }
  56067. }
  56068. }
  56069. #endif
  56070. // (methods common to both platforms..)
  56071. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  56072. {
  56073. Handle dataRef = 0;
  56074. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  56075. if (err == noErr)
  56076. {
  56077. Str255 suffix;
  56078. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  56079. StringPtr name = suffix;
  56080. err = PtrAndHand (name, dataRef, name[0] + 1);
  56081. if (err == noErr)
  56082. {
  56083. long atoms[3];
  56084. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  56085. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  56086. atoms[2] = EndianU32_NtoB (MovieFileType);
  56087. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  56088. if (err == noErr)
  56089. return dataRef;
  56090. }
  56091. DisposeHandle (dataRef);
  56092. }
  56093. return 0;
  56094. }
  56095. static CFStringRef juceStringToCFString (const String& s)
  56096. {
  56097. const int len = s.length();
  56098. const juce_wchar* const t = (const juce_wchar*) s;
  56099. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  56100. for (int i = 0; i <= len; ++i)
  56101. temp[i] = t[i];
  56102. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  56103. juce_free (temp);
  56104. return result;
  56105. }
  56106. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  56107. {
  56108. Boolean trueBool = true;
  56109. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  56110. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  56111. props[prop].propValueSize = sizeof (trueBool);
  56112. props[prop].propValueAddress = &trueBool;
  56113. ++prop;
  56114. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  56115. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  56116. props[prop].propValueSize = sizeof (trueBool);
  56117. props[prop].propValueAddress = &trueBool;
  56118. ++prop;
  56119. Boolean isActive = true;
  56120. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  56121. props[prop].propID = kQTNewMoviePropertyID_Active;
  56122. props[prop].propValueSize = sizeof (isActive);
  56123. props[prop].propValueAddress = &isActive;
  56124. ++prop;
  56125. #if JUCE_MAC
  56126. SetPort (0);
  56127. #else
  56128. MacSetPort (0);
  56129. #endif
  56130. jassert (prop <= 5);
  56131. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  56132. return err == noErr;
  56133. }
  56134. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  56135. {
  56136. if (input == 0)
  56137. return false;
  56138. dataHandle = 0;
  56139. bool ok = false;
  56140. QTNewMoviePropertyElement props[5];
  56141. zeromem (props, sizeof (props));
  56142. int prop = 0;
  56143. DataReferenceRecord dr;
  56144. props[prop].propClass = kQTPropertyClass_DataLocation;
  56145. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  56146. props[prop].propValueSize = sizeof (dr);
  56147. props[prop].propValueAddress = (void*) &dr;
  56148. ++prop;
  56149. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  56150. if (fin != 0)
  56151. {
  56152. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  56153. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  56154. &dr.dataRef, &dr.dataRefType);
  56155. ok = openMovie (props, prop, movie);
  56156. DisposeHandle (dr.dataRef);
  56157. CFRelease (filePath);
  56158. }
  56159. else
  56160. {
  56161. // sanity-check because this currently needs to load the whole stream into memory..
  56162. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  56163. dataHandle = NewHandle ((Size) input->getTotalLength());
  56164. HLock (dataHandle);
  56165. // read the entire stream into memory - this is a pain, but can't get it to work
  56166. // properly using a custom callback to supply the data.
  56167. input->read (*dataHandle, (int) input->getTotalLength());
  56168. HUnlock (dataHandle);
  56169. // different types to get QT to try. (We should really be a bit smarter here by
  56170. // working out in advance which one the stream contains, rather than just trying
  56171. // each one)
  56172. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  56173. "\04.avi", "\04.m4a" };
  56174. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  56175. {
  56176. /* // this fails for some bizarre reason - it can be bodged to work with
  56177. // movies, but can't seem to do it for other file types..
  56178. QTNewMovieUserProcRecord procInfo;
  56179. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  56180. procInfo.getMovieUserProcRefcon = this;
  56181. procInfo.defaultDataRef.dataRef = dataRef;
  56182. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  56183. props[prop].propClass = kQTPropertyClass_DataLocation;
  56184. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  56185. props[prop].propValueSize = sizeof (procInfo);
  56186. props[prop].propValueAddress = (void*) &procInfo;
  56187. ++prop; */
  56188. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  56189. dr.dataRefType = HandleDataHandlerSubType;
  56190. ok = openMovie (props, prop, movie);
  56191. DisposeHandle (dr.dataRef);
  56192. }
  56193. }
  56194. return ok;
  56195. }
  56196. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  56197. const bool isControllerVisible)
  56198. {
  56199. const bool ok = loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible);
  56200. movieFile = movieFile_;
  56201. return ok;
  56202. }
  56203. void QuickTimeMovieComponent::goToStart()
  56204. {
  56205. setPosition (0.0);
  56206. }
  56207. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  56208. const RectanglePlacement& placement)
  56209. {
  56210. int normalWidth, normalHeight;
  56211. getMovieNormalSize (normalWidth, normalHeight);
  56212. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  56213. {
  56214. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  56215. placement.applyTo (x, y, w, h,
  56216. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  56217. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  56218. if (w > 0 && h > 0)
  56219. {
  56220. setBounds (roundDoubleToInt (x), roundDoubleToInt (y),
  56221. roundDoubleToInt (w), roundDoubleToInt (h));
  56222. }
  56223. }
  56224. else
  56225. {
  56226. setBounds (spaceToFitWithin);
  56227. }
  56228. }
  56229. END_JUCE_NAMESPACE
  56230. #endif
  56231. /********* End of inlined file: juce_QuickTimeMovieComponent.cpp *********/
  56232. /********* Start of inlined file: juce_SystemTrayIconComponent.cpp *********/
  56233. #if JUCE_WIN32 || JUCE_LINUX
  56234. BEGIN_JUCE_NAMESPACE
  56235. SystemTrayIconComponent::SystemTrayIconComponent()
  56236. {
  56237. addToDesktop (0);
  56238. }
  56239. SystemTrayIconComponent::~SystemTrayIconComponent()
  56240. {
  56241. }
  56242. END_JUCE_NAMESPACE
  56243. #endif
  56244. /********* End of inlined file: juce_SystemTrayIconComponent.cpp *********/
  56245. /********* Start of inlined file: juce_AlertWindow.cpp *********/
  56246. BEGIN_JUCE_NAMESPACE
  56247. static const int titleH = 24;
  56248. static const int iconWidth = 80;
  56249. class AlertWindowTextEditor : public TextEditor
  56250. {
  56251. public:
  56252. #if JUCE_LINUX
  56253. #define PASSWORD_CHAR 0x2022
  56254. #else
  56255. #define PASSWORD_CHAR 0x25cf
  56256. #endif
  56257. AlertWindowTextEditor (const String& name,
  56258. const bool isPasswordBox)
  56259. : TextEditor (name,
  56260. isPasswordBox ? (const tchar) PASSWORD_CHAR
  56261. : (const tchar) 0)
  56262. {
  56263. setSelectAllWhenFocused (true);
  56264. }
  56265. ~AlertWindowTextEditor()
  56266. {
  56267. }
  56268. void returnPressed()
  56269. {
  56270. // pass these up the component hierarchy to be trigger the buttons
  56271. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, T('\n')));
  56272. }
  56273. void escapePressed()
  56274. {
  56275. // pass these up the component hierarchy to be trigger the buttons
  56276. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  56277. }
  56278. private:
  56279. AlertWindowTextEditor (const AlertWindowTextEditor&);
  56280. const AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  56281. };
  56282. AlertWindow::AlertWindow (const String& title,
  56283. const String& message,
  56284. AlertIconType iconType)
  56285. : TopLevelWindow (title, true),
  56286. alertIconType (iconType)
  56287. {
  56288. if (message.isEmpty())
  56289. text = T(" "); // to force an update if the message is empty
  56290. setMessage (message);
  56291. #if JUCE_MAC
  56292. setAlwaysOnTop (true);
  56293. #else
  56294. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  56295. {
  56296. Component* const c = Desktop::getInstance().getComponent (i);
  56297. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  56298. {
  56299. setAlwaysOnTop (true);
  56300. break;
  56301. }
  56302. }
  56303. #endif
  56304. lookAndFeelChanged();
  56305. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  56306. }
  56307. AlertWindow::~AlertWindow()
  56308. {
  56309. for (int i = customComps.size(); --i >= 0;)
  56310. removeChildComponent ((Component*) customComps[i]);
  56311. deleteAllChildren();
  56312. }
  56313. void AlertWindow::setMessage (const String& message)
  56314. {
  56315. const String newMessage (message.substring (0, 2048));
  56316. if (text != newMessage)
  56317. {
  56318. text = newMessage;
  56319. font.setHeight (15.0f);
  56320. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  56321. textLayout.setText (getName() + T("\n\n"), titleFont);
  56322. textLayout.appendText (text, font);
  56323. updateLayout (true);
  56324. repaint();
  56325. }
  56326. }
  56327. void AlertWindow::buttonClicked (Button* button)
  56328. {
  56329. for (int i = 0; i < buttons.size(); i++)
  56330. {
  56331. TextButton* const c = (TextButton*) buttons[i];
  56332. if (button->getName() == c->getName())
  56333. {
  56334. if (c->getParentComponent() != 0)
  56335. c->getParentComponent()->exitModalState (c->getCommandID());
  56336. break;
  56337. }
  56338. }
  56339. }
  56340. void AlertWindow::addButton (const String& name,
  56341. const int returnValue,
  56342. const KeyPress& shortcutKey1,
  56343. const KeyPress& shortcutKey2)
  56344. {
  56345. TextButton* const b = new TextButton (name, String::empty);
  56346. b->setWantsKeyboardFocus (true);
  56347. b->setMouseClickGrabsKeyboardFocus (false);
  56348. b->setCommandToTrigger (0, returnValue, false);
  56349. b->addShortcut (shortcutKey1);
  56350. b->addShortcut (shortcutKey2);
  56351. b->addButtonListener (this);
  56352. b->changeWidthToFitText (28);
  56353. addAndMakeVisible (b, 0);
  56354. buttons.add (b);
  56355. updateLayout (false);
  56356. }
  56357. int AlertWindow::getNumButtons() const
  56358. {
  56359. return buttons.size();
  56360. }
  56361. void AlertWindow::addTextEditor (const String& name,
  56362. const String& initialContents,
  56363. const String& onScreenLabel,
  56364. const bool isPasswordBox)
  56365. {
  56366. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  56367. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  56368. tc->setFont (font);
  56369. tc->setText (initialContents);
  56370. tc->setCaretPosition (initialContents.length());
  56371. addAndMakeVisible (tc);
  56372. textBoxes.add (tc);
  56373. allComps.add (tc);
  56374. textboxNames.add (onScreenLabel);
  56375. updateLayout (false);
  56376. }
  56377. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  56378. {
  56379. for (int i = textBoxes.size(); --i >= 0;)
  56380. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  56381. return ((TextEditor*)textBoxes[i])->getText();
  56382. return String::empty;
  56383. }
  56384. void AlertWindow::addComboBox (const String& name,
  56385. const StringArray& items,
  56386. const String& onScreenLabel)
  56387. {
  56388. ComboBox* const cb = new ComboBox (name);
  56389. for (int i = 0; i < items.size(); ++i)
  56390. cb->addItem (items[i], i + 1);
  56391. addAndMakeVisible (cb);
  56392. cb->setSelectedItemIndex (0);
  56393. comboBoxes.add (cb);
  56394. allComps.add (cb);
  56395. comboBoxNames.add (onScreenLabel);
  56396. updateLayout (false);
  56397. }
  56398. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  56399. {
  56400. for (int i = comboBoxes.size(); --i >= 0;)
  56401. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  56402. return (ComboBox*) comboBoxes[i];
  56403. return 0;
  56404. }
  56405. class AlertTextComp : public TextEditor
  56406. {
  56407. AlertTextComp (const AlertTextComp&);
  56408. const AlertTextComp& operator= (const AlertTextComp&);
  56409. int bestWidth;
  56410. public:
  56411. AlertTextComp (const String& message,
  56412. const Font& font)
  56413. {
  56414. setReadOnly (true);
  56415. setMultiLine (true, true);
  56416. setCaretVisible (false);
  56417. setScrollbarsShown (true);
  56418. lookAndFeelChanged();
  56419. setWantsKeyboardFocus (false);
  56420. setFont (font);
  56421. setText (message, false);
  56422. bestWidth = 2 * (int) sqrt (font.getHeight() * font.getStringWidth (message));
  56423. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  56424. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  56425. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  56426. }
  56427. ~AlertTextComp()
  56428. {
  56429. }
  56430. int getPreferredWidth() const throw() { return bestWidth; }
  56431. void updateLayout (const int width)
  56432. {
  56433. TextLayout text;
  56434. text.appendText (getText(), getFont());
  56435. text.layout (width - 8, Justification::topLeft, true);
  56436. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  56437. }
  56438. };
  56439. void AlertWindow::addTextBlock (const String& text)
  56440. {
  56441. AlertTextComp* const c = new AlertTextComp (text, font);
  56442. textBlocks.add (c);
  56443. allComps.add (c);
  56444. addAndMakeVisible (c);
  56445. updateLayout (false);
  56446. }
  56447. void AlertWindow::addProgressBarComponent (double& progressValue)
  56448. {
  56449. ProgressBar* const pb = new ProgressBar (progressValue);
  56450. progressBars.add (pb);
  56451. allComps.add (pb);
  56452. addAndMakeVisible (pb);
  56453. updateLayout (false);
  56454. }
  56455. void AlertWindow::addCustomComponent (Component* const component)
  56456. {
  56457. customComps.add (component);
  56458. allComps.add (component);
  56459. addAndMakeVisible (component);
  56460. updateLayout (false);
  56461. }
  56462. int AlertWindow::getNumCustomComponents() const
  56463. {
  56464. return customComps.size();
  56465. }
  56466. Component* AlertWindow::getCustomComponent (const int index) const
  56467. {
  56468. return (Component*) customComps [index];
  56469. }
  56470. Component* AlertWindow::removeCustomComponent (const int index)
  56471. {
  56472. Component* const c = getCustomComponent (index);
  56473. if (c != 0)
  56474. {
  56475. customComps.removeValue (c);
  56476. allComps.removeValue (c);
  56477. removeChildComponent (c);
  56478. updateLayout (false);
  56479. }
  56480. return c;
  56481. }
  56482. void AlertWindow::paint (Graphics& g)
  56483. {
  56484. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  56485. g.setColour (Colours::black);
  56486. g.setFont (12.0f);
  56487. int i;
  56488. for (i = textBoxes.size(); --i >= 0;)
  56489. {
  56490. if (textboxNames[i].isNotEmpty())
  56491. {
  56492. const TextEditor* const te = (TextEditor*) textBoxes[i];
  56493. g.drawFittedText (textboxNames[i],
  56494. te->getX(), te->getY() - 14,
  56495. te->getWidth(), 14,
  56496. Justification::centredLeft, 1);
  56497. }
  56498. }
  56499. for (i = comboBoxNames.size(); --i >= 0;)
  56500. {
  56501. if (comboBoxNames[i].isNotEmpty())
  56502. {
  56503. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  56504. g.drawFittedText (comboBoxNames[i],
  56505. cb->getX(), cb->getY() - 14,
  56506. cb->getWidth(), 14,
  56507. Justification::centredLeft, 1);
  56508. }
  56509. }
  56510. }
  56511. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  56512. {
  56513. const int wid = jmax (font.getStringWidth (text),
  56514. font.getStringWidth (getName()));
  56515. const int sw = (int) sqrt (font.getHeight() * wid);
  56516. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  56517. const int edgeGap = 10;
  56518. int iconSpace;
  56519. if (alertIconType == NoIcon)
  56520. {
  56521. textLayout.layout (w, Justification::horizontallyCentred, true);
  56522. iconSpace = 0;
  56523. }
  56524. else
  56525. {
  56526. textLayout.layout (w, Justification::left, true);
  56527. iconSpace = iconWidth;
  56528. }
  56529. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  56530. w = jmin (w, (int) (getParentWidth() * 0.7f));
  56531. const int textLayoutH = textLayout.getHeight();
  56532. const int textBottom = 16 + titleH + textLayoutH;
  56533. int h = textBottom;
  56534. int buttonW = 40;
  56535. int i;
  56536. for (i = 0; i < buttons.size(); ++i)
  56537. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  56538. w = jmax (buttonW, w);
  56539. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  56540. if (buttons.size() > 0)
  56541. h += 20 + ((TextButton*) buttons[0])->getHeight();
  56542. for (i = customComps.size(); --i >= 0;)
  56543. {
  56544. w = jmax (w, ((Component*) customComps[i])->getWidth() + 40);
  56545. h += 10 + ((Component*) customComps[i])->getHeight();
  56546. }
  56547. for (i = textBlocks.size(); --i >= 0;)
  56548. {
  56549. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  56550. w = jmax (w, ac->getPreferredWidth());
  56551. }
  56552. w = jmin (w, (int) (getParentWidth() * 0.7f));
  56553. for (i = textBlocks.size(); --i >= 0;)
  56554. {
  56555. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  56556. ac->updateLayout ((int) (w * 0.8f));
  56557. h += ac->getHeight() + 10;
  56558. }
  56559. h = jmin (getParentHeight() - 50, h);
  56560. if (onlyIncreaseSize)
  56561. {
  56562. w = jmax (w, getWidth());
  56563. h = jmax (h, getHeight());
  56564. }
  56565. if (! isVisible())
  56566. {
  56567. centreAroundComponent (0, w, h);
  56568. }
  56569. else
  56570. {
  56571. const int cx = getX() + getWidth() / 2;
  56572. const int cy = getY() + getHeight() / 2;
  56573. setBounds (cx - w / 2,
  56574. cy - h / 2,
  56575. w, h);
  56576. }
  56577. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  56578. const int spacer = 16;
  56579. int totalWidth = -spacer;
  56580. for (i = buttons.size(); --i >= 0;)
  56581. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  56582. int x = (w - totalWidth) / 2;
  56583. int y = (int) (getHeight() * 0.95f);
  56584. for (i = 0; i < buttons.size(); ++i)
  56585. {
  56586. TextButton* const c = (TextButton*) buttons[i];
  56587. int ny = proportionOfHeight (0.95f) - c->getHeight();
  56588. c->setTopLeftPosition (x, ny);
  56589. if (ny < y)
  56590. y = ny;
  56591. x += c->getWidth() + spacer;
  56592. c->toFront (false);
  56593. }
  56594. y = textBottom;
  56595. for (i = 0; i < allComps.size(); ++i)
  56596. {
  56597. Component* const c = (Component*) allComps[i];
  56598. const int h = 22;
  56599. const int comboIndex = comboBoxes.indexOf (c);
  56600. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  56601. y += 18;
  56602. const int tbIndex = textBoxes.indexOf (c);
  56603. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  56604. y += 18;
  56605. if (customComps.contains (c) || textBlocks.contains (c))
  56606. {
  56607. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  56608. y += c->getHeight() + 10;
  56609. }
  56610. else
  56611. {
  56612. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  56613. y += h + 10;
  56614. }
  56615. }
  56616. setWantsKeyboardFocus (getNumChildComponents() == 0);
  56617. }
  56618. bool AlertWindow::containsAnyExtraComponents() const
  56619. {
  56620. return textBoxes.size()
  56621. + comboBoxes.size()
  56622. + progressBars.size()
  56623. + customComps.size() > 0;
  56624. }
  56625. void AlertWindow::mouseDown (const MouseEvent&)
  56626. {
  56627. dragger.startDraggingComponent (this, &constrainer);
  56628. }
  56629. void AlertWindow::mouseDrag (const MouseEvent& e)
  56630. {
  56631. dragger.dragComponent (this, e);
  56632. }
  56633. bool AlertWindow::keyPressed (const KeyPress& key)
  56634. {
  56635. for (int i = buttons.size(); --i >= 0;)
  56636. {
  56637. TextButton* const b = (TextButton*) buttons[i];
  56638. if (b->isRegisteredForShortcut (key))
  56639. {
  56640. b->triggerClick();
  56641. return true;
  56642. }
  56643. }
  56644. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  56645. {
  56646. exitModalState (0);
  56647. return true;
  56648. }
  56649. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  56650. {
  56651. ((TextButton*) buttons.getFirst())->triggerClick();
  56652. return true;
  56653. }
  56654. return false;
  56655. }
  56656. void AlertWindow::lookAndFeelChanged()
  56657. {
  56658. const int flags = getLookAndFeel().getAlertBoxWindowFlags();
  56659. setUsingNativeTitleBar ((flags & ComponentPeer::windowHasTitleBar) != 0);
  56660. setDropShadowEnabled ((flags & ComponentPeer::windowHasDropShadow) != 0);
  56661. }
  56662. struct AlertWindowInfo
  56663. {
  56664. String title, message, button1, button2, button3;
  56665. AlertWindow::AlertIconType iconType;
  56666. int numButtons;
  56667. int run() const
  56668. {
  56669. return (int) (pointer_sized_int)
  56670. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  56671. }
  56672. private:
  56673. int show() const
  56674. {
  56675. AlertWindow aw (title, message, iconType);
  56676. if (numButtons == 1)
  56677. {
  56678. aw.addButton (button1, 0,
  56679. KeyPress (KeyPress::escapeKey, 0, 0),
  56680. KeyPress (KeyPress::returnKey, 0, 0));
  56681. }
  56682. else
  56683. {
  56684. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  56685. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  56686. if (button1ShortCut == button2ShortCut)
  56687. button2ShortCut = KeyPress();
  56688. if (numButtons == 2)
  56689. {
  56690. aw.addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  56691. aw.addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  56692. }
  56693. else
  56694. {
  56695. jassert (numButtons == 3);
  56696. aw.addButton (button1, 1, button1ShortCut);
  56697. aw.addButton (button2, 2, button2ShortCut);
  56698. aw.addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  56699. }
  56700. }
  56701. return aw.runModalLoop();
  56702. }
  56703. static void* showCallback (void* userData)
  56704. {
  56705. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  56706. }
  56707. };
  56708. void AlertWindow::showMessageBox (AlertIconType iconType,
  56709. const String& title,
  56710. const String& message,
  56711. const String& buttonText)
  56712. {
  56713. AlertWindowInfo info;
  56714. info.title = title;
  56715. info.message = message;
  56716. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  56717. info.iconType = iconType;
  56718. info.numButtons = 1;
  56719. info.run();
  56720. }
  56721. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  56722. const String& title,
  56723. const String& message,
  56724. const String& button1Text,
  56725. const String& button2Text)
  56726. {
  56727. AlertWindowInfo info;
  56728. info.title = title;
  56729. info.message = message;
  56730. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  56731. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  56732. info.iconType = iconType;
  56733. info.numButtons = 2;
  56734. return info.run() != 0;
  56735. }
  56736. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  56737. const String& title,
  56738. const String& message,
  56739. const String& button1Text,
  56740. const String& button2Text,
  56741. const String& button3Text)
  56742. {
  56743. AlertWindowInfo info;
  56744. info.title = title;
  56745. info.message = message;
  56746. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  56747. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  56748. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  56749. info.iconType = iconType;
  56750. info.numButtons = 3;
  56751. return info.run();
  56752. }
  56753. END_JUCE_NAMESPACE
  56754. /********* End of inlined file: juce_AlertWindow.cpp *********/
  56755. /********* Start of inlined file: juce_ComponentPeer.cpp *********/
  56756. BEGIN_JUCE_NAMESPACE
  56757. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  56758. // these are over in juce_component.cpp
  56759. extern int64 juce_recentMouseDownTimes[4];
  56760. extern int juce_recentMouseDownX [4];
  56761. extern int juce_recentMouseDownY [4];
  56762. extern Component* juce_recentMouseDownComponent [4];
  56763. extern int juce_LastMousePosX;
  56764. extern int juce_LastMousePosY;
  56765. extern int juce_MouseClickCounter;
  56766. extern bool juce_MouseHasMovedSignificantlySincePressed;
  56767. static const int fakeMouseMoveMessage = 0x7fff00ff;
  56768. static VoidArray heavyweightPeers (4);
  56769. ComponentPeer::ComponentPeer (Component* const component_,
  56770. const int styleFlags_) throw()
  56771. : component (component_),
  56772. styleFlags (styleFlags_),
  56773. lastPaintTime (0),
  56774. constrainer (0),
  56775. lastFocusedComponent (0),
  56776. dragAndDropTargetComponent (0),
  56777. lastDragAndDropCompUnderMouse (0),
  56778. fakeMouseMessageSent (false),
  56779. isWindowMinimised (false)
  56780. {
  56781. heavyweightPeers.add (this);
  56782. }
  56783. ComponentPeer::~ComponentPeer()
  56784. {
  56785. heavyweightPeers.removeValue (this);
  56786. delete dragAndDropTargetComponent;
  56787. }
  56788. int ComponentPeer::getNumPeers() throw()
  56789. {
  56790. return heavyweightPeers.size();
  56791. }
  56792. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  56793. {
  56794. return (ComponentPeer*) heavyweightPeers [index];
  56795. }
  56796. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  56797. {
  56798. for (int i = heavyweightPeers.size(); --i >= 0;)
  56799. {
  56800. ComponentPeer* const peer = (ComponentPeer*) heavyweightPeers.getUnchecked(i);
  56801. if (peer->getComponent() == component)
  56802. return peer;
  56803. }
  56804. return 0;
  56805. }
  56806. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  56807. {
  56808. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  56809. }
  56810. void ComponentPeer::updateCurrentModifiers() throw()
  56811. {
  56812. ModifierKeys::updateCurrentModifiers();
  56813. }
  56814. void ComponentPeer::handleMouseEnter (int x, int y, const int64 time)
  56815. {
  56816. jassert (component->isValidComponent());
  56817. updateCurrentModifiers();
  56818. Component* c = component->getComponentAt (x, y);
  56819. const ComponentDeletionWatcher deletionChecker (component);
  56820. if (c != Component::componentUnderMouse && Component::componentUnderMouse != 0)
  56821. {
  56822. jassert (Component::componentUnderMouse->isValidComponent());
  56823. const int oldX = x;
  56824. const int oldY = y;
  56825. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56826. Component::componentUnderMouse->internalMouseExit (x, y, time);
  56827. Component::componentUnderMouse = 0;
  56828. if (deletionChecker.hasBeenDeleted())
  56829. return;
  56830. c = component->getComponentAt (oldX, oldY);
  56831. }
  56832. Component::componentUnderMouse = c;
  56833. if (Component::componentUnderMouse != 0)
  56834. {
  56835. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56836. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  56837. }
  56838. }
  56839. void ComponentPeer::handleMouseMove (int x, int y, const int64 time)
  56840. {
  56841. jassert (component->isValidComponent());
  56842. updateCurrentModifiers();
  56843. fakeMouseMessageSent = false;
  56844. const ComponentDeletionWatcher deletionChecker (component);
  56845. Component* c = component->getComponentAt (x, y);
  56846. if (c != Component::componentUnderMouse)
  56847. {
  56848. const int oldX = x;
  56849. const int oldY = y;
  56850. if (Component::componentUnderMouse != 0)
  56851. {
  56852. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56853. Component::componentUnderMouse->internalMouseExit (x, y, time);
  56854. x = oldX;
  56855. y = oldY;
  56856. Component::componentUnderMouse = 0;
  56857. if (deletionChecker.hasBeenDeleted())
  56858. return; // if this window has just been deleted..
  56859. c = component->getComponentAt (x, y);
  56860. }
  56861. Component::componentUnderMouse = c;
  56862. if (c != 0)
  56863. {
  56864. component->relativePositionToOtherComponent (c, x, y);
  56865. c->internalMouseEnter (x, y, time);
  56866. x = oldX;
  56867. y = oldY;
  56868. if (deletionChecker.hasBeenDeleted())
  56869. return; // if this window has just been deleted..
  56870. }
  56871. }
  56872. if (Component::componentUnderMouse != 0)
  56873. {
  56874. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56875. Component::componentUnderMouse->internalMouseMove (x, y, time);
  56876. }
  56877. }
  56878. void ComponentPeer::handleMouseDown (int x, int y, const int64 time)
  56879. {
  56880. ++juce_MouseClickCounter;
  56881. updateCurrentModifiers();
  56882. int numMouseButtonsDown = 0;
  56883. if (ModifierKeys::getCurrentModifiers().isLeftButtonDown())
  56884. ++numMouseButtonsDown;
  56885. if (ModifierKeys::getCurrentModifiers().isRightButtonDown())
  56886. ++numMouseButtonsDown;
  56887. if (ModifierKeys::getCurrentModifiers().isMiddleButtonDown())
  56888. ++numMouseButtonsDown;
  56889. if (numMouseButtonsDown == 1)
  56890. {
  56891. Component::componentUnderMouse = component->getComponentAt (x, y);
  56892. if (Component::componentUnderMouse != 0)
  56893. {
  56894. // can't set these in the mouseDownInt() method, because it's re-entrant, so do it here..
  56895. for (int i = numElementsInArray (juce_recentMouseDownTimes); --i > 0;)
  56896. {
  56897. juce_recentMouseDownTimes [i] = juce_recentMouseDownTimes [i - 1];
  56898. juce_recentMouseDownX [i] = juce_recentMouseDownX [i - 1];
  56899. juce_recentMouseDownY [i] = juce_recentMouseDownY [i - 1];
  56900. juce_recentMouseDownComponent [i] = juce_recentMouseDownComponent [i - 1];
  56901. }
  56902. juce_recentMouseDownTimes[0] = time;
  56903. juce_recentMouseDownX[0] = x;
  56904. juce_recentMouseDownY[0] = y;
  56905. juce_recentMouseDownComponent[0] = Component::componentUnderMouse;
  56906. relativePositionToGlobal (juce_recentMouseDownX[0], juce_recentMouseDownY[0]);
  56907. juce_MouseHasMovedSignificantlySincePressed = false;
  56908. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56909. Component::componentUnderMouse->internalMouseDown (x, y);
  56910. }
  56911. }
  56912. }
  56913. void ComponentPeer::handleMouseDrag (int x, int y, const int64 time)
  56914. {
  56915. updateCurrentModifiers();
  56916. if (Component::componentUnderMouse != 0)
  56917. {
  56918. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56919. Component::componentUnderMouse->internalMouseDrag (x, y, time);
  56920. }
  56921. }
  56922. void ComponentPeer::handleMouseUp (const int oldModifiers, int x, int y, const int64 time)
  56923. {
  56924. updateCurrentModifiers();
  56925. int numMouseButtonsDown = 0;
  56926. if ((oldModifiers & ModifierKeys::leftButtonModifier) != 0)
  56927. ++numMouseButtonsDown;
  56928. if ((oldModifiers & ModifierKeys::rightButtonModifier) != 0)
  56929. ++numMouseButtonsDown;
  56930. if ((oldModifiers & ModifierKeys::middleButtonModifier) != 0)
  56931. ++numMouseButtonsDown;
  56932. if (numMouseButtonsDown == 1)
  56933. {
  56934. const ComponentDeletionWatcher deletionChecker (component);
  56935. Component* c = component->getComponentAt (x, y);
  56936. if (c != Component::componentUnderMouse)
  56937. {
  56938. const int oldX = x;
  56939. const int oldY = y;
  56940. if (Component::componentUnderMouse != 0)
  56941. {
  56942. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56943. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  56944. x = oldX;
  56945. y = oldY;
  56946. if (Component::componentUnderMouse != 0)
  56947. Component::componentUnderMouse->internalMouseExit (x, y, time);
  56948. if (deletionChecker.hasBeenDeleted())
  56949. return;
  56950. c = component->getComponentAt (oldX, oldY);
  56951. }
  56952. Component::componentUnderMouse = c;
  56953. if (Component::componentUnderMouse != 0)
  56954. {
  56955. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56956. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  56957. }
  56958. }
  56959. else
  56960. {
  56961. if (Component::componentUnderMouse != 0)
  56962. {
  56963. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56964. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  56965. }
  56966. }
  56967. }
  56968. }
  56969. void ComponentPeer::handleMouseExit (int x, int y, const int64 time)
  56970. {
  56971. jassert (component->isValidComponent());
  56972. updateCurrentModifiers();
  56973. if (Component::componentUnderMouse != 0)
  56974. {
  56975. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56976. Component::componentUnderMouse->internalMouseExit (x, y, time);
  56977. Component::componentUnderMouse = 0;
  56978. }
  56979. }
  56980. void ComponentPeer::handleMouseWheel (const int amountX, const int amountY, const int64 time)
  56981. {
  56982. updateCurrentModifiers();
  56983. if (Component::componentUnderMouse != 0)
  56984. Component::componentUnderMouse->internalMouseWheel (amountX, amountY, time);
  56985. }
  56986. void ComponentPeer::sendFakeMouseMove() throw()
  56987. {
  56988. if ((! fakeMouseMessageSent)
  56989. && component->flags.hasHeavyweightPeerFlag
  56990. && ! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  56991. {
  56992. if (! isMinimised())
  56993. {
  56994. int realX, realY, realW, realH;
  56995. getBounds (realX, realY, realW, realH);
  56996. component->bounds_.setBounds (realX, realY, realW, realH);
  56997. }
  56998. int x, y;
  56999. component->getMouseXYRelative (x, y);
  57000. if (((unsigned int) x) < (unsigned int) component->getWidth()
  57001. && ((unsigned int) y) < (unsigned int) component->getHeight()
  57002. && contains (x, y, false))
  57003. {
  57004. postMessage (new Message (fakeMouseMoveMessage, x, y, 0));
  57005. }
  57006. fakeMouseMessageSent = true;
  57007. }
  57008. }
  57009. void ComponentPeer::handleMessage (const Message& message)
  57010. {
  57011. if (message.intParameter1 == fakeMouseMoveMessage)
  57012. {
  57013. handleMouseMove (message.intParameter2,
  57014. message.intParameter3,
  57015. Time::currentTimeMillis());
  57016. }
  57017. }
  57018. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  57019. {
  57020. Graphics g (&contextToPaintTo);
  57021. #if JUCE_ENABLE_REPAINT_DEBUGGING
  57022. g.saveState();
  57023. #endif
  57024. JUCE_TRY
  57025. {
  57026. component->paintEntireComponent (g);
  57027. }
  57028. JUCE_CATCH_EXCEPTION
  57029. #if JUCE_ENABLE_REPAINT_DEBUGGING
  57030. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  57031. // clearly when things are being repainted.
  57032. {
  57033. g.restoreState();
  57034. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  57035. (uint8) Random::getSystemRandom().nextInt (255),
  57036. (uint8) Random::getSystemRandom().nextInt (255),
  57037. (uint8) 0x50));
  57038. }
  57039. #endif
  57040. }
  57041. bool ComponentPeer::handleKeyPress (const int keyCode,
  57042. const juce_wchar textCharacter)
  57043. {
  57044. updateCurrentModifiers();
  57045. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  57046. ? Component::currentlyFocusedComponent
  57047. : component;
  57048. if (target->isCurrentlyBlockedByAnotherModalComponent())
  57049. {
  57050. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  57051. if (currentModalComp != 0)
  57052. target = currentModalComp;
  57053. }
  57054. const KeyPress keyInfo (keyCode,
  57055. ModifierKeys::getCurrentModifiers().getRawFlags()
  57056. & ModifierKeys::allKeyboardModifiers,
  57057. textCharacter);
  57058. bool keyWasUsed = false;
  57059. while (target != 0)
  57060. {
  57061. const ComponentDeletionWatcher deletionChecker (target);
  57062. if (target->keyListeners_ != 0)
  57063. {
  57064. for (int i = target->keyListeners_->size(); --i >= 0;)
  57065. {
  57066. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyPressed (keyInfo, target);
  57067. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  57068. return keyWasUsed;
  57069. i = jmin (i, target->keyListeners_->size());
  57070. }
  57071. }
  57072. keyWasUsed = target->keyPressed (keyInfo);
  57073. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  57074. break;
  57075. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  57076. {
  57077. Component::getCurrentlyFocusedComponent()
  57078. ->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  57079. keyWasUsed = true;
  57080. break;
  57081. }
  57082. target = target->parentComponent_;
  57083. }
  57084. return keyWasUsed;
  57085. }
  57086. bool ComponentPeer::handleKeyUpOrDown()
  57087. {
  57088. updateCurrentModifiers();
  57089. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  57090. ? Component::currentlyFocusedComponent
  57091. : component;
  57092. if (target->isCurrentlyBlockedByAnotherModalComponent())
  57093. {
  57094. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  57095. if (currentModalComp != 0)
  57096. target = currentModalComp;
  57097. }
  57098. bool keyWasUsed = false;
  57099. while (target != 0)
  57100. {
  57101. const ComponentDeletionWatcher deletionChecker (target);
  57102. keyWasUsed = target->keyStateChanged();
  57103. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  57104. break;
  57105. if (target->keyListeners_ != 0)
  57106. {
  57107. for (int i = target->keyListeners_->size(); --i >= 0;)
  57108. {
  57109. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyStateChanged (target);
  57110. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  57111. return keyWasUsed;
  57112. i = jmin (i, target->keyListeners_->size());
  57113. }
  57114. }
  57115. target = target->parentComponent_;
  57116. }
  57117. return keyWasUsed;
  57118. }
  57119. void ComponentPeer::handleModifierKeysChange()
  57120. {
  57121. updateCurrentModifiers();
  57122. Component* target = Component::getComponentUnderMouse();
  57123. if (target == 0)
  57124. target = Component::getCurrentlyFocusedComponent();
  57125. if (target == 0)
  57126. target = component;
  57127. if (target->isValidComponent())
  57128. target->internalModifierKeysChanged();
  57129. }
  57130. void ComponentPeer::handleBroughtToFront()
  57131. {
  57132. updateCurrentModifiers();
  57133. if (component != 0)
  57134. component->internalBroughtToFront();
  57135. }
  57136. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  57137. {
  57138. constrainer = newConstrainer;
  57139. }
  57140. void ComponentPeer::handleMovedOrResized()
  57141. {
  57142. jassert (component->isValidComponent());
  57143. updateCurrentModifiers();
  57144. const bool nowMinimised = isMinimised();
  57145. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  57146. {
  57147. const ComponentDeletionWatcher deletionChecker (component);
  57148. int realX, realY, realW, realH;
  57149. getBounds (realX, realY, realW, realH);
  57150. const bool wasMoved = (component->getX() != realX || component->getY() != realY);
  57151. const bool wasResized = (component->getWidth() != realW || component->getHeight() != realH);
  57152. if (wasMoved || wasResized)
  57153. {
  57154. component->bounds_.setBounds (realX, realY, realW, realH);
  57155. if (wasResized)
  57156. component->repaint();
  57157. component->sendMovedResizedMessages (wasMoved, wasResized);
  57158. if (deletionChecker.hasBeenDeleted())
  57159. return;
  57160. }
  57161. }
  57162. if (isWindowMinimised != nowMinimised)
  57163. {
  57164. isWindowMinimised = nowMinimised;
  57165. component->minimisationStateChanged (nowMinimised);
  57166. component->sendVisibilityChangeMessage();
  57167. }
  57168. if (! isFullScreen())
  57169. lastNonFullscreenBounds = component->getBounds();
  57170. }
  57171. void ComponentPeer::handleFocusGain()
  57172. {
  57173. updateCurrentModifiers();
  57174. if (component->isParentOf (lastFocusedComponent))
  57175. {
  57176. Component::currentlyFocusedComponent = lastFocusedComponent;
  57177. Desktop::getInstance().triggerFocusCallback();
  57178. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  57179. }
  57180. else
  57181. {
  57182. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  57183. {
  57184. component->grabKeyboardFocus();
  57185. }
  57186. else
  57187. {
  57188. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  57189. if (currentModalComp != 0)
  57190. currentModalComp->toFront (! currentModalComp->hasKeyboardFocus (true));
  57191. }
  57192. }
  57193. }
  57194. void ComponentPeer::handleFocusLoss()
  57195. {
  57196. updateCurrentModifiers();
  57197. if (component->hasKeyboardFocus (true))
  57198. {
  57199. lastFocusedComponent = Component::currentlyFocusedComponent;
  57200. if (lastFocusedComponent != 0)
  57201. {
  57202. Component::currentlyFocusedComponent = 0;
  57203. Desktop::getInstance().triggerFocusCallback();
  57204. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  57205. }
  57206. }
  57207. }
  57208. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  57209. {
  57210. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  57211. ? lastFocusedComponent
  57212. : component;
  57213. }
  57214. void ComponentPeer::handleScreenSizeChange()
  57215. {
  57216. updateCurrentModifiers();
  57217. component->parentSizeChanged();
  57218. handleMovedOrResized();
  57219. }
  57220. void ComponentPeer::setNonFullScreenBounds (const Rectangle& newBounds) throw()
  57221. {
  57222. lastNonFullscreenBounds = newBounds;
  57223. }
  57224. const Rectangle& ComponentPeer::getNonFullScreenBounds() const throw()
  57225. {
  57226. return lastNonFullscreenBounds;
  57227. }
  57228. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  57229. const StringArray& files,
  57230. FileDragAndDropTarget* const lastOne)
  57231. {
  57232. while (c != 0)
  57233. {
  57234. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  57235. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  57236. return t;
  57237. c = c->getParentComponent();
  57238. }
  57239. return 0;
  57240. }
  57241. void ComponentPeer::handleFileDragMove (const StringArray& files, int x, int y)
  57242. {
  57243. updateCurrentModifiers();
  57244. FileDragAndDropTarget* lastTarget = 0;
  57245. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  57246. lastTarget = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  57247. FileDragAndDropTarget* newTarget = 0;
  57248. Component* const compUnderMouse = component->getComponentAt (x, y);
  57249. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  57250. {
  57251. lastDragAndDropCompUnderMouse = compUnderMouse;
  57252. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  57253. if (newTarget != lastTarget)
  57254. {
  57255. if (lastTarget != 0)
  57256. lastTarget->fileDragExit (files);
  57257. deleteAndZero (dragAndDropTargetComponent);
  57258. if (newTarget != 0)
  57259. {
  57260. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  57261. int mx = x, my = y;
  57262. component->relativePositionToOtherComponent (targetComp, mx, my);
  57263. dragAndDropTargetComponent = new ComponentDeletionWatcher (dynamic_cast <Component*> (newTarget));
  57264. newTarget->fileDragEnter (files, mx, my);
  57265. }
  57266. }
  57267. }
  57268. else
  57269. {
  57270. newTarget = lastTarget;
  57271. }
  57272. if (newTarget != 0)
  57273. {
  57274. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  57275. component->relativePositionToOtherComponent (targetComp, x, y);
  57276. newTarget->fileDragMove (files, x, y);
  57277. }
  57278. }
  57279. void ComponentPeer::handleFileDragExit (const StringArray& files)
  57280. {
  57281. handleFileDragMove (files, -1, -1);
  57282. jassert (dragAndDropTargetComponent == 0);
  57283. lastDragAndDropCompUnderMouse = 0;
  57284. }
  57285. void ComponentPeer::handleFileDragDrop (const StringArray& files, int x, int y)
  57286. {
  57287. handleFileDragMove (files, x, y);
  57288. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  57289. {
  57290. FileDragAndDropTarget* const target = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  57291. deleteAndZero (dragAndDropTargetComponent);
  57292. lastDragAndDropCompUnderMouse = 0;
  57293. if (target != 0)
  57294. {
  57295. Component* const targetComp = dynamic_cast <Component*> (target);
  57296. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  57297. {
  57298. targetComp->internalModalInputAttempt();
  57299. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  57300. return;
  57301. }
  57302. component->relativePositionToOtherComponent (targetComp, x, y);
  57303. target->filesDropped (files, x, y);
  57304. }
  57305. }
  57306. }
  57307. void ComponentPeer::handleUserClosingWindow()
  57308. {
  57309. updateCurrentModifiers();
  57310. component->userTriedToCloseWindow();
  57311. }
  57312. void ComponentPeer::clearMaskedRegion() throw()
  57313. {
  57314. maskedRegion.clear();
  57315. }
  57316. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h) throw()
  57317. {
  57318. maskedRegion.add (x, y, w, h);
  57319. }
  57320. END_JUCE_NAMESPACE
  57321. /********* End of inlined file: juce_ComponentPeer.cpp *********/
  57322. /********* Start of inlined file: juce_DialogWindow.cpp *********/
  57323. BEGIN_JUCE_NAMESPACE
  57324. DialogWindow::DialogWindow (const String& name,
  57325. const Colour& backgroundColour_,
  57326. const bool escapeKeyTriggersCloseButton_,
  57327. const bool addToDesktop_)
  57328. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  57329. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  57330. {
  57331. }
  57332. DialogWindow::~DialogWindow()
  57333. {
  57334. }
  57335. void DialogWindow::resized()
  57336. {
  57337. DocumentWindow::resized();
  57338. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  57339. if (escapeKeyTriggersCloseButton
  57340. && getCloseButton() != 0
  57341. && ! getCloseButton()->isRegisteredForShortcut (esc))
  57342. {
  57343. getCloseButton()->addShortcut (esc);
  57344. }
  57345. }
  57346. class TempDialogWindow : public DialogWindow
  57347. {
  57348. public:
  57349. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  57350. : DialogWindow (title, colour, escapeCloses, true)
  57351. {
  57352. }
  57353. ~TempDialogWindow()
  57354. {
  57355. }
  57356. void closeButtonPressed()
  57357. {
  57358. setVisible (false);
  57359. }
  57360. private:
  57361. TempDialogWindow (const TempDialogWindow&);
  57362. const TempDialogWindow& operator= (const TempDialogWindow&);
  57363. };
  57364. int DialogWindow::showModalDialog (const String& dialogTitle,
  57365. Component* contentComponent,
  57366. Component* componentToCentreAround,
  57367. const Colour& colour,
  57368. const bool escapeKeyTriggersCloseButton,
  57369. const bool shouldBeResizable,
  57370. const bool useBottomRightCornerResizer)
  57371. {
  57372. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  57373. dw.setContentComponent (contentComponent, true, true);
  57374. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  57375. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  57376. const int result = dw.runModalLoop();
  57377. dw.setContentComponent (0, false);
  57378. return result;
  57379. }
  57380. END_JUCE_NAMESPACE
  57381. /********* End of inlined file: juce_DialogWindow.cpp *********/
  57382. /********* Start of inlined file: juce_DocumentWindow.cpp *********/
  57383. BEGIN_JUCE_NAMESPACE
  57384. DocumentWindow::DocumentWindow (const String& title,
  57385. const Colour& backgroundColour,
  57386. const int requiredButtons_,
  57387. const bool addToDesktop_)
  57388. : ResizableWindow (title, backgroundColour, addToDesktop_),
  57389. titleBarHeight (26),
  57390. menuBarHeight (24),
  57391. requiredButtons (requiredButtons_),
  57392. #if JUCE_MAC
  57393. positionTitleBarButtonsOnLeft (true),
  57394. #else
  57395. positionTitleBarButtonsOnLeft (false),
  57396. #endif
  57397. drawTitleTextCentred (true),
  57398. titleBarIcon (0),
  57399. menuBar (0),
  57400. menuBarModel (0)
  57401. {
  57402. zeromem (titleBarButtons, sizeof (titleBarButtons));
  57403. setResizeLimits (128, 128, 32768, 32768);
  57404. lookAndFeelChanged();
  57405. }
  57406. DocumentWindow::~DocumentWindow()
  57407. {
  57408. for (int i = 0; i < 3; ++i)
  57409. delete titleBarButtons[i];
  57410. delete titleBarIcon;
  57411. delete menuBar;
  57412. }
  57413. void DocumentWindow::repaintTitleBar()
  57414. {
  57415. const int border = getBorderSize();
  57416. repaint (border, border, getWidth() - border * 2, getTitleBarHeight());
  57417. }
  57418. void DocumentWindow::setName (const String& newName)
  57419. {
  57420. if (newName != getName())
  57421. {
  57422. Component::setName (newName);
  57423. repaintTitleBar();
  57424. }
  57425. }
  57426. void DocumentWindow::setIcon (const Image* imageToUse)
  57427. {
  57428. deleteAndZero (titleBarIcon);
  57429. if (imageToUse != 0)
  57430. titleBarIcon = imageToUse->createCopy();
  57431. repaintTitleBar();
  57432. }
  57433. void DocumentWindow::setTitleBarHeight (const int newHeight)
  57434. {
  57435. titleBarHeight = newHeight;
  57436. resized();
  57437. repaintTitleBar();
  57438. }
  57439. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  57440. const bool positionTitleBarButtonsOnLeft_)
  57441. {
  57442. requiredButtons = requiredButtons_;
  57443. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  57444. lookAndFeelChanged();
  57445. }
  57446. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  57447. {
  57448. drawTitleTextCentred = textShouldBeCentred;
  57449. repaintTitleBar();
  57450. }
  57451. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  57452. const int menuBarHeight_)
  57453. {
  57454. if (menuBarModel != menuBarModel_)
  57455. {
  57456. delete menuBar;
  57457. menuBar = 0;
  57458. menuBarModel = menuBarModel_;
  57459. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  57460. : getLookAndFeel().getDefaultMenuBarHeight();
  57461. if (menuBarModel != 0)
  57462. {
  57463. // (call the Component method directly to avoid the assertion in ResizableWindow)
  57464. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  57465. menuBar->setEnabled (isActiveWindow());
  57466. }
  57467. resized();
  57468. }
  57469. }
  57470. void DocumentWindow::closeButtonPressed()
  57471. {
  57472. /* If you've got a close button, you have to override this method to get
  57473. rid of your window!
  57474. If the window is just a pop-up, you should override this method and make
  57475. it delete the window in whatever way is appropriate for your app. E.g. you
  57476. might just want to call "delete this".
  57477. If your app is centred around this window such that the whole app should quit when
  57478. the window is closed, then you will probably want to use this method as an opportunity
  57479. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  57480. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  57481. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  57482. or closing it via the taskbar icon on Windows).
  57483. */
  57484. jassertfalse
  57485. }
  57486. void DocumentWindow::minimiseButtonPressed()
  57487. {
  57488. setMinimised (true);
  57489. }
  57490. void DocumentWindow::maximiseButtonPressed()
  57491. {
  57492. setFullScreen (! isFullScreen());
  57493. }
  57494. void DocumentWindow::paint (Graphics& g)
  57495. {
  57496. ResizableWindow::paint (g);
  57497. if (resizableBorder == 0 && getBorderSize() == 1)
  57498. {
  57499. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  57500. g.drawRect (0, 0, getWidth(), getHeight());
  57501. }
  57502. const int border = getBorderSize();
  57503. g.setOrigin (border, border);
  57504. g.reduceClipRegion (0, 0, getWidth() - border * 2, getTitleBarHeight());
  57505. int titleSpaceX1 = 6;
  57506. int titleSpaceX2 = getWidth() - 6;
  57507. for (int i = 0; i < 3; ++i)
  57508. {
  57509. if (titleBarButtons[i] != 0)
  57510. {
  57511. if (positionTitleBarButtonsOnLeft)
  57512. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  57513. else
  57514. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  57515. }
  57516. }
  57517. getLookAndFeel()
  57518. .drawDocumentWindowTitleBar (*this, g,
  57519. getWidth() - border * 2,
  57520. getTitleBarHeight(),
  57521. titleSpaceX1, jmax (1, titleSpaceX2 - titleSpaceX1),
  57522. titleBarIcon, ! drawTitleTextCentred);
  57523. }
  57524. void DocumentWindow::resized()
  57525. {
  57526. ResizableWindow::resized();
  57527. if (titleBarButtons[1] != 0)
  57528. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  57529. const int border = getBorderSize();
  57530. getLookAndFeel()
  57531. .positionDocumentWindowButtons (*this,
  57532. border, border,
  57533. getWidth() - border * 2, getTitleBarHeight(),
  57534. titleBarButtons[0],
  57535. titleBarButtons[1],
  57536. titleBarButtons[2],
  57537. positionTitleBarButtonsOnLeft);
  57538. if (menuBar != 0)
  57539. menuBar->setBounds (border, border + getTitleBarHeight(),
  57540. getWidth() - border * 2, menuBarHeight);
  57541. }
  57542. Button* DocumentWindow::getCloseButton() const throw()
  57543. {
  57544. return titleBarButtons[2];
  57545. }
  57546. Button* DocumentWindow::getMinimiseButton() const throw()
  57547. {
  57548. return titleBarButtons[0];
  57549. }
  57550. Button* DocumentWindow::getMaximiseButton() const throw()
  57551. {
  57552. return titleBarButtons[1];
  57553. }
  57554. int DocumentWindow::getDesktopWindowStyleFlags() const
  57555. {
  57556. int flags = ResizableWindow::getDesktopWindowStyleFlags();
  57557. if ((requiredButtons & minimiseButton) != 0)
  57558. flags |= ComponentPeer::windowHasMinimiseButton;
  57559. if ((requiredButtons & maximiseButton) != 0)
  57560. flags |= ComponentPeer::windowHasMaximiseButton;
  57561. if ((requiredButtons & closeButton) != 0)
  57562. flags |= ComponentPeer::windowHasCloseButton;
  57563. return flags;
  57564. }
  57565. void DocumentWindow::lookAndFeelChanged()
  57566. {
  57567. int i;
  57568. for (i = 0; i < 3; ++i)
  57569. deleteAndZero (titleBarButtons[i]);
  57570. if (! isUsingNativeTitleBar())
  57571. {
  57572. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  57573. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  57574. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  57575. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  57576. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  57577. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  57578. for (i = 0; i < 3; ++i)
  57579. {
  57580. if (titleBarButtons[i] != 0)
  57581. {
  57582. buttonListener.owner = this;
  57583. titleBarButtons[i]->addButtonListener (&buttonListener);
  57584. titleBarButtons[i]->setWantsKeyboardFocus (false);
  57585. // (call the Component method directly to avoid the assertion in ResizableWindow)
  57586. Component::addAndMakeVisible (titleBarButtons[i]);
  57587. }
  57588. }
  57589. if (getCloseButton() != 0)
  57590. {
  57591. #if JUCE_MAC
  57592. getCloseButton()->addShortcut (KeyPress (T('w'), ModifierKeys::commandModifier, 0));
  57593. #else
  57594. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  57595. #endif
  57596. }
  57597. }
  57598. activeWindowStatusChanged();
  57599. ResizableWindow::lookAndFeelChanged();
  57600. }
  57601. void DocumentWindow::parentHierarchyChanged()
  57602. {
  57603. lookAndFeelChanged();
  57604. }
  57605. void DocumentWindow::activeWindowStatusChanged()
  57606. {
  57607. ResizableWindow::activeWindowStatusChanged();
  57608. for (int i = 0; i < 3; ++i)
  57609. if (titleBarButtons[i] != 0)
  57610. titleBarButtons[i]->setEnabled (isActiveWindow());
  57611. if (menuBar != 0)
  57612. menuBar->setEnabled (isActiveWindow());
  57613. }
  57614. const BorderSize DocumentWindow::getBorderThickness()
  57615. {
  57616. return BorderSize (getBorderSize());
  57617. }
  57618. const BorderSize DocumentWindow::getContentComponentBorder()
  57619. {
  57620. const int size = getBorderSize();
  57621. return BorderSize (size
  57622. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  57623. + (menuBar != 0 ? menuBarHeight : 0),
  57624. size, size, size);
  57625. }
  57626. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  57627. {
  57628. const int border = getBorderSize();
  57629. if (e.x >= border
  57630. && e.y >= border
  57631. && e.x < getWidth() - border
  57632. && e.y < border + getTitleBarHeight()
  57633. && getMaximiseButton() != 0)
  57634. {
  57635. getMaximiseButton()->triggerClick();
  57636. }
  57637. }
  57638. void DocumentWindow::userTriedToCloseWindow()
  57639. {
  57640. closeButtonPressed();
  57641. }
  57642. int DocumentWindow::getTitleBarHeight() const
  57643. {
  57644. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  57645. }
  57646. int DocumentWindow::getBorderSize() const
  57647. {
  57648. return (isFullScreen() || isUsingNativeTitleBar()) ? 0 : (resizableBorder != 0 ? 4 : 1);
  57649. }
  57650. DocumentWindow::ButtonListenerProxy::ButtonListenerProxy()
  57651. {
  57652. }
  57653. void DocumentWindow::ButtonListenerProxy::buttonClicked (Button* button)
  57654. {
  57655. if (button == owner->getMinimiseButton())
  57656. {
  57657. owner->minimiseButtonPressed();
  57658. }
  57659. else if (button == owner->getMaximiseButton())
  57660. {
  57661. owner->maximiseButtonPressed();
  57662. }
  57663. else if (button == owner->getCloseButton())
  57664. {
  57665. owner->closeButtonPressed();
  57666. }
  57667. }
  57668. END_JUCE_NAMESPACE
  57669. /********* End of inlined file: juce_DocumentWindow.cpp *********/
  57670. /********* Start of inlined file: juce_ResizableWindow.cpp *********/
  57671. BEGIN_JUCE_NAMESPACE
  57672. ResizableWindow::ResizableWindow (const String& name,
  57673. const Colour& backgroundColour_,
  57674. const bool addToDesktop_)
  57675. : TopLevelWindow (name, addToDesktop_),
  57676. resizableCorner (0),
  57677. resizableBorder (0),
  57678. contentComponent (0),
  57679. resizeToFitContent (false),
  57680. fullscreen (false),
  57681. constrainer (0)
  57682. #ifdef JUCE_DEBUG
  57683. , hasBeenResized (false)
  57684. #endif
  57685. {
  57686. setBackgroundColour (backgroundColour_);
  57687. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  57688. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  57689. if (addToDesktop_)
  57690. Component::addToDesktop (getDesktopWindowStyleFlags());
  57691. }
  57692. ResizableWindow::~ResizableWindow()
  57693. {
  57694. deleteAndZero (resizableCorner);
  57695. deleteAndZero (resizableBorder);
  57696. deleteAndZero (contentComponent);
  57697. // have you been adding your own components directly to this window..? tut tut tut.
  57698. // Read the instructions for using a ResizableWindow!
  57699. jassert (getNumChildComponents() == 0);
  57700. }
  57701. int ResizableWindow::getDesktopWindowStyleFlags() const
  57702. {
  57703. int flags = TopLevelWindow::getDesktopWindowStyleFlags();
  57704. if (isResizable() && (flags & ComponentPeer::windowHasTitleBar) != 0)
  57705. flags |= ComponentPeer::windowIsResizable;
  57706. return flags;
  57707. }
  57708. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  57709. const bool deleteOldOne,
  57710. const bool resizeToFit)
  57711. {
  57712. resizeToFitContent = resizeToFit;
  57713. if (contentComponent != newContentComponent)
  57714. {
  57715. if (deleteOldOne)
  57716. delete contentComponent;
  57717. else
  57718. removeChildComponent (contentComponent);
  57719. contentComponent = newContentComponent;
  57720. Component::addAndMakeVisible (contentComponent);
  57721. }
  57722. if (resizeToFit)
  57723. childBoundsChanged (contentComponent);
  57724. resized(); // must always be called to position the new content comp
  57725. }
  57726. void ResizableWindow::setContentComponentSize (int width, int height)
  57727. {
  57728. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  57729. const BorderSize border (getContentComponentBorder());
  57730. setSize (width + border.getLeftAndRight(),
  57731. height + border.getTopAndBottom());
  57732. }
  57733. const BorderSize ResizableWindow::getBorderThickness()
  57734. {
  57735. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  57736. }
  57737. const BorderSize ResizableWindow::getContentComponentBorder()
  57738. {
  57739. return getBorderThickness();
  57740. }
  57741. void ResizableWindow::moved()
  57742. {
  57743. updateLastPos();
  57744. }
  57745. void ResizableWindow::visibilityChanged()
  57746. {
  57747. TopLevelWindow::visibilityChanged();
  57748. updateLastPos();
  57749. }
  57750. void ResizableWindow::resized()
  57751. {
  57752. if (resizableBorder != 0)
  57753. {
  57754. resizableBorder->setVisible (! isFullScreen());
  57755. resizableBorder->setBorderThickness (getBorderThickness());
  57756. resizableBorder->setSize (getWidth(), getHeight());
  57757. resizableBorder->toBack();
  57758. }
  57759. if (resizableCorner != 0)
  57760. {
  57761. resizableCorner->setVisible (! isFullScreen());
  57762. const int resizerSize = 18;
  57763. resizableCorner->setBounds (getWidth() - resizerSize,
  57764. getHeight() - resizerSize,
  57765. resizerSize, resizerSize);
  57766. }
  57767. if (contentComponent != 0)
  57768. contentComponent->setBoundsInset (getContentComponentBorder());
  57769. updateLastPos();
  57770. #ifdef JUCE_DEBUG
  57771. hasBeenResized = true;
  57772. #endif
  57773. }
  57774. void ResizableWindow::childBoundsChanged (Component* child)
  57775. {
  57776. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  57777. {
  57778. // not going to look very good if this component has a zero size..
  57779. jassert (child->getWidth() > 0);
  57780. jassert (child->getHeight() > 0);
  57781. const BorderSize borders (getContentComponentBorder());
  57782. setSize (child->getWidth() + borders.getLeftAndRight(),
  57783. child->getHeight() + borders.getTopAndBottom());
  57784. }
  57785. }
  57786. void ResizableWindow::activeWindowStatusChanged()
  57787. {
  57788. const BorderSize borders (getContentComponentBorder());
  57789. repaint (0, 0, getWidth(), borders.getTop());
  57790. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  57791. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  57792. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  57793. }
  57794. void ResizableWindow::setResizable (const bool shouldBeResizable,
  57795. const bool useBottomRightCornerResizer)
  57796. {
  57797. if (shouldBeResizable)
  57798. {
  57799. if (useBottomRightCornerResizer)
  57800. {
  57801. deleteAndZero (resizableBorder);
  57802. if (resizableCorner == 0)
  57803. {
  57804. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  57805. resizableCorner->setAlwaysOnTop (true);
  57806. }
  57807. }
  57808. else
  57809. {
  57810. deleteAndZero (resizableCorner);
  57811. if (resizableBorder == 0)
  57812. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  57813. }
  57814. }
  57815. else
  57816. {
  57817. deleteAndZero (resizableCorner);
  57818. deleteAndZero (resizableBorder);
  57819. }
  57820. if (isUsingNativeTitleBar())
  57821. recreateDesktopWindow();
  57822. childBoundsChanged (contentComponent);
  57823. resized();
  57824. }
  57825. bool ResizableWindow::isResizable() const throw()
  57826. {
  57827. return resizableCorner != 0
  57828. || resizableBorder != 0;
  57829. }
  57830. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  57831. const int newMinimumHeight,
  57832. const int newMaximumWidth,
  57833. const int newMaximumHeight) throw()
  57834. {
  57835. // if you've set up a custom constrainer then these settings won't have any effect..
  57836. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  57837. if (constrainer == 0)
  57838. setConstrainer (&defaultConstrainer);
  57839. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  57840. newMaximumWidth, newMaximumHeight);
  57841. setBoundsConstrained (getX(), getY(), getWidth(), getHeight());
  57842. }
  57843. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  57844. {
  57845. if (constrainer != newConstrainer)
  57846. {
  57847. constrainer = newConstrainer;
  57848. const bool useBottomRightCornerResizer = resizableCorner != 0;
  57849. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  57850. deleteAndZero (resizableCorner);
  57851. deleteAndZero (resizableBorder);
  57852. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  57853. ComponentPeer* const peer = getPeer();
  57854. if (peer != 0)
  57855. peer->setConstrainer (newConstrainer);
  57856. }
  57857. }
  57858. void ResizableWindow::setBoundsConstrained (int x, int y, int w, int h)
  57859. {
  57860. if (constrainer != 0)
  57861. constrainer->setBoundsForComponent (this, x, y, w, h, false, false, false, false);
  57862. else
  57863. setBounds (x, y, w, h);
  57864. }
  57865. void ResizableWindow::paint (Graphics& g)
  57866. {
  57867. g.fillAll (backgroundColour);
  57868. if (! isFullScreen())
  57869. {
  57870. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  57871. getBorderThickness(), *this);
  57872. }
  57873. #ifdef JUCE_DEBUG
  57874. /* If this fails, then you've probably written a subclass with a resized()
  57875. callback but forgotten to make it call its parent class's resized() method.
  57876. It's important when you override methods like resized(), moved(),
  57877. etc., that you make sure the base class methods also get called.
  57878. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  57879. because your content should all be inside the content component - and it's the
  57880. content component's resized() method that you should be using to do your
  57881. layout.
  57882. */
  57883. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  57884. #endif
  57885. }
  57886. void ResizableWindow::lookAndFeelChanged()
  57887. {
  57888. resized();
  57889. if (isOnDesktop())
  57890. {
  57891. Component::addToDesktop (getDesktopWindowStyleFlags());
  57892. ComponentPeer* const peer = getPeer();
  57893. if (peer != 0)
  57894. peer->setConstrainer (constrainer);
  57895. }
  57896. }
  57897. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  57898. {
  57899. if (Desktop::canUseSemiTransparentWindows())
  57900. backgroundColour = newColour;
  57901. else
  57902. backgroundColour = newColour.withAlpha (1.0f);
  57903. setOpaque (backgroundColour.isOpaque());
  57904. repaint();
  57905. }
  57906. bool ResizableWindow::isFullScreen() const
  57907. {
  57908. if (isOnDesktop())
  57909. {
  57910. ComponentPeer* const peer = getPeer();
  57911. return peer != 0 && peer->isFullScreen();
  57912. }
  57913. return fullscreen;
  57914. }
  57915. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  57916. {
  57917. if (shouldBeFullScreen != isFullScreen())
  57918. {
  57919. updateLastPos();
  57920. fullscreen = shouldBeFullScreen;
  57921. if (isOnDesktop())
  57922. {
  57923. ComponentPeer* const peer = getPeer();
  57924. if (peer != 0)
  57925. {
  57926. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  57927. const Rectangle lastPos (lastNonFullScreenPos);
  57928. peer->setFullScreen (shouldBeFullScreen);
  57929. if (! shouldBeFullScreen)
  57930. setBounds (lastPos);
  57931. }
  57932. else
  57933. {
  57934. jassertfalse
  57935. }
  57936. }
  57937. else
  57938. {
  57939. if (shouldBeFullScreen)
  57940. setBounds (0, 0, getParentWidth(), getParentHeight());
  57941. else
  57942. setBounds (lastNonFullScreenPos);
  57943. }
  57944. resized();
  57945. }
  57946. }
  57947. bool ResizableWindow::isMinimised() const
  57948. {
  57949. ComponentPeer* const peer = getPeer();
  57950. return (peer != 0) && peer->isMinimised();
  57951. }
  57952. void ResizableWindow::setMinimised (const bool shouldMinimise)
  57953. {
  57954. if (shouldMinimise != isMinimised())
  57955. {
  57956. ComponentPeer* const peer = getPeer();
  57957. if (peer != 0)
  57958. {
  57959. updateLastPos();
  57960. peer->setMinimised (shouldMinimise);
  57961. }
  57962. else
  57963. {
  57964. jassertfalse
  57965. }
  57966. }
  57967. }
  57968. void ResizableWindow::updateLastPos()
  57969. {
  57970. if (isShowing() && ! (isFullScreen() || isMinimised()))
  57971. {
  57972. lastNonFullScreenPos = getBounds();
  57973. }
  57974. }
  57975. void ResizableWindow::parentSizeChanged()
  57976. {
  57977. if (isFullScreen() && getParentComponent() != 0)
  57978. {
  57979. setBounds (0, 0, getParentWidth(), getParentHeight());
  57980. }
  57981. }
  57982. const String ResizableWindow::getWindowStateAsString()
  57983. {
  57984. updateLastPos();
  57985. String s;
  57986. if (isFullScreen())
  57987. s << "fs ";
  57988. s << lastNonFullScreenPos.getX() << T(' ')
  57989. << lastNonFullScreenPos.getY() << T(' ')
  57990. << lastNonFullScreenPos.getWidth() << T(' ')
  57991. << lastNonFullScreenPos.getHeight();
  57992. return s;
  57993. }
  57994. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  57995. {
  57996. StringArray tokens;
  57997. tokens.addTokens (s, false);
  57998. tokens.removeEmptyStrings();
  57999. tokens.trim();
  58000. const bool fs = tokens[0].startsWithIgnoreCase (T("fs"));
  58001. const int n = fs ? 1 : 0;
  58002. if (tokens.size() != 4 + n)
  58003. return false;
  58004. Rectangle r (tokens[n].getIntValue(),
  58005. tokens[n + 1].getIntValue(),
  58006. tokens[n + 2].getIntValue(),
  58007. tokens[n + 3].getIntValue());
  58008. if (r.isEmpty())
  58009. return false;
  58010. const Rectangle screen (Desktop::getInstance().getMonitorAreaContaining (r.getX(), r.getY()));
  58011. r = r.getIntersection (screen);
  58012. lastNonFullScreenPos = r;
  58013. if (isOnDesktop())
  58014. {
  58015. ComponentPeer* const peer = getPeer();
  58016. if (peer != 0)
  58017. peer->setNonFullScreenBounds (r);
  58018. }
  58019. setFullScreen (fs);
  58020. if (! fs)
  58021. setBoundsConstrained (r.getX(),
  58022. r.getY(),
  58023. r.getWidth(),
  58024. r.getHeight());
  58025. return true;
  58026. }
  58027. void ResizableWindow::mouseDown (const MouseEvent&)
  58028. {
  58029. if (! isFullScreen())
  58030. dragger.startDraggingComponent (this, constrainer);
  58031. }
  58032. void ResizableWindow::mouseDrag (const MouseEvent& e)
  58033. {
  58034. if (! isFullScreen())
  58035. dragger.dragComponent (this, e);
  58036. }
  58037. #ifdef JUCE_DEBUG
  58038. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  58039. {
  58040. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  58041. manages its child components automatically, and if you add your own it'll cause
  58042. trouble. Instead, use setContentComponent() to give it a component which
  58043. will be automatically resized and kept in the right place - then you can add
  58044. subcomponents to the content comp. See the notes for the ResizableWindow class
  58045. for more info.
  58046. If you really know what you're doing and want to avoid this assertion, just call
  58047. Component::addChildComponent directly.
  58048. */
  58049. jassertfalse
  58050. Component::addChildComponent (child, zOrder);
  58051. }
  58052. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  58053. {
  58054. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  58055. manages its child components automatically, and if you add your own it'll cause
  58056. trouble. Instead, use setContentComponent() to give it a component which
  58057. will be automatically resized and kept in the right place - then you can add
  58058. subcomponents to the content comp. See the notes for the ResizableWindow class
  58059. for more info.
  58060. If you really know what you're doing and want to avoid this assertion, just call
  58061. Component::addAndMakeVisible directly.
  58062. */
  58063. jassertfalse
  58064. Component::addAndMakeVisible (child, zOrder);
  58065. }
  58066. #endif
  58067. END_JUCE_NAMESPACE
  58068. /********* End of inlined file: juce_ResizableWindow.cpp *********/
  58069. /********* Start of inlined file: juce_SplashScreen.cpp *********/
  58070. BEGIN_JUCE_NAMESPACE
  58071. SplashScreen::SplashScreen()
  58072. : backgroundImage (0),
  58073. isImageInCache (false)
  58074. {
  58075. setOpaque (true);
  58076. }
  58077. SplashScreen::~SplashScreen()
  58078. {
  58079. if (isImageInCache)
  58080. ImageCache::release (backgroundImage);
  58081. else
  58082. delete backgroundImage;
  58083. }
  58084. void SplashScreen::show (const String& title,
  58085. Image* const backgroundImage_,
  58086. const int minimumTimeToDisplayFor,
  58087. const bool useDropShadow,
  58088. const bool removeOnMouseClick)
  58089. {
  58090. backgroundImage = backgroundImage_;
  58091. jassert (backgroundImage_ != 0);
  58092. if (backgroundImage_ != 0)
  58093. {
  58094. isImageInCache = ImageCache::isImageInCache (backgroundImage_);
  58095. setOpaque (! backgroundImage_->hasAlphaChannel());
  58096. show (title,
  58097. backgroundImage_->getWidth(),
  58098. backgroundImage_->getHeight(),
  58099. minimumTimeToDisplayFor,
  58100. useDropShadow,
  58101. removeOnMouseClick);
  58102. }
  58103. }
  58104. void SplashScreen::show (const String& title,
  58105. const int width,
  58106. const int height,
  58107. const int minimumTimeToDisplayFor,
  58108. const bool useDropShadow,
  58109. const bool removeOnMouseClick)
  58110. {
  58111. setName (title);
  58112. setAlwaysOnTop (true);
  58113. setVisible (true);
  58114. centreWithSize (width, height);
  58115. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  58116. toFront (false);
  58117. MessageManager::getInstance()->dispatchPendingMessages();
  58118. repaint();
  58119. originalClickCounter = removeOnMouseClick
  58120. ? Desktop::getMouseButtonClickCounter()
  58121. : INT_MAX;
  58122. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  58123. startTimer (50);
  58124. }
  58125. void SplashScreen::paint (Graphics& g)
  58126. {
  58127. if (backgroundImage != 0)
  58128. {
  58129. g.setOpacity (1.0f);
  58130. g.drawImage (backgroundImage,
  58131. 0, 0, getWidth(), getHeight(),
  58132. 0, 0, backgroundImage->getWidth(), backgroundImage->getHeight());
  58133. }
  58134. }
  58135. void SplashScreen::timerCallback()
  58136. {
  58137. if (Time::getCurrentTime() > earliestTimeToDelete
  58138. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  58139. {
  58140. delete this;
  58141. }
  58142. }
  58143. END_JUCE_NAMESPACE
  58144. /********* End of inlined file: juce_SplashScreen.cpp *********/
  58145. /********* Start of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  58146. BEGIN_JUCE_NAMESPACE
  58147. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  58148. const bool hasProgressBar,
  58149. const bool hasCancelButton,
  58150. const int timeOutMsWhenCancelling_,
  58151. const String& cancelButtonText)
  58152. : Thread ("Juce Progress Window"),
  58153. progress (0.0),
  58154. alertWindow (title, String::empty, AlertWindow::NoIcon),
  58155. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  58156. {
  58157. if (hasProgressBar)
  58158. alertWindow.addProgressBarComponent (progress);
  58159. if (hasCancelButton)
  58160. alertWindow.addButton (cancelButtonText, 1);
  58161. }
  58162. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  58163. {
  58164. stopThread (timeOutMsWhenCancelling);
  58165. }
  58166. bool ThreadWithProgressWindow::runThread (const int priority)
  58167. {
  58168. startThread (priority);
  58169. startTimer (100);
  58170. {
  58171. const ScopedLock sl (messageLock);
  58172. alertWindow.setMessage (message);
  58173. }
  58174. const bool wasCancelled = alertWindow.runModalLoop() != 0;
  58175. stopThread (timeOutMsWhenCancelling);
  58176. alertWindow.setVisible (false);
  58177. return ! wasCancelled;
  58178. }
  58179. void ThreadWithProgressWindow::setProgress (const double newProgress)
  58180. {
  58181. progress = newProgress;
  58182. }
  58183. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  58184. {
  58185. const ScopedLock sl (messageLock);
  58186. message = newStatusMessage;
  58187. }
  58188. void ThreadWithProgressWindow::timerCallback()
  58189. {
  58190. if (! isThreadRunning())
  58191. {
  58192. // thread has finished normally..
  58193. alertWindow.exitModalState (0);
  58194. alertWindow.setVisible (false);
  58195. }
  58196. else
  58197. {
  58198. const ScopedLock sl (messageLock);
  58199. alertWindow.setMessage (message);
  58200. }
  58201. }
  58202. END_JUCE_NAMESPACE
  58203. /********* End of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  58204. /********* Start of inlined file: juce_TooltipWindow.cpp *********/
  58205. BEGIN_JUCE_NAMESPACE
  58206. TooltipWindow::TooltipWindow (Component* const parentComponent,
  58207. const int millisecondsBeforeTipAppears_)
  58208. : Component ("tooltip"),
  58209. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  58210. mouseX (0),
  58211. mouseY (0),
  58212. lastMouseMoveTime (0),
  58213. lastHideTime (0),
  58214. lastComponentUnderMouse (0),
  58215. changedCompsSinceShown (true)
  58216. {
  58217. startTimer (123);
  58218. setAlwaysOnTop (true);
  58219. setOpaque (true);
  58220. if (parentComponent != 0)
  58221. {
  58222. parentComponent->addChildComponent (this);
  58223. }
  58224. else
  58225. {
  58226. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  58227. addToDesktop (ComponentPeer::windowHasDropShadow
  58228. | ComponentPeer::windowIsTemporary);
  58229. }
  58230. }
  58231. TooltipWindow::~TooltipWindow()
  58232. {
  58233. }
  58234. void TooltipWindow::paint (Graphics& g)
  58235. {
  58236. getLookAndFeel().drawTooltip (g, tip, getWidth(), getHeight());
  58237. }
  58238. void TooltipWindow::mouseEnter (const MouseEvent&)
  58239. {
  58240. setVisible (false);
  58241. }
  58242. void TooltipWindow::showFor (Component* const c)
  58243. {
  58244. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  58245. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  58246. tip = ttc->getTooltip();
  58247. else
  58248. tip = String::empty;
  58249. if (tip.isEmpty())
  58250. {
  58251. setVisible (false);
  58252. }
  58253. else
  58254. {
  58255. int mx, my;
  58256. Desktop::getMousePosition (mx, my);
  58257. if (getParentComponent() != 0)
  58258. getParentComponent()->globalPositionToRelative (mx, my);
  58259. int x, y, w, h;
  58260. getLookAndFeel().getTooltipSize (tip, w, h);
  58261. if (mx > getParentWidth() / 2)
  58262. x = mx - (w + 12);
  58263. else
  58264. x = mx + 24;
  58265. if (my > getParentHeight() / 2)
  58266. y = my - (h + 6);
  58267. else
  58268. y = my + 6;
  58269. setBounds (x, y, w, h);
  58270. setVisible (true);
  58271. toFront (false);
  58272. }
  58273. }
  58274. void TooltipWindow::timerCallback()
  58275. {
  58276. int mx, my;
  58277. Desktop::getMousePosition (mx, my);
  58278. const unsigned int now = Time::getApproximateMillisecondCounter();
  58279. Component* const underMouse = Component::getComponentUnderMouse();
  58280. const bool changedComp = (underMouse != lastComponentUnderMouse);
  58281. lastComponentUnderMouse = underMouse;
  58282. if (changedComp
  58283. || abs (mx - mouseX) > 4
  58284. || abs (my - mouseY) > 4
  58285. || Desktop::getInstance().getMouseButtonClickCounter() > mouseClicks)
  58286. {
  58287. lastMouseMoveTime = now;
  58288. if (isVisible())
  58289. {
  58290. lastHideTime = now;
  58291. setVisible (false);
  58292. }
  58293. changedCompsSinceShown = changedCompsSinceShown || changedComp;
  58294. tip = String::empty;
  58295. mouseX = mx;
  58296. mouseY = my;
  58297. }
  58298. if (changedCompsSinceShown)
  58299. {
  58300. if ((now > lastMouseMoveTime + millisecondsBeforeTipAppears
  58301. || now < lastHideTime + 500)
  58302. && ! isVisible())
  58303. {
  58304. if (underMouse->isValidComponent())
  58305. showFor (underMouse);
  58306. changedCompsSinceShown = false;
  58307. }
  58308. }
  58309. mouseClicks = Desktop::getInstance().getMouseButtonClickCounter();
  58310. }
  58311. END_JUCE_NAMESPACE
  58312. /********* End of inlined file: juce_TooltipWindow.cpp *********/
  58313. /********* Start of inlined file: juce_TopLevelWindow.cpp *********/
  58314. BEGIN_JUCE_NAMESPACE
  58315. /** Keeps track of the active top level window.
  58316. */
  58317. class TopLevelWindowManager : public Timer,
  58318. public DeletedAtShutdown
  58319. {
  58320. public:
  58321. TopLevelWindowManager()
  58322. : windows (8),
  58323. currentActive (0)
  58324. {
  58325. }
  58326. ~TopLevelWindowManager()
  58327. {
  58328. clearSingletonInstance();
  58329. }
  58330. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  58331. void timerCallback()
  58332. {
  58333. startTimer (1731);
  58334. TopLevelWindow* active = 0;
  58335. if (Process::isForegroundProcess())
  58336. {
  58337. active = currentActive;
  58338. Component* const c = Component::getCurrentlyFocusedComponent();
  58339. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  58340. if (tlw == 0 && c != 0)
  58341. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  58342. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  58343. if (tlw != 0)
  58344. active = tlw;
  58345. }
  58346. if (active != currentActive)
  58347. {
  58348. currentActive = active;
  58349. for (int i = windows.size(); --i >= 0;)
  58350. {
  58351. TopLevelWindow* const tlw = (TopLevelWindow*) windows.getUnchecked (i);
  58352. tlw->setWindowActive (isWindowActive (tlw));
  58353. i = jmin (i, windows.size() - 1);
  58354. }
  58355. Desktop::getInstance().triggerFocusCallback();
  58356. }
  58357. }
  58358. bool addWindow (TopLevelWindow* const w) throw()
  58359. {
  58360. windows.add (w);
  58361. startTimer (10);
  58362. return isWindowActive (w);
  58363. }
  58364. void removeWindow (TopLevelWindow* const w) throw()
  58365. {
  58366. startTimer (10);
  58367. if (currentActive == w)
  58368. currentActive = 0;
  58369. windows.removeValue (w);
  58370. if (windows.size() == 0)
  58371. deleteInstance();
  58372. }
  58373. VoidArray windows;
  58374. private:
  58375. TopLevelWindow* currentActive;
  58376. bool isWindowActive (TopLevelWindow* const tlw) const throw()
  58377. {
  58378. return (tlw == currentActive
  58379. || tlw->isParentOf (currentActive)
  58380. || tlw->hasKeyboardFocus (true))
  58381. && tlw->isShowing();
  58382. }
  58383. TopLevelWindowManager (const TopLevelWindowManager&);
  58384. const TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  58385. };
  58386. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  58387. void juce_CheckCurrentlyFocusedTopLevelWindow() throw()
  58388. {
  58389. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  58390. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  58391. }
  58392. TopLevelWindow::TopLevelWindow (const String& name,
  58393. const bool addToDesktop_)
  58394. : Component (name),
  58395. useDropShadow (true),
  58396. useNativeTitleBar (false),
  58397. windowIsActive_ (false),
  58398. shadower (0)
  58399. {
  58400. setOpaque (true);
  58401. if (addToDesktop_)
  58402. Component::addToDesktop (getDesktopWindowStyleFlags());
  58403. else
  58404. setDropShadowEnabled (true);
  58405. setWantsKeyboardFocus (true);
  58406. setBroughtToFrontOnMouseClick (true);
  58407. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  58408. }
  58409. TopLevelWindow::~TopLevelWindow()
  58410. {
  58411. deleteAndZero (shadower);
  58412. TopLevelWindowManager::getInstance()->removeWindow (this);
  58413. }
  58414. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  58415. {
  58416. if (hasKeyboardFocus (true))
  58417. TopLevelWindowManager::getInstance()->timerCallback();
  58418. else
  58419. TopLevelWindowManager::getInstance()->startTimer (10);
  58420. }
  58421. void TopLevelWindow::setWindowActive (const bool isNowActive) throw()
  58422. {
  58423. if (windowIsActive_ != isNowActive)
  58424. {
  58425. windowIsActive_ = isNowActive;
  58426. activeWindowStatusChanged();
  58427. }
  58428. }
  58429. void TopLevelWindow::activeWindowStatusChanged()
  58430. {
  58431. }
  58432. void TopLevelWindow::parentHierarchyChanged()
  58433. {
  58434. setDropShadowEnabled (useDropShadow);
  58435. }
  58436. void TopLevelWindow::visibilityChanged()
  58437. {
  58438. if (isShowing())
  58439. toFront (true);
  58440. }
  58441. int TopLevelWindow::getDesktopWindowStyleFlags() const
  58442. {
  58443. int flags = ComponentPeer::windowAppearsOnTaskbar;
  58444. if (useDropShadow)
  58445. flags |= ComponentPeer::windowHasDropShadow;
  58446. if (useNativeTitleBar)
  58447. flags |= ComponentPeer::windowHasTitleBar;
  58448. return flags;
  58449. }
  58450. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  58451. {
  58452. useDropShadow = useShadow;
  58453. if (isOnDesktop())
  58454. {
  58455. deleteAndZero (shadower);
  58456. Component::addToDesktop (getDesktopWindowStyleFlags());
  58457. }
  58458. else
  58459. {
  58460. if (useShadow && isOpaque())
  58461. {
  58462. if (shadower == 0)
  58463. {
  58464. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  58465. if (shadower != 0)
  58466. shadower->setOwner (this);
  58467. }
  58468. }
  58469. else
  58470. {
  58471. deleteAndZero (shadower);
  58472. }
  58473. }
  58474. }
  58475. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  58476. {
  58477. if (useNativeTitleBar != useNativeTitleBar_)
  58478. {
  58479. useNativeTitleBar = useNativeTitleBar_;
  58480. recreateDesktopWindow();
  58481. sendLookAndFeelChange();
  58482. }
  58483. }
  58484. void TopLevelWindow::recreateDesktopWindow()
  58485. {
  58486. if (isOnDesktop())
  58487. {
  58488. Component::addToDesktop (getDesktopWindowStyleFlags());
  58489. toFront (true);
  58490. }
  58491. }
  58492. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  58493. {
  58494. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  58495. because this class needs to make sure its layout corresponds with settings like whether
  58496. it's got a native title bar or not.
  58497. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  58498. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  58499. method, then add or remove whatever flags are necessary from this value before returning it.
  58500. */
  58501. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  58502. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  58503. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  58504. if (windowStyleFlags != getDesktopWindowStyleFlags())
  58505. sendLookAndFeelChange();
  58506. }
  58507. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  58508. {
  58509. if (c == 0)
  58510. c = TopLevelWindow::getActiveTopLevelWindow();
  58511. if (c == 0)
  58512. {
  58513. centreWithSize (width, height);
  58514. }
  58515. else
  58516. {
  58517. int x = (c->getWidth() - width) / 2;
  58518. int y = (c->getHeight() - height) / 2;
  58519. c->relativePositionToGlobal (x, y);
  58520. Rectangle parentArea (c->getParentMonitorArea());
  58521. if (getParentComponent() != 0)
  58522. {
  58523. getParentComponent()->globalPositionToRelative (x, y);
  58524. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  58525. }
  58526. parentArea.reduce (12, 12);
  58527. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), x),
  58528. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), y),
  58529. width, height);
  58530. }
  58531. }
  58532. int TopLevelWindow::getNumTopLevelWindows() throw()
  58533. {
  58534. return TopLevelWindowManager::getInstance()->windows.size();
  58535. }
  58536. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  58537. {
  58538. return (TopLevelWindow*) TopLevelWindowManager::getInstance()->windows [index];
  58539. }
  58540. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  58541. {
  58542. TopLevelWindow* best = 0;
  58543. int bestNumTWLParents = -1;
  58544. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  58545. {
  58546. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  58547. if (tlw->isActiveWindow())
  58548. {
  58549. int numTWLParents = 0;
  58550. const Component* c = tlw->getParentComponent();
  58551. while (c != 0)
  58552. {
  58553. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  58554. ++numTWLParents;
  58555. c = c->getParentComponent();
  58556. }
  58557. if (bestNumTWLParents < numTWLParents)
  58558. {
  58559. best = tlw;
  58560. bestNumTWLParents = numTWLParents;
  58561. }
  58562. }
  58563. }
  58564. return best;
  58565. }
  58566. END_JUCE_NAMESPACE
  58567. /********* End of inlined file: juce_TopLevelWindow.cpp *********/
  58568. /********* Start of inlined file: juce_Brush.cpp *********/
  58569. BEGIN_JUCE_NAMESPACE
  58570. Brush::Brush() throw()
  58571. {
  58572. }
  58573. Brush::~Brush() throw()
  58574. {
  58575. }
  58576. void Brush::paintVerticalLine (LowLevelGraphicsContext& context,
  58577. int x, float y1, float y2) throw()
  58578. {
  58579. Path p;
  58580. p.addRectangle ((float) x, y1, 1.0f, y2 - y1);
  58581. paintPath (context, p, AffineTransform::identity);
  58582. }
  58583. void Brush::paintHorizontalLine (LowLevelGraphicsContext& context,
  58584. int y, float x1, float x2) throw()
  58585. {
  58586. Path p;
  58587. p.addRectangle (x1, (float) y, x2 - x1, 1.0f);
  58588. paintPath (context, p, AffineTransform::identity);
  58589. }
  58590. void Brush::paintLine (LowLevelGraphicsContext& context,
  58591. float x1, float y1, float x2, float y2) throw()
  58592. {
  58593. Path p;
  58594. p.addLineSegment (x1, y1, x2, y2, 1.0f);
  58595. paintPath (context, p, AffineTransform::identity);
  58596. }
  58597. END_JUCE_NAMESPACE
  58598. /********* End of inlined file: juce_Brush.cpp *********/
  58599. /********* Start of inlined file: juce_GradientBrush.cpp *********/
  58600. BEGIN_JUCE_NAMESPACE
  58601. GradientBrush::GradientBrush (const Colour& colour1,
  58602. const float x1,
  58603. const float y1,
  58604. const Colour& colour2,
  58605. const float x2,
  58606. const float y2,
  58607. const bool isRadial) throw()
  58608. : gradient (colour1, x1, y1,
  58609. colour2, x2, y2,
  58610. isRadial)
  58611. {
  58612. }
  58613. GradientBrush::GradientBrush (const ColourGradient& gradient_) throw()
  58614. : gradient (gradient_)
  58615. {
  58616. }
  58617. GradientBrush::~GradientBrush() throw()
  58618. {
  58619. }
  58620. Brush* GradientBrush::createCopy() const throw()
  58621. {
  58622. return new GradientBrush (gradient);
  58623. }
  58624. void GradientBrush::applyTransform (const AffineTransform& transform) throw()
  58625. {
  58626. gradient.transform = gradient.transform.followedBy (transform);
  58627. }
  58628. void GradientBrush::multiplyOpacity (const float multiple) throw()
  58629. {
  58630. gradient.multiplyOpacity (multiple);
  58631. }
  58632. bool GradientBrush::isInvisible() const throw()
  58633. {
  58634. return gradient.isInvisible();
  58635. }
  58636. void GradientBrush::paintPath (LowLevelGraphicsContext& context,
  58637. const Path& path, const AffineTransform& transform) throw()
  58638. {
  58639. context.fillPathWithGradient (path, transform, gradient, EdgeTable::Oversampling_4times);
  58640. }
  58641. void GradientBrush::paintRectangle (LowLevelGraphicsContext& context,
  58642. int x, int y, int w, int h) throw()
  58643. {
  58644. context.fillRectWithGradient (x, y, w, h, gradient);
  58645. }
  58646. void GradientBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  58647. const Image& alphaChannelImage, int imageX, int imageY,
  58648. int x, int y, int w, int h) throw()
  58649. {
  58650. context.saveState();
  58651. if (context.reduceClipRegion (x, y, w, h))
  58652. context.fillAlphaChannelWithGradient (alphaChannelImage, imageX, imageY, gradient);
  58653. context.restoreState();
  58654. }
  58655. END_JUCE_NAMESPACE
  58656. /********* End of inlined file: juce_GradientBrush.cpp *********/
  58657. /********* Start of inlined file: juce_ImageBrush.cpp *********/
  58658. BEGIN_JUCE_NAMESPACE
  58659. ImageBrush::ImageBrush (Image* const image_,
  58660. const int anchorX_,
  58661. const int anchorY_,
  58662. const float opacity_) throw()
  58663. : image (image_),
  58664. anchorX (anchorX_),
  58665. anchorY (anchorY_),
  58666. opacity (opacity_)
  58667. {
  58668. jassert (image != 0); // not much point creating a brush without an image, is there?
  58669. if (image != 0)
  58670. {
  58671. if (image->getWidth() == 0 || image->getHeight() == 0)
  58672. {
  58673. jassertfalse // you've passed in an empty image - not exactly brilliant for tiling.
  58674. image = 0;
  58675. }
  58676. }
  58677. }
  58678. ImageBrush::~ImageBrush() throw()
  58679. {
  58680. }
  58681. Brush* ImageBrush::createCopy() const throw()
  58682. {
  58683. return new ImageBrush (image, anchorX, anchorY, opacity);
  58684. }
  58685. void ImageBrush::multiplyOpacity (const float multiple) throw()
  58686. {
  58687. opacity *= multiple;
  58688. }
  58689. bool ImageBrush::isInvisible() const throw()
  58690. {
  58691. return opacity == 0.0f;
  58692. }
  58693. void ImageBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  58694. {
  58695. //xxx should probably be smarter and warp the image
  58696. }
  58697. void ImageBrush::getStartXY (int& x, int& y) const throw()
  58698. {
  58699. x -= anchorX;
  58700. y -= anchorY;
  58701. const int iw = image->getWidth();
  58702. const int ih = image->getHeight();
  58703. if (x < 0)
  58704. x = ((x / iw) - 1) * iw;
  58705. else
  58706. x = (x / iw) * iw;
  58707. if (y < 0)
  58708. y = ((y / ih) - 1) * ih;
  58709. else
  58710. y = (y / ih) * ih;
  58711. x += anchorX;
  58712. y += anchorY;
  58713. }
  58714. void ImageBrush::paintRectangle (LowLevelGraphicsContext& context,
  58715. int x, int y, int w, int h) throw()
  58716. {
  58717. context.saveState();
  58718. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  58719. {
  58720. const int right = x + w;
  58721. const int bottom = y + h;
  58722. const int iw = image->getWidth();
  58723. const int ih = image->getHeight();
  58724. int startX = x;
  58725. getStartXY (startX, y);
  58726. while (y < bottom)
  58727. {
  58728. x = startX;
  58729. while (x < right)
  58730. {
  58731. context.blendImage (*image, x, y, iw, ih, 0, 0, opacity);
  58732. x += iw;
  58733. }
  58734. y += ih;
  58735. }
  58736. }
  58737. context.restoreState();
  58738. }
  58739. void ImageBrush::paintPath (LowLevelGraphicsContext& context,
  58740. const Path& path, const AffineTransform& transform) throw()
  58741. {
  58742. if (image != 0)
  58743. {
  58744. Rectangle clip (context.getClipBounds());
  58745. {
  58746. float x, y, w, h;
  58747. path.getBoundsTransformed (transform, x, y, w, h);
  58748. clip = clip.getIntersection (Rectangle ((int) floorf (x),
  58749. (int) floorf (y),
  58750. 2 + (int) floorf (w),
  58751. 2 + (int) floorf (h)));
  58752. }
  58753. int x = clip.getX();
  58754. int y = clip.getY();
  58755. const int right = clip.getRight();
  58756. const int bottom = clip.getBottom();
  58757. const int iw = image->getWidth();
  58758. const int ih = image->getHeight();
  58759. int startX = x;
  58760. getStartXY (startX, y);
  58761. while (y < bottom)
  58762. {
  58763. x = startX;
  58764. while (x < right)
  58765. {
  58766. context.fillPathWithImage (path, transform, *image, x, y, opacity, EdgeTable::Oversampling_4times);
  58767. x += iw;
  58768. }
  58769. y += ih;
  58770. }
  58771. }
  58772. }
  58773. void ImageBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  58774. const Image& alphaChannelImage, int imageX, int imageY,
  58775. int x, int y, int w, int h) throw()
  58776. {
  58777. context.saveState();
  58778. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  58779. {
  58780. const Rectangle clip (context.getClipBounds());
  58781. x = clip.getX();
  58782. y = clip.getY();
  58783. const int right = clip.getRight();
  58784. const int bottom = clip.getBottom();
  58785. const int iw = image->getWidth();
  58786. const int ih = image->getHeight();
  58787. int startX = x;
  58788. getStartXY (startX, y);
  58789. while (y < bottom)
  58790. {
  58791. x = startX;
  58792. while (x < right)
  58793. {
  58794. context.fillAlphaChannelWithImage (alphaChannelImage,
  58795. imageX, imageY, *image,
  58796. x, y, opacity);
  58797. x += iw;
  58798. }
  58799. y += ih;
  58800. }
  58801. }
  58802. context.restoreState();
  58803. }
  58804. END_JUCE_NAMESPACE
  58805. /********* End of inlined file: juce_ImageBrush.cpp *********/
  58806. /********* Start of inlined file: juce_SolidColourBrush.cpp *********/
  58807. BEGIN_JUCE_NAMESPACE
  58808. SolidColourBrush::SolidColourBrush() throw()
  58809. : colour (0xff000000)
  58810. {
  58811. }
  58812. SolidColourBrush::SolidColourBrush (const Colour& colour_) throw()
  58813. : colour (colour_)
  58814. {
  58815. }
  58816. SolidColourBrush::~SolidColourBrush() throw()
  58817. {
  58818. }
  58819. Brush* SolidColourBrush::createCopy() const throw()
  58820. {
  58821. return new SolidColourBrush (colour);
  58822. }
  58823. void SolidColourBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  58824. {
  58825. }
  58826. void SolidColourBrush::multiplyOpacity (const float multiple) throw()
  58827. {
  58828. colour = colour.withMultipliedAlpha (multiple);
  58829. }
  58830. bool SolidColourBrush::isInvisible() const throw()
  58831. {
  58832. return colour.isTransparent();
  58833. }
  58834. void SolidColourBrush::paintPath (LowLevelGraphicsContext& context,
  58835. const Path& path, const AffineTransform& transform) throw()
  58836. {
  58837. if (! colour.isTransparent())
  58838. context.fillPathWithColour (path, transform, colour, EdgeTable::Oversampling_4times);
  58839. }
  58840. void SolidColourBrush::paintRectangle (LowLevelGraphicsContext& context,
  58841. int x, int y, int w, int h) throw()
  58842. {
  58843. if (! colour.isTransparent())
  58844. context.fillRectWithColour (x, y, w, h, colour, false);
  58845. }
  58846. void SolidColourBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  58847. const Image& alphaChannelImage, int imageX, int imageY,
  58848. int x, int y, int w, int h) throw()
  58849. {
  58850. if (! colour.isTransparent())
  58851. {
  58852. context.saveState();
  58853. if (context.reduceClipRegion (x, y, w, h))
  58854. context.fillAlphaChannelWithColour (alphaChannelImage, imageX, imageY, colour);
  58855. context.restoreState();
  58856. }
  58857. }
  58858. void SolidColourBrush::paintVerticalLine (LowLevelGraphicsContext& context,
  58859. int x, float y1, float y2) throw()
  58860. {
  58861. context.drawVerticalLine (x, y1, y2, colour);
  58862. }
  58863. void SolidColourBrush::paintHorizontalLine (LowLevelGraphicsContext& context,
  58864. int y, float x1, float x2) throw()
  58865. {
  58866. context.drawHorizontalLine (y, x1, x2, colour);
  58867. }
  58868. void SolidColourBrush::paintLine (LowLevelGraphicsContext& context,
  58869. float x1, float y1, float x2, float y2) throw()
  58870. {
  58871. context.drawLine (x1, y1, x2, y2, colour);
  58872. }
  58873. END_JUCE_NAMESPACE
  58874. /********* End of inlined file: juce_SolidColourBrush.cpp *********/
  58875. /********* Start of inlined file: juce_Colour.cpp *********/
  58876. BEGIN_JUCE_NAMESPACE
  58877. static forcedinline uint8 floatAlphaToInt (const float alpha)
  58878. {
  58879. return (uint8) jlimit (0, 0xff, roundFloatToInt (alpha * 255.0f));
  58880. }
  58881. static const float oneOver255 = 1.0f / 255.0f;
  58882. Colour::Colour() throw()
  58883. : argb (0)
  58884. {
  58885. }
  58886. Colour::Colour (const Colour& other) throw()
  58887. : argb (other.argb)
  58888. {
  58889. }
  58890. const Colour& Colour::operator= (const Colour& other) throw()
  58891. {
  58892. argb = other.argb;
  58893. return *this;
  58894. }
  58895. bool Colour::operator== (const Colour& other) const throw()
  58896. {
  58897. return argb.getARGB() == other.argb.getARGB();
  58898. }
  58899. bool Colour::operator!= (const Colour& other) const throw()
  58900. {
  58901. return argb.getARGB() != other.argb.getARGB();
  58902. }
  58903. Colour::Colour (const uint32 argb_) throw()
  58904. : argb (argb_)
  58905. {
  58906. }
  58907. Colour::Colour (const uint8 red,
  58908. const uint8 green,
  58909. const uint8 blue) throw()
  58910. {
  58911. argb.setARGB (0xff, red, green, blue);
  58912. }
  58913. const Colour Colour::fromRGB (const uint8 red,
  58914. const uint8 green,
  58915. const uint8 blue) throw()
  58916. {
  58917. return Colour (red, green, blue);
  58918. }
  58919. Colour::Colour (const uint8 red,
  58920. const uint8 green,
  58921. const uint8 blue,
  58922. const uint8 alpha) throw()
  58923. {
  58924. argb.setARGB (alpha, red, green, blue);
  58925. }
  58926. const Colour Colour::fromRGBA (const uint8 red,
  58927. const uint8 green,
  58928. const uint8 blue,
  58929. const uint8 alpha) throw()
  58930. {
  58931. return Colour (red, green, blue, alpha);
  58932. }
  58933. Colour::Colour (const uint8 red,
  58934. const uint8 green,
  58935. const uint8 blue,
  58936. const float alpha) throw()
  58937. {
  58938. argb.setARGB (floatAlphaToInt (alpha), red, green, blue);
  58939. }
  58940. const Colour Colour::fromRGBAFloat (const uint8 red,
  58941. const uint8 green,
  58942. const uint8 blue,
  58943. const float alpha) throw()
  58944. {
  58945. return Colour (red, green, blue, alpha);
  58946. }
  58947. static void convertHSBtoRGB (float h, const float s, float v,
  58948. uint8& r, uint8& g, uint8& b) throw()
  58949. {
  58950. v *= 255.0f;
  58951. const uint8 intV = (uint8) roundFloatToInt (v);
  58952. if (s == 0)
  58953. {
  58954. r = intV;
  58955. g = intV;
  58956. b = intV;
  58957. }
  58958. else
  58959. {
  58960. h = (h - floorf (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  58961. const float f = h - floorf (h);
  58962. const uint8 x = (uint8) roundFloatToInt (v * (1.0f - s));
  58963. const float y = v * (1.0f - s * f);
  58964. const float z = v * (1.0f - (s * (1.0f - f)));
  58965. if (h < 1.0f)
  58966. {
  58967. r = intV;
  58968. g = (uint8) roundFloatToInt (z);
  58969. b = x;
  58970. }
  58971. else if (h < 2.0f)
  58972. {
  58973. r = (uint8) roundFloatToInt (y);
  58974. g = intV;
  58975. b = x;
  58976. }
  58977. else if (h < 3.0f)
  58978. {
  58979. r = x;
  58980. g = intV;
  58981. b = (uint8) roundFloatToInt (z);
  58982. }
  58983. else if (h < 4.0f)
  58984. {
  58985. r = x;
  58986. g = (uint8) roundFloatToInt (y);
  58987. b = intV;
  58988. }
  58989. else if (h < 5.0f)
  58990. {
  58991. r = (uint8) roundFloatToInt (z);
  58992. g = x;
  58993. b = intV;
  58994. }
  58995. else if (h < 6.0f)
  58996. {
  58997. r = intV;
  58998. g = x;
  58999. b = (uint8) roundFloatToInt (y);
  59000. }
  59001. else
  59002. {
  59003. r = 0;
  59004. g = 0;
  59005. b = 0;
  59006. }
  59007. }
  59008. }
  59009. Colour::Colour (const float hue,
  59010. const float saturation,
  59011. const float brightness,
  59012. const float alpha) throw()
  59013. {
  59014. uint8 r = getRed(), g = getGreen(), b = getBlue();
  59015. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  59016. argb.setARGB (floatAlphaToInt (alpha), r, g, b);
  59017. }
  59018. const Colour Colour::fromHSV (const float hue,
  59019. const float saturation,
  59020. const float brightness,
  59021. const float alpha) throw()
  59022. {
  59023. return Colour (hue, saturation, brightness, alpha);
  59024. }
  59025. Colour::Colour (const float hue,
  59026. const float saturation,
  59027. const float brightness,
  59028. const uint8 alpha) throw()
  59029. {
  59030. uint8 r = getRed(), g = getGreen(), b = getBlue();
  59031. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  59032. argb.setARGB (alpha, r, g, b);
  59033. }
  59034. Colour::~Colour() throw()
  59035. {
  59036. }
  59037. const PixelARGB Colour::getPixelARGB() const throw()
  59038. {
  59039. PixelARGB p (argb);
  59040. p.premultiply();
  59041. return p;
  59042. }
  59043. uint32 Colour::getARGB() const throw()
  59044. {
  59045. return argb.getARGB();
  59046. }
  59047. bool Colour::isTransparent() const throw()
  59048. {
  59049. return getAlpha() == 0;
  59050. }
  59051. bool Colour::isOpaque() const throw()
  59052. {
  59053. return getAlpha() == 0xff;
  59054. }
  59055. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  59056. {
  59057. PixelARGB newCol (argb);
  59058. newCol.setAlpha (newAlpha);
  59059. return Colour (newCol.getARGB());
  59060. }
  59061. const Colour Colour::withAlpha (const float newAlpha) const throw()
  59062. {
  59063. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  59064. PixelARGB newCol (argb);
  59065. newCol.setAlpha (floatAlphaToInt (newAlpha));
  59066. return Colour (newCol.getARGB());
  59067. }
  59068. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  59069. {
  59070. jassert (alphaMultiplier >= 0);
  59071. PixelARGB newCol (argb);
  59072. newCol.setAlpha ((uint8) jmin (0xff, roundFloatToInt (alphaMultiplier * newCol.getAlpha())));
  59073. return Colour (newCol.getARGB());
  59074. }
  59075. const Colour Colour::overlaidWith (const Colour& src) const throw()
  59076. {
  59077. const int destAlpha = getAlpha();
  59078. if (destAlpha > 0)
  59079. {
  59080. const int invA = 0xff - (int) src.getAlpha();
  59081. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  59082. if (resA > 0)
  59083. {
  59084. const int da = (invA * destAlpha) / resA;
  59085. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  59086. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  59087. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  59088. (uint8) resA);
  59089. }
  59090. return *this;
  59091. }
  59092. else
  59093. {
  59094. return src;
  59095. }
  59096. }
  59097. float Colour::getFloatRed() const throw()
  59098. {
  59099. return getRed() * oneOver255;
  59100. }
  59101. float Colour::getFloatGreen() const throw()
  59102. {
  59103. return getGreen() * oneOver255;
  59104. }
  59105. float Colour::getFloatBlue() const throw()
  59106. {
  59107. return getBlue() * oneOver255;
  59108. }
  59109. float Colour::getFloatAlpha() const throw()
  59110. {
  59111. return getAlpha() * oneOver255;
  59112. }
  59113. void Colour::getHSB (float& h, float& s, float& v) const throw()
  59114. {
  59115. const int r = getRed();
  59116. const int g = getGreen();
  59117. const int b = getBlue();
  59118. const int hi = jmax (r, g, b);
  59119. const int lo = jmin (r, g, b);
  59120. if (hi != 0)
  59121. {
  59122. s = (hi - lo) / (float) hi;
  59123. if (s != 0)
  59124. {
  59125. const float invDiff = 1.0f / (hi - lo);
  59126. const float red = (hi - r) * invDiff;
  59127. const float green = (hi - g) * invDiff;
  59128. const float blue = (hi - b) * invDiff;
  59129. if (r == hi)
  59130. h = blue - green;
  59131. else if (g == hi)
  59132. h = 2.0f + red - blue;
  59133. else
  59134. h = 4.0f + green - red;
  59135. h *= 1.0f / 6.0f;
  59136. if (h < 0)
  59137. ++h;
  59138. }
  59139. else
  59140. {
  59141. h = 0;
  59142. }
  59143. }
  59144. else
  59145. {
  59146. s = 0;
  59147. h = 0;
  59148. }
  59149. v = hi * oneOver255;
  59150. }
  59151. float Colour::getHue() const throw()
  59152. {
  59153. float h, s, b;
  59154. getHSB (h, s, b);
  59155. return h;
  59156. }
  59157. const Colour Colour::withHue (const float hue) const throw()
  59158. {
  59159. float h, s, b;
  59160. getHSB (h, s, b);
  59161. return Colour (hue, s, b, getAlpha());
  59162. }
  59163. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  59164. {
  59165. float h, s, b;
  59166. getHSB (h, s, b);
  59167. h += amountToRotate;
  59168. h -= floorf (h);
  59169. return Colour (h, s, b, getAlpha());
  59170. }
  59171. float Colour::getSaturation() const throw()
  59172. {
  59173. float h, s, b;
  59174. getHSB (h, s, b);
  59175. return s;
  59176. }
  59177. const Colour Colour::withSaturation (const float saturation) const throw()
  59178. {
  59179. float h, s, b;
  59180. getHSB (h, s, b);
  59181. return Colour (h, saturation, b, getAlpha());
  59182. }
  59183. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  59184. {
  59185. float h, s, b;
  59186. getHSB (h, s, b);
  59187. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  59188. }
  59189. float Colour::getBrightness() const throw()
  59190. {
  59191. float h, s, b;
  59192. getHSB (h, s, b);
  59193. return b;
  59194. }
  59195. const Colour Colour::withBrightness (const float brightness) const throw()
  59196. {
  59197. float h, s, b;
  59198. getHSB (h, s, b);
  59199. return Colour (h, s, brightness, getAlpha());
  59200. }
  59201. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  59202. {
  59203. float h, s, b;
  59204. getHSB (h, s, b);
  59205. b *= amount;
  59206. if (b > 1.0f)
  59207. b = 1.0f;
  59208. return Colour (h, s, b, getAlpha());
  59209. }
  59210. const Colour Colour::brighter (float amount) const throw()
  59211. {
  59212. amount = 1.0f / (1.0f + amount);
  59213. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  59214. (uint8) (255 - (amount * (255 - getGreen()))),
  59215. (uint8) (255 - (amount * (255 - getBlue()))),
  59216. getAlpha());
  59217. }
  59218. const Colour Colour::darker (float amount) const throw()
  59219. {
  59220. amount = 1.0f / (1.0f + amount);
  59221. return Colour ((uint8) (amount * getRed()),
  59222. (uint8) (amount * getGreen()),
  59223. (uint8) (amount * getBlue()),
  59224. getAlpha());
  59225. }
  59226. const Colour Colour::greyLevel (const float brightness) throw()
  59227. {
  59228. const uint8 level
  59229. = (uint8) jlimit (0x00, 0xff, roundFloatToInt (brightness * 255.0f));
  59230. return Colour (level, level, level);
  59231. }
  59232. const Colour Colour::contrasting (const float amount) const throw()
  59233. {
  59234. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  59235. ? Colours::black
  59236. : Colours::white).withAlpha (amount));
  59237. }
  59238. const Colour Colour::contrasting (const Colour& colour1,
  59239. const Colour& colour2) throw()
  59240. {
  59241. const float b1 = colour1.getBrightness();
  59242. const float b2 = colour2.getBrightness();
  59243. float best = 0.0f;
  59244. float bestDist = 0.0f;
  59245. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  59246. {
  59247. const float d1 = fabsf (i - b1);
  59248. const float d2 = fabsf (i - b2);
  59249. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  59250. if (dist > bestDist)
  59251. {
  59252. best = i;
  59253. bestDist = dist;
  59254. }
  59255. }
  59256. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  59257. .withBrightness (best);
  59258. }
  59259. const String Colour::toString() const throw()
  59260. {
  59261. return String::toHexString ((int) argb.getARGB());
  59262. }
  59263. const Colour Colour::fromString (const String& encodedColourString)
  59264. {
  59265. return Colour ((uint32) encodedColourString.getHexValue32());
  59266. }
  59267. END_JUCE_NAMESPACE
  59268. /********* End of inlined file: juce_Colour.cpp *********/
  59269. /********* Start of inlined file: juce_ColourGradient.cpp *********/
  59270. BEGIN_JUCE_NAMESPACE
  59271. ColourGradient::ColourGradient() throw()
  59272. : colours (4)
  59273. {
  59274. #ifdef JUCE_DEBUG
  59275. x1 = 987654.0f;
  59276. #endif
  59277. }
  59278. ColourGradient::ColourGradient (const Colour& colour1,
  59279. const float x1_,
  59280. const float y1_,
  59281. const Colour& colour2,
  59282. const float x2_,
  59283. const float y2_,
  59284. const bool isRadial_) throw()
  59285. : x1 (x1_),
  59286. y1 (y1_),
  59287. x2 (x2_),
  59288. y2 (y2_),
  59289. isRadial (isRadial_),
  59290. colours (4)
  59291. {
  59292. colours.add (0);
  59293. colours.add (colour1.getPixelARGB().getARGB());
  59294. colours.add (1 << 16);
  59295. colours.add (colour2.getPixelARGB().getARGB());
  59296. }
  59297. ColourGradient::~ColourGradient() throw()
  59298. {
  59299. }
  59300. void ColourGradient::clearColours() throw()
  59301. {
  59302. colours.clear();
  59303. }
  59304. void ColourGradient::addColour (const double proportionAlongGradient,
  59305. const Colour& colour) throw()
  59306. {
  59307. // must be within the two end-points
  59308. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  59309. const uint32 pos = jlimit (0, 65535, roundDoubleToInt (proportionAlongGradient * 65536.0));
  59310. int i;
  59311. for (i = 0; i < colours.size(); i += 2)
  59312. if (colours.getUnchecked(i) > pos)
  59313. break;
  59314. colours.insert (i, pos);
  59315. colours.insert (i + 1, colour.getPixelARGB().getARGB());
  59316. }
  59317. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  59318. {
  59319. for (int i = 1; i < colours.size(); i += 2)
  59320. {
  59321. PixelARGB pix (colours.getUnchecked(i));
  59322. pix.multiplyAlpha (multiplier);
  59323. colours.set (i, pix.getARGB());
  59324. }
  59325. }
  59326. int ColourGradient::getNumColours() const throw()
  59327. {
  59328. return colours.size() >> 1;
  59329. }
  59330. double ColourGradient::getColourPosition (const int index) const throw()
  59331. {
  59332. return colours [index << 1];
  59333. }
  59334. const Colour ColourGradient::getColour (const int index) const throw()
  59335. {
  59336. PixelARGB pix (colours [(index << 1) + 1]);
  59337. pix.unpremultiply();
  59338. return Colour (pix.getARGB());
  59339. }
  59340. PixelARGB* ColourGradient::createLookupTable (int& numEntries) const throw()
  59341. {
  59342. #ifdef JUCE_DEBUG
  59343. // trying to use the object without setting its co-ordinates? Have a careful read of
  59344. // the comments for the constructors.
  59345. jassert (x1 != 987654.0f);
  59346. #endif
  59347. const int numColours = colours.size() >> 1;
  59348. float tx1 = x1, ty1 = y1, tx2 = x2, ty2 = y2;
  59349. transform.transformPoint (tx1, ty1);
  59350. transform.transformPoint (tx2, ty2);
  59351. const double distance = juce_hypot (tx1 - tx2, ty1 - ty2);
  59352. numEntries = jlimit (1, (numColours - 1) << 8, 3 * (int) distance);
  59353. PixelARGB* const lookupTable = (PixelARGB*) juce_calloc (numEntries * sizeof (PixelARGB));
  59354. if (numColours >= 2)
  59355. {
  59356. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  59357. PixelARGB pix1 (colours.getUnchecked (1));
  59358. int index = 0;
  59359. for (int j = 2; j < colours.size(); j += 2)
  59360. {
  59361. const int numToDo = ((colours.getUnchecked (j) * numEntries) >> 16) - index;
  59362. const PixelARGB pix2 (colours.getUnchecked (j + 1));
  59363. for (int i = 0; i < numToDo; ++i)
  59364. {
  59365. jassert (index >= 0 && index < numEntries);
  59366. lookupTable[index] = pix1;
  59367. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  59368. ++index;
  59369. }
  59370. pix1 = pix2;
  59371. }
  59372. while (index < numEntries)
  59373. lookupTable [index++] = pix1;
  59374. }
  59375. else
  59376. {
  59377. jassertfalse // no colours specified!
  59378. }
  59379. return lookupTable;
  59380. }
  59381. bool ColourGradient::isOpaque() const throw()
  59382. {
  59383. for (int i = 1; i < colours.size(); i += 2)
  59384. if (PixelARGB (colours.getUnchecked(i)).getAlpha() < 0xff)
  59385. return false;
  59386. return true;
  59387. }
  59388. bool ColourGradient::isInvisible() const throw()
  59389. {
  59390. for (int i = 1; i < colours.size(); i += 2)
  59391. if (PixelARGB (colours.getUnchecked(i)).getAlpha() > 0)
  59392. return false;
  59393. return true;
  59394. }
  59395. END_JUCE_NAMESPACE
  59396. /********* End of inlined file: juce_ColourGradient.cpp *********/
  59397. /********* Start of inlined file: juce_Colours.cpp *********/
  59398. BEGIN_JUCE_NAMESPACE
  59399. const Colour Colours::transparentBlack (0);
  59400. const Colour Colours::transparentWhite (0x00ffffff);
  59401. const Colour Colours::aliceblue (0xfff0f8ff);
  59402. const Colour Colours::antiquewhite (0xfffaebd7);
  59403. const Colour Colours::aqua (0xff00ffff);
  59404. const Colour Colours::aquamarine (0xff7fffd4);
  59405. const Colour Colours::azure (0xfff0ffff);
  59406. const Colour Colours::beige (0xfff5f5dc);
  59407. const Colour Colours::bisque (0xffffe4c4);
  59408. const Colour Colours::black (0xff000000);
  59409. const Colour Colours::blanchedalmond (0xffffebcd);
  59410. const Colour Colours::blue (0xff0000ff);
  59411. const Colour Colours::blueviolet (0xff8a2be2);
  59412. const Colour Colours::brown (0xffa52a2a);
  59413. const Colour Colours::burlywood (0xffdeb887);
  59414. const Colour Colours::cadetblue (0xff5f9ea0);
  59415. const Colour Colours::chartreuse (0xff7fff00);
  59416. const Colour Colours::chocolate (0xffd2691e);
  59417. const Colour Colours::coral (0xffff7f50);
  59418. const Colour Colours::cornflowerblue (0xff6495ed);
  59419. const Colour Colours::cornsilk (0xfffff8dc);
  59420. const Colour Colours::crimson (0xffdc143c);
  59421. const Colour Colours::cyan (0xff00ffff);
  59422. const Colour Colours::darkblue (0xff00008b);
  59423. const Colour Colours::darkcyan (0xff008b8b);
  59424. const Colour Colours::darkgoldenrod (0xffb8860b);
  59425. const Colour Colours::darkgrey (0xff555555);
  59426. const Colour Colours::darkgreen (0xff006400);
  59427. const Colour Colours::darkkhaki (0xffbdb76b);
  59428. const Colour Colours::darkmagenta (0xff8b008b);
  59429. const Colour Colours::darkolivegreen (0xff556b2f);
  59430. const Colour Colours::darkorange (0xffff8c00);
  59431. const Colour Colours::darkorchid (0xff9932cc);
  59432. const Colour Colours::darkred (0xff8b0000);
  59433. const Colour Colours::darksalmon (0xffe9967a);
  59434. const Colour Colours::darkseagreen (0xff8fbc8f);
  59435. const Colour Colours::darkslateblue (0xff483d8b);
  59436. const Colour Colours::darkslategrey (0xff2f4f4f);
  59437. const Colour Colours::darkturquoise (0xff00ced1);
  59438. const Colour Colours::darkviolet (0xff9400d3);
  59439. const Colour Colours::deeppink (0xffff1493);
  59440. const Colour Colours::deepskyblue (0xff00bfff);
  59441. const Colour Colours::dimgrey (0xff696969);
  59442. const Colour Colours::dodgerblue (0xff1e90ff);
  59443. const Colour Colours::firebrick (0xffb22222);
  59444. const Colour Colours::floralwhite (0xfffffaf0);
  59445. const Colour Colours::forestgreen (0xff228b22);
  59446. const Colour Colours::fuchsia (0xffff00ff);
  59447. const Colour Colours::gainsboro (0xffdcdcdc);
  59448. const Colour Colours::gold (0xffffd700);
  59449. const Colour Colours::goldenrod (0xffdaa520);
  59450. const Colour Colours::grey (0xff808080);
  59451. const Colour Colours::green (0xff008000);
  59452. const Colour Colours::greenyellow (0xffadff2f);
  59453. const Colour Colours::honeydew (0xfff0fff0);
  59454. const Colour Colours::hotpink (0xffff69b4);
  59455. const Colour Colours::indianred (0xffcd5c5c);
  59456. const Colour Colours::indigo (0xff4b0082);
  59457. const Colour Colours::ivory (0xfffffff0);
  59458. const Colour Colours::khaki (0xfff0e68c);
  59459. const Colour Colours::lavender (0xffe6e6fa);
  59460. const Colour Colours::lavenderblush (0xfffff0f5);
  59461. const Colour Colours::lemonchiffon (0xfffffacd);
  59462. const Colour Colours::lightblue (0xffadd8e6);
  59463. const Colour Colours::lightcoral (0xfff08080);
  59464. const Colour Colours::lightcyan (0xffe0ffff);
  59465. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  59466. const Colour Colours::lightgreen (0xff90ee90);
  59467. const Colour Colours::lightgrey (0xffd3d3d3);
  59468. const Colour Colours::lightpink (0xffffb6c1);
  59469. const Colour Colours::lightsalmon (0xffffa07a);
  59470. const Colour Colours::lightseagreen (0xff20b2aa);
  59471. const Colour Colours::lightskyblue (0xff87cefa);
  59472. const Colour Colours::lightslategrey (0xff778899);
  59473. const Colour Colours::lightsteelblue (0xffb0c4de);
  59474. const Colour Colours::lightyellow (0xffffffe0);
  59475. const Colour Colours::lime (0xff00ff00);
  59476. const Colour Colours::limegreen (0xff32cd32);
  59477. const Colour Colours::linen (0xfffaf0e6);
  59478. const Colour Colours::magenta (0xffff00ff);
  59479. const Colour Colours::maroon (0xff800000);
  59480. const Colour Colours::mediumaquamarine (0xff66cdaa);
  59481. const Colour Colours::mediumblue (0xff0000cd);
  59482. const Colour Colours::mediumorchid (0xffba55d3);
  59483. const Colour Colours::mediumpurple (0xff9370db);
  59484. const Colour Colours::mediumseagreen (0xff3cb371);
  59485. const Colour Colours::mediumslateblue (0xff7b68ee);
  59486. const Colour Colours::mediumspringgreen (0xff00fa9a);
  59487. const Colour Colours::mediumturquoise (0xff48d1cc);
  59488. const Colour Colours::mediumvioletred (0xffc71585);
  59489. const Colour Colours::midnightblue (0xff191970);
  59490. const Colour Colours::mintcream (0xfff5fffa);
  59491. const Colour Colours::mistyrose (0xffffe4e1);
  59492. const Colour Colours::navajowhite (0xffffdead);
  59493. const Colour Colours::navy (0xff000080);
  59494. const Colour Colours::oldlace (0xfffdf5e6);
  59495. const Colour Colours::olive (0xff808000);
  59496. const Colour Colours::olivedrab (0xff6b8e23);
  59497. const Colour Colours::orange (0xffffa500);
  59498. const Colour Colours::orangered (0xffff4500);
  59499. const Colour Colours::orchid (0xffda70d6);
  59500. const Colour Colours::palegoldenrod (0xffeee8aa);
  59501. const Colour Colours::palegreen (0xff98fb98);
  59502. const Colour Colours::paleturquoise (0xffafeeee);
  59503. const Colour Colours::palevioletred (0xffdb7093);
  59504. const Colour Colours::papayawhip (0xffffefd5);
  59505. const Colour Colours::peachpuff (0xffffdab9);
  59506. const Colour Colours::peru (0xffcd853f);
  59507. const Colour Colours::pink (0xffffc0cb);
  59508. const Colour Colours::plum (0xffdda0dd);
  59509. const Colour Colours::powderblue (0xffb0e0e6);
  59510. const Colour Colours::purple (0xff800080);
  59511. const Colour Colours::red (0xffff0000);
  59512. const Colour Colours::rosybrown (0xffbc8f8f);
  59513. const Colour Colours::royalblue (0xff4169e1);
  59514. const Colour Colours::saddlebrown (0xff8b4513);
  59515. const Colour Colours::salmon (0xfffa8072);
  59516. const Colour Colours::sandybrown (0xfff4a460);
  59517. const Colour Colours::seagreen (0xff2e8b57);
  59518. const Colour Colours::seashell (0xfffff5ee);
  59519. const Colour Colours::sienna (0xffa0522d);
  59520. const Colour Colours::silver (0xffc0c0c0);
  59521. const Colour Colours::skyblue (0xff87ceeb);
  59522. const Colour Colours::slateblue (0xff6a5acd);
  59523. const Colour Colours::slategrey (0xff708090);
  59524. const Colour Colours::snow (0xfffffafa);
  59525. const Colour Colours::springgreen (0xff00ff7f);
  59526. const Colour Colours::steelblue (0xff4682b4);
  59527. const Colour Colours::tan (0xffd2b48c);
  59528. const Colour Colours::teal (0xff008080);
  59529. const Colour Colours::thistle (0xffd8bfd8);
  59530. const Colour Colours::tomato (0xffff6347);
  59531. const Colour Colours::turquoise (0xff40e0d0);
  59532. const Colour Colours::violet (0xffee82ee);
  59533. const Colour Colours::wheat (0xfff5deb3);
  59534. const Colour Colours::white (0xffffffff);
  59535. const Colour Colours::whitesmoke (0xfff5f5f5);
  59536. const Colour Colours::yellow (0xffffff00);
  59537. const Colour Colours::yellowgreen (0xff9acd32);
  59538. const Colour Colours::findColourForName (const String& colourName,
  59539. const Colour& defaultColour)
  59540. {
  59541. static const int presets[] =
  59542. {
  59543. // (first value is the string's hashcode, second is ARGB)
  59544. 0x05978fff, 0xff000000, /* black */
  59545. 0x06bdcc29, 0xffffffff, /* white */
  59546. 0x002e305a, 0xff0000ff, /* blue */
  59547. 0x00308adf, 0xff808080, /* grey */
  59548. 0x05e0cf03, 0xff008000, /* green */
  59549. 0x0001b891, 0xffff0000, /* red */
  59550. 0xd43c6474, 0xffffff00, /* yellow */
  59551. 0x620886da, 0xfff0f8ff, /* aliceblue */
  59552. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  59553. 0x002dcebc, 0xff00ffff, /* aqua */
  59554. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  59555. 0x0590228f, 0xfff0ffff, /* azure */
  59556. 0x05947fe4, 0xfff5f5dc, /* beige */
  59557. 0xad388e35, 0xffffe4c4, /* bisque */
  59558. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  59559. 0x39129959, 0xff8a2be2, /* blueviolet */
  59560. 0x059a8136, 0xffa52a2a, /* brown */
  59561. 0x89cea8f9, 0xffdeb887, /* burlywood */
  59562. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  59563. 0x6b748956, 0xff7fff00, /* chartreuse */
  59564. 0x2903623c, 0xffd2691e, /* chocolate */
  59565. 0x05a74431, 0xffff7f50, /* coral */
  59566. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  59567. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  59568. 0x3d8c4edf, 0xffdc143c, /* crimson */
  59569. 0x002ed323, 0xff00ffff, /* cyan */
  59570. 0x67cc74d0, 0xff00008b, /* darkblue */
  59571. 0x67cd1799, 0xff008b8b, /* darkcyan */
  59572. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  59573. 0x67cecf55, 0xff555555, /* darkgrey */
  59574. 0x920b194d, 0xff006400, /* darkgreen */
  59575. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  59576. 0x5c293873, 0xff8b008b, /* darkmagenta */
  59577. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  59578. 0xbcfd2524, 0xffff8c00, /* darkorange */
  59579. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  59580. 0x55ee0d5b, 0xff8b0000, /* darkred */
  59581. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  59582. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  59583. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  59584. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  59585. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  59586. 0xc8769375, 0xff9400d3, /* darkviolet */
  59587. 0x25832862, 0xffff1493, /* deeppink */
  59588. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  59589. 0x634c8b67, 0xff696969, /* dimgrey */
  59590. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  59591. 0xef19e3cb, 0xffb22222, /* firebrick */
  59592. 0xb852b195, 0xfffffaf0, /* floralwhite */
  59593. 0xd086fd06, 0xff228b22, /* forestgreen */
  59594. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  59595. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  59596. 0x00308060, 0xffffd700, /* gold */
  59597. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  59598. 0xbab8a537, 0xffadff2f, /* greenyellow */
  59599. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  59600. 0x41892743, 0xffff69b4, /* hotpink */
  59601. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  59602. 0xb969fed2, 0xff4b0082, /* indigo */
  59603. 0x05fef6a9, 0xfffffff0, /* ivory */
  59604. 0x06149302, 0xfff0e68c, /* khaki */
  59605. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  59606. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  59607. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  59608. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  59609. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  59610. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  59611. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  59612. 0xf40157ad, 0xff90ee90, /* lightgreen */
  59613. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  59614. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  59615. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  59616. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  59617. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  59618. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  59619. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  59620. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  59621. 0x0032afd5, 0xff00ff00, /* lime */
  59622. 0x607bbc4e, 0xff32cd32, /* limegreen */
  59623. 0x06234efa, 0xfffaf0e6, /* linen */
  59624. 0x316858a9, 0xffff00ff, /* magenta */
  59625. 0xbf8ca470, 0xff800000, /* maroon */
  59626. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  59627. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  59628. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  59629. 0x07556b71, 0xff9370db, /* mediumpurple */
  59630. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  59631. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  59632. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  59633. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  59634. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  59635. 0x168eb32a, 0xff191970, /* midnightblue */
  59636. 0x4306b960, 0xfff5fffa, /* mintcream */
  59637. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  59638. 0xe97218a6, 0xffffdead, /* navajowhite */
  59639. 0x00337bb6, 0xff000080, /* navy */
  59640. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  59641. 0x064ee1db, 0xff808000, /* olive */
  59642. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  59643. 0xc3de262e, 0xffffa500, /* orange */
  59644. 0x58bebba3, 0xffff4500, /* orangered */
  59645. 0xc3def8a3, 0xffda70d6, /* orchid */
  59646. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  59647. 0x3d9dd619, 0xff98fb98, /* palegreen */
  59648. 0x74022737, 0xffafeeee, /* paleturquoise */
  59649. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  59650. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  59651. 0x93e1b776, 0xffffdab9, /* peachpuff */
  59652. 0x003472f8, 0xffcd853f, /* peru */
  59653. 0x00348176, 0xffffc0cb, /* pink */
  59654. 0x00348d94, 0xffdda0dd, /* plum */
  59655. 0xd036be93, 0xffb0e0e6, /* powderblue */
  59656. 0xc5c507bc, 0xff800080, /* purple */
  59657. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  59658. 0xbd9413e1, 0xff4169e1, /* royalblue */
  59659. 0xf456044f, 0xff8b4513, /* saddlebrown */
  59660. 0xc9c6f66e, 0xfffa8072, /* salmon */
  59661. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  59662. 0x34636c14, 0xff2e8b57, /* seagreen */
  59663. 0x3507fb41, 0xfffff5ee, /* seashell */
  59664. 0xca348772, 0xffa0522d, /* sienna */
  59665. 0xca37d30d, 0xffc0c0c0, /* silver */
  59666. 0x80da74fb, 0xff87ceeb, /* skyblue */
  59667. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  59668. 0x44ab37f8, 0xff708090, /* slategrey */
  59669. 0x0035f183, 0xfffffafa, /* snow */
  59670. 0xd5440d16, 0xff00ff7f, /* springgreen */
  59671. 0x3e1524a5, 0xff4682b4, /* steelblue */
  59672. 0x0001bfa1, 0xffd2b48c, /* tan */
  59673. 0x0036425c, 0xff008080, /* teal */
  59674. 0xafc8858f, 0xffd8bfd8, /* thistle */
  59675. 0xcc41600a, 0xffff6347, /* tomato */
  59676. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  59677. 0xcf57947f, 0xffee82ee, /* violet */
  59678. 0x06bdbae7, 0xfff5deb3, /* wheat */
  59679. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  59680. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  59681. };
  59682. const int hash = colourName.trim().toLowerCase().hashCode();
  59683. for (int i = 0; i < numElementsInArray (presets); i += 2)
  59684. if (presets [i] == hash)
  59685. return Colour (presets [i + 1]);
  59686. return defaultColour;
  59687. }
  59688. END_JUCE_NAMESPACE
  59689. /********* End of inlined file: juce_Colours.cpp *********/
  59690. /********* Start of inlined file: juce_EdgeTable.cpp *********/
  59691. BEGIN_JUCE_NAMESPACE
  59692. EdgeTable::EdgeTable (const int top_,
  59693. const int height_,
  59694. const OversamplingLevel oversampling_,
  59695. const int expectedEdgesPerLine) throw()
  59696. : top (top_),
  59697. height (height_),
  59698. maxEdgesPerLine (expectedEdgesPerLine),
  59699. lineStrideElements ((expectedEdgesPerLine << 1) + 1),
  59700. oversampling (oversampling_)
  59701. {
  59702. table = (int*) juce_calloc ((height << (int)oversampling_)
  59703. * lineStrideElements * sizeof (int));
  59704. }
  59705. EdgeTable::EdgeTable (const EdgeTable& other) throw()
  59706. : table (0)
  59707. {
  59708. operator= (other);
  59709. }
  59710. const EdgeTable& EdgeTable::operator= (const EdgeTable& other) throw()
  59711. {
  59712. juce_free (table);
  59713. top = other.top;
  59714. height = other.height;
  59715. maxEdgesPerLine = other.maxEdgesPerLine;
  59716. lineStrideElements = other.lineStrideElements;
  59717. oversampling = other.oversampling;
  59718. const int tableSize = (height << (int)oversampling)
  59719. * lineStrideElements * sizeof (int);
  59720. table = (int*) juce_malloc (tableSize);
  59721. memcpy (table, other.table, tableSize);
  59722. return *this;
  59723. }
  59724. EdgeTable::~EdgeTable() throw()
  59725. {
  59726. juce_free (table);
  59727. }
  59728. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  59729. {
  59730. if (newNumEdgesPerLine != maxEdgesPerLine)
  59731. {
  59732. maxEdgesPerLine = newNumEdgesPerLine;
  59733. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  59734. int* const newTable = (int*) juce_malloc ((height << (int) oversampling)
  59735. * newLineStrideElements * sizeof (int));
  59736. for (int i = 0; i < (height << (int) oversampling); ++i)
  59737. {
  59738. const int* srcLine = table + lineStrideElements * i;
  59739. int* dstLine = newTable + newLineStrideElements * i;
  59740. int num = *srcLine++;
  59741. *dstLine++ = num;
  59742. num <<= 1;
  59743. while (--num >= 0)
  59744. *dstLine++ = *srcLine++;
  59745. }
  59746. juce_free (table);
  59747. table = newTable;
  59748. lineStrideElements = newLineStrideElements;
  59749. }
  59750. }
  59751. void EdgeTable::optimiseTable() throw()
  59752. {
  59753. int maxLineElements = 0;
  59754. for (int i = height; --i >= 0;)
  59755. maxLineElements = jmax (maxLineElements,
  59756. table [i * lineStrideElements]);
  59757. remapTableForNumEdges (maxLineElements);
  59758. }
  59759. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  59760. {
  59761. jassert (y >= 0 && y < (height << oversampling))
  59762. int* lineStart = table + lineStrideElements * y;
  59763. int n = lineStart[0];
  59764. if (n >= maxEdgesPerLine)
  59765. {
  59766. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  59767. lineStart = table + lineStrideElements * y;
  59768. }
  59769. n <<= 1;
  59770. int* const line = lineStart + 1;
  59771. while (n > 0)
  59772. {
  59773. const int cx = line [n - 2];
  59774. if (cx <= x)
  59775. break;
  59776. line [n] = cx;
  59777. line [n + 1] = line [n - 1];
  59778. n -= 2;
  59779. }
  59780. line [n] = x;
  59781. line [n + 1] = winding;
  59782. lineStart[0]++;
  59783. }
  59784. void EdgeTable::addPath (const Path& path,
  59785. const AffineTransform& transform) throw()
  59786. {
  59787. const int windingAmount = 256 / (1 << (int) oversampling);
  59788. const float timesOversampling = (float) (1 << (int) oversampling);
  59789. const int bottomLimit = (height << (int) oversampling);
  59790. PathFlatteningIterator iter (path, transform);
  59791. while (iter.next())
  59792. {
  59793. int y1 = roundFloatToInt (iter.y1 * timesOversampling) - (top << (int) oversampling);
  59794. int y2 = roundFloatToInt (iter.y2 * timesOversampling) - (top << (int) oversampling);
  59795. if (y1 != y2)
  59796. {
  59797. const double x1 = 256.0 * iter.x1;
  59798. const double x2 = 256.0 * iter.x2;
  59799. const double multiplier = (x2 - x1) / (y2 - y1);
  59800. const int oldY1 = y1;
  59801. int winding;
  59802. if (y1 > y2)
  59803. {
  59804. swapVariables (y1, y2);
  59805. winding = windingAmount;
  59806. }
  59807. else
  59808. {
  59809. winding = -windingAmount;
  59810. }
  59811. jassert (y1 < y2);
  59812. if (y1 < 0)
  59813. y1 = 0;
  59814. if (y2 > bottomLimit)
  59815. y2 = bottomLimit;
  59816. while (y1 < y2)
  59817. {
  59818. addEdgePoint (roundDoubleToInt (x1 + multiplier * (y1 - oldY1)),
  59819. y1,
  59820. winding);
  59821. ++y1;
  59822. }
  59823. }
  59824. }
  59825. if (! path.isUsingNonZeroWinding())
  59826. {
  59827. // if it's an alternate-winding path, we need to go through and
  59828. // make sure all the windings are alternating.
  59829. int* lineStart = table;
  59830. for (int i = height << (int) oversampling; --i >= 0;)
  59831. {
  59832. int* line = lineStart;
  59833. lineStart += lineStrideElements;
  59834. int num = *line;
  59835. while (--num >= 0)
  59836. {
  59837. line += 2;
  59838. *line = abs (*line);
  59839. if (--num >= 0)
  59840. {
  59841. line += 2;
  59842. *line = -abs (*line);
  59843. }
  59844. }
  59845. }
  59846. }
  59847. }
  59848. END_JUCE_NAMESPACE
  59849. /********* End of inlined file: juce_EdgeTable.cpp *********/
  59850. /********* Start of inlined file: juce_Graphics.cpp *********/
  59851. BEGIN_JUCE_NAMESPACE
  59852. static const Graphics::ResamplingQuality defaultQuality = Graphics::mediumResamplingQuality;
  59853. #define MINIMUM_COORD -0x3fffffff
  59854. #define MAXIMUM_COORD 0x3fffffff
  59855. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  59856. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  59857. jassert ((int) x >= MINIMUM_COORD \
  59858. && (int) x <= MAXIMUM_COORD \
  59859. && (int) y >= MINIMUM_COORD \
  59860. && (int) y <= MAXIMUM_COORD \
  59861. && (int) w >= MINIMUM_COORD \
  59862. && (int) w <= MAXIMUM_COORD \
  59863. && (int) h >= MINIMUM_COORD \
  59864. && (int) h <= MAXIMUM_COORD);
  59865. LowLevelGraphicsContext::LowLevelGraphicsContext()
  59866. {
  59867. }
  59868. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  59869. {
  59870. }
  59871. Graphics::Graphics (Image& imageToDrawOnto) throw()
  59872. : context (imageToDrawOnto.createLowLevelContext()),
  59873. ownsContext (true),
  59874. state (new GraphicsState()),
  59875. saveStatePending (false)
  59876. {
  59877. }
  59878. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  59879. : context (internalContext),
  59880. ownsContext (false),
  59881. state (new GraphicsState()),
  59882. saveStatePending (false)
  59883. {
  59884. }
  59885. Graphics::~Graphics() throw()
  59886. {
  59887. delete state;
  59888. if (ownsContext)
  59889. delete context;
  59890. }
  59891. void Graphics::resetToDefaultState() throw()
  59892. {
  59893. setColour (Colours::black);
  59894. state->font.resetToDefaultState();
  59895. state->quality = defaultQuality;
  59896. }
  59897. bool Graphics::isVectorDevice() const throw()
  59898. {
  59899. return context->isVectorDevice();
  59900. }
  59901. bool Graphics::reduceClipRegion (const int x, const int y,
  59902. const int w, const int h) throw()
  59903. {
  59904. saveStateIfPending();
  59905. return context->reduceClipRegion (x, y, w, h);
  59906. }
  59907. bool Graphics::reduceClipRegion (const RectangleList& clipRegion) throw()
  59908. {
  59909. saveStateIfPending();
  59910. return context->reduceClipRegion (clipRegion);
  59911. }
  59912. void Graphics::excludeClipRegion (const int x, const int y,
  59913. const int w, const int h) throw()
  59914. {
  59915. saveStateIfPending();
  59916. context->excludeClipRegion (x, y, w, h);
  59917. }
  59918. bool Graphics::isClipEmpty() const throw()
  59919. {
  59920. return context->isClipEmpty();
  59921. }
  59922. const Rectangle Graphics::getClipBounds() const throw()
  59923. {
  59924. return context->getClipBounds();
  59925. }
  59926. void Graphics::saveState() throw()
  59927. {
  59928. saveStateIfPending();
  59929. saveStatePending = true;
  59930. }
  59931. void Graphics::restoreState() throw()
  59932. {
  59933. if (saveStatePending)
  59934. {
  59935. saveStatePending = false;
  59936. }
  59937. else
  59938. {
  59939. const int stackSize = stateStack.size();
  59940. if (stackSize > 0)
  59941. {
  59942. context->restoreState();
  59943. delete state;
  59944. state = stateStack.getUnchecked (stackSize - 1);
  59945. stateStack.removeLast (1, false);
  59946. }
  59947. else
  59948. {
  59949. // Trying to call restoreState() more times than you've called saveState() !
  59950. // Be careful to correctly match each saveState() with exactly one call to restoreState().
  59951. jassertfalse
  59952. }
  59953. }
  59954. }
  59955. void Graphics::saveStateIfPending() throw()
  59956. {
  59957. if (saveStatePending)
  59958. {
  59959. saveStatePending = false;
  59960. context->saveState();
  59961. stateStack.add (new GraphicsState (*state));
  59962. }
  59963. }
  59964. void Graphics::setOrigin (const int newOriginX,
  59965. const int newOriginY) throw()
  59966. {
  59967. saveStateIfPending();
  59968. context->setOrigin (newOriginX, newOriginY);
  59969. }
  59970. bool Graphics::clipRegionIntersects (const int x, const int y,
  59971. const int w, const int h) const throw()
  59972. {
  59973. return context->clipRegionIntersects (x, y, w, h);
  59974. }
  59975. void Graphics::setColour (const Colour& newColour) throw()
  59976. {
  59977. saveStateIfPending();
  59978. state->colour = newColour;
  59979. deleteAndZero (state->brush);
  59980. }
  59981. const Colour& Graphics::getCurrentColour() const throw()
  59982. {
  59983. return state->colour;
  59984. }
  59985. void Graphics::setOpacity (const float newOpacity) throw()
  59986. {
  59987. saveStateIfPending();
  59988. state->colour = state->colour.withAlpha (newOpacity);
  59989. }
  59990. void Graphics::setBrush (const Brush* const newBrush) throw()
  59991. {
  59992. saveStateIfPending();
  59993. delete state->brush;
  59994. if (newBrush != 0)
  59995. state->brush = newBrush->createCopy();
  59996. else
  59997. state->brush = 0;
  59998. }
  59999. Graphics::GraphicsState::GraphicsState() throw()
  60000. : colour (Colours::black),
  60001. brush (0),
  60002. quality (defaultQuality)
  60003. {
  60004. }
  60005. Graphics::GraphicsState::GraphicsState (const GraphicsState& other) throw()
  60006. : colour (other.colour),
  60007. brush (other.brush != 0 ? other.brush->createCopy() : 0),
  60008. font (other.font),
  60009. quality (other.quality)
  60010. {
  60011. }
  60012. Graphics::GraphicsState::~GraphicsState() throw()
  60013. {
  60014. delete brush;
  60015. }
  60016. void Graphics::setFont (const Font& newFont) throw()
  60017. {
  60018. saveStateIfPending();
  60019. state->font = newFont;
  60020. }
  60021. void Graphics::setFont (const float newFontHeight,
  60022. const int newFontStyleFlags) throw()
  60023. {
  60024. saveStateIfPending();
  60025. state->font.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0.0f);
  60026. }
  60027. const Font& Graphics::getCurrentFont() const throw()
  60028. {
  60029. return state->font;
  60030. }
  60031. void Graphics::drawSingleLineText (const String& text,
  60032. const int startX,
  60033. const int baselineY) const throw()
  60034. {
  60035. if (text.isNotEmpty()
  60036. && startX < context->getClipBounds().getRight())
  60037. {
  60038. GlyphArrangement arr;
  60039. arr.addLineOfText (state->font, text, (float) startX, (float) baselineY);
  60040. arr.draw (*this);
  60041. }
  60042. }
  60043. void Graphics::drawTextAsPath (const String& text,
  60044. const AffineTransform& transform) const throw()
  60045. {
  60046. if (text.isNotEmpty())
  60047. {
  60048. GlyphArrangement arr;
  60049. arr.addLineOfText (state->font, text, 0.0f, 0.0f);
  60050. arr.draw (*this, transform);
  60051. }
  60052. }
  60053. void Graphics::drawMultiLineText (const String& text,
  60054. const int startX,
  60055. const int baselineY,
  60056. const int maximumLineWidth) const throw()
  60057. {
  60058. if (text.isNotEmpty()
  60059. && startX < context->getClipBounds().getRight())
  60060. {
  60061. GlyphArrangement arr;
  60062. arr.addJustifiedText (state->font, text,
  60063. (float) startX, (float) baselineY, (float) maximumLineWidth,
  60064. Justification::left);
  60065. arr.draw (*this);
  60066. }
  60067. }
  60068. void Graphics::drawText (const String& text,
  60069. const int x,
  60070. const int y,
  60071. const int width,
  60072. const int height,
  60073. const Justification& justificationType,
  60074. const bool useEllipsesIfTooBig) const throw()
  60075. {
  60076. if (text.isNotEmpty() && context->clipRegionIntersects (x, y, width, height))
  60077. {
  60078. GlyphArrangement arr;
  60079. arr.addCurtailedLineOfText (state->font, text,
  60080. 0.0f, 0.0f, (float)width,
  60081. useEllipsesIfTooBig);
  60082. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  60083. (float) x, (float) y,
  60084. (float) width, (float) height,
  60085. justificationType);
  60086. arr.draw (*this);
  60087. }
  60088. }
  60089. void Graphics::drawFittedText (const String& text,
  60090. const int x,
  60091. const int y,
  60092. const int width,
  60093. const int height,
  60094. const Justification& justification,
  60095. const int maximumNumberOfLines,
  60096. const float minimumHorizontalScale) const throw()
  60097. {
  60098. if (text.isNotEmpty()
  60099. && width > 0 && height > 0
  60100. && context->clipRegionIntersects (x, y, width, height))
  60101. {
  60102. GlyphArrangement arr;
  60103. arr.addFittedText (state->font, text,
  60104. (float) x, (float) y,
  60105. (float) width, (float) height,
  60106. justification,
  60107. maximumNumberOfLines,
  60108. minimumHorizontalScale);
  60109. arr.draw (*this);
  60110. }
  60111. }
  60112. void Graphics::fillRect (int x,
  60113. int y,
  60114. int width,
  60115. int height) const throw()
  60116. {
  60117. // passing in a silly number can cause maths problems in rendering!
  60118. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60119. SolidColourBrush colourBrush (state->colour);
  60120. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, width, height);
  60121. }
  60122. void Graphics::fillRect (const Rectangle& r) const throw()
  60123. {
  60124. fillRect (r.getX(),
  60125. r.getY(),
  60126. r.getWidth(),
  60127. r.getHeight());
  60128. }
  60129. void Graphics::fillRect (const float x,
  60130. const float y,
  60131. const float width,
  60132. const float height) const throw()
  60133. {
  60134. // passing in a silly number can cause maths problems in rendering!
  60135. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60136. Path p;
  60137. p.addRectangle (x, y, width, height);
  60138. fillPath (p);
  60139. }
  60140. void Graphics::setPixel (int x, int y) const throw()
  60141. {
  60142. if (context->clipRegionIntersects (x, y, 1, 1))
  60143. {
  60144. SolidColourBrush colourBrush (state->colour);
  60145. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, 1, 1);
  60146. }
  60147. }
  60148. void Graphics::fillAll() const throw()
  60149. {
  60150. fillRect (context->getClipBounds());
  60151. }
  60152. void Graphics::fillAll (const Colour& colourToUse) const throw()
  60153. {
  60154. if (! colourToUse.isTransparent())
  60155. {
  60156. const Rectangle clip (context->getClipBounds());
  60157. context->fillRectWithColour (clip.getX(), clip.getY(), clip.getWidth(), clip.getHeight(),
  60158. colourToUse, false);
  60159. }
  60160. }
  60161. void Graphics::fillPath (const Path& path,
  60162. const AffineTransform& transform) const throw()
  60163. {
  60164. if ((! context->isClipEmpty()) && ! path.isEmpty())
  60165. {
  60166. SolidColourBrush colourBrush (state->colour);
  60167. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintPath (*context, path, transform);
  60168. }
  60169. }
  60170. void Graphics::strokePath (const Path& path,
  60171. const PathStrokeType& strokeType,
  60172. const AffineTransform& transform) const throw()
  60173. {
  60174. if (! state->colour.isTransparent())
  60175. {
  60176. Path stroke;
  60177. strokeType.createStrokedPath (stroke, path, transform);
  60178. fillPath (stroke);
  60179. }
  60180. }
  60181. void Graphics::drawRect (const int x,
  60182. const int y,
  60183. const int width,
  60184. const int height,
  60185. const int lineThickness) const throw()
  60186. {
  60187. // passing in a silly number can cause maths problems in rendering!
  60188. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60189. SolidColourBrush colourBrush (state->colour);
  60190. Brush& b = (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush);
  60191. b.paintRectangle (*context, x, y, width, lineThickness);
  60192. b.paintRectangle (*context, x, y + lineThickness, lineThickness, height - lineThickness * 2);
  60193. b.paintRectangle (*context, x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2);
  60194. b.paintRectangle (*context, x, y + height - lineThickness, width, lineThickness);
  60195. }
  60196. void Graphics::drawRect (const float x,
  60197. const float y,
  60198. const float width,
  60199. const float height,
  60200. const float lineThickness) const throw()
  60201. {
  60202. // passing in a silly number can cause maths problems in rendering!
  60203. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60204. Path p;
  60205. p.addRectangle (x, y, width, lineThickness);
  60206. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  60207. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  60208. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  60209. fillPath (p);
  60210. }
  60211. void Graphics::drawRect (const Rectangle& r,
  60212. const int lineThickness) const throw()
  60213. {
  60214. drawRect (r.getX(), r.getY(),
  60215. r.getWidth(), r.getHeight(),
  60216. lineThickness);
  60217. }
  60218. void Graphics::drawBevel (const int x,
  60219. const int y,
  60220. const int width,
  60221. const int height,
  60222. const int bevelThickness,
  60223. const Colour& topLeftColour,
  60224. const Colour& bottomRightColour,
  60225. const bool useGradient) const throw()
  60226. {
  60227. // passing in a silly number can cause maths problems in rendering!
  60228. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60229. if (clipRegionIntersects (x, y, width, height))
  60230. {
  60231. const float oldOpacity = state->colour.getFloatAlpha();
  60232. const float ramp = oldOpacity / bevelThickness;
  60233. for (int i = bevelThickness; --i >= 0;)
  60234. {
  60235. const float op = useGradient ? ramp * (bevelThickness - i)
  60236. : oldOpacity;
  60237. context->fillRectWithColour (x + i, y + i, width - i * 2, 1, topLeftColour.withMultipliedAlpha (op), false);
  60238. context->fillRectWithColour (x + i, y + i + 1, 1, height - i * 2 - 2, topLeftColour.withMultipliedAlpha (op * 0.75f), false);
  60239. context->fillRectWithColour (x + i, y + height - i - 1, width - i * 2, 1, bottomRightColour.withMultipliedAlpha (op), false);
  60240. context->fillRectWithColour (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2, bottomRightColour.withMultipliedAlpha (op * 0.75f), false);
  60241. }
  60242. }
  60243. }
  60244. void Graphics::fillEllipse (const float x,
  60245. const float y,
  60246. const float width,
  60247. const float height) const throw()
  60248. {
  60249. // passing in a silly number can cause maths problems in rendering!
  60250. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60251. Path p;
  60252. p.addEllipse (x, y, width, height);
  60253. fillPath (p);
  60254. }
  60255. void Graphics::drawEllipse (const float x,
  60256. const float y,
  60257. const float width,
  60258. const float height,
  60259. const float lineThickness) const throw()
  60260. {
  60261. // passing in a silly number can cause maths problems in rendering!
  60262. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60263. Path p;
  60264. p.addEllipse (x, y, width, height);
  60265. strokePath (p, PathStrokeType (lineThickness));
  60266. }
  60267. void Graphics::fillRoundedRectangle (const float x,
  60268. const float y,
  60269. const float width,
  60270. const float height,
  60271. const float cornerSize) const throw()
  60272. {
  60273. // passing in a silly number can cause maths problems in rendering!
  60274. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60275. Path p;
  60276. p.addRoundedRectangle (x, y, width, height, cornerSize);
  60277. fillPath (p);
  60278. }
  60279. void Graphics::fillRoundedRectangle (const Rectangle& r,
  60280. const float cornerSize) const throw()
  60281. {
  60282. fillRoundedRectangle ((float) r.getX(),
  60283. (float) r.getY(),
  60284. (float) r.getWidth(),
  60285. (float) r.getHeight(),
  60286. cornerSize);
  60287. }
  60288. void Graphics::drawRoundedRectangle (const float x,
  60289. const float y,
  60290. const float width,
  60291. const float height,
  60292. const float cornerSize,
  60293. const float lineThickness) const throw()
  60294. {
  60295. // passing in a silly number can cause maths problems in rendering!
  60296. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60297. Path p;
  60298. p.addRoundedRectangle (x, y, width, height, cornerSize);
  60299. strokePath (p, PathStrokeType (lineThickness));
  60300. }
  60301. void Graphics::drawRoundedRectangle (const Rectangle& r,
  60302. const float cornerSize,
  60303. const float lineThickness) const throw()
  60304. {
  60305. drawRoundedRectangle ((float) r.getX(),
  60306. (float) r.getY(),
  60307. (float) r.getWidth(),
  60308. (float) r.getHeight(),
  60309. cornerSize, lineThickness);
  60310. }
  60311. void Graphics::drawArrow (const float startX,
  60312. const float startY,
  60313. const float endX,
  60314. const float endY,
  60315. const float lineThickness,
  60316. const float arrowheadWidth,
  60317. const float arrowheadLength) const throw()
  60318. {
  60319. Path p;
  60320. p.addArrow (startX, startY, endX, endY,
  60321. lineThickness, arrowheadWidth, arrowheadLength);
  60322. fillPath (p);
  60323. }
  60324. void Graphics::fillCheckerBoard (int x, int y,
  60325. int width, int height,
  60326. const int checkWidth,
  60327. const int checkHeight,
  60328. const Colour& colour1,
  60329. const Colour& colour2) const throw()
  60330. {
  60331. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  60332. if (checkWidth > 0 && checkHeight > 0)
  60333. {
  60334. if (colour1 == colour2)
  60335. {
  60336. context->fillRectWithColour (x, y, width, height, colour1, false);
  60337. }
  60338. else
  60339. {
  60340. const Rectangle clip (context->getClipBounds());
  60341. const int right = jmin (x + width, clip.getRight());
  60342. const int bottom = jmin (y + height, clip.getBottom());
  60343. int cy = 0;
  60344. while (y < bottom)
  60345. {
  60346. int cx = cy;
  60347. for (int xx = x; xx < right; xx += checkWidth)
  60348. context->fillRectWithColour (xx, y,
  60349. jmin (checkWidth, right - xx),
  60350. jmin (checkHeight, bottom - y),
  60351. ((cx++ & 1) == 0) ? colour1 : colour2,
  60352. false);
  60353. ++cy;
  60354. y += checkHeight;
  60355. }
  60356. }
  60357. }
  60358. }
  60359. void Graphics::drawVerticalLine (const int x, float top, float bottom) const throw()
  60360. {
  60361. SolidColourBrush colourBrush (state->colour);
  60362. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintVerticalLine (*context, x, top, bottom);
  60363. }
  60364. void Graphics::drawHorizontalLine (const int y, float left, float right) const throw()
  60365. {
  60366. SolidColourBrush colourBrush (state->colour);
  60367. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintHorizontalLine (*context, y, left, right);
  60368. }
  60369. void Graphics::drawLine (float x1, float y1,
  60370. float x2, float y2) const throw()
  60371. {
  60372. if (! context->isClipEmpty())
  60373. {
  60374. SolidColourBrush colourBrush (state->colour);
  60375. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintLine (*context, x1, y1, x2, y2);
  60376. }
  60377. }
  60378. void Graphics::drawLine (const float startX,
  60379. const float startY,
  60380. const float endX,
  60381. const float endY,
  60382. const float lineThickness) const throw()
  60383. {
  60384. Path p;
  60385. p.addLineSegment (startX, startY, endX, endY, lineThickness);
  60386. fillPath (p);
  60387. }
  60388. void Graphics::drawLine (const Line& line) const throw()
  60389. {
  60390. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  60391. }
  60392. void Graphics::drawLine (const Line& line,
  60393. const float lineThickness) const throw()
  60394. {
  60395. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY(), lineThickness);
  60396. }
  60397. void Graphics::drawDashedLine (const float startX,
  60398. const float startY,
  60399. const float endX,
  60400. const float endY,
  60401. const float* const dashLengths,
  60402. const int numDashLengths,
  60403. const float lineThickness) const throw()
  60404. {
  60405. const double dx = endX - startX;
  60406. const double dy = endY - startY;
  60407. const double totalLen = juce_hypot (dx, dy);
  60408. if (totalLen >= 0.5)
  60409. {
  60410. const double onePixAlpha = 1.0 / totalLen;
  60411. double alpha = 0.0;
  60412. float x = startX;
  60413. float y = startY;
  60414. int n = 0;
  60415. while (alpha < 1.0f)
  60416. {
  60417. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  60418. n = n % numDashLengths;
  60419. const float oldX = x;
  60420. const float oldY = y;
  60421. x = (float) (startX + dx * alpha);
  60422. y = (float) (startY + dy * alpha);
  60423. if ((n & 1) != 0)
  60424. {
  60425. if (lineThickness != 1.0f)
  60426. drawLine (oldX, oldY, x, y, lineThickness);
  60427. else
  60428. drawLine (oldX, oldY, x, y);
  60429. }
  60430. }
  60431. }
  60432. }
  60433. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality) throw()
  60434. {
  60435. saveStateIfPending();
  60436. state->quality = newQuality;
  60437. }
  60438. void Graphics::drawImageAt (const Image* const imageToDraw,
  60439. const int topLeftX,
  60440. const int topLeftY,
  60441. const bool fillAlphaChannelWithCurrentBrush) const throw()
  60442. {
  60443. if (imageToDraw != 0)
  60444. {
  60445. const int imageW = imageToDraw->getWidth();
  60446. const int imageH = imageToDraw->getHeight();
  60447. drawImage (imageToDraw,
  60448. topLeftX, topLeftY, imageW, imageH,
  60449. 0, 0, imageW, imageH,
  60450. fillAlphaChannelWithCurrentBrush);
  60451. }
  60452. }
  60453. void Graphics::drawImageWithin (const Image* const imageToDraw,
  60454. const int destX,
  60455. const int destY,
  60456. const int destW,
  60457. const int destH,
  60458. const RectanglePlacement& placementWithinTarget,
  60459. const bool fillAlphaChannelWithCurrentBrush) const throw()
  60460. {
  60461. // passing in a silly number can cause maths problems in rendering!
  60462. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (destX, destY, destW, destH);
  60463. if (imageToDraw != 0)
  60464. {
  60465. const int imageW = imageToDraw->getWidth();
  60466. const int imageH = imageToDraw->getHeight();
  60467. if (imageW > 0 && imageH > 0)
  60468. {
  60469. double newX = 0.0, newY = 0.0;
  60470. double newW = imageW;
  60471. double newH = imageH;
  60472. placementWithinTarget.applyTo (newX, newY, newW, newH,
  60473. destX, destY, destW, destH);
  60474. if (newW > 0 && newH > 0)
  60475. {
  60476. drawImage (imageToDraw,
  60477. roundDoubleToInt (newX), roundDoubleToInt (newY),
  60478. roundDoubleToInt (newW), roundDoubleToInt (newH),
  60479. 0, 0, imageW, imageH,
  60480. fillAlphaChannelWithCurrentBrush);
  60481. }
  60482. }
  60483. }
  60484. }
  60485. void Graphics::drawImage (const Image* const imageToDraw,
  60486. int dx, int dy, int dw, int dh,
  60487. int sx, int sy, int sw, int sh,
  60488. const bool fillAlphaChannelWithCurrentBrush) const throw()
  60489. {
  60490. // passing in a silly number can cause maths problems in rendering!
  60491. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (dx, dy, dw, dh);
  60492. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (sx, sy, sw, sh);
  60493. if (imageToDraw == 0 || ! context->clipRegionIntersects (dx, dy, dw, dh))
  60494. return;
  60495. if (sw == dw && sh == dh)
  60496. {
  60497. if (sx < 0)
  60498. {
  60499. dx -= sx;
  60500. dw += sx;
  60501. sw += sx;
  60502. sx = 0;
  60503. }
  60504. if (sx + sw > imageToDraw->getWidth())
  60505. {
  60506. const int amount = sx + sw - imageToDraw->getWidth();
  60507. dw -= amount;
  60508. sw -= amount;
  60509. }
  60510. if (sy < 0)
  60511. {
  60512. dy -= sy;
  60513. dh += sy;
  60514. sh += sy;
  60515. sy = 0;
  60516. }
  60517. if (sy + sh > imageToDraw->getHeight())
  60518. {
  60519. const int amount = sy + sh - imageToDraw->getHeight();
  60520. dh -= amount;
  60521. sh -= amount;
  60522. }
  60523. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  60524. return;
  60525. if (fillAlphaChannelWithCurrentBrush)
  60526. {
  60527. SolidColourBrush colourBrush (state->colour);
  60528. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  60529. .paintAlphaChannel (*context, *imageToDraw,
  60530. dx - sx, dy - sy,
  60531. dx, dy,
  60532. dw, dh);
  60533. }
  60534. else
  60535. {
  60536. context->blendImage (*imageToDraw,
  60537. dx, dy, dw, dh, sx, sy,
  60538. state->colour.getFloatAlpha());
  60539. }
  60540. }
  60541. else
  60542. {
  60543. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  60544. return;
  60545. if (fillAlphaChannelWithCurrentBrush)
  60546. {
  60547. if (imageToDraw->isRGB())
  60548. {
  60549. fillRect (dx, dy, dw, dh);
  60550. }
  60551. else
  60552. {
  60553. int tx = dx;
  60554. int ty = dy;
  60555. int tw = dw;
  60556. int th = dh;
  60557. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  60558. {
  60559. Image temp (imageToDraw->getFormat(), tw, th, true);
  60560. Graphics g (temp);
  60561. g.setImageResamplingQuality (state->quality);
  60562. g.setOrigin (dx - tx, dy - ty);
  60563. g.drawImage (imageToDraw,
  60564. 0, 0, dw, dh,
  60565. sx, sy, sw, sh,
  60566. false);
  60567. SolidColourBrush colourBrush (state->colour);
  60568. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  60569. .paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  60570. }
  60571. }
  60572. }
  60573. else
  60574. {
  60575. context->blendImageRescaling (*imageToDraw,
  60576. dx, dy, dw, dh,
  60577. sx, sy, sw, sh,
  60578. state->colour.getFloatAlpha(),
  60579. state->quality);
  60580. }
  60581. }
  60582. }
  60583. void Graphics::drawImageTransformed (const Image* const imageToDraw,
  60584. int sourceClipX,
  60585. int sourceClipY,
  60586. int sourceClipWidth,
  60587. int sourceClipHeight,
  60588. const AffineTransform& transform,
  60589. const bool fillAlphaChannelWithCurrentBrush) const throw()
  60590. {
  60591. if (imageToDraw != 0
  60592. && (! context->isClipEmpty())
  60593. && ! transform.isSingularity())
  60594. {
  60595. if (fillAlphaChannelWithCurrentBrush)
  60596. {
  60597. Path p;
  60598. p.addRectangle ((float) sourceClipX, (float) sourceClipY,
  60599. (float) sourceClipWidth, (float) sourceClipHeight);
  60600. p.applyTransform (transform);
  60601. float dx, dy, dw, dh;
  60602. p.getBounds (dx, dy, dw, dh);
  60603. int tx = (int) dx;
  60604. int ty = (int) dy;
  60605. int tw = roundFloatToInt (dw) + 2;
  60606. int th = roundFloatToInt (dh) + 2;
  60607. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  60608. {
  60609. Image temp (imageToDraw->getFormat(), tw, th, true);
  60610. Graphics g (temp);
  60611. g.setImageResamplingQuality (state->quality);
  60612. g.drawImageTransformed (imageToDraw,
  60613. sourceClipX,
  60614. sourceClipY,
  60615. sourceClipWidth,
  60616. sourceClipHeight,
  60617. transform.translated ((float) -tx, (float) -ty),
  60618. false);
  60619. SolidColourBrush colourBrush (state->colour);
  60620. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  60621. }
  60622. }
  60623. else
  60624. {
  60625. context->blendImageWarping (*imageToDraw,
  60626. sourceClipX,
  60627. sourceClipY,
  60628. sourceClipWidth,
  60629. sourceClipHeight,
  60630. transform,
  60631. state->colour.getFloatAlpha(),
  60632. state->quality);
  60633. }
  60634. }
  60635. }
  60636. END_JUCE_NAMESPACE
  60637. /********* End of inlined file: juce_Graphics.cpp *********/
  60638. /********* Start of inlined file: juce_Justification.cpp *********/
  60639. BEGIN_JUCE_NAMESPACE
  60640. Justification::Justification (const Justification& other) throw()
  60641. : flags (other.flags)
  60642. {
  60643. }
  60644. const Justification& Justification::operator= (const Justification& other) throw()
  60645. {
  60646. flags = other.flags;
  60647. return *this;
  60648. }
  60649. int Justification::getOnlyVerticalFlags() const throw()
  60650. {
  60651. return flags & (top | bottom | verticallyCentred);
  60652. }
  60653. int Justification::getOnlyHorizontalFlags() const throw()
  60654. {
  60655. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  60656. }
  60657. void Justification::applyToRectangle (int& x, int& y,
  60658. const int w, const int h,
  60659. const int spaceX, const int spaceY,
  60660. const int spaceW, const int spaceH) const throw()
  60661. {
  60662. if ((flags & horizontallyCentred) != 0)
  60663. {
  60664. x = spaceX + ((spaceW - w) >> 1);
  60665. }
  60666. else if ((flags & right) != 0)
  60667. {
  60668. x = spaceX + spaceW - w;
  60669. }
  60670. else
  60671. {
  60672. x = spaceX;
  60673. }
  60674. if ((flags & verticallyCentred) != 0)
  60675. {
  60676. y = spaceY + ((spaceH - h) >> 1);
  60677. }
  60678. else if ((flags & bottom) != 0)
  60679. {
  60680. y = spaceY + spaceH - h;
  60681. }
  60682. else
  60683. {
  60684. y = spaceY;
  60685. }
  60686. }
  60687. END_JUCE_NAMESPACE
  60688. /********* End of inlined file: juce_Justification.cpp *********/
  60689. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  60690. BEGIN_JUCE_NAMESPACE
  60691. #if JUCE_MSVC
  60692. #pragma warning (disable: 4996) // deprecated sprintf warning
  60693. #endif
  60694. // this will throw an assertion if you try to draw something that's not
  60695. // possible in postscript
  60696. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  60697. #if defined (JUCE_DEBUG) && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  60698. #define notPossibleInPostscriptAssert jassertfalse
  60699. #else
  60700. #define notPossibleInPostscriptAssert
  60701. #endif
  60702. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  60703. const String& documentTitle,
  60704. const int totalWidth_,
  60705. const int totalHeight_)
  60706. : out (resultingPostScript),
  60707. totalWidth (totalWidth_),
  60708. totalHeight (totalHeight_),
  60709. xOffset (0),
  60710. yOffset (0),
  60711. needToClip (true)
  60712. {
  60713. clip = new RectangleList (Rectangle (0, 0, totalWidth_, totalHeight_));
  60714. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  60715. out << "%!PS-Adobe-3.0 EPSF-3.0"
  60716. "\n%%BoundingBox: 0 0 600 824"
  60717. "\n%%Pages: 0"
  60718. "\n%%Creator: Raw Material Software JUCE"
  60719. "\n%%Title: " << documentTitle <<
  60720. "\n%%CreationDate: none"
  60721. "\n%%LanguageLevel: 2"
  60722. "\n%%EndComments"
  60723. "\n%%BeginProlog"
  60724. "\n%%BeginResource: JRes"
  60725. "\n/bd {bind def} bind def"
  60726. "\n/c {setrgbcolor} bd"
  60727. "\n/m {moveto} bd"
  60728. "\n/l {lineto} bd"
  60729. "\n/rl {rlineto} bd"
  60730. "\n/ct {curveto} bd"
  60731. "\n/cp {closepath} bd"
  60732. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  60733. "\n/doclip {initclip newpath} bd"
  60734. "\n/endclip {clip newpath} bd"
  60735. "\n%%EndResource"
  60736. "\n%%EndProlog"
  60737. "\n%%BeginSetup"
  60738. "\n%%EndSetup"
  60739. "\n%%Page: 1 1"
  60740. "\n%%BeginPageSetup"
  60741. "\n%%EndPageSetup\n\n"
  60742. << "40 800 translate\n"
  60743. << scale << ' ' << scale << " scale\n\n";
  60744. }
  60745. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  60746. {
  60747. delete clip;
  60748. }
  60749. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  60750. {
  60751. return true;
  60752. }
  60753. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  60754. {
  60755. if (x != 0 || y != 0)
  60756. {
  60757. xOffset += x;
  60758. yOffset += y;
  60759. needToClip = true;
  60760. }
  60761. }
  60762. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (int x, int y, int w, int h)
  60763. {
  60764. needToClip = true;
  60765. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  60766. }
  60767. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (const RectangleList& clipRegion)
  60768. {
  60769. needToClip = true;
  60770. return clip->clipTo (clipRegion);
  60771. }
  60772. void LowLevelGraphicsPostScriptRenderer::excludeClipRegion (int x, int y, int w, int h)
  60773. {
  60774. needToClip = true;
  60775. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  60776. }
  60777. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (int x, int y, int w, int h)
  60778. {
  60779. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  60780. }
  60781. const Rectangle LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  60782. {
  60783. return clip->getBounds().translated (-xOffset, -yOffset);
  60784. }
  60785. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  60786. {
  60787. return clip->isEmpty();
  60788. }
  60789. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState (RectangleList* const clip_,
  60790. const int xOffset_, const int yOffset_)
  60791. : clip (clip_),
  60792. xOffset (xOffset_),
  60793. yOffset (yOffset_)
  60794. {
  60795. }
  60796. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  60797. {
  60798. delete clip;
  60799. }
  60800. void LowLevelGraphicsPostScriptRenderer::saveState()
  60801. {
  60802. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  60803. }
  60804. void LowLevelGraphicsPostScriptRenderer::restoreState()
  60805. {
  60806. SavedState* const top = stateStack.getLast();
  60807. if (top != 0)
  60808. {
  60809. clip->swapWith (*top->clip);
  60810. xOffset = top->xOffset;
  60811. yOffset = top->yOffset;
  60812. stateStack.removeLast();
  60813. needToClip = true;
  60814. }
  60815. else
  60816. {
  60817. jassertfalse // trying to pop with an empty stack!
  60818. }
  60819. }
  60820. void LowLevelGraphicsPostScriptRenderer::writeClip()
  60821. {
  60822. if (needToClip)
  60823. {
  60824. needToClip = false;
  60825. out << "doclip ";
  60826. int itemsOnLine = 0;
  60827. for (RectangleList::Iterator i (*clip); i.next();)
  60828. {
  60829. if (++itemsOnLine == 6)
  60830. {
  60831. itemsOnLine = 0;
  60832. out << '\n';
  60833. }
  60834. const Rectangle& r = *i.getRectangle();
  60835. out << r.getX() << ' ' << -r.getY() << ' '
  60836. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  60837. }
  60838. out << "endclip\n";
  60839. }
  60840. }
  60841. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  60842. {
  60843. Colour c (Colours::white.overlaidWith (colour));
  60844. if (lastColour != c)
  60845. {
  60846. lastColour = c;
  60847. out << String (c.getFloatRed(), 3) << ' '
  60848. << String (c.getFloatGreen(), 3) << ' '
  60849. << String (c.getFloatBlue(), 3) << " c\n";
  60850. }
  60851. }
  60852. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  60853. {
  60854. out << String (x, 2) << ' '
  60855. << String (-y, 2) << ' ';
  60856. }
  60857. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  60858. {
  60859. out << "newpath ";
  60860. float lastX = 0.0f;
  60861. float lastY = 0.0f;
  60862. int itemsOnLine = 0;
  60863. Path::Iterator i (path);
  60864. while (i.next())
  60865. {
  60866. if (++itemsOnLine == 4)
  60867. {
  60868. itemsOnLine = 0;
  60869. out << '\n';
  60870. }
  60871. switch (i.elementType)
  60872. {
  60873. case Path::Iterator::startNewSubPath:
  60874. writeXY (i.x1, i.y1);
  60875. lastX = i.x1;
  60876. lastY = i.y1;
  60877. out << "m ";
  60878. break;
  60879. case Path::Iterator::lineTo:
  60880. writeXY (i.x1, i.y1);
  60881. lastX = i.x1;
  60882. lastY = i.y1;
  60883. out << "l ";
  60884. break;
  60885. case Path::Iterator::quadraticTo:
  60886. {
  60887. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  60888. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  60889. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  60890. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  60891. writeXY (cp1x, cp1y);
  60892. writeXY (cp2x, cp2y);
  60893. writeXY (i.x2, i.y2);
  60894. out << "ct ";
  60895. lastX = i.x2;
  60896. lastY = i.y2;
  60897. }
  60898. break;
  60899. case Path::Iterator::cubicTo:
  60900. writeXY (i.x1, i.y1);
  60901. writeXY (i.x2, i.y2);
  60902. writeXY (i.x3, i.y3);
  60903. out << "ct ";
  60904. lastX = i.x3;
  60905. lastY = i.y3;
  60906. break;
  60907. case Path::Iterator::closePath:
  60908. out << "cp ";
  60909. break;
  60910. default:
  60911. jassertfalse
  60912. break;
  60913. }
  60914. }
  60915. out << '\n';
  60916. }
  60917. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  60918. {
  60919. out << "[ "
  60920. << trans.mat00 << ' '
  60921. << trans.mat10 << ' '
  60922. << trans.mat01 << ' '
  60923. << trans.mat11 << ' '
  60924. << trans.mat02 << ' '
  60925. << trans.mat12 << " ] concat ";
  60926. }
  60927. void LowLevelGraphicsPostScriptRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool /*replaceExistingContents*/)
  60928. {
  60929. writeClip();
  60930. writeColour (colour);
  60931. x += xOffset;
  60932. y += yOffset;
  60933. out << x << ' ' << -(y + h) << ' ' << w << ' ' << h << " rectfill\n";
  60934. }
  60935. void LowLevelGraphicsPostScriptRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  60936. {
  60937. Path p;
  60938. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  60939. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_256times);
  60940. }
  60941. void LowLevelGraphicsPostScriptRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  60942. const Colour& colour, EdgeTable::OversamplingLevel /*quality*/)
  60943. {
  60944. writeClip();
  60945. Path p (path);
  60946. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  60947. writePath (p);
  60948. writeColour (colour);
  60949. out << "fill\n";
  60950. }
  60951. void LowLevelGraphicsPostScriptRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel /*quality*/)
  60952. {
  60953. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  60954. // postscript can't do semi-transparent ones.
  60955. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  60956. writeClip();
  60957. out << "gsave ";
  60958. {
  60959. Path p (path);
  60960. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  60961. writePath (p);
  60962. out << "clip\n";
  60963. }
  60964. int numColours = 256;
  60965. PixelARGB* const colours = gradient.createLookupTable (numColours);
  60966. for (int i = numColours; --i >= 0;)
  60967. colours[i].unpremultiply();
  60968. const Rectangle bounds (clip->getBounds());
  60969. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  60970. // time-being, this just fills it with the average colour..
  60971. writeColour (Colour (colours [numColours / 2].getARGB()));
  60972. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  60973. juce_free (colours);
  60974. out << "grestore\n";
  60975. }
  60976. void LowLevelGraphicsPostScriptRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  60977. const Image& sourceImage,
  60978. int imageX, int imageY,
  60979. float opacity, EdgeTable::OversamplingLevel /*quality*/)
  60980. {
  60981. writeClip();
  60982. out << "gsave ";
  60983. Path p (path);
  60984. p.applyTransform (transform.translated ((float) xOffset, (float) yOffset));
  60985. writePath (p);
  60986. out << "clip\n";
  60987. blendImage (sourceImage, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight(), 0, 0, opacity);
  60988. out << "grestore\n";
  60989. }
  60990. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithColour (const Image& /*clipImage*/, int x, int y, const Colour& colour)
  60991. {
  60992. x += xOffset;
  60993. y += yOffset;
  60994. writeClip();
  60995. writeColour (colour);
  60996. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  60997. }
  60998. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithGradient (const Image& /*alphaChannelImage*/, int imageX, int imageY, const ColourGradient& /*gradient*/)
  60999. {
  61000. imageX += xOffset;
  61001. imageY += yOffset;
  61002. writeClip();
  61003. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  61004. }
  61005. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithImage (const Image& /*alphaImage*/, int alphaImageX, int alphaImageY,
  61006. const Image& /*fillerImage*/, int fillerImageX, int fillerImageY, float /*opacity*/)
  61007. {
  61008. alphaImageX += xOffset;
  61009. alphaImageY += yOffset;
  61010. fillerImageX += xOffset;
  61011. fillerImageY += yOffset;
  61012. writeClip();
  61013. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  61014. }
  61015. void LowLevelGraphicsPostScriptRenderer::blendImageRescaling (const Image& sourceImage,
  61016. int dx, int dy, int dw, int dh,
  61017. int sx, int sy, int sw, int sh,
  61018. float alpha,
  61019. const Graphics::ResamplingQuality quality)
  61020. {
  61021. if (sw > 0 && sh > 0)
  61022. {
  61023. jassert (sx >= 0 && sx + sw <= sourceImage.getWidth());
  61024. jassert (sy >= 0 && sy + sh <= sourceImage.getHeight());
  61025. if (sw == dw && sh == dh)
  61026. {
  61027. blendImage (sourceImage,
  61028. dx, dy, dw, dh,
  61029. sx, sy, alpha);
  61030. }
  61031. else
  61032. {
  61033. blendImageWarping (sourceImage,
  61034. sx, sy, sw, sh,
  61035. AffineTransform::scale (dw / (float) sw,
  61036. dh / (float) sh)
  61037. .translated ((float) (dx - sx),
  61038. (float) (dy - sy)),
  61039. alpha,
  61040. quality);
  61041. }
  61042. }
  61043. }
  61044. void LowLevelGraphicsPostScriptRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  61045. {
  61046. blendImageWarping (sourceImage,
  61047. sx, sy, dw, dh,
  61048. AffineTransform::translation ((float) dx, (float) dy),
  61049. opacity, Graphics::highResamplingQuality);
  61050. }
  61051. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  61052. const int sx, const int sy,
  61053. const int maxW, const int maxH) const
  61054. {
  61055. out << "{<\n";
  61056. const int w = jmin (maxW, im.getWidth());
  61057. const int h = jmin (maxH, im.getHeight());
  61058. int charsOnLine = 0;
  61059. int lineStride, pixelStride;
  61060. const uint8* data = im.lockPixelDataReadOnly (0, 0, w, h, lineStride, pixelStride);
  61061. Colour pixel;
  61062. for (int y = h; --y >= 0;)
  61063. {
  61064. for (int x = 0; x < w; ++x)
  61065. {
  61066. const uint8* pixelData = data + lineStride * y + pixelStride * x;
  61067. if (x >= sx && y >= sy)
  61068. {
  61069. if (im.isARGB())
  61070. {
  61071. PixelARGB p (*(const PixelARGB*) pixelData);
  61072. p.unpremultiply();
  61073. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  61074. }
  61075. else if (im.isRGB())
  61076. {
  61077. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  61078. }
  61079. else
  61080. {
  61081. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  61082. }
  61083. }
  61084. else
  61085. {
  61086. pixel = Colours::transparentWhite;
  61087. }
  61088. char colourString [16];
  61089. sprintf (colourString, "%x%x%x", pixel.getRed(), pixel.getGreen(), pixel.getBlue());
  61090. out << (const char*) colourString;
  61091. charsOnLine += 3;
  61092. if (charsOnLine > 100)
  61093. {
  61094. out << '\n';
  61095. charsOnLine = 0;
  61096. }
  61097. }
  61098. }
  61099. im.releasePixelDataReadOnly (data);
  61100. out << "\n>}\n";
  61101. }
  61102. void LowLevelGraphicsPostScriptRenderer::blendImageWarping (const Image& sourceImage,
  61103. int srcClipX, int srcClipY,
  61104. int srcClipW, int srcClipH,
  61105. const AffineTransform& t,
  61106. float /*opacity*/,
  61107. const Graphics::ResamplingQuality /*quality*/)
  61108. {
  61109. const int w = jmin (sourceImage.getWidth(), srcClipX + srcClipW);
  61110. const int h = jmin (sourceImage.getHeight(), srcClipY + srcClipH);
  61111. writeClip();
  61112. out << "gsave ";
  61113. writeTransform (t.translated ((float) xOffset, (float) yOffset)
  61114. .scaled (1.0f, -1.0f));
  61115. RectangleList imageClip;
  61116. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  61117. imageClip.clipTo (Rectangle (srcClipX, srcClipY, srcClipW, srcClipH));
  61118. out << "newpath ";
  61119. int itemsOnLine = 0;
  61120. for (RectangleList::Iterator i (imageClip); i.next();)
  61121. {
  61122. if (++itemsOnLine == 6)
  61123. {
  61124. out << '\n';
  61125. itemsOnLine = 0;
  61126. }
  61127. const Rectangle& r = *i.getRectangle();
  61128. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  61129. }
  61130. out << " clip newpath\n";
  61131. out << w << ' ' << h << " scale\n";
  61132. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  61133. writeImage (sourceImage, srcClipX, srcClipY, srcClipW, srcClipH);
  61134. out << "false 3 colorimage grestore\n";
  61135. needToClip = true;
  61136. }
  61137. void LowLevelGraphicsPostScriptRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  61138. {
  61139. Path p;
  61140. p.addLineSegment ((float) x1, (float) y1, (float) x2, (float) y2, 1.0f);
  61141. fillPathWithColour (p, AffineTransform::identity, colour, EdgeTable::Oversampling_256times);
  61142. }
  61143. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  61144. {
  61145. drawLine (x, top, x, bottom, col);
  61146. }
  61147. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  61148. {
  61149. drawLine (left, y, right, y, col);
  61150. }
  61151. END_JUCE_NAMESPACE
  61152. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  61153. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  61154. BEGIN_JUCE_NAMESPACE
  61155. #if ! (defined (JUCE_MAC) || (defined (JUCE_WIN32) && defined (JUCE_64BIT)))
  61156. #define JUCE_USE_SSE_INSTRUCTIONS 1
  61157. #endif
  61158. #if defined (JUCE_DEBUG) && JUCE_MSVC
  61159. #pragma warning (disable: 4714)
  61160. #endif
  61161. #define MINIMUM_COORD -0x3fffffff
  61162. #define MAXIMUM_COORD 0x3fffffff
  61163. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  61164. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  61165. jassert ((int) x >= MINIMUM_COORD \
  61166. && (int) x <= MAXIMUM_COORD \
  61167. && (int) y >= MINIMUM_COORD \
  61168. && (int) y <= MAXIMUM_COORD \
  61169. && (int) w >= 0 \
  61170. && (int) w < MAXIMUM_COORD \
  61171. && (int) h >= 0 \
  61172. && (int) h < MAXIMUM_COORD);
  61173. static void replaceRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  61174. {
  61175. const PixelARGB blendColour (colour.getPixelARGB());
  61176. if (w < 32)
  61177. {
  61178. while (--h >= 0)
  61179. {
  61180. PixelRGB* dest = (PixelRGB*) pixels;
  61181. for (int i = w; --i >= 0;)
  61182. (dest++)->set (blendColour);
  61183. pixels += stride;
  61184. }
  61185. }
  61186. else
  61187. {
  61188. // for wider fills, it's worth using some optimisations..
  61189. const uint8 r = blendColour.getRed();
  61190. const uint8 g = blendColour.getGreen();
  61191. const uint8 b = blendColour.getBlue();
  61192. if (r == g && r == b) // if all the component values are the same, we can cheat..
  61193. {
  61194. while (--h >= 0)
  61195. {
  61196. memset (pixels, r, w * 3);
  61197. pixels += stride;
  61198. }
  61199. }
  61200. else
  61201. {
  61202. PixelRGB filler [4];
  61203. filler[0].set (blendColour);
  61204. filler[1].set (blendColour);
  61205. filler[2].set (blendColour);
  61206. filler[3].set (blendColour);
  61207. const int* const intFiller = (const int*) filler;
  61208. while (--h >= 0)
  61209. {
  61210. uint8* dest = (uint8*) pixels;
  61211. int i = w;
  61212. while ((i > 8) && (((pointer_sized_int) dest & 7) != 0))
  61213. {
  61214. ((PixelRGB*) dest)->set (blendColour);
  61215. dest += 3;
  61216. --i;
  61217. }
  61218. while (i >= 4)
  61219. {
  61220. ((int*) dest) [0] = intFiller[0];
  61221. ((int*) dest) [1] = intFiller[1];
  61222. ((int*) dest) [2] = intFiller[2];
  61223. dest += 12;
  61224. i -= 4;
  61225. }
  61226. while (--i >= 0)
  61227. {
  61228. ((PixelRGB*) dest)->set (blendColour);
  61229. dest += 3;
  61230. }
  61231. pixels += stride;
  61232. }
  61233. }
  61234. }
  61235. }
  61236. static void replaceRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  61237. {
  61238. const PixelARGB blendColour (colour.getPixelARGB());
  61239. while (--h >= 0)
  61240. {
  61241. PixelARGB* const dest = (PixelARGB*) pixels;
  61242. for (int i = 0; i < w; ++i)
  61243. dest[i] = blendColour;
  61244. pixels += stride;
  61245. }
  61246. }
  61247. static void blendRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  61248. {
  61249. if (colour.isOpaque())
  61250. {
  61251. replaceRectRGB (pixels, w, h, stride, colour);
  61252. }
  61253. else
  61254. {
  61255. const PixelARGB blendColour (colour.getPixelARGB());
  61256. const int alpha = blendColour.getAlpha();
  61257. if (alpha <= 0)
  61258. return;
  61259. #if defined (JUCE_USE_SSE_INSTRUCTIONS) && ! JUCE_64BIT
  61260. if (SystemStats::hasSSE())
  61261. {
  61262. int64 rgb0 = (((int64) blendColour.getRed()) << 32)
  61263. | (int64) ((blendColour.getGreen() << 16)
  61264. | blendColour.getBlue());
  61265. const int invAlpha = 0xff - alpha;
  61266. int64 aaaa = (invAlpha << 16) | invAlpha;
  61267. aaaa = (aaaa << 16) | aaaa;
  61268. #ifndef JUCE_GCC
  61269. __asm
  61270. {
  61271. movq mm1, aaaa
  61272. movq mm2, rgb0
  61273. pxor mm7, mm7
  61274. }
  61275. while (--h >= 0)
  61276. {
  61277. __asm
  61278. {
  61279. mov edx, pixels
  61280. mov ebx, w
  61281. pixloop:
  61282. prefetchnta [edx]
  61283. mov ax, [edx + 1]
  61284. shl eax, 8
  61285. mov al, [edx]
  61286. movd mm0, eax
  61287. punpcklbw mm0, mm7
  61288. pmullw mm0, mm1
  61289. psrlw mm0, 8
  61290. paddw mm0, mm2
  61291. packuswb mm0, mm7
  61292. movd eax, mm0
  61293. mov [edx], al
  61294. inc edx
  61295. shr eax, 8
  61296. mov [edx], ax
  61297. add edx, 2
  61298. dec ebx
  61299. jg pixloop
  61300. }
  61301. pixels += stride;
  61302. }
  61303. __asm emms
  61304. #else
  61305. __asm__ __volatile__ (
  61306. "movq %[aaaa], %%mm1 \n"
  61307. "\tmovq %[rgb0], %%mm2 \n"
  61308. "\tpxor %%mm7, %%mm7 \n"
  61309. ".lineLoop2: \n"
  61310. "\tmovl %%esi,%%edx \n"
  61311. "\tmovl %[w], %%ebx \n"
  61312. ".pixLoop2: \n"
  61313. "\tprefetchnta (%%edx) \n"
  61314. "\tmov (%%edx), %%ax \n"
  61315. "\tshl $8, %%eax \n"
  61316. "\tmov 2(%%edx), %%al \n"
  61317. "\tmovd %%eax, %%mm0 \n"
  61318. "\tpunpcklbw %%mm7, %%mm0 \n"
  61319. "\tpmullw %%mm1, %%mm0 \n"
  61320. "\tpsrlw $8, %%mm0 \n"
  61321. "\tpaddw %%mm2, %%mm0 \n"
  61322. "\tpackuswb %%mm7, %%mm0 \n"
  61323. "\tmovd %%mm0, %%eax \n"
  61324. "\tmovb %%al, (%%edx) \n"
  61325. "\tinc %%edx \n"
  61326. "\tshr $8, %%eax \n"
  61327. "\tmovw %%ax, (%%edx) \n"
  61328. "\tadd $2, %%edx \n"
  61329. "\tdec %%ebx \n"
  61330. "\tjg .pixLoop2 \n"
  61331. "\tadd %%edi, %%esi \n"
  61332. "\tdec %%ecx \n"
  61333. "\tjg .lineLoop2 \n"
  61334. "\temms \n"
  61335. : /* No output registers */
  61336. : [aaaa] "m" (aaaa), /* Input registers */
  61337. [rgb0] "m" (rgb0),
  61338. [w] "m" (w),
  61339. "c" (h),
  61340. [stride] "D" (stride),
  61341. [pixels] "S" (pixels)
  61342. : "cc", "eax", "edx", "memory" /* Clobber list */
  61343. );
  61344. #endif
  61345. }
  61346. else
  61347. #endif
  61348. {
  61349. while (--h >= 0)
  61350. {
  61351. PixelRGB* dest = (PixelRGB*) pixels;
  61352. for (int i = w; --i >= 0;)
  61353. (dest++)->blend (blendColour);
  61354. pixels += stride;
  61355. }
  61356. }
  61357. }
  61358. }
  61359. static void blendRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  61360. {
  61361. if (colour.isOpaque())
  61362. {
  61363. replaceRectARGB (pixels, w, h, stride, colour);
  61364. }
  61365. else
  61366. {
  61367. const PixelARGB blendColour (colour.getPixelARGB());
  61368. const int alpha = blendColour.getAlpha();
  61369. if (alpha <= 0)
  61370. return;
  61371. while (--h >= 0)
  61372. {
  61373. PixelARGB* dest = (PixelARGB*) pixels;
  61374. for (int i = w; --i >= 0;)
  61375. (dest++)->blend (blendColour);
  61376. pixels += stride;
  61377. }
  61378. }
  61379. }
  61380. static void blendAlphaMapARGB (uint8* destPixel, const int imageStride,
  61381. const uint8* alphaValues, const int w, int h,
  61382. const int pixelStride, const int lineStride,
  61383. const Colour& colour) throw()
  61384. {
  61385. const PixelARGB srcPix (colour.getPixelARGB());
  61386. while (--h >= 0)
  61387. {
  61388. PixelARGB* dest = (PixelARGB*) destPixel;
  61389. const uint8* src = alphaValues;
  61390. int i = w;
  61391. while (--i >= 0)
  61392. {
  61393. unsigned int srcAlpha = *src;
  61394. src += pixelStride;
  61395. if (srcAlpha > 0)
  61396. dest->blend (srcPix, srcAlpha);
  61397. ++dest;
  61398. }
  61399. alphaValues += lineStride;
  61400. destPixel += imageStride;
  61401. }
  61402. }
  61403. static void blendAlphaMapRGB (uint8* destPixel, const int imageStride,
  61404. const uint8* alphaValues, int const width, int height,
  61405. const int pixelStride, const int lineStride,
  61406. const Colour& colour) throw()
  61407. {
  61408. const PixelARGB srcPix (colour.getPixelARGB());
  61409. while (--height >= 0)
  61410. {
  61411. PixelRGB* dest = (PixelRGB*) destPixel;
  61412. const uint8* src = alphaValues;
  61413. int i = width;
  61414. while (--i >= 0)
  61415. {
  61416. unsigned int srcAlpha = *src;
  61417. src += pixelStride;
  61418. if (srcAlpha > 0)
  61419. dest->blend (srcPix, srcAlpha);
  61420. ++dest;
  61421. }
  61422. alphaValues += lineStride;
  61423. destPixel += imageStride;
  61424. }
  61425. }
  61426. template <class PixelType>
  61427. class SolidColourEdgeTableRenderer
  61428. {
  61429. uint8* const data;
  61430. const int stride;
  61431. PixelType* linePixels;
  61432. PixelARGB sourceColour;
  61433. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  61434. const SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  61435. public:
  61436. SolidColourEdgeTableRenderer (uint8* const data_,
  61437. const int stride_,
  61438. const Colour& colour) throw()
  61439. : data (data_),
  61440. stride (stride_),
  61441. sourceColour (colour.getPixelARGB())
  61442. {
  61443. }
  61444. forcedinline void setEdgeTableYPos (const int y) throw()
  61445. {
  61446. linePixels = (PixelType*) (data + stride * y);
  61447. }
  61448. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  61449. {
  61450. linePixels[x].blend (sourceColour, alphaLevel);
  61451. }
  61452. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  61453. {
  61454. PixelARGB p (sourceColour);
  61455. p.multiplyAlpha (alphaLevel);
  61456. PixelType* dest = linePixels + x;
  61457. if (p.getAlpha() < 0xff)
  61458. {
  61459. do
  61460. {
  61461. dest->blend (p);
  61462. ++dest;
  61463. } while (--width > 0);
  61464. }
  61465. else
  61466. {
  61467. do
  61468. {
  61469. dest->set (p);
  61470. ++dest;
  61471. } while (--width > 0);
  61472. }
  61473. }
  61474. };
  61475. class AlphaBitmapRenderer
  61476. {
  61477. uint8* data;
  61478. int stride;
  61479. uint8* lineStart;
  61480. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  61481. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  61482. public:
  61483. AlphaBitmapRenderer (uint8* const data_,
  61484. const int stride_) throw()
  61485. : data (data_),
  61486. stride (stride_)
  61487. {
  61488. }
  61489. forcedinline void setEdgeTableYPos (const int y) throw()
  61490. {
  61491. lineStart = data + (stride * y);
  61492. }
  61493. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  61494. {
  61495. lineStart [x] = (uint8) alphaLevel;
  61496. }
  61497. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  61498. {
  61499. uint8* d = lineStart + x;
  61500. while (--width >= 0)
  61501. *d++ = (uint8) alphaLevel;
  61502. }
  61503. };
  61504. static const int numScaleBits = 12;
  61505. class LinearGradientPixelGenerator
  61506. {
  61507. const PixelARGB* const lookupTable;
  61508. const int numEntries;
  61509. PixelARGB linePix;
  61510. int start, scale;
  61511. double grad, yTerm;
  61512. bool vertical, horizontal;
  61513. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  61514. const LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  61515. public:
  61516. LinearGradientPixelGenerator (const ColourGradient& gradient,
  61517. const PixelARGB* const lookupTable_, const int numEntries_)
  61518. : lookupTable (lookupTable_),
  61519. numEntries (numEntries_)
  61520. {
  61521. jassert (numEntries_ >= 0);
  61522. float x1 = gradient.x1;
  61523. float y1 = gradient.y1;
  61524. float x2 = gradient.x2;
  61525. float y2 = gradient.y2;
  61526. if (! gradient.transform.isIdentity())
  61527. {
  61528. Line l (x2, y2, x1, y1);
  61529. const Point p3 = l.getPointAlongLine (0.0, 100.0f);
  61530. float x3 = p3.getX();
  61531. float y3 = p3.getY();
  61532. gradient.transform.transformPoint (x1, y1);
  61533. gradient.transform.transformPoint (x2, y2);
  61534. gradient.transform.transformPoint (x3, y3);
  61535. Line l2 (x2, y2, x3, y3);
  61536. float prop = l2.findNearestPointTo (x1, y1);
  61537. const Point newP2 (l2.getPointAlongLineProportionally (prop));
  61538. x2 = newP2.getX();
  61539. y2 = newP2.getY();
  61540. }
  61541. vertical = fabs (x1 - x2) < 0.001f;
  61542. horizontal = fabs (y1 - y2) < 0.001f;
  61543. if (vertical)
  61544. {
  61545. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (y2 - y1));
  61546. start = roundDoubleToInt (y1 * scale);
  61547. }
  61548. else if (horizontal)
  61549. {
  61550. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (x2 - x1));
  61551. start = roundDoubleToInt (x1 * scale);
  61552. }
  61553. else
  61554. {
  61555. grad = (y2 - y1) / (double) (x1 - x2);
  61556. yTerm = y1 - x1 / grad;
  61557. scale = roundDoubleToInt ((numEntries << numScaleBits) / (yTerm * grad - (y2 * grad - x2)));
  61558. grad *= scale;
  61559. }
  61560. }
  61561. forcedinline void setY (const int y) throw()
  61562. {
  61563. if (vertical)
  61564. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> numScaleBits)];
  61565. else if (! horizontal)
  61566. start = roundDoubleToInt ((y - yTerm) * grad);
  61567. }
  61568. forcedinline const PixelARGB getPixel (const int x) const throw()
  61569. {
  61570. if (vertical)
  61571. return linePix;
  61572. return lookupTable [jlimit (0, numEntries, (x * scale - start) >> numScaleBits)];
  61573. }
  61574. };
  61575. class RadialGradientPixelGenerator
  61576. {
  61577. protected:
  61578. const PixelARGB* const lookupTable;
  61579. const int numEntries;
  61580. const double gx1, gy1;
  61581. double maxDist, invScale;
  61582. double dy;
  61583. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  61584. const RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  61585. public:
  61586. RadialGradientPixelGenerator (const ColourGradient& gradient,
  61587. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  61588. : lookupTable (lookupTable_),
  61589. numEntries (numEntries_),
  61590. gx1 (gradient.x1),
  61591. gy1 (gradient.y1)
  61592. {
  61593. jassert (numEntries_ >= 0);
  61594. const float dx = gradient.x1 - gradient.x2;
  61595. const float dy = gradient.y1 - gradient.y2;
  61596. maxDist = dx * dx + dy * dy;
  61597. invScale = (numEntries + 1) / sqrt (maxDist);
  61598. }
  61599. forcedinline void setY (const int y) throw()
  61600. {
  61601. dy = y - gy1;
  61602. dy *= dy;
  61603. }
  61604. forcedinline const PixelARGB getPixel (const int px) const throw()
  61605. {
  61606. double x = px - gx1;
  61607. x *= x;
  61608. x += dy;
  61609. if (x >= maxDist)
  61610. return lookupTable [numEntries];
  61611. else
  61612. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  61613. }
  61614. };
  61615. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  61616. {
  61617. double tM10, tM00, lineYM01, lineYM11;
  61618. AffineTransform inverseTransform;
  61619. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  61620. const TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  61621. public:
  61622. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient,
  61623. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  61624. : RadialGradientPixelGenerator (gradient, lookupTable_, numEntries_),
  61625. inverseTransform (gradient.transform.inverted())
  61626. {
  61627. tM10 = inverseTransform.mat10;
  61628. tM00 = inverseTransform.mat00;
  61629. }
  61630. forcedinline void setY (const int y) throw()
  61631. {
  61632. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  61633. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  61634. }
  61635. forcedinline const PixelARGB getPixel (const int px) const throw()
  61636. {
  61637. double x = px;
  61638. const double y = tM10 * x + lineYM11;
  61639. x = tM00 * x + lineYM01;
  61640. x *= x;
  61641. x += y * y;
  61642. if (x >= maxDist)
  61643. return lookupTable [numEntries];
  61644. else
  61645. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  61646. }
  61647. };
  61648. template <class PixelType, class GradientType>
  61649. class GradientEdgeTableRenderer : public GradientType
  61650. {
  61651. uint8* const data;
  61652. const int stride;
  61653. PixelType* linePixels;
  61654. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  61655. const GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  61656. public:
  61657. GradientEdgeTableRenderer (uint8* const data_,
  61658. const int stride_,
  61659. const ColourGradient& gradient,
  61660. const PixelARGB* const lookupTable, const int numEntries) throw()
  61661. : GradientType (gradient, lookupTable, numEntries - 1),
  61662. data (data_),
  61663. stride (stride_)
  61664. {
  61665. }
  61666. forcedinline void setEdgeTableYPos (const int y) throw()
  61667. {
  61668. linePixels = (PixelType*) (data + stride * y);
  61669. GradientType::setY (y);
  61670. }
  61671. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  61672. {
  61673. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  61674. }
  61675. forcedinline void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  61676. {
  61677. PixelType* dest = linePixels + x;
  61678. if (alphaLevel < 0xff)
  61679. {
  61680. do
  61681. {
  61682. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  61683. } while (--width > 0);
  61684. }
  61685. else
  61686. {
  61687. do
  61688. {
  61689. (dest++)->blend (GradientType::getPixel (x++));
  61690. } while (--width > 0);
  61691. }
  61692. }
  61693. };
  61694. template <class DestPixelType, class SrcPixelType>
  61695. class ImageFillEdgeTableRenderer
  61696. {
  61697. uint8* const destImageData;
  61698. const uint8* srcImageData;
  61699. int stride, srcStride, extraAlpha;
  61700. DestPixelType* linePixels;
  61701. SrcPixelType* sourceLineStart;
  61702. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  61703. const ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  61704. public:
  61705. ImageFillEdgeTableRenderer (uint8* const destImageData_,
  61706. const int stride_,
  61707. const uint8* srcImageData_,
  61708. const int srcStride_,
  61709. int extraAlpha_,
  61710. SrcPixelType*) throw() // dummy param to avoid compiler error
  61711. : destImageData (destImageData_),
  61712. srcImageData (srcImageData_),
  61713. stride (stride_),
  61714. srcStride (srcStride_),
  61715. extraAlpha (extraAlpha_)
  61716. {
  61717. }
  61718. forcedinline void setEdgeTableYPos (int y) throw()
  61719. {
  61720. linePixels = (DestPixelType*) (destImageData + stride * y);
  61721. sourceLineStart = (SrcPixelType*) (srcImageData + srcStride * y);
  61722. }
  61723. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  61724. {
  61725. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  61726. linePixels[x].blend (sourceLineStart [x], alphaLevel);
  61727. }
  61728. forcedinline void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  61729. {
  61730. DestPixelType* dest = linePixels + x;
  61731. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  61732. if (alphaLevel < 0xfe)
  61733. {
  61734. do
  61735. {
  61736. dest++ ->blend (sourceLineStart [x++], alphaLevel);
  61737. } while (--width > 0);
  61738. }
  61739. else
  61740. {
  61741. do
  61742. {
  61743. dest++ ->blend (sourceLineStart [x++]);
  61744. } while (--width > 0);
  61745. }
  61746. }
  61747. };
  61748. static void blendRowOfPixels (PixelARGB* dst,
  61749. const PixelRGB* src,
  61750. int width) throw()
  61751. {
  61752. while (--width >= 0)
  61753. (dst++)->set (*src++);
  61754. }
  61755. static void blendRowOfPixels (PixelRGB* dst,
  61756. const PixelRGB* src,
  61757. int width) throw()
  61758. {
  61759. memcpy (dst, src, 3 * width);
  61760. }
  61761. static void blendRowOfPixels (PixelRGB* dst,
  61762. const PixelARGB* src,
  61763. int width) throw()
  61764. {
  61765. while (--width >= 0)
  61766. (dst++)->blend (*src++);
  61767. }
  61768. static void blendRowOfPixels (PixelARGB* dst,
  61769. const PixelARGB* src,
  61770. int width) throw()
  61771. {
  61772. while (--width >= 0)
  61773. (dst++)->blend (*src++);
  61774. }
  61775. static void blendRowOfPixels (PixelARGB* dst,
  61776. const PixelRGB* src,
  61777. int width,
  61778. const uint8 alpha) throw()
  61779. {
  61780. while (--width >= 0)
  61781. (dst++)->blend (*src++, alpha);
  61782. }
  61783. static void blendRowOfPixels (PixelRGB* dst,
  61784. const PixelRGB* src,
  61785. int width,
  61786. const uint8 alpha) throw()
  61787. {
  61788. uint8* d = (uint8*) dst;
  61789. const uint8* s = (const uint8*) src;
  61790. const int inverseAlpha = 0xff - alpha;
  61791. while (--width >= 0)
  61792. {
  61793. d[0] = (uint8) (s[0] + (((d[0] - s[0]) * inverseAlpha) >> 8));
  61794. d[1] = (uint8) (s[1] + (((d[1] - s[1]) * inverseAlpha) >> 8));
  61795. d[2] = (uint8) (s[2] + (((d[2] - s[2]) * inverseAlpha) >> 8));
  61796. d += 3;
  61797. s += 3;
  61798. }
  61799. }
  61800. static void blendRowOfPixels (PixelRGB* dst,
  61801. const PixelARGB* src,
  61802. int width,
  61803. const uint8 alpha) throw()
  61804. {
  61805. while (--width >= 0)
  61806. (dst++)->blend (*src++, alpha);
  61807. }
  61808. static void blendRowOfPixels (PixelARGB* dst,
  61809. const PixelARGB* src,
  61810. int width,
  61811. const uint8 alpha) throw()
  61812. {
  61813. while (--width >= 0)
  61814. (dst++)->blend (*src++, alpha);
  61815. }
  61816. template <class DestPixelType, class SrcPixelType>
  61817. static void overlayImage (DestPixelType* dest,
  61818. const int destStride,
  61819. const SrcPixelType* src,
  61820. const int srcStride,
  61821. const int width,
  61822. int height,
  61823. const uint8 alpha) throw()
  61824. {
  61825. if (alpha < 0xff)
  61826. {
  61827. while (--height >= 0)
  61828. {
  61829. blendRowOfPixels (dest, src, width, alpha);
  61830. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  61831. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  61832. }
  61833. }
  61834. else
  61835. {
  61836. while (--height >= 0)
  61837. {
  61838. blendRowOfPixels (dest, src, width);
  61839. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  61840. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  61841. }
  61842. }
  61843. }
  61844. template <class DestPixelType, class SrcPixelType>
  61845. static void transformedImageRender (Image& destImage,
  61846. const Image& sourceImage,
  61847. const int destClipX, const int destClipY,
  61848. const int destClipW, const int destClipH,
  61849. const int srcClipX, const int srcClipY,
  61850. const int srcClipWidth, const int srcClipHeight,
  61851. double srcX, double srcY,
  61852. const double lineDX, const double lineDY,
  61853. const double pixelDX, const double pixelDY,
  61854. const uint8 alpha,
  61855. const Graphics::ResamplingQuality quality,
  61856. DestPixelType*,
  61857. SrcPixelType*) throw() // forced by a compiler bug to include dummy
  61858. // parameters of the templated classes to
  61859. // make it use the correct instance of this function..
  61860. {
  61861. int destStride, destPixelStride;
  61862. uint8* const destPixels = destImage.lockPixelDataReadWrite (destClipX, destClipY, destClipW, destClipH, destStride, destPixelStride);
  61863. int srcStride, srcPixelStride;
  61864. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (srcClipX, srcClipY, srcClipWidth, srcClipHeight, srcStride, srcPixelStride);
  61865. if (quality == Graphics::lowResamplingQuality) // nearest-neighbour..
  61866. {
  61867. for (int y = 0; y < destClipH; ++y)
  61868. {
  61869. double sx = srcX;
  61870. double sy = srcY;
  61871. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  61872. for (int x = 0; x < destClipW; ++x)
  61873. {
  61874. const int ix = roundDoubleToInt (floor (sx)) - srcClipX;
  61875. if (((unsigned int) ix) < (unsigned int) srcClipWidth)
  61876. {
  61877. const int iy = roundDoubleToInt (floor (sy)) - srcClipY;
  61878. if (((unsigned int) iy) < (unsigned int) srcClipHeight)
  61879. {
  61880. const SrcPixelType* const src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  61881. dest->blend (*src, alpha);
  61882. }
  61883. }
  61884. ++dest;
  61885. sx += pixelDX;
  61886. sy += pixelDY;
  61887. }
  61888. srcX += lineDX;
  61889. srcY += lineDY;
  61890. }
  61891. }
  61892. else
  61893. {
  61894. jassert (quality == Graphics::mediumResamplingQuality); // (only bilinear is implemented, so that's what you'll get here..)
  61895. for (int y = 0; y < destClipH; ++y)
  61896. {
  61897. double sx = srcX;
  61898. double sy = srcY;
  61899. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  61900. for (int x = 0; x < destClipW; ++x)
  61901. {
  61902. const double fx = floor (sx);
  61903. const double fy = floor (sy);
  61904. const int ix = roundDoubleToInt (fx) - srcClipX;
  61905. const int iy = roundDoubleToInt (fy) - srcClipY;
  61906. if (ix < srcClipWidth && iy < srcClipHeight)
  61907. {
  61908. PixelARGB p1 (0), p2 (0), p3 (0), p4 (0);
  61909. const SrcPixelType* src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  61910. if (iy >= 0)
  61911. {
  61912. if (ix >= 0)
  61913. p1.set (src[0]);
  61914. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  61915. p2.set (src[1]);
  61916. }
  61917. if (((unsigned int) (iy + 1)) < (unsigned int) srcClipHeight)
  61918. {
  61919. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  61920. if (ix >= 0)
  61921. p3.set (src[0]);
  61922. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  61923. p4.set (src[1]);
  61924. }
  61925. const int dx = roundDoubleToInt ((sx - fx) * 255.0);
  61926. p1.tween (p2, dx);
  61927. p3.tween (p4, dx);
  61928. p1.tween (p3, roundDoubleToInt ((sy - fy) * 255.0));
  61929. if (p1.getAlpha() > 0)
  61930. dest->blend (p1, alpha);
  61931. }
  61932. ++dest;
  61933. sx += pixelDX;
  61934. sy += pixelDY;
  61935. }
  61936. srcX += lineDX;
  61937. srcY += lineDY;
  61938. }
  61939. }
  61940. destImage.releasePixelDataReadWrite (destPixels);
  61941. sourceImage.releasePixelDataReadOnly (srcPixels);
  61942. }
  61943. template <class SrcPixelType, class DestPixelType>
  61944. static void renderAlphaMap (DestPixelType* destPixels,
  61945. int destStride,
  61946. SrcPixelType* srcPixels,
  61947. int srcStride,
  61948. const uint8* alphaValues,
  61949. const int lineStride, const int pixelStride,
  61950. int width, int height,
  61951. const int extraAlpha) throw()
  61952. {
  61953. while (--height >= 0)
  61954. {
  61955. SrcPixelType* srcPix = srcPixels;
  61956. srcPixels = (SrcPixelType*) (((const uint8*) srcPixels) + srcStride);
  61957. DestPixelType* destPix = destPixels;
  61958. destPixels = (DestPixelType*) (((uint8*) destPixels) + destStride);
  61959. const uint8* alpha = alphaValues;
  61960. alphaValues += lineStride;
  61961. if (extraAlpha < 0x100)
  61962. {
  61963. for (int i = width; --i >= 0;)
  61964. {
  61965. destPix++ ->blend (*srcPix++, (extraAlpha * *alpha) >> 8);
  61966. alpha += pixelStride;
  61967. }
  61968. }
  61969. else
  61970. {
  61971. for (int i = width; --i >= 0;)
  61972. {
  61973. destPix++ ->blend (*srcPix++, *alpha);
  61974. alpha += pixelStride;
  61975. }
  61976. }
  61977. }
  61978. }
  61979. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (Image& image_)
  61980. : image (image_),
  61981. xOffset (0),
  61982. yOffset (0),
  61983. stateStack (20)
  61984. {
  61985. clip = new RectangleList (Rectangle (0, 0, image_.getWidth(), image_.getHeight()));
  61986. }
  61987. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  61988. {
  61989. delete clip;
  61990. }
  61991. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  61992. {
  61993. return false;
  61994. }
  61995. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  61996. {
  61997. xOffset += x;
  61998. yOffset += y;
  61999. }
  62000. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (int x, int y, int w, int h)
  62001. {
  62002. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  62003. }
  62004. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (const RectangleList& clipRegion)
  62005. {
  62006. RectangleList temp (clipRegion);
  62007. temp.offsetAll (xOffset, yOffset);
  62008. return clip->clipTo (temp);
  62009. }
  62010. void LowLevelGraphicsSoftwareRenderer::excludeClipRegion (int x, int y, int w, int h)
  62011. {
  62012. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  62013. }
  62014. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (int x, int y, int w, int h)
  62015. {
  62016. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  62017. }
  62018. const Rectangle LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  62019. {
  62020. return clip->getBounds().translated (-xOffset, -yOffset);
  62021. }
  62022. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  62023. {
  62024. return clip->isEmpty();
  62025. }
  62026. LowLevelGraphicsSoftwareRenderer::SavedState::SavedState (RectangleList* const clip_,
  62027. const int xOffset_, const int yOffset_)
  62028. : clip (clip_),
  62029. xOffset (xOffset_),
  62030. yOffset (yOffset_)
  62031. {
  62032. }
  62033. LowLevelGraphicsSoftwareRenderer::SavedState::~SavedState()
  62034. {
  62035. delete clip;
  62036. }
  62037. void LowLevelGraphicsSoftwareRenderer::saveState()
  62038. {
  62039. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  62040. }
  62041. void LowLevelGraphicsSoftwareRenderer::restoreState()
  62042. {
  62043. SavedState* const top = stateStack.getLast();
  62044. if (top != 0)
  62045. {
  62046. clip->swapWith (*top->clip);
  62047. xOffset = top->xOffset;
  62048. yOffset = top->yOffset;
  62049. stateStack.removeLast();
  62050. }
  62051. else
  62052. {
  62053. jassertfalse // trying to pop with an empty stack!
  62054. }
  62055. }
  62056. void LowLevelGraphicsSoftwareRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  62057. {
  62058. x += xOffset;
  62059. y += yOffset;
  62060. for (RectangleList::Iterator i (*clip); i.next();)
  62061. {
  62062. clippedFillRectWithColour (*i.getRectangle(), x, y, w, h, colour, replaceExistingContents);
  62063. }
  62064. }
  62065. void LowLevelGraphicsSoftwareRenderer::clippedFillRectWithColour (const Rectangle& clipRect,
  62066. int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  62067. {
  62068. if (clipRect.intersectRectangle (x, y, w, h))
  62069. {
  62070. int stride, pixelStride;
  62071. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  62072. if (image.getFormat() == Image::RGB)
  62073. {
  62074. if (replaceExistingContents)
  62075. replaceRectRGB (pixels, w, h, stride, colour);
  62076. else
  62077. blendRectRGB (pixels, w, h, stride, colour);
  62078. }
  62079. else if (image.getFormat() == Image::ARGB)
  62080. {
  62081. if (replaceExistingContents)
  62082. replaceRectARGB (pixels, w, h, stride, colour);
  62083. else
  62084. blendRectARGB (pixels, w, h, stride, colour);
  62085. }
  62086. else
  62087. {
  62088. jassertfalse // not done!
  62089. }
  62090. image.releasePixelDataReadWrite (pixels);
  62091. }
  62092. }
  62093. void LowLevelGraphicsSoftwareRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  62094. {
  62095. Path p;
  62096. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  62097. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_none);
  62098. }
  62099. bool LowLevelGraphicsSoftwareRenderer::getPathBounds (int clipX, int clipY, int clipW, int clipH,
  62100. const Path& path, const AffineTransform& transform,
  62101. int& x, int& y, int& w, int& h) const
  62102. {
  62103. float tx, ty, tw, th;
  62104. path.getBoundsTransformed (transform, tx, ty, tw, th);
  62105. x = roundDoubleToInt (tx) - 1;
  62106. y = roundDoubleToInt (ty) - 1;
  62107. w = roundDoubleToInt (tw) + 2;
  62108. h = roundDoubleToInt (th) + 2;
  62109. // seems like this operation is using some crazy out-of-range numbers..
  62110. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, w, h);
  62111. return Rectangle::intersectRectangles (x, y, w, h, clipX, clipY, clipW, clipH);
  62112. }
  62113. void LowLevelGraphicsSoftwareRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  62114. const Colour& colour, EdgeTable::OversamplingLevel quality)
  62115. {
  62116. for (RectangleList::Iterator i (*clip); i.next();)
  62117. {
  62118. const Rectangle& r = *i.getRectangle();
  62119. clippedFillPathWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(), path, t, colour, quality);
  62120. }
  62121. }
  62122. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  62123. const Colour& colour, EdgeTable::OversamplingLevel quality)
  62124. {
  62125. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  62126. int cx, cy, cw, ch;
  62127. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  62128. {
  62129. EdgeTable edgeTable (0, ch, quality);
  62130. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  62131. int stride, pixelStride;
  62132. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  62133. if (image.getFormat() == Image::RGB)
  62134. {
  62135. jassert (pixelStride == 3);
  62136. SolidColourEdgeTableRenderer <PixelRGB> renderer (pixels, stride, colour);
  62137. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62138. }
  62139. else if (image.getFormat() == Image::ARGB)
  62140. {
  62141. jassert (pixelStride == 4);
  62142. SolidColourEdgeTableRenderer <PixelARGB> renderer (pixels, stride, colour);
  62143. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62144. }
  62145. else if (image.getFormat() == Image::SingleChannel)
  62146. {
  62147. jassert (pixelStride == 1);
  62148. AlphaBitmapRenderer renderer (pixels, stride);
  62149. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62150. }
  62151. image.releasePixelDataReadWrite (pixels);
  62152. }
  62153. }
  62154. void LowLevelGraphicsSoftwareRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  62155. {
  62156. for (RectangleList::Iterator i (*clip); i.next();)
  62157. {
  62158. const Rectangle& r = *i.getRectangle();
  62159. clippedFillPathWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62160. path, t, gradient, quality);
  62161. }
  62162. }
  62163. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  62164. const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  62165. {
  62166. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  62167. int cx, cy, cw, ch;
  62168. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  62169. {
  62170. int stride, pixelStride;
  62171. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  62172. ColourGradient g2 (gradient);
  62173. const bool isIdentity = g2.transform.isIdentity();
  62174. if (isIdentity)
  62175. {
  62176. g2.x1 += xOffset - cx;
  62177. g2.x2 += xOffset - cx;
  62178. g2.y1 += yOffset - cy;
  62179. g2.y2 += yOffset - cy;
  62180. }
  62181. else
  62182. {
  62183. g2.transform = g2.transform.translated ((float) (xOffset - cx),
  62184. (float) (yOffset - cy));
  62185. }
  62186. int numLookupEntries;
  62187. PixelARGB* const lookupTable = g2.createLookupTable (numLookupEntries);
  62188. jassert (numLookupEntries > 0);
  62189. EdgeTable edgeTable (0, ch, quality);
  62190. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  62191. if (image.getFormat() == Image::RGB)
  62192. {
  62193. jassert (pixelStride == 3);
  62194. if (g2.isRadial)
  62195. {
  62196. if (isIdentity)
  62197. {
  62198. GradientEdgeTableRenderer <PixelRGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62199. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62200. }
  62201. else
  62202. {
  62203. GradientEdgeTableRenderer <PixelRGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62204. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62205. }
  62206. }
  62207. else
  62208. {
  62209. GradientEdgeTableRenderer <PixelRGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62210. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62211. }
  62212. }
  62213. else if (image.getFormat() == Image::ARGB)
  62214. {
  62215. jassert (pixelStride == 4);
  62216. if (g2.isRadial)
  62217. {
  62218. if (isIdentity)
  62219. {
  62220. GradientEdgeTableRenderer <PixelARGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62221. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62222. }
  62223. else
  62224. {
  62225. GradientEdgeTableRenderer <PixelARGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62226. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62227. }
  62228. }
  62229. else
  62230. {
  62231. GradientEdgeTableRenderer <PixelARGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62232. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62233. }
  62234. }
  62235. else if (image.getFormat() == Image::SingleChannel)
  62236. {
  62237. jassertfalse // not done!
  62238. }
  62239. juce_free (lookupTable);
  62240. image.releasePixelDataReadWrite (pixels);
  62241. }
  62242. }
  62243. void LowLevelGraphicsSoftwareRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  62244. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  62245. {
  62246. imageX += xOffset;
  62247. imageY += yOffset;
  62248. for (RectangleList::Iterator i (*clip); i.next();)
  62249. {
  62250. const Rectangle& r = *i.getRectangle();
  62251. clippedFillPathWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62252. path, transform, sourceImage, imageX, imageY, opacity, quality);
  62253. }
  62254. }
  62255. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithImage (int x, int y, int w, int h, const Path& path, const AffineTransform& transform,
  62256. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  62257. {
  62258. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight()))
  62259. {
  62260. EdgeTable edgeTable (0, h, quality);
  62261. edgeTable.addPath (path, transform.translated ((float) (xOffset - x), (float) (yOffset - y)));
  62262. int stride, pixelStride;
  62263. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  62264. int srcStride, srcPixelStride;
  62265. const uint8* const srcPix = (const uint8*) sourceImage.lockPixelDataReadOnly (x - imageX, y - imageY, w, h, srcStride, srcPixelStride);
  62266. const int alpha = jlimit (0, 255, roundDoubleToInt (opacity * 255.0f));
  62267. if (image.getFormat() == Image::RGB)
  62268. {
  62269. if (sourceImage.getFormat() == Image::RGB)
  62270. {
  62271. ImageFillEdgeTableRenderer <PixelRGB, PixelRGB> renderer (pixels, stride,
  62272. srcPix, srcStride,
  62273. alpha, (PixelRGB*) 0);
  62274. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  62275. }
  62276. else if (sourceImage.getFormat() == Image::ARGB)
  62277. {
  62278. ImageFillEdgeTableRenderer <PixelRGB, PixelARGB> renderer (pixels, stride,
  62279. srcPix, srcStride,
  62280. alpha, (PixelARGB*) 0);
  62281. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  62282. }
  62283. else
  62284. {
  62285. jassertfalse // not done!
  62286. }
  62287. }
  62288. else if (image.getFormat() == Image::ARGB)
  62289. {
  62290. if (sourceImage.getFormat() == Image::RGB)
  62291. {
  62292. ImageFillEdgeTableRenderer <PixelARGB, PixelRGB> renderer (pixels, stride,
  62293. srcPix, srcStride,
  62294. alpha, (PixelRGB*) 0);
  62295. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  62296. }
  62297. else if (sourceImage.getFormat() == Image::ARGB)
  62298. {
  62299. ImageFillEdgeTableRenderer <PixelARGB, PixelARGB> renderer (pixels, stride,
  62300. srcPix, srcStride,
  62301. alpha, (PixelARGB*) 0);
  62302. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  62303. }
  62304. else
  62305. {
  62306. jassertfalse // not done!
  62307. }
  62308. }
  62309. else
  62310. {
  62311. jassertfalse // not done!
  62312. }
  62313. sourceImage.releasePixelDataReadOnly (srcPix);
  62314. image.releasePixelDataReadWrite (pixels);
  62315. }
  62316. }
  62317. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithColour (const Image& clipImage, int x, int y, const Colour& colour)
  62318. {
  62319. x += xOffset;
  62320. y += yOffset;
  62321. for (RectangleList::Iterator i (*clip); i.next();)
  62322. {
  62323. const Rectangle& r = *i.getRectangle();
  62324. clippedFillAlphaChannelWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62325. clipImage, x, y, colour);
  62326. }
  62327. }
  62328. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& clipImage, int x, int y, const Colour& colour)
  62329. {
  62330. int w = clipImage.getWidth();
  62331. int h = clipImage.getHeight();
  62332. int sx = 0;
  62333. int sy = 0;
  62334. if (x < clipX)
  62335. {
  62336. sx = clipX - x;
  62337. w -= clipX - x;
  62338. x = clipX;
  62339. }
  62340. if (y < clipY)
  62341. {
  62342. sy = clipY - y;
  62343. h -= clipY - y;
  62344. y = clipY;
  62345. }
  62346. if (x + w > clipX + clipW)
  62347. w = clipX + clipW - x;
  62348. if (y + h > clipY + clipH)
  62349. h = clipY + clipH - y;
  62350. if (w > 0 && h > 0)
  62351. {
  62352. int stride, alphaStride, pixelStride;
  62353. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  62354. const uint8* const alphaValues
  62355. = clipImage.lockPixelDataReadOnly (sx, sy, w, h, alphaStride, pixelStride);
  62356. #if JUCE_MAC
  62357. const uint8* const alphas = alphaValues;
  62358. #else
  62359. const uint8* const alphas = alphaValues + (clipImage.getFormat() == Image::ARGB ? 3 : 0);
  62360. #endif
  62361. if (image.getFormat() == Image::RGB)
  62362. {
  62363. blendAlphaMapRGB (pixels, stride,
  62364. alphas, w, h,
  62365. pixelStride, alphaStride,
  62366. colour);
  62367. }
  62368. else if (image.getFormat() == Image::ARGB)
  62369. {
  62370. blendAlphaMapARGB (pixels, stride,
  62371. alphas, w, h,
  62372. pixelStride, alphaStride,
  62373. colour);
  62374. }
  62375. else
  62376. {
  62377. jassertfalse // not done!
  62378. }
  62379. clipImage.releasePixelDataReadOnly (alphaValues);
  62380. image.releasePixelDataReadWrite (pixels);
  62381. }
  62382. }
  62383. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithGradient (const Image& alphaChannelImage, int imageX, int imageY, const ColourGradient& gradient)
  62384. {
  62385. imageX += xOffset;
  62386. imageY += yOffset;
  62387. for (RectangleList::Iterator i (*clip); i.next();)
  62388. {
  62389. const Rectangle& r = *i.getRectangle();
  62390. clippedFillAlphaChannelWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62391. alphaChannelImage, imageX, imageY, gradient);
  62392. }
  62393. }
  62394. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithGradient (int x, int y, int w, int h,
  62395. const Image& alphaChannelImage,
  62396. int imageX, int imageY, const ColourGradient& gradient)
  62397. {
  62398. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, alphaChannelImage.getWidth(), alphaChannelImage.getHeight()))
  62399. {
  62400. ColourGradient g2 (gradient);
  62401. g2.x1 += xOffset - x;
  62402. g2.x2 += xOffset - x;
  62403. g2.y1 += yOffset - y;
  62404. g2.y2 += yOffset - y;
  62405. Image temp (g2.isOpaque() ? Image::RGB : Image::ARGB, w, h, true);
  62406. LowLevelGraphicsSoftwareRenderer tempG (temp);
  62407. tempG.fillRectWithGradient (0, 0, w, h, g2);
  62408. clippedFillAlphaChannelWithImage (x, y, w, h,
  62409. alphaChannelImage, imageX, imageY,
  62410. temp, x, y, 1.0f);
  62411. }
  62412. }
  62413. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  62414. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  62415. {
  62416. alphaImageX += xOffset;
  62417. alphaImageY += yOffset;
  62418. fillerImageX += xOffset;
  62419. fillerImageY += yOffset;
  62420. for (RectangleList::Iterator i (*clip); i.next();)
  62421. {
  62422. const Rectangle& r = *i.getRectangle();
  62423. clippedFillAlphaChannelWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62424. alphaImage, alphaImageX, alphaImageY,
  62425. fillerImage, fillerImageX, fillerImageY, opacity);
  62426. }
  62427. }
  62428. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithImage (int x, int y, int w, int h, const Image& alphaImage, int alphaImageX, int alphaImageY,
  62429. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  62430. {
  62431. if (Rectangle::intersectRectangles (x, y, w, h, alphaImageX, alphaImageY, alphaImage.getWidth(), alphaImage.getHeight())
  62432. && Rectangle::intersectRectangles (x, y, w, h, fillerImageX, fillerImageY, fillerImage.getWidth(), fillerImage.getHeight()))
  62433. {
  62434. int dstStride, dstPixStride;
  62435. uint8* const dstPix = image.lockPixelDataReadWrite (x, y, w, h, dstStride, dstPixStride);
  62436. int srcStride, srcPixStride;
  62437. const uint8* const srcPix = fillerImage.lockPixelDataReadOnly (x - fillerImageX, y - fillerImageY, w, h, srcStride, srcPixStride);
  62438. int maskStride, maskPixStride;
  62439. const uint8* const alpha
  62440. = alphaImage.lockPixelDataReadOnly (x - alphaImageX, y - alphaImageY, w, h, maskStride, maskPixStride);
  62441. #if JUCE_MAC
  62442. const uint8* const alphaValues = alpha;
  62443. #else
  62444. const uint8* const alphaValues = alpha + (alphaImage.getFormat() == Image::ARGB ? 3 : 0);
  62445. #endif
  62446. const int extraAlpha = jlimit (0, 0x100, roundDoubleToInt (opacity * 256.0f));
  62447. if (image.getFormat() == Image::RGB)
  62448. {
  62449. if (fillerImage.getFormat() == Image::RGB)
  62450. {
  62451. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  62452. }
  62453. else if (fillerImage.getFormat() == Image::ARGB)
  62454. {
  62455. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  62456. }
  62457. else
  62458. {
  62459. jassertfalse // not done!
  62460. }
  62461. }
  62462. else if (image.getFormat() == Image::ARGB)
  62463. {
  62464. if (fillerImage.getFormat() == Image::RGB)
  62465. {
  62466. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  62467. }
  62468. else if (fillerImage.getFormat() == Image::ARGB)
  62469. {
  62470. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  62471. }
  62472. else
  62473. {
  62474. jassertfalse // not done!
  62475. }
  62476. }
  62477. else
  62478. {
  62479. jassertfalse // not done!
  62480. }
  62481. alphaImage.releasePixelDataReadOnly (alphaValues);
  62482. fillerImage.releasePixelDataReadOnly (srcPix);
  62483. image.releasePixelDataReadWrite (dstPix);
  62484. }
  62485. }
  62486. void LowLevelGraphicsSoftwareRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  62487. {
  62488. dx += xOffset;
  62489. dy += yOffset;
  62490. for (RectangleList::Iterator i (*clip); i.next();)
  62491. {
  62492. const Rectangle& r = *i.getRectangle();
  62493. clippedBlendImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62494. sourceImage, dx, dy, dw, dh, sx, sy, opacity);
  62495. }
  62496. }
  62497. void LowLevelGraphicsSoftwareRenderer::clippedBlendImage (int clipX, int clipY, int clipW, int clipH,
  62498. const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  62499. {
  62500. if (dx < clipX)
  62501. {
  62502. sx += clipX - dx;
  62503. dw -= clipX - dx;
  62504. dx = clipX;
  62505. }
  62506. if (dy < clipY)
  62507. {
  62508. sy += clipY - dy;
  62509. dh -= clipY - dy;
  62510. dy = clipY;
  62511. }
  62512. if (dx + dw > clipX + clipW)
  62513. dw = clipX + clipW - dx;
  62514. if (dy + dh > clipY + clipH)
  62515. dh = clipY + clipH - dy;
  62516. if (dw <= 0 || dh <= 0)
  62517. return;
  62518. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  62519. if (alpha == 0)
  62520. return;
  62521. int dstStride, dstPixelStride;
  62522. uint8* const dstPixels = image.lockPixelDataReadWrite (dx, dy, dw, dh, dstStride, dstPixelStride);
  62523. int srcStride, srcPixelStride;
  62524. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (sx, sy, dw, dh, srcStride, srcPixelStride);
  62525. if (image.getFormat() == Image::ARGB)
  62526. {
  62527. if (sourceImage.getFormat() == Image::ARGB)
  62528. {
  62529. overlayImage ((PixelARGB*) dstPixels, dstStride,
  62530. (PixelARGB*) srcPixels, srcStride,
  62531. dw, dh, alpha);
  62532. }
  62533. else if (sourceImage.getFormat() == Image::RGB)
  62534. {
  62535. overlayImage ((PixelARGB*) dstPixels, dstStride,
  62536. (PixelRGB*) srcPixels, srcStride,
  62537. dw, dh, alpha);
  62538. }
  62539. else
  62540. {
  62541. jassertfalse
  62542. }
  62543. }
  62544. else if (image.getFormat() == Image::RGB)
  62545. {
  62546. if (sourceImage.getFormat() == Image::ARGB)
  62547. {
  62548. overlayImage ((PixelRGB*) dstPixels, dstStride,
  62549. (PixelARGB*) srcPixels, srcStride,
  62550. dw, dh, alpha);
  62551. }
  62552. else if (sourceImage.getFormat() == Image::RGB)
  62553. {
  62554. overlayImage ((PixelRGB*) dstPixels, dstStride,
  62555. (PixelRGB*) srcPixels, srcStride,
  62556. dw, dh, alpha);
  62557. }
  62558. else
  62559. {
  62560. jassertfalse
  62561. }
  62562. }
  62563. else
  62564. {
  62565. jassertfalse
  62566. }
  62567. image.releasePixelDataReadWrite (dstPixels);
  62568. sourceImage.releasePixelDataReadOnly (srcPixels);
  62569. }
  62570. void LowLevelGraphicsSoftwareRenderer::blendImageRescaling (const Image& sourceImage,
  62571. int dx, int dy, int dw, int dh,
  62572. int sx, int sy, int sw, int sh,
  62573. float alpha,
  62574. const Graphics::ResamplingQuality quality)
  62575. {
  62576. if (sw > 0 && sh > 0)
  62577. {
  62578. if (sw == dw && sh == dh)
  62579. {
  62580. blendImage (sourceImage,
  62581. dx, dy, dw, dh,
  62582. sx, sy, alpha);
  62583. }
  62584. else
  62585. {
  62586. blendImageWarping (sourceImage,
  62587. sx, sy, sw, sh,
  62588. AffineTransform::translation ((float) -sx,
  62589. (float) -sy)
  62590. .scaled (dw / (float) sw,
  62591. dh / (float) sh)
  62592. .translated ((float) dx,
  62593. (float) dy),
  62594. alpha,
  62595. quality);
  62596. }
  62597. }
  62598. }
  62599. void LowLevelGraphicsSoftwareRenderer::blendImageWarping (const Image& sourceImage,
  62600. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  62601. const AffineTransform& t,
  62602. float opacity,
  62603. const Graphics::ResamplingQuality quality)
  62604. {
  62605. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  62606. for (RectangleList::Iterator i (*clip); i.next();)
  62607. {
  62608. const Rectangle& r = *i.getRectangle();
  62609. clippedBlendImageWarping (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62610. sourceImage, srcClipX, srcClipY, srcClipW, srcClipH,
  62611. transform, opacity, quality);
  62612. }
  62613. }
  62614. void LowLevelGraphicsSoftwareRenderer::clippedBlendImageWarping (int destClipX, int destClipY, int destClipW, int destClipH,
  62615. const Image& sourceImage,
  62616. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  62617. const AffineTransform& transform,
  62618. float opacity,
  62619. const Graphics::ResamplingQuality quality)
  62620. {
  62621. if (opacity > 0 && destClipW > 0 && destClipH > 0 && ! transform.isSingularity())
  62622. {
  62623. Rectangle::intersectRectangles (srcClipX, srcClipY, srcClipW, srcClipH,
  62624. 0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  62625. if (srcClipW <= 0 || srcClipH <= 0)
  62626. return;
  62627. jassert (srcClipX >= 0 && srcClipY >= 0);
  62628. Path imageBounds;
  62629. imageBounds.addRectangle ((float) srcClipX, (float) srcClipY, (float) srcClipW, (float) srcClipH);
  62630. imageBounds.applyTransform (transform);
  62631. float imX, imY, imW, imH;
  62632. imageBounds.getBounds (imX, imY, imW, imH);
  62633. if (Rectangle::intersectRectangles (destClipX, destClipY, destClipW, destClipH,
  62634. (int) floorf (imX),
  62635. (int) floorf (imY),
  62636. 1 + roundDoubleToInt (imW),
  62637. 1 + roundDoubleToInt (imH)))
  62638. {
  62639. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  62640. float srcX1 = (float) destClipX;
  62641. float srcY1 = (float) destClipY;
  62642. float srcX2 = (float) (destClipX + destClipW);
  62643. float srcY2 = srcY1;
  62644. float srcX3 = srcX1;
  62645. float srcY3 = (float) (destClipY + destClipH);
  62646. AffineTransform inverse (transform.inverted());
  62647. inverse.transformPoint (srcX1, srcY1);
  62648. inverse.transformPoint (srcX2, srcY2);
  62649. inverse.transformPoint (srcX3, srcY3);
  62650. const double lineDX = (double) (srcX3 - srcX1) / destClipH;
  62651. const double lineDY = (double) (srcY3 - srcY1) / destClipH;
  62652. const double pixelDX = (double) (srcX2 - srcX1) / destClipW;
  62653. const double pixelDY = (double) (srcY2 - srcY1) / destClipW;
  62654. if (image.getFormat() == Image::ARGB)
  62655. {
  62656. if (sourceImage.getFormat() == Image::ARGB)
  62657. {
  62658. transformedImageRender (image, sourceImage,
  62659. destClipX, destClipY, destClipW, destClipH,
  62660. srcClipX, srcClipY, srcClipW, srcClipH,
  62661. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  62662. alpha, quality, (PixelARGB*)0, (PixelARGB*)0);
  62663. }
  62664. else if (sourceImage.getFormat() == Image::RGB)
  62665. {
  62666. transformedImageRender (image, sourceImage,
  62667. destClipX, destClipY, destClipW, destClipH,
  62668. srcClipX, srcClipY, srcClipW, srcClipH,
  62669. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  62670. alpha, quality, (PixelARGB*)0, (PixelRGB*)0);
  62671. }
  62672. else
  62673. {
  62674. jassertfalse
  62675. }
  62676. }
  62677. else if (image.getFormat() == Image::RGB)
  62678. {
  62679. if (sourceImage.getFormat() == Image::ARGB)
  62680. {
  62681. transformedImageRender (image, sourceImage,
  62682. destClipX, destClipY, destClipW, destClipH,
  62683. srcClipX, srcClipY, srcClipW, srcClipH,
  62684. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  62685. alpha, quality, (PixelRGB*)0, (PixelARGB*)0);
  62686. }
  62687. else if (sourceImage.getFormat() == Image::RGB)
  62688. {
  62689. transformedImageRender (image, sourceImage,
  62690. destClipX, destClipY, destClipW, destClipH,
  62691. srcClipX, srcClipY, srcClipW, srcClipH,
  62692. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  62693. alpha, quality, (PixelRGB*)0, (PixelRGB*)0);
  62694. }
  62695. else
  62696. {
  62697. jassertfalse
  62698. }
  62699. }
  62700. else
  62701. {
  62702. jassertfalse
  62703. }
  62704. }
  62705. }
  62706. }
  62707. void LowLevelGraphicsSoftwareRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  62708. {
  62709. x1 += xOffset;
  62710. y1 += yOffset;
  62711. x2 += xOffset;
  62712. y2 += yOffset;
  62713. for (RectangleList::Iterator i (*clip); i.next();)
  62714. {
  62715. const Rectangle& r = *i.getRectangle();
  62716. clippedDrawLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62717. x1, y1, x2, y2, colour);
  62718. }
  62719. }
  62720. void LowLevelGraphicsSoftwareRenderer::clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour)
  62721. {
  62722. if (clipW > 0 && clipH > 0)
  62723. {
  62724. if (x1 == x2)
  62725. {
  62726. if (y2 < y1)
  62727. swapVariables (y1, y2);
  62728. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (x1), y1, y2, colour);
  62729. }
  62730. else if (y1 == y2)
  62731. {
  62732. if (x2 < x1)
  62733. swapVariables (x1, x2);
  62734. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (y1), x1, x2, colour);
  62735. }
  62736. else
  62737. {
  62738. double gradient = (y2 - y1) / (x2 - x1);
  62739. if (fabs (gradient) > 1.0)
  62740. {
  62741. gradient = 1.0 / gradient;
  62742. int y = roundDoubleToInt (y1);
  62743. const int startY = y;
  62744. int endY = roundDoubleToInt (y2);
  62745. if (y > endY)
  62746. swapVariables (y, endY);
  62747. while (y < endY)
  62748. {
  62749. const double x = x1 + gradient * (y - startY);
  62750. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, y, x, x + 1.0, colour);
  62751. ++y;
  62752. }
  62753. }
  62754. else
  62755. {
  62756. int x = roundDoubleToInt (x1);
  62757. const int startX = x;
  62758. int endX = roundDoubleToInt (x2);
  62759. if (x > endX)
  62760. swapVariables (x, endX);
  62761. while (x < endX)
  62762. {
  62763. const double y = y1 + gradient * (x - startX);
  62764. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, x, y, y + 1.0, colour);
  62765. ++x;
  62766. }
  62767. }
  62768. }
  62769. }
  62770. }
  62771. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  62772. {
  62773. for (RectangleList::Iterator i (*clip); i.next();)
  62774. {
  62775. const Rectangle& r = *i.getRectangle();
  62776. clippedDrawVerticalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62777. x + xOffset, top + yOffset, bottom + yOffset, col);
  62778. }
  62779. }
  62780. void LowLevelGraphicsSoftwareRenderer::clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH,
  62781. const int x, double top, double bottom, const Colour& col)
  62782. {
  62783. jassert (top <= bottom);
  62784. if (((unsigned int) (x - clipX)) < (unsigned int) clipW
  62785. && top < clipY + clipH
  62786. && bottom > clipY
  62787. && clipW > 0)
  62788. {
  62789. if (top < clipY)
  62790. top = clipY;
  62791. if (bottom > clipY + clipH)
  62792. bottom = clipY + clipH;
  62793. if (bottom > top)
  62794. drawVertical (x, top, bottom, col);
  62795. }
  62796. }
  62797. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  62798. {
  62799. for (RectangleList::Iterator i (*clip); i.next();)
  62800. {
  62801. const Rectangle& r = *i.getRectangle();
  62802. clippedDrawHorizontalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62803. y + yOffset, left + xOffset, right + xOffset, col);
  62804. }
  62805. }
  62806. void LowLevelGraphicsSoftwareRenderer::clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH,
  62807. const int y, double left, double right, const Colour& col)
  62808. {
  62809. jassert (left <= right);
  62810. if (((unsigned int) (y - clipY)) < (unsigned int) clipH
  62811. && left < clipX + clipW
  62812. && right > clipX
  62813. && clipW > 0)
  62814. {
  62815. if (left < clipX)
  62816. left = clipX;
  62817. if (right > clipX + clipW)
  62818. right = clipX + clipW;
  62819. if (right > left)
  62820. drawHorizontal (y, left, right, col);
  62821. }
  62822. }
  62823. void LowLevelGraphicsSoftwareRenderer::drawVertical (const int x,
  62824. const double top,
  62825. const double bottom,
  62826. const Colour& col)
  62827. {
  62828. int wholeStart = (int) top;
  62829. const int wholeEnd = (int) bottom;
  62830. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  62831. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  62832. if (totalPixels <= 0)
  62833. return;
  62834. int lineStride, dstPixelStride;
  62835. uint8* const dstPixels = image.lockPixelDataReadWrite (x, wholeStart, 1, totalPixels, lineStride, dstPixelStride);
  62836. uint8* dest = dstPixels;
  62837. PixelARGB colour (col.getPixelARGB());
  62838. if (wholeEnd == wholeStart)
  62839. {
  62840. if (image.getFormat() == Image::ARGB)
  62841. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  62842. else if (image.getFormat() == Image::RGB)
  62843. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  62844. else
  62845. {
  62846. jassertfalse
  62847. }
  62848. }
  62849. else
  62850. {
  62851. if (image.getFormat() == Image::ARGB)
  62852. {
  62853. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  62854. ++wholeStart;
  62855. dest += lineStride;
  62856. if (colour.getAlpha() == 0xff)
  62857. {
  62858. while (wholeEnd > wholeStart)
  62859. {
  62860. ((PixelARGB*) dest)->set (colour);
  62861. ++wholeStart;
  62862. dest += lineStride;
  62863. }
  62864. }
  62865. else
  62866. {
  62867. while (wholeEnd > wholeStart)
  62868. {
  62869. ((PixelARGB*) dest)->blend (colour);
  62870. ++wholeStart;
  62871. dest += lineStride;
  62872. }
  62873. }
  62874. if (lastAlpha > 0)
  62875. {
  62876. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  62877. }
  62878. }
  62879. else if (image.getFormat() == Image::RGB)
  62880. {
  62881. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  62882. ++wholeStart;
  62883. dest += lineStride;
  62884. if (colour.getAlpha() == 0xff)
  62885. {
  62886. while (wholeEnd > wholeStart)
  62887. {
  62888. ((PixelRGB*) dest)->set (colour);
  62889. ++wholeStart;
  62890. dest += lineStride;
  62891. }
  62892. }
  62893. else
  62894. {
  62895. while (wholeEnd > wholeStart)
  62896. {
  62897. ((PixelRGB*) dest)->blend (colour);
  62898. ++wholeStart;
  62899. dest += lineStride;
  62900. }
  62901. }
  62902. if (lastAlpha > 0)
  62903. {
  62904. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  62905. }
  62906. }
  62907. else
  62908. {
  62909. jassertfalse
  62910. }
  62911. }
  62912. image.releasePixelDataReadWrite (dstPixels);
  62913. }
  62914. void LowLevelGraphicsSoftwareRenderer::drawHorizontal (const int y,
  62915. const double top,
  62916. const double bottom,
  62917. const Colour& col)
  62918. {
  62919. int wholeStart = (int) top;
  62920. const int wholeEnd = (int) bottom;
  62921. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  62922. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  62923. if (totalPixels <= 0)
  62924. return;
  62925. int lineStride, dstPixelStride;
  62926. uint8* const dstPixels = image.lockPixelDataReadWrite (wholeStart, y, totalPixels, 1, lineStride, dstPixelStride);
  62927. uint8* dest = dstPixels;
  62928. PixelARGB colour (col.getPixelARGB());
  62929. if (wholeEnd == wholeStart)
  62930. {
  62931. if (image.getFormat() == Image::ARGB)
  62932. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  62933. else if (image.getFormat() == Image::RGB)
  62934. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  62935. else
  62936. {
  62937. jassertfalse
  62938. }
  62939. }
  62940. else
  62941. {
  62942. if (image.getFormat() == Image::ARGB)
  62943. {
  62944. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  62945. dest += dstPixelStride;
  62946. ++wholeStart;
  62947. if (colour.getAlpha() == 0xff)
  62948. {
  62949. while (wholeEnd > wholeStart)
  62950. {
  62951. ((PixelARGB*) dest)->set (colour);
  62952. dest += dstPixelStride;
  62953. ++wholeStart;
  62954. }
  62955. }
  62956. else
  62957. {
  62958. while (wholeEnd > wholeStart)
  62959. {
  62960. ((PixelARGB*) dest)->blend (colour);
  62961. dest += dstPixelStride;
  62962. ++wholeStart;
  62963. }
  62964. }
  62965. if (lastAlpha > 0)
  62966. {
  62967. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  62968. }
  62969. }
  62970. else if (image.getFormat() == Image::RGB)
  62971. {
  62972. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  62973. dest += dstPixelStride;
  62974. ++wholeStart;
  62975. if (colour.getAlpha() == 0xff)
  62976. {
  62977. while (wholeEnd > wholeStart)
  62978. {
  62979. ((PixelRGB*) dest)->set (colour);
  62980. dest += dstPixelStride;
  62981. ++wholeStart;
  62982. }
  62983. }
  62984. else
  62985. {
  62986. while (wholeEnd > wholeStart)
  62987. {
  62988. ((PixelRGB*) dest)->blend (colour);
  62989. dest += dstPixelStride;
  62990. ++wholeStart;
  62991. }
  62992. }
  62993. if (lastAlpha > 0)
  62994. {
  62995. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  62996. }
  62997. }
  62998. else
  62999. {
  63000. jassertfalse
  63001. }
  63002. }
  63003. image.releasePixelDataReadWrite (dstPixels);
  63004. }
  63005. END_JUCE_NAMESPACE
  63006. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  63007. /********* Start of inlined file: juce_RectanglePlacement.cpp *********/
  63008. BEGIN_JUCE_NAMESPACE
  63009. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  63010. : flags (other.flags)
  63011. {
  63012. }
  63013. const RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  63014. {
  63015. flags = other.flags;
  63016. return *this;
  63017. }
  63018. void RectanglePlacement::applyTo (double& x, double& y,
  63019. double& w, double& h,
  63020. const double dx, const double dy,
  63021. const double dw, const double dh) const throw()
  63022. {
  63023. if (w == 0 || h == 0)
  63024. return;
  63025. if ((flags & stretchToFit) != 0)
  63026. {
  63027. x = dx;
  63028. y = dy;
  63029. w = dw;
  63030. h = dh;
  63031. }
  63032. else
  63033. {
  63034. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  63035. : jmin (dw / w, dh / h);
  63036. if ((flags & onlyReduceInSize) != 0)
  63037. scale = jmin (scale, 1.0);
  63038. if ((flags & onlyIncreaseInSize) != 0)
  63039. scale = jmax (scale, 1.0);
  63040. w *= scale;
  63041. h *= scale;
  63042. if ((flags & xLeft) != 0)
  63043. x = dx;
  63044. else if ((flags & xRight) != 0)
  63045. x = dx + dw - w;
  63046. else
  63047. x = dx + (dw - w) * 0.5;
  63048. if ((flags & yTop) != 0)
  63049. y = dy;
  63050. else if ((flags & yBottom) != 0)
  63051. y = dy + dh - h;
  63052. else
  63053. y = dy + (dh - h) * 0.5;
  63054. }
  63055. }
  63056. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  63057. float w, float h,
  63058. const float dx, const float dy,
  63059. const float dw, const float dh) const throw()
  63060. {
  63061. if (w == 0 || h == 0)
  63062. return AffineTransform::identity;
  63063. const float scaleX = dw / w;
  63064. const float scaleY = dh / h;
  63065. if ((flags & stretchToFit) != 0)
  63066. {
  63067. return AffineTransform::translation (-x, -y)
  63068. .scaled (scaleX, scaleY)
  63069. .translated (dx - x, dy - y);
  63070. }
  63071. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  63072. : jmin (scaleX, scaleY);
  63073. if ((flags & onlyReduceInSize) != 0)
  63074. scale = jmin (scale, 1.0f);
  63075. if ((flags & onlyIncreaseInSize) != 0)
  63076. scale = jmax (scale, 1.0f);
  63077. w *= scale;
  63078. h *= scale;
  63079. float newX = dx;
  63080. if ((flags & xRight) != 0)
  63081. newX += dw - w; // right
  63082. else if ((flags & xLeft) == 0)
  63083. newX += (dw - w) / 2.0f; // centre
  63084. float newY = dy;
  63085. if ((flags & yBottom) != 0)
  63086. newY += dh - h; // bottom
  63087. else if ((flags & yTop) == 0)
  63088. newY += (dh - h) / 2.0f; // centre
  63089. return AffineTransform::translation (-x, -y)
  63090. .scaled (scale, scale)
  63091. .translated (newX, newY);
  63092. }
  63093. END_JUCE_NAMESPACE
  63094. /********* End of inlined file: juce_RectanglePlacement.cpp *********/
  63095. /********* Start of inlined file: juce_Drawable.cpp *********/
  63096. BEGIN_JUCE_NAMESPACE
  63097. Drawable::Drawable()
  63098. {
  63099. }
  63100. Drawable::~Drawable()
  63101. {
  63102. }
  63103. void Drawable::drawAt (Graphics& g, const float x, const float y) const
  63104. {
  63105. draw (g, AffineTransform::translation (x, y));
  63106. }
  63107. void Drawable::drawWithin (Graphics& g,
  63108. const int destX,
  63109. const int destY,
  63110. const int destW,
  63111. const int destH,
  63112. const RectanglePlacement& placement) const
  63113. {
  63114. if (destW > 0 && destH > 0)
  63115. {
  63116. float x, y, w, h;
  63117. getBounds (x, y, w, h);
  63118. draw (g, placement.getTransformToFit (x, y, w, h,
  63119. (float) destX, (float) destY,
  63120. (float) destW, (float) destH));
  63121. }
  63122. }
  63123. Drawable* Drawable::createFromImageData (const void* data, const int numBytes)
  63124. {
  63125. Drawable* result = 0;
  63126. Image* const image = ImageFileFormat::loadFrom (data, numBytes);
  63127. if (image != 0)
  63128. {
  63129. DrawableImage* const di = new DrawableImage();
  63130. di->setImage (image, true);
  63131. result = di;
  63132. }
  63133. else
  63134. {
  63135. const String asString (String::createStringFromData (data, numBytes));
  63136. XmlDocument doc (asString);
  63137. XmlElement* const outer = doc.getDocumentElement (true);
  63138. if (outer != 0 && outer->hasTagName (T("svg")))
  63139. {
  63140. XmlElement* const svg = doc.getDocumentElement();
  63141. if (svg != 0)
  63142. {
  63143. result = Drawable::createFromSVG (*svg);
  63144. delete svg;
  63145. }
  63146. }
  63147. delete outer;
  63148. }
  63149. return result;
  63150. }
  63151. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  63152. {
  63153. MemoryBlock mb;
  63154. dataSource.readIntoMemoryBlock (mb);
  63155. return createFromImageData (mb.getData(), mb.getSize());
  63156. }
  63157. Drawable* Drawable::createFromImageFile (const File& file)
  63158. {
  63159. FileInputStream* fin = file.createInputStream();
  63160. if (fin == 0)
  63161. return 0;
  63162. Drawable* d = createFromImageDataStream (*fin);
  63163. delete fin;
  63164. return d;
  63165. }
  63166. END_JUCE_NAMESPACE
  63167. /********* End of inlined file: juce_Drawable.cpp *********/
  63168. /********* Start of inlined file: juce_DrawableComposite.cpp *********/
  63169. BEGIN_JUCE_NAMESPACE
  63170. DrawableComposite::DrawableComposite()
  63171. {
  63172. }
  63173. DrawableComposite::~DrawableComposite()
  63174. {
  63175. }
  63176. void DrawableComposite::insertDrawable (Drawable* drawable,
  63177. const AffineTransform& transform,
  63178. const int index)
  63179. {
  63180. if (drawable != 0)
  63181. {
  63182. if (! drawables.contains (drawable))
  63183. {
  63184. drawables.insert (index, drawable);
  63185. if (transform.isIdentity())
  63186. transforms.insert (index, 0);
  63187. else
  63188. transforms.insert (index, new AffineTransform (transform));
  63189. }
  63190. else
  63191. {
  63192. jassertfalse // trying to add a drawable that's already in here!
  63193. }
  63194. }
  63195. }
  63196. void DrawableComposite::insertDrawable (const Drawable& drawable,
  63197. const AffineTransform& transform,
  63198. const int index)
  63199. {
  63200. insertDrawable (drawable.createCopy(), transform, index);
  63201. }
  63202. void DrawableComposite::removeDrawable (const int index)
  63203. {
  63204. drawables.remove (index);
  63205. transforms.remove (index);
  63206. }
  63207. void DrawableComposite::bringToFront (const int index)
  63208. {
  63209. if (index >= 0 && index < drawables.size() - 1)
  63210. {
  63211. drawables.move (index, -1);
  63212. transforms.move (index, -1);
  63213. }
  63214. }
  63215. void DrawableComposite::draw (Graphics& g, const AffineTransform& transform) const
  63216. {
  63217. for (int i = 0; i < drawables.size(); ++i)
  63218. {
  63219. const AffineTransform* const t = transforms.getUnchecked(i);
  63220. drawables.getUnchecked(i)->draw (g, t == 0 ? transform
  63221. : t->followedBy (transform));
  63222. }
  63223. }
  63224. void DrawableComposite::getBounds (float& x, float& y, float& width, float& height) const
  63225. {
  63226. Path totalPath;
  63227. for (int i = 0; i < drawables.size(); ++i)
  63228. {
  63229. drawables.getUnchecked(i)->getBounds (x, y, width, height);
  63230. if (width > 0.0f && height > 0.0f)
  63231. {
  63232. Path outline;
  63233. outline.addRectangle (x, y, width, height);
  63234. const AffineTransform* const t = transforms.getUnchecked(i);
  63235. if (t == 0)
  63236. totalPath.addPath (outline);
  63237. else
  63238. totalPath.addPath (outline, *t);
  63239. }
  63240. }
  63241. totalPath.getBounds (x, y, width, height);
  63242. }
  63243. bool DrawableComposite::hitTest (float x, float y) const
  63244. {
  63245. for (int i = 0; i < drawables.size(); ++i)
  63246. {
  63247. float tx = x;
  63248. float ty = y;
  63249. const AffineTransform* const t = transforms.getUnchecked(i);
  63250. if (t != 0)
  63251. t->inverted().transformPoint (tx, ty);
  63252. if (drawables.getUnchecked(i)->hitTest (tx, ty))
  63253. return true;
  63254. }
  63255. return false;
  63256. }
  63257. Drawable* DrawableComposite::createCopy() const
  63258. {
  63259. DrawableComposite* const dc = new DrawableComposite();
  63260. for (int i = 0; i < drawables.size(); ++i)
  63261. {
  63262. dc->drawables.add (drawables.getUnchecked(i)->createCopy());
  63263. const AffineTransform* const t = transforms.getUnchecked(i);
  63264. dc->transforms.add (t != 0 ? new AffineTransform (*t) : 0);
  63265. }
  63266. return dc;
  63267. }
  63268. END_JUCE_NAMESPACE
  63269. /********* End of inlined file: juce_DrawableComposite.cpp *********/
  63270. /********* Start of inlined file: juce_DrawableImage.cpp *********/
  63271. BEGIN_JUCE_NAMESPACE
  63272. DrawableImage::DrawableImage()
  63273. : image (0),
  63274. canDeleteImage (false),
  63275. opacity (1.0f),
  63276. overlayColour (0x00000000)
  63277. {
  63278. }
  63279. DrawableImage::~DrawableImage()
  63280. {
  63281. clearImage();
  63282. }
  63283. void DrawableImage::clearImage()
  63284. {
  63285. if (canDeleteImage && image != 0)
  63286. {
  63287. if (ImageCache::isImageInCache (image))
  63288. ImageCache::release (image);
  63289. else
  63290. delete image;
  63291. }
  63292. image = 0;
  63293. }
  63294. void DrawableImage::setImage (const Image& imageToCopy)
  63295. {
  63296. clearImage();
  63297. image = new Image (imageToCopy);
  63298. canDeleteImage = true;
  63299. }
  63300. void DrawableImage::setImage (Image* imageToUse,
  63301. const bool releaseWhenNotNeeded)
  63302. {
  63303. clearImage();
  63304. image = imageToUse;
  63305. canDeleteImage = releaseWhenNotNeeded;
  63306. }
  63307. void DrawableImage::setOpacity (const float newOpacity)
  63308. {
  63309. opacity = newOpacity;
  63310. }
  63311. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  63312. {
  63313. overlayColour = newOverlayColour;
  63314. }
  63315. void DrawableImage::draw (Graphics& g, const AffineTransform& transform) const
  63316. {
  63317. if (image != 0)
  63318. {
  63319. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  63320. if (opacity > 0.0f && ! overlayColour.isOpaque())
  63321. {
  63322. g.setColour (oldColour.withMultipliedAlpha (opacity));
  63323. g.drawImageTransformed (image,
  63324. 0, 0, image->getWidth(), image->getHeight(),
  63325. transform, false);
  63326. }
  63327. if (! overlayColour.isTransparent())
  63328. {
  63329. g.setColour (overlayColour.withMultipliedAlpha (oldColour.getFloatAlpha()));
  63330. g.drawImageTransformed (image,
  63331. 0, 0, image->getWidth(), image->getHeight(),
  63332. transform, true);
  63333. }
  63334. g.setColour (oldColour);
  63335. }
  63336. }
  63337. void DrawableImage::getBounds (float& x, float& y, float& width, float& height) const
  63338. {
  63339. x = 0.0f;
  63340. y = 0.0f;
  63341. width = 0.0f;
  63342. height = 0.0f;
  63343. if (image != 0)
  63344. {
  63345. width = (float) image->getWidth();
  63346. height = (float) image->getHeight();
  63347. }
  63348. }
  63349. bool DrawableImage::hitTest (float x, float y) const
  63350. {
  63351. return image != 0
  63352. && x >= 0.0f
  63353. && y >= 0.0f
  63354. && x < image->getWidth()
  63355. && y < image->getHeight()
  63356. && image->getPixelAt (roundFloatToInt (x), roundFloatToInt (y)).getAlpha() >= 127;
  63357. }
  63358. Drawable* DrawableImage::createCopy() const
  63359. {
  63360. DrawableImage* const di = new DrawableImage();
  63361. di->opacity = opacity;
  63362. di->overlayColour = overlayColour;
  63363. if (image != 0)
  63364. {
  63365. if ((! canDeleteImage) || ! ImageCache::isImageInCache (image))
  63366. {
  63367. di->setImage (*image);
  63368. }
  63369. else
  63370. {
  63371. ImageCache::incReferenceCount (image);
  63372. di->setImage (image, true);
  63373. }
  63374. }
  63375. return di;
  63376. }
  63377. END_JUCE_NAMESPACE
  63378. /********* End of inlined file: juce_DrawableImage.cpp *********/
  63379. /********* Start of inlined file: juce_DrawablePath.cpp *********/
  63380. BEGIN_JUCE_NAMESPACE
  63381. DrawablePath::DrawablePath()
  63382. : fillBrush (new SolidColourBrush (Colours::black)),
  63383. strokeBrush (0),
  63384. strokeType (0.0f)
  63385. {
  63386. }
  63387. DrawablePath::~DrawablePath()
  63388. {
  63389. delete fillBrush;
  63390. delete strokeBrush;
  63391. }
  63392. void DrawablePath::setPath (const Path& newPath)
  63393. {
  63394. path = newPath;
  63395. updateOutline();
  63396. }
  63397. void DrawablePath::setSolidFill (const Colour& newColour)
  63398. {
  63399. delete fillBrush;
  63400. fillBrush = new SolidColourBrush (newColour);
  63401. }
  63402. void DrawablePath::setFillBrush (const Brush& newBrush)
  63403. {
  63404. delete fillBrush;
  63405. fillBrush = newBrush.createCopy();
  63406. }
  63407. void DrawablePath::setOutline (const float thickness, const Colour& colour)
  63408. {
  63409. strokeType = PathStrokeType (thickness);
  63410. delete strokeBrush;
  63411. strokeBrush = new SolidColourBrush (colour);
  63412. updateOutline();
  63413. }
  63414. void DrawablePath::setOutline (const PathStrokeType& strokeType_, const Brush& newStrokeBrush)
  63415. {
  63416. strokeType = strokeType_;
  63417. delete strokeBrush;
  63418. strokeBrush = newStrokeBrush.createCopy();
  63419. updateOutline();
  63420. }
  63421. void DrawablePath::draw (Graphics& g, const AffineTransform& transform) const
  63422. {
  63423. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  63424. const float currentOpacity = oldColour.getFloatAlpha();
  63425. {
  63426. Brush* const tempBrush = fillBrush->createCopy();
  63427. tempBrush->applyTransform (transform);
  63428. tempBrush->multiplyOpacity (currentOpacity);
  63429. g.setBrush (tempBrush);
  63430. g.fillPath (path, transform);
  63431. delete tempBrush;
  63432. }
  63433. if (strokeBrush != 0 && strokeType.getStrokeThickness() > 0.0f)
  63434. {
  63435. Brush* const tempBrush = strokeBrush->createCopy();
  63436. tempBrush->applyTransform (transform);
  63437. tempBrush->multiplyOpacity (currentOpacity);
  63438. g.setBrush (tempBrush);
  63439. g.fillPath (outline, transform);
  63440. delete tempBrush;
  63441. }
  63442. g.setColour (oldColour);
  63443. }
  63444. void DrawablePath::updateOutline()
  63445. {
  63446. outline.clear();
  63447. strokeType.createStrokedPath (outline, path, AffineTransform::identity, 4.0f);
  63448. }
  63449. void DrawablePath::getBounds (float& x, float& y, float& width, float& height) const
  63450. {
  63451. if (strokeType.getStrokeThickness() > 0.0f)
  63452. outline.getBounds (x, y, width, height);
  63453. else
  63454. path.getBounds (x, y, width, height);
  63455. }
  63456. bool DrawablePath::hitTest (float x, float y) const
  63457. {
  63458. return path.contains (x, y)
  63459. || outline.contains (x, y);
  63460. }
  63461. Drawable* DrawablePath::createCopy() const
  63462. {
  63463. DrawablePath* const dp = new DrawablePath();
  63464. dp->path = path;
  63465. dp->setFillBrush (*fillBrush);
  63466. if (strokeBrush != 0)
  63467. dp->setOutline (strokeType, *strokeBrush);
  63468. return dp;
  63469. }
  63470. END_JUCE_NAMESPACE
  63471. /********* End of inlined file: juce_DrawablePath.cpp *********/
  63472. /********* Start of inlined file: juce_DrawableText.cpp *********/
  63473. BEGIN_JUCE_NAMESPACE
  63474. DrawableText::DrawableText()
  63475. : colour (Colours::white)
  63476. {
  63477. }
  63478. DrawableText::~DrawableText()
  63479. {
  63480. }
  63481. void DrawableText::setText (const GlyphArrangement& newText)
  63482. {
  63483. text = newText;
  63484. }
  63485. void DrawableText::setText (const String& newText, const Font& fontToUse)
  63486. {
  63487. text.clear();
  63488. text.addLineOfText (fontToUse, newText, 0.0f, 0.0f);
  63489. }
  63490. void DrawableText::setColour (const Colour& newColour)
  63491. {
  63492. colour = newColour;
  63493. }
  63494. void DrawableText::draw (Graphics& g, const AffineTransform& transform) const
  63495. {
  63496. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  63497. g.setColour (colour.withMultipliedAlpha (oldColour.getFloatAlpha()));
  63498. text.draw (g, transform);
  63499. g.setColour (oldColour);
  63500. }
  63501. void DrawableText::getBounds (float& x, float& y, float& width, float& height) const
  63502. {
  63503. text.getBoundingBox (0, -1, x, y, width, height, false); // (really returns top, left, bottom, right)
  63504. width -= x;
  63505. height -= y;
  63506. }
  63507. bool DrawableText::hitTest (float x, float y) const
  63508. {
  63509. return text.findGlyphIndexAt (x, y) >= 0;
  63510. }
  63511. Drawable* DrawableText::createCopy() const
  63512. {
  63513. DrawableText* const dt = new DrawableText();
  63514. dt->text = text;
  63515. dt->colour = colour;
  63516. return dt;
  63517. }
  63518. END_JUCE_NAMESPACE
  63519. /********* End of inlined file: juce_DrawableText.cpp *********/
  63520. /********* Start of inlined file: juce_SVGParser.cpp *********/
  63521. BEGIN_JUCE_NAMESPACE
  63522. class SVGState
  63523. {
  63524. public:
  63525. SVGState (const XmlElement* const topLevel)
  63526. : topLevelXml (topLevel),
  63527. x (0), y (0),
  63528. width (512), height (512),
  63529. viewBoxW (0), viewBoxH (0)
  63530. {
  63531. }
  63532. ~SVGState()
  63533. {
  63534. }
  63535. Drawable* parseSVGElement (const XmlElement& xml)
  63536. {
  63537. if (! xml.hasTagName (T("svg")))
  63538. return 0;
  63539. DrawableComposite* const drawable = new DrawableComposite();
  63540. drawable->setName (xml.getStringAttribute (T("id")));
  63541. SVGState newState (*this);
  63542. if (xml.hasAttribute (T("transform")))
  63543. newState.addTransform (xml);
  63544. newState.x = getCoordLength (xml.getStringAttribute (T("x"), String (newState.x)), viewBoxW);
  63545. newState.y = getCoordLength (xml.getStringAttribute (T("y"), String (newState.y)), viewBoxH);
  63546. newState.width = getCoordLength (xml.getStringAttribute (T("width"), String (newState.width)), viewBoxW);
  63547. newState.height = getCoordLength (xml.getStringAttribute (T("height"), String (newState.height)), viewBoxH);
  63548. if (xml.hasAttribute (T("viewBox")))
  63549. {
  63550. const String viewParams (xml.getStringAttribute (T("viewBox")));
  63551. int i = 0;
  63552. float vx, vy, vw, vh;
  63553. if (parseCoords (viewParams, vx, vy, i, true)
  63554. && parseCoords (viewParams, vw, vh, i, true)
  63555. && vw > 0
  63556. && vh > 0)
  63557. {
  63558. newState.viewBoxW = vw;
  63559. newState.viewBoxH = vh;
  63560. int placementFlags = 0;
  63561. const String aspect (xml.getStringAttribute (T("preserveAspectRatio")));
  63562. if (aspect.containsIgnoreCase (T("none")))
  63563. {
  63564. placementFlags = RectanglePlacement::stretchToFit;
  63565. }
  63566. else
  63567. {
  63568. if (aspect.containsIgnoreCase (T("slice")))
  63569. placementFlags |= RectanglePlacement::fillDestination;
  63570. if (aspect.containsIgnoreCase (T("xMin")))
  63571. placementFlags |= RectanglePlacement::xLeft;
  63572. else if (aspect.containsIgnoreCase (T("xMax")))
  63573. placementFlags |= RectanglePlacement::xRight;
  63574. else
  63575. placementFlags |= RectanglePlacement::xMid;
  63576. if (aspect.containsIgnoreCase (T("yMin")))
  63577. placementFlags |= RectanglePlacement::yTop;
  63578. else if (aspect.containsIgnoreCase (T("yMax")))
  63579. placementFlags |= RectanglePlacement::yBottom;
  63580. else
  63581. placementFlags |= RectanglePlacement::yMid;
  63582. }
  63583. const RectanglePlacement placement (placementFlags);
  63584. newState.transform
  63585. = placement.getTransformToFit (vx, vy, vw, vh,
  63586. 0.0f, 0.0f, newState.width, newState.height)
  63587. .followedBy (newState.transform);
  63588. }
  63589. }
  63590. else
  63591. {
  63592. if (viewBoxW == 0)
  63593. newState.viewBoxW = newState.width;
  63594. if (viewBoxH == 0)
  63595. newState.viewBoxH = newState.height;
  63596. }
  63597. newState.parseSubElements (xml, drawable);
  63598. return drawable;
  63599. }
  63600. private:
  63601. const XmlElement* const topLevelXml;
  63602. float x, y, width, height, viewBoxW, viewBoxH;
  63603. AffineTransform transform;
  63604. String cssStyleText;
  63605. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  63606. {
  63607. forEachXmlChildElement (xml, e)
  63608. {
  63609. Drawable* d = 0;
  63610. if (e->hasTagName (T("g")))
  63611. d = parseGroupElement (*e);
  63612. else if (e->hasTagName (T("svg")))
  63613. d = parseSVGElement (*e);
  63614. else if (e->hasTagName (T("path")))
  63615. d = parsePath (*e);
  63616. else if (e->hasTagName (T("rect")))
  63617. d = parseRect (*e);
  63618. else if (e->hasTagName (T("circle")))
  63619. d = parseCircle (*e);
  63620. else if (e->hasTagName (T("ellipse")))
  63621. d = parseEllipse (*e);
  63622. else if (e->hasTagName (T("line")))
  63623. d = parseLine (*e);
  63624. else if (e->hasTagName (T("polyline")))
  63625. d = parsePolygon (*e, true);
  63626. else if (e->hasTagName (T("polygon")))
  63627. d = parsePolygon (*e, false);
  63628. else if (e->hasTagName (T("text")))
  63629. d = parseText (*e);
  63630. else if (e->hasTagName (T("switch")))
  63631. d = parseSwitch (*e);
  63632. else if (e->hasTagName (T("style")))
  63633. parseCSSStyle (*e);
  63634. parentDrawable->insertDrawable (d);
  63635. }
  63636. }
  63637. DrawableComposite* parseSwitch (const XmlElement& xml)
  63638. {
  63639. const XmlElement* const group = xml.getChildByName (T("g"));
  63640. if (group != 0)
  63641. return parseGroupElement (*group);
  63642. return 0;
  63643. }
  63644. DrawableComposite* parseGroupElement (const XmlElement& xml)
  63645. {
  63646. DrawableComposite* const drawable = new DrawableComposite();
  63647. drawable->setName (xml.getStringAttribute (T("id")));
  63648. if (xml.hasAttribute (T("transform")))
  63649. {
  63650. SVGState newState (*this);
  63651. newState.addTransform (xml);
  63652. newState.parseSubElements (xml, drawable);
  63653. }
  63654. else
  63655. {
  63656. parseSubElements (xml, drawable);
  63657. }
  63658. return drawable;
  63659. }
  63660. Drawable* parsePath (const XmlElement& xml) const
  63661. {
  63662. const String d (xml.getStringAttribute (T("d")).trimStart());
  63663. Path path;
  63664. if (getStyleAttribute (&xml, T("fill-rule")).trim().equalsIgnoreCase (T("evenodd")))
  63665. path.setUsingNonZeroWinding (false);
  63666. int index = 0;
  63667. float lastX = 0, lastY = 0;
  63668. float lastX2 = 0, lastY2 = 0;
  63669. tchar lastCommandChar = 0;
  63670. bool carryOn = true;
  63671. const String validCommandChars (T("MmLlHhVvCcSsQqTtAaZz"));
  63672. for (;;)
  63673. {
  63674. float x, y, x2, y2, x3, y3;
  63675. const bool isRelative = (d[index] >= 'a' && d[index] <= 'z');
  63676. if (validCommandChars.containsChar (d[index]))
  63677. lastCommandChar = d [index++];
  63678. switch (lastCommandChar)
  63679. {
  63680. case T('M'):
  63681. case T('m'):
  63682. case T('L'):
  63683. case T('l'):
  63684. if (parseCoords (d, x, y, index, false))
  63685. {
  63686. if (isRelative)
  63687. {
  63688. x += lastX;
  63689. y += lastY;
  63690. }
  63691. if (lastCommandChar == T('M') || lastCommandChar == T('m'))
  63692. path.startNewSubPath (x, y);
  63693. else
  63694. path.lineTo (x, y);
  63695. lastX2 = lastX;
  63696. lastY2 = lastY;
  63697. lastX = x;
  63698. lastY = y;
  63699. }
  63700. else
  63701. {
  63702. ++index;
  63703. }
  63704. break;
  63705. case T('H'):
  63706. case T('h'):
  63707. if (parseCoord (d, x, index, false, true))
  63708. {
  63709. if (isRelative)
  63710. x += lastX;
  63711. path.lineTo (x, lastY);
  63712. lastX2 = lastX;
  63713. lastX = x;
  63714. }
  63715. else
  63716. {
  63717. ++index;
  63718. }
  63719. break;
  63720. case T('V'):
  63721. case T('v'):
  63722. if (parseCoord (d, y, index, false, false))
  63723. {
  63724. if (isRelative)
  63725. y += lastY;
  63726. path.lineTo (lastX, y);
  63727. lastY2 = lastY;
  63728. lastY = y;
  63729. }
  63730. else
  63731. {
  63732. ++index;
  63733. }
  63734. break;
  63735. case T('C'):
  63736. case T('c'):
  63737. if (parseCoords (d, x, y, index, false)
  63738. && parseCoords (d, x2, y2, index, false)
  63739. && parseCoords (d, x3, y3, index, false))
  63740. {
  63741. if (isRelative)
  63742. {
  63743. x += lastX;
  63744. y += lastY;
  63745. x2 += lastX;
  63746. y2 += lastY;
  63747. x3 += lastX;
  63748. y3 += lastY;
  63749. }
  63750. path.cubicTo (x, y, x2, y2, x3, y3);
  63751. lastX2 = x2;
  63752. lastY2 = y2;
  63753. lastX = x3;
  63754. lastY = y3;
  63755. }
  63756. else
  63757. {
  63758. ++index;
  63759. }
  63760. break;
  63761. case T('S'):
  63762. case T('s'):
  63763. if (parseCoords (d, x, y, index, false)
  63764. && parseCoords (d, x3, y3, index, false))
  63765. {
  63766. if (isRelative)
  63767. {
  63768. x += lastX;
  63769. y += lastY;
  63770. x3 += lastX;
  63771. y3 += lastY;
  63772. }
  63773. x2 = lastX + (lastX - lastX2);
  63774. y2 = lastY + (lastY - lastY2);
  63775. path.cubicTo (x2, y2, x, y, x3, y3);
  63776. lastX2 = x2;
  63777. lastY2 = y2;
  63778. lastX = x3;
  63779. lastY = y3;
  63780. }
  63781. else
  63782. {
  63783. ++index;
  63784. }
  63785. break;
  63786. case T('Q'):
  63787. case T('q'):
  63788. if (parseCoords (d, x, y, index, false)
  63789. && parseCoords (d, x2, y2, index, false))
  63790. {
  63791. if (isRelative)
  63792. {
  63793. x += lastX;
  63794. y += lastY;
  63795. x2 += lastX;
  63796. y2 += lastY;
  63797. }
  63798. path.quadraticTo (x, y, x2, y2);
  63799. lastX2 = x;
  63800. lastY2 = y;
  63801. lastX = x2;
  63802. lastY = y2;
  63803. }
  63804. else
  63805. {
  63806. ++index;
  63807. }
  63808. break;
  63809. case T('T'):
  63810. case T('t'):
  63811. if (parseCoords (d, x, y, index, false))
  63812. {
  63813. if (isRelative)
  63814. {
  63815. x += lastX;
  63816. y += lastY;
  63817. }
  63818. x2 = lastX + (lastX - lastX2);
  63819. y2 = lastY + (lastY - lastY2);
  63820. path.quadraticTo (x2, y2, x, y);
  63821. lastX2 = x2;
  63822. lastY2 = y2;
  63823. lastX = x;
  63824. lastY = y;
  63825. }
  63826. else
  63827. {
  63828. ++index;
  63829. }
  63830. break;
  63831. case T('A'):
  63832. case T('a'):
  63833. if (parseCoords (d, x, y, index, false))
  63834. {
  63835. String num;
  63836. if (parseNextNumber (d, num, index, false))
  63837. {
  63838. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  63839. if (parseNextNumber (d, num, index, false))
  63840. {
  63841. const bool largeArc = num.getIntValue() != 0;
  63842. if (parseNextNumber (d, num, index, false))
  63843. {
  63844. const bool sweep = num.getIntValue() != 0;
  63845. if (parseCoords (d, x2, y2, index, false))
  63846. {
  63847. if (isRelative)
  63848. {
  63849. x2 += lastX;
  63850. y2 += lastY;
  63851. }
  63852. if (lastX != x2 || lastY != y2)
  63853. {
  63854. double centreX, centreY, startAngle, deltaAngle;
  63855. double rx = x, ry = y;
  63856. endpointToCentreParameters (lastX, lastY, x2, y2,
  63857. angle, largeArc, sweep,
  63858. rx, ry, centreX, centreY,
  63859. startAngle, deltaAngle);
  63860. path.addCentredArc ((float) centreX, (float) centreY,
  63861. (float) rx, (float) ry,
  63862. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  63863. false);
  63864. path.lineTo (x2, y2);
  63865. }
  63866. lastX2 = lastX;
  63867. lastY2 = lastY;
  63868. lastX = x2;
  63869. lastY = y2;
  63870. }
  63871. }
  63872. }
  63873. }
  63874. }
  63875. else
  63876. {
  63877. ++index;
  63878. }
  63879. break;
  63880. case T('Z'):
  63881. case T('z'):
  63882. path.closeSubPath();
  63883. while (CharacterFunctions::isWhitespace (d [index]))
  63884. ++index;
  63885. break;
  63886. default:
  63887. carryOn = false;
  63888. break;
  63889. }
  63890. if (! carryOn)
  63891. break;
  63892. }
  63893. return parseShape (xml, path);
  63894. }
  63895. Drawable* parseRect (const XmlElement& xml) const
  63896. {
  63897. Path rect;
  63898. const bool hasRX = xml.hasAttribute (T("rx"));
  63899. const bool hasRY = xml.hasAttribute (T("ry"));
  63900. if (hasRX || hasRY)
  63901. {
  63902. float rx = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  63903. float ry = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  63904. if (! hasRX)
  63905. rx = ry;
  63906. else if (! hasRY)
  63907. ry = rx;
  63908. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  63909. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  63910. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  63911. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH),
  63912. rx, ry);
  63913. }
  63914. else
  63915. {
  63916. rect.addRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  63917. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  63918. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  63919. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH));
  63920. }
  63921. return parseShape (xml, rect);
  63922. }
  63923. Drawable* parseCircle (const XmlElement& xml) const
  63924. {
  63925. Path circle;
  63926. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  63927. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  63928. const float radius = getCoordLength (xml.getStringAttribute (T("r")), viewBoxW);
  63929. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  63930. return parseShape (xml, circle);
  63931. }
  63932. Drawable* parseEllipse (const XmlElement& xml) const
  63933. {
  63934. Path ellipse;
  63935. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  63936. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  63937. const float radiusX = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  63938. const float radiusY = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  63939. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  63940. return parseShape (xml, ellipse);
  63941. }
  63942. Drawable* parseLine (const XmlElement& xml) const
  63943. {
  63944. Path line;
  63945. const float x1 = getCoordLength (xml.getStringAttribute (T("x1")), viewBoxW);
  63946. const float y1 = getCoordLength (xml.getStringAttribute (T("y1")), viewBoxH);
  63947. const float x2 = getCoordLength (xml.getStringAttribute (T("x2")), viewBoxW);
  63948. const float y2 = getCoordLength (xml.getStringAttribute (T("y2")), viewBoxH);
  63949. line.startNewSubPath (x1, y1);
  63950. line.lineTo (x2, y2);
  63951. return parseShape (xml, line);
  63952. }
  63953. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  63954. {
  63955. const String points (xml.getStringAttribute (T("points")));
  63956. Path path;
  63957. int index = 0;
  63958. float x, y;
  63959. if (parseCoords (points, x, y, index, true))
  63960. {
  63961. float firstX = x;
  63962. float firstY = y;
  63963. float lastX = 0, lastY = 0;
  63964. path.startNewSubPath (x, y);
  63965. while (parseCoords (points, x, y, index, true))
  63966. {
  63967. lastX = x;
  63968. lastY = y;
  63969. path.lineTo (x, y);
  63970. }
  63971. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  63972. path.closeSubPath();
  63973. }
  63974. return parseShape (xml, path);
  63975. }
  63976. Drawable* parseShape (const XmlElement& xml, Path& path,
  63977. const bool parseTransform = true) const
  63978. {
  63979. if (parseTransform && xml.hasAttribute (T("transform")))
  63980. {
  63981. SVGState newState (*this);
  63982. newState.addTransform (xml);
  63983. return newState.parseShape (xml, path, false);
  63984. }
  63985. DrawablePath* dp = new DrawablePath();
  63986. dp->setSolidFill (Colours::transparentBlack);
  63987. path.applyTransform (transform);
  63988. dp->setPath (path);
  63989. Path::Iterator iter (path);
  63990. bool containsClosedSubPath = false;
  63991. while (iter.next())
  63992. {
  63993. if (iter.elementType == Path::Iterator::closePath)
  63994. {
  63995. containsClosedSubPath = true;
  63996. break;
  63997. }
  63998. }
  63999. Brush* const fillBrush
  64000. = getBrushForFill (path,
  64001. getStyleAttribute (&xml, T("fill")),
  64002. getStyleAttribute (&xml, T("fill-opacity")),
  64003. getStyleAttribute (&xml, T("opacity")),
  64004. containsClosedSubPath ? Colours::black
  64005. : Colours::transparentBlack);
  64006. if (fillBrush != 0)
  64007. {
  64008. if (! fillBrush->isInvisible())
  64009. {
  64010. fillBrush->applyTransform (transform);
  64011. dp->setFillBrush (*fillBrush);
  64012. }
  64013. delete fillBrush;
  64014. }
  64015. const String strokeType (getStyleAttribute (&xml, T("stroke")));
  64016. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase (T("none")))
  64017. {
  64018. Brush* const strokeBrush
  64019. = getBrushForFill (path, strokeType,
  64020. getStyleAttribute (&xml, T("stroke-opacity")),
  64021. getStyleAttribute (&xml, T("opacity")),
  64022. Colours::transparentBlack);
  64023. if (strokeBrush != 0)
  64024. {
  64025. const PathStrokeType stroke (getStrokeFor (&xml));
  64026. if (! strokeBrush->isInvisible())
  64027. {
  64028. strokeBrush->applyTransform (transform);
  64029. dp->setOutline (stroke, *strokeBrush);
  64030. }
  64031. delete strokeBrush;
  64032. }
  64033. }
  64034. return dp;
  64035. }
  64036. const XmlElement* findLinkedElement (const XmlElement* e) const
  64037. {
  64038. const String id (e->getStringAttribute (T("xlink:href")));
  64039. if (! id.startsWithChar (T('#')))
  64040. return 0;
  64041. return findElementForId (topLevelXml, id.substring (1));
  64042. }
  64043. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  64044. {
  64045. if (fillXml == 0)
  64046. return;
  64047. forEachXmlChildElementWithTagName (*fillXml, e, T("stop"))
  64048. {
  64049. int index = 0;
  64050. Colour col (parseColour (getStyleAttribute (e, T("stop-color")), index, Colours::black));
  64051. const String opacity (getStyleAttribute (e, T("stop-opacity"), T("1")));
  64052. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  64053. double offset = e->getDoubleAttribute (T("offset"));
  64054. if (e->getStringAttribute (T("offset")).containsChar (T('%')))
  64055. offset *= 0.01;
  64056. cg.addColour (jlimit (0.0, 1.0, offset), col);
  64057. }
  64058. }
  64059. Brush* getBrushForFill (const Path& path,
  64060. const String& fill,
  64061. const String& fillOpacity,
  64062. const String& overallOpacity,
  64063. const Colour& defaultColour) const
  64064. {
  64065. float opacity = 1.0f;
  64066. if (overallOpacity.isNotEmpty())
  64067. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  64068. if (fillOpacity.isNotEmpty())
  64069. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  64070. if (fill.startsWithIgnoreCase (T("url")))
  64071. {
  64072. const String id (fill.fromFirstOccurrenceOf (T("#"), false, false)
  64073. .upToLastOccurrenceOf (T(")"), false, false).trim());
  64074. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  64075. if (fillXml != 0
  64076. && (fillXml->hasTagName (T("linearGradient"))
  64077. || fillXml->hasTagName (T("radialGradient"))))
  64078. {
  64079. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  64080. ColourGradient cg;
  64081. addGradientStopsIn (cg, inheritedFrom);
  64082. addGradientStopsIn (cg, fillXml);
  64083. if (cg.getNumColours() > 0)
  64084. {
  64085. cg.addColour (0.0, cg.getColour (0));
  64086. cg.addColour (1.0, cg.getColour (cg.getNumColours() - 1));
  64087. }
  64088. else
  64089. {
  64090. cg.addColour (0.0, Colours::black);
  64091. cg.addColour (1.0, Colours::black);
  64092. }
  64093. if (overallOpacity.isNotEmpty())
  64094. cg.multiplyOpacity (overallOpacity.getFloatValue());
  64095. jassert (cg.getNumColours() > 0);
  64096. cg.isRadial = fillXml->hasTagName (T("radialGradient"));
  64097. cg.transform = parseTransform (fillXml->getStringAttribute (T("gradientTransform")));
  64098. float width = viewBoxW;
  64099. float height = viewBoxH;
  64100. float dx = 0.0;
  64101. float dy = 0.0;
  64102. const bool userSpace = fillXml->getStringAttribute (T("gradientUnits")).equalsIgnoreCase (T("userSpaceOnUse"));
  64103. if (! userSpace)
  64104. path.getBounds (dx, dy, width, height);
  64105. if (cg.isRadial)
  64106. {
  64107. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("cx"), T("50%")), width);
  64108. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("cy"), T("50%")), height);
  64109. const float radius = getCoordLength (fillXml->getStringAttribute (T("r"), T("50%")), width);
  64110. cg.x2 = cg.x1 + radius;
  64111. cg.y2 = cg.y1;
  64112. //xxx (the fx, fy focal point isn't handled properly here..)
  64113. }
  64114. else
  64115. {
  64116. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("x1"), T("0%")), width);
  64117. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("y1"), T("0%")), height);
  64118. cg.x2 = dx + getCoordLength (fillXml->getStringAttribute (T("x2"), T("100%")), width);
  64119. cg.y2 = dy + getCoordLength (fillXml->getStringAttribute (T("y2"), T("0%")), height);
  64120. if (cg.x1 == cg.x2 && cg.y1 == cg.y2)
  64121. return new SolidColourBrush (cg.getColour (cg.getNumColours() - 1));
  64122. }
  64123. return new GradientBrush (cg);
  64124. }
  64125. }
  64126. if (fill.equalsIgnoreCase (T("none")))
  64127. return new SolidColourBrush (Colours::transparentBlack);
  64128. int i = 0;
  64129. Colour colour (parseColour (fill, i, defaultColour));
  64130. colour = colour.withMultipliedAlpha (opacity);
  64131. return new SolidColourBrush (colour);
  64132. }
  64133. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  64134. {
  64135. const String width (getStyleAttribute (xml, T("stroke-width")));
  64136. const String cap (getStyleAttribute (xml, T("stroke-linecap")));
  64137. const String join (getStyleAttribute (xml, T("stroke-linejoin")));
  64138. //const String mitreLimit (getStyleAttribute (xml, T("stroke-miterlimit")));
  64139. //const String dashArray (getStyleAttribute (xml, T("stroke-dasharray")));
  64140. //const String dashOffset (getStyleAttribute (xml, T("stroke-dashoffset")));
  64141. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  64142. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  64143. if (join.equalsIgnoreCase (T("round")))
  64144. joinStyle = PathStrokeType::curved;
  64145. else if (join.equalsIgnoreCase (T("bevel")))
  64146. joinStyle = PathStrokeType::beveled;
  64147. if (cap.equalsIgnoreCase (T("round")))
  64148. capStyle = PathStrokeType::rounded;
  64149. else if (cap.equalsIgnoreCase (T("square")))
  64150. capStyle = PathStrokeType::square;
  64151. float ox = 0.0f, oy = 0.0f;
  64152. transform.transformPoint (ox, oy);
  64153. float x = getCoordLength (width, viewBoxW), y = 0.0f;
  64154. transform.transformPoint (x, y);
  64155. return PathStrokeType (width.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  64156. joinStyle, capStyle);
  64157. }
  64158. Drawable* parseText (const XmlElement& xml)
  64159. {
  64160. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  64161. getCoordList (xCoords, getInheritedAttribute (&xml, T("x")), true, true);
  64162. getCoordList (yCoords, getInheritedAttribute (&xml, T("y")), true, false);
  64163. getCoordList (dxCoords, getInheritedAttribute (&xml, T("dx")), true, true);
  64164. getCoordList (dyCoords, getInheritedAttribute (&xml, T("dy")), true, false);
  64165. //xxx not done text yet!
  64166. forEachXmlChildElement (xml, e)
  64167. {
  64168. if (e->isTextElement())
  64169. {
  64170. const String text (e->getText());
  64171. Path path;
  64172. Drawable* s = parseShape (*e, path);
  64173. delete s;
  64174. }
  64175. else if (e->hasTagName (T("tspan")))
  64176. {
  64177. Drawable* s = parseText (*e);
  64178. delete s;
  64179. }
  64180. }
  64181. return 0;
  64182. }
  64183. void addTransform (const XmlElement& xml)
  64184. {
  64185. transform = parseTransform (xml.getStringAttribute (T("transform")))
  64186. .followedBy (transform);
  64187. }
  64188. bool parseCoord (const String& s, float& value, int& index,
  64189. const bool allowUnits, const bool isX) const
  64190. {
  64191. String number;
  64192. if (! parseNextNumber (s, number, index, allowUnits))
  64193. {
  64194. value = 0;
  64195. return false;
  64196. }
  64197. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  64198. return true;
  64199. }
  64200. bool parseCoords (const String& s, float& x, float& y,
  64201. int& index, const bool allowUnits) const
  64202. {
  64203. return parseCoord (s, x, index, allowUnits, true)
  64204. && parseCoord (s, y, index, allowUnits, false);
  64205. }
  64206. float getCoordLength (const String& s, const float sizeForProportions) const
  64207. {
  64208. float n = s.getFloatValue();
  64209. const int len = s.length();
  64210. if (len > 2)
  64211. {
  64212. const float dpi = 96.0f;
  64213. const tchar n1 = s [len - 2];
  64214. const tchar n2 = s [len - 1];
  64215. if (n1 == T('i') && n2 == T('n'))
  64216. n *= dpi;
  64217. else if (n1 == T('m') && n2 == T('m'))
  64218. n *= dpi / 25.4f;
  64219. else if (n1 == T('c') && n2 == T('m'))
  64220. n *= dpi / 2.54f;
  64221. else if (n1 == T('p') && n2 == T('c'))
  64222. n *= 15.0f;
  64223. else if (n2 == T('%'))
  64224. n *= 0.01f * sizeForProportions;
  64225. }
  64226. return n;
  64227. }
  64228. void getCoordList (Array <float>& coords, const String& list,
  64229. const bool allowUnits, const bool isX) const
  64230. {
  64231. int index = 0;
  64232. float value;
  64233. while (parseCoord (list, value, index, allowUnits, isX))
  64234. coords.add (value);
  64235. }
  64236. void parseCSSStyle (const XmlElement& xml)
  64237. {
  64238. cssStyleText = xml.getAllSubText() + T("\n") + cssStyleText;
  64239. }
  64240. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  64241. const String& defaultValue = String::empty) const
  64242. {
  64243. if (xml->hasAttribute (attributeName))
  64244. return xml->getStringAttribute (attributeName, defaultValue);
  64245. const String styleAtt (xml->getStringAttribute (T("style")));
  64246. if (styleAtt.isNotEmpty())
  64247. {
  64248. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  64249. if (value.isNotEmpty())
  64250. return value;
  64251. }
  64252. else if (xml->hasAttribute (T("class")))
  64253. {
  64254. const String className (T(".") + xml->getStringAttribute (T("class")));
  64255. int index = cssStyleText.indexOfIgnoreCase (className + T(" "));
  64256. if (index < 0)
  64257. index = cssStyleText.indexOfIgnoreCase (className + T("{"));
  64258. if (index >= 0)
  64259. {
  64260. const int openBracket = cssStyleText.indexOfChar (index, T('{'));
  64261. if (openBracket > index)
  64262. {
  64263. const int closeBracket = cssStyleText.indexOfChar (openBracket, T('}'));
  64264. if (closeBracket > openBracket)
  64265. {
  64266. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  64267. if (value.isNotEmpty())
  64268. return value;
  64269. }
  64270. }
  64271. }
  64272. }
  64273. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  64274. if (xml != 0)
  64275. return getStyleAttribute (xml, attributeName, defaultValue);
  64276. return defaultValue;
  64277. }
  64278. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  64279. {
  64280. if (xml->hasAttribute (attributeName))
  64281. return xml->getStringAttribute (attributeName);
  64282. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  64283. if (xml != 0)
  64284. return getInheritedAttribute (xml, attributeName);
  64285. return String::empty;
  64286. }
  64287. static bool isIdentifierChar (const tchar c)
  64288. {
  64289. return CharacterFunctions::isLetter (c) || c == T('-');
  64290. }
  64291. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  64292. {
  64293. int i = 0;
  64294. for (;;)
  64295. {
  64296. i = list.indexOf (i, attributeName);
  64297. if (i < 0)
  64298. break;
  64299. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  64300. && ! isIdentifierChar (list [i + attributeName.length()]))
  64301. {
  64302. i = list.indexOfChar (i, T(':'));
  64303. if (i < 0)
  64304. break;
  64305. int end = list.indexOfChar (i, T(';'));
  64306. if (end < 0)
  64307. end = 0x7ffff;
  64308. return list.substring (i + 1, end).trim();
  64309. }
  64310. ++i;
  64311. }
  64312. return defaultValue;
  64313. }
  64314. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  64315. {
  64316. const tchar* const s = (const tchar*) source;
  64317. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  64318. ++index;
  64319. int start = index;
  64320. if (CharacterFunctions::isDigit (s[index]) || s[index] == T('.') || s[index] == T('-'))
  64321. ++index;
  64322. while (CharacterFunctions::isDigit (s[index]) || s[index] == T('.'))
  64323. ++index;
  64324. if ((s[index] == T('e') || s[index] == T('E'))
  64325. && (CharacterFunctions::isDigit (s[index + 1])
  64326. || s[index + 1] == T('-')
  64327. || s[index + 1] == T('+')))
  64328. {
  64329. index += 2;
  64330. while (CharacterFunctions::isDigit (s[index]))
  64331. ++index;
  64332. }
  64333. if (allowUnits)
  64334. {
  64335. while (CharacterFunctions::isLetter (s[index]))
  64336. ++index;
  64337. }
  64338. if (index == start)
  64339. return false;
  64340. value = String (s + start, index - start);
  64341. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  64342. ++index;
  64343. return true;
  64344. }
  64345. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  64346. {
  64347. if (s [index] == T('#'))
  64348. {
  64349. uint32 hex [6];
  64350. zeromem (hex, sizeof (hex));
  64351. int numChars = 0;
  64352. for (int i = 6; --i >= 0;)
  64353. {
  64354. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  64355. if (hexValue >= 0)
  64356. hex [numChars++] = hexValue;
  64357. else
  64358. break;
  64359. }
  64360. if (numChars <= 3)
  64361. return Colour ((uint8) (hex [0] * 0x11),
  64362. (uint8) (hex [1] * 0x11),
  64363. (uint8) (hex [2] * 0x11));
  64364. else
  64365. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  64366. (uint8) ((hex [2] << 4) + hex [3]),
  64367. (uint8) ((hex [4] << 4) + hex [5]));
  64368. }
  64369. else if (s [index] == T('r')
  64370. && s [index + 1] == T('g')
  64371. && s [index + 2] == T('b'))
  64372. {
  64373. const int openBracket = s.indexOfChar (index, T('('));
  64374. const int closeBracket = s.indexOfChar (openBracket, T(')'));
  64375. if (openBracket >= 3 && closeBracket > openBracket)
  64376. {
  64377. index = closeBracket;
  64378. StringArray tokens;
  64379. tokens.addTokens (s.substring (openBracket + 1, closeBracket), T(","), T(""));
  64380. tokens.trim();
  64381. tokens.removeEmptyStrings();
  64382. if (tokens[0].containsChar T('%'))
  64383. return Colour ((uint8) roundDoubleToInt (2.55 * tokens[0].getDoubleValue()),
  64384. (uint8) roundDoubleToInt (2.55 * tokens[1].getDoubleValue()),
  64385. (uint8) roundDoubleToInt (2.55 * tokens[2].getDoubleValue()));
  64386. else
  64387. return Colour ((uint8) tokens[0].getIntValue(),
  64388. (uint8) tokens[1].getIntValue(),
  64389. (uint8) tokens[2].getIntValue());
  64390. }
  64391. }
  64392. return Colours::findColourForName (s, defaultColour);
  64393. }
  64394. static const AffineTransform parseTransform (String t)
  64395. {
  64396. AffineTransform result;
  64397. while (t.isNotEmpty())
  64398. {
  64399. StringArray tokens;
  64400. tokens.addTokens (t.fromFirstOccurrenceOf (T("("), false, false)
  64401. .upToFirstOccurrenceOf (T(")"), false, false),
  64402. T(", "), 0);
  64403. tokens.removeEmptyStrings (true);
  64404. float numbers [6];
  64405. for (int i = 0; i < 6; ++i)
  64406. numbers[i] = tokens[i].getFloatValue();
  64407. AffineTransform trans;
  64408. if (t.startsWithIgnoreCase (T("matrix")))
  64409. {
  64410. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  64411. numbers[1], numbers[3], numbers[5]);
  64412. }
  64413. else if (t.startsWithIgnoreCase (T("translate")))
  64414. {
  64415. trans = trans.translated (numbers[0], numbers[1]);
  64416. }
  64417. else if (t.startsWithIgnoreCase (T("scale")))
  64418. {
  64419. if (tokens.size() == 1)
  64420. trans = trans.scaled (numbers[0], numbers[0]);
  64421. else
  64422. trans = trans.scaled (numbers[0], numbers[1]);
  64423. }
  64424. else if (t.startsWithIgnoreCase (T("rotate")))
  64425. {
  64426. if (tokens.size() != 3)
  64427. trans = trans.rotated (numbers[0] / (180.0f / float_Pi));
  64428. else
  64429. trans = trans.rotated (numbers[0] / (180.0f / float_Pi),
  64430. numbers[1], numbers[2]);
  64431. }
  64432. else if (t.startsWithIgnoreCase (T("skewX")))
  64433. {
  64434. trans = AffineTransform (1.0f, tanf (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  64435. 0.0f, 1.0f, 0.0f);
  64436. }
  64437. else if (t.startsWithIgnoreCase (T("skewY")))
  64438. {
  64439. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  64440. tanf (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  64441. }
  64442. result = trans.followedBy (result);
  64443. t = t.fromFirstOccurrenceOf (T(")"), false, false).trimStart();
  64444. }
  64445. return result;
  64446. }
  64447. static void endpointToCentreParameters (const double x1, const double y1,
  64448. const double x2, const double y2,
  64449. const double angle,
  64450. const bool largeArc, const bool sweep,
  64451. double& rx, double& ry,
  64452. double& centreX, double& centreY,
  64453. double& startAngle, double& deltaAngle)
  64454. {
  64455. const double midX = (x1 - x2) * 0.5;
  64456. const double midY = (y1 - y2) * 0.5;
  64457. const double cosAngle = cos (angle);
  64458. const double sinAngle = sin (angle);
  64459. const double xp = cosAngle * midX + sinAngle * midY;
  64460. const double yp = cosAngle * midY - sinAngle * midX;
  64461. const double xp2 = xp * xp;
  64462. const double yp2 = yp * yp;
  64463. double rx2 = rx * rx;
  64464. double ry2 = ry * ry;
  64465. const double s = (xp2 / rx2) + (yp2 / ry2);
  64466. double c;
  64467. if (s <= 1.0)
  64468. {
  64469. c = sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  64470. / (( rx2 * yp2) + (ry2 * xp2))));
  64471. if (largeArc == sweep)
  64472. c = -c;
  64473. }
  64474. else
  64475. {
  64476. const double s2 = sqrt (s);
  64477. rx *= s2;
  64478. ry *= s2;
  64479. rx2 = rx * rx;
  64480. ry2 = ry * ry;
  64481. c = 0;
  64482. }
  64483. const double cpx = ((rx * yp) / ry) * c;
  64484. const double cpy = ((-ry * xp) / rx) * c;
  64485. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  64486. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  64487. const double ux = (xp - cpx) / rx;
  64488. const double uy = (yp - cpy) / ry;
  64489. const double vx = (-xp - cpx) / rx;
  64490. const double vy = (-yp - cpy) / ry;
  64491. const double length = juce_hypot (ux, uy);
  64492. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  64493. if (uy < 0)
  64494. startAngle = -startAngle;
  64495. startAngle += double_Pi * 0.5;
  64496. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  64497. / (length * juce_hypot (vx, vy))));
  64498. if ((ux * vy) - (uy * vx) < 0)
  64499. deltaAngle = -deltaAngle;
  64500. if (sweep)
  64501. {
  64502. if (deltaAngle < 0)
  64503. deltaAngle += double_Pi * 2.0;
  64504. }
  64505. else
  64506. {
  64507. if (deltaAngle > 0)
  64508. deltaAngle -= double_Pi * 2.0;
  64509. }
  64510. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  64511. }
  64512. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  64513. {
  64514. forEachXmlChildElement (*parent, e)
  64515. {
  64516. if (e->compareAttribute (T("id"), id))
  64517. return e;
  64518. const XmlElement* const found = findElementForId (e, id);
  64519. if (found != 0)
  64520. return found;
  64521. }
  64522. return 0;
  64523. }
  64524. const SVGState& operator= (const SVGState&);
  64525. };
  64526. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  64527. {
  64528. SVGState state (&svgDocument);
  64529. return state.parseSVGElement (svgDocument);
  64530. }
  64531. END_JUCE_NAMESPACE
  64532. /********* End of inlined file: juce_SVGParser.cpp *********/
  64533. /********* Start of inlined file: juce_DropShadowEffect.cpp *********/
  64534. BEGIN_JUCE_NAMESPACE
  64535. #if JUCE_MSVC
  64536. #pragma optimize ("t", on) // try to avoid slowing everything down in debug builds
  64537. #endif
  64538. DropShadowEffect::DropShadowEffect()
  64539. : offsetX (0),
  64540. offsetY (0),
  64541. radius (4),
  64542. opacity (0.6f)
  64543. {
  64544. }
  64545. DropShadowEffect::~DropShadowEffect()
  64546. {
  64547. }
  64548. void DropShadowEffect::setShadowProperties (const float newRadius,
  64549. const float newOpacity,
  64550. const int newShadowOffsetX,
  64551. const int newShadowOffsetY)
  64552. {
  64553. radius = jmax (1.1f, newRadius);
  64554. offsetX = newShadowOffsetX;
  64555. offsetY = newShadowOffsetY;
  64556. opacity = newOpacity;
  64557. }
  64558. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  64559. {
  64560. const int w = image.getWidth();
  64561. const int h = image.getHeight();
  64562. int lineStride, pixelStride;
  64563. const PixelARGB* srcPixels = (const PixelARGB*) image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(), lineStride, pixelStride);
  64564. Image shadowImage (Image::SingleChannel, w, h, false);
  64565. int destStride, destPixelStride;
  64566. uint8* const shadowChannel = (uint8*) shadowImage.lockPixelDataReadWrite (0, 0, w, h, destStride, destPixelStride);
  64567. const int filter = roundFloatToInt (63.0f / radius);
  64568. const int radiusMinus1 = roundFloatToInt ((radius - 1.0f) * 63.0f);
  64569. for (int x = w; --x >= 0;)
  64570. {
  64571. int shadowAlpha = 0;
  64572. const PixelARGB* src = srcPixels + x;
  64573. uint8* shadowPix = shadowChannel + x;
  64574. for (int y = h; --y >= 0;)
  64575. {
  64576. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  64577. *shadowPix = (uint8) shadowAlpha;
  64578. src = (const PixelARGB*) (((const uint8*) src) + lineStride);
  64579. shadowPix += destStride;
  64580. }
  64581. }
  64582. for (int y = h; --y >= 0;)
  64583. {
  64584. int shadowAlpha = 0;
  64585. uint8* shadowPix = shadowChannel + y * destStride;
  64586. for (int x = w; --x >= 0;)
  64587. {
  64588. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  64589. *shadowPix++ = (uint8) shadowAlpha;
  64590. }
  64591. }
  64592. image.releasePixelDataReadOnly (srcPixels);
  64593. shadowImage.releasePixelDataReadWrite (shadowChannel);
  64594. g.setColour (Colours::black.withAlpha (opacity));
  64595. g.drawImageAt (&shadowImage, offsetX, offsetY, true);
  64596. g.setOpacity (1.0f);
  64597. g.drawImageAt (&image, 0, 0);
  64598. }
  64599. END_JUCE_NAMESPACE
  64600. /********* End of inlined file: juce_DropShadowEffect.cpp *********/
  64601. /********* Start of inlined file: juce_GlowEffect.cpp *********/
  64602. BEGIN_JUCE_NAMESPACE
  64603. GlowEffect::GlowEffect()
  64604. : radius (2.0f),
  64605. colour (Colours::white)
  64606. {
  64607. }
  64608. GlowEffect::~GlowEffect()
  64609. {
  64610. }
  64611. void GlowEffect::setGlowProperties (const float newRadius,
  64612. const Colour& newColour)
  64613. {
  64614. radius = newRadius;
  64615. colour = newColour;
  64616. }
  64617. void GlowEffect::applyEffect (Image& image, Graphics& g)
  64618. {
  64619. const int w = image.getWidth();
  64620. const int h = image.getHeight();
  64621. Image temp (image.getFormat(), w, h, true);
  64622. ImageConvolutionKernel blurKernel (roundFloatToInt (radius * 2.0f));
  64623. blurKernel.createGaussianBlur (radius);
  64624. blurKernel.rescaleAllValues (radius);
  64625. blurKernel.applyToImage (temp, &image, 0, 0, w, h);
  64626. g.setColour (colour);
  64627. g.drawImageAt (&temp, 0, 0, true);
  64628. g.setOpacity (1.0f);
  64629. g.drawImageAt (&image, 0, 0, false);
  64630. }
  64631. END_JUCE_NAMESPACE
  64632. /********* End of inlined file: juce_GlowEffect.cpp *********/
  64633. /********* Start of inlined file: juce_ReduceOpacityEffect.cpp *********/
  64634. BEGIN_JUCE_NAMESPACE
  64635. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  64636. : opacity (opacity_)
  64637. {
  64638. }
  64639. ReduceOpacityEffect::~ReduceOpacityEffect()
  64640. {
  64641. }
  64642. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  64643. {
  64644. opacity = jlimit (0.0f, 1.0f, newOpacity);
  64645. }
  64646. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  64647. {
  64648. g.setOpacity (opacity);
  64649. g.drawImageAt (&image, 0, 0);
  64650. }
  64651. END_JUCE_NAMESPACE
  64652. /********* End of inlined file: juce_ReduceOpacityEffect.cpp *********/
  64653. /********* Start of inlined file: juce_Font.cpp *********/
  64654. BEGIN_JUCE_NAMESPACE
  64655. static const float minFontHeight = 0.1f;
  64656. static const float maxFontHeight = 10000.0f;
  64657. static const float defaultFontHeight = 14.0f;
  64658. static String defaultSans, defaultSerif, defaultFixed, fallbackFont;
  64659. Font::Font() throw()
  64660. : typefaceName (defaultSans),
  64661. height (defaultFontHeight),
  64662. horizontalScale (1.0f),
  64663. kerning (0),
  64664. ascent (0),
  64665. styleFlags (Font::plain)
  64666. {
  64667. }
  64668. void Font::resetToDefaultState() throw()
  64669. {
  64670. typefaceName = defaultSans;
  64671. height = defaultFontHeight;
  64672. horizontalScale = 1.0f;
  64673. kerning = 0;
  64674. ascent = 0;
  64675. styleFlags = Font::plain;
  64676. typeface = 0;
  64677. }
  64678. Font::Font (const float fontHeight,
  64679. const int styleFlags_) throw()
  64680. : typefaceName (defaultSans),
  64681. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  64682. horizontalScale (1.0f),
  64683. kerning (0),
  64684. ascent (0),
  64685. styleFlags (styleFlags_)
  64686. {
  64687. }
  64688. Font::Font (const String& typefaceName_,
  64689. const float fontHeight,
  64690. const int styleFlags_) throw()
  64691. : typefaceName (typefaceName_),
  64692. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  64693. horizontalScale (1.0f),
  64694. kerning (0),
  64695. ascent (0),
  64696. styleFlags (styleFlags_)
  64697. {
  64698. }
  64699. Font::Font (const Font& other) throw()
  64700. : typefaceName (other.typefaceName),
  64701. height (other.height),
  64702. horizontalScale (other.horizontalScale),
  64703. kerning (other.kerning),
  64704. ascent (other.ascent),
  64705. styleFlags (other.styleFlags),
  64706. typeface (other.typeface)
  64707. {
  64708. }
  64709. const Font& Font::operator= (const Font& other) throw()
  64710. {
  64711. if (this != &other)
  64712. {
  64713. typefaceName = other.typefaceName;
  64714. height = other.height;
  64715. styleFlags = other.styleFlags;
  64716. horizontalScale = other.horizontalScale;
  64717. kerning = other.kerning;
  64718. ascent = other.ascent;
  64719. typeface = other.typeface;
  64720. }
  64721. return *this;
  64722. }
  64723. Font::~Font() throw()
  64724. {
  64725. }
  64726. Font::Font (const Typeface& face) throw()
  64727. : height (11.0f),
  64728. horizontalScale (1.0f),
  64729. kerning (0),
  64730. ascent (0),
  64731. styleFlags (plain)
  64732. {
  64733. typefaceName = face.getName();
  64734. setBold (face.isBold());
  64735. setItalic (face.isItalic());
  64736. typeface = new Typeface (face);
  64737. }
  64738. bool Font::operator== (const Font& other) const throw()
  64739. {
  64740. return height == other.height
  64741. && horizontalScale == other.horizontalScale
  64742. && kerning == other.kerning
  64743. && styleFlags == other.styleFlags
  64744. && typefaceName == other.typefaceName;
  64745. }
  64746. bool Font::operator!= (const Font& other) const throw()
  64747. {
  64748. return ! operator== (other);
  64749. }
  64750. void Font::setTypefaceName (const String& faceName) throw()
  64751. {
  64752. typefaceName = faceName;
  64753. typeface = 0;
  64754. ascent = 0;
  64755. }
  64756. void Font::initialiseDefaultFontNames() throw()
  64757. {
  64758. Font::getDefaultFontNames (defaultSans,
  64759. defaultSerif,
  64760. defaultFixed);
  64761. }
  64762. void clearUpDefaultFontNames() throw() // called at shutdown by code in Typface
  64763. {
  64764. defaultSans = String::empty;
  64765. defaultSerif = String::empty;
  64766. defaultFixed = String::empty;
  64767. fallbackFont = String::empty;
  64768. }
  64769. const String Font::getDefaultSansSerifFontName() throw()
  64770. {
  64771. return defaultSans;
  64772. }
  64773. const String Font::getDefaultSerifFontName() throw()
  64774. {
  64775. return defaultSerif;
  64776. }
  64777. const String Font::getDefaultMonospacedFontName() throw()
  64778. {
  64779. return defaultFixed;
  64780. }
  64781. void Font::setDefaultSansSerifFontName (const String& name) throw()
  64782. {
  64783. defaultSans = name;
  64784. }
  64785. const String Font::getFallbackFontName() throw()
  64786. {
  64787. return fallbackFont;
  64788. }
  64789. void Font::setFallbackFontName (const String& name) throw()
  64790. {
  64791. fallbackFont = name;
  64792. }
  64793. void Font::setHeight (float newHeight) throw()
  64794. {
  64795. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  64796. }
  64797. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  64798. {
  64799. newHeight = jlimit (minFontHeight, maxFontHeight, newHeight);
  64800. horizontalScale *= (height / newHeight);
  64801. height = newHeight;
  64802. }
  64803. void Font::setStyleFlags (const int newFlags) throw()
  64804. {
  64805. if (styleFlags != newFlags)
  64806. {
  64807. styleFlags = newFlags;
  64808. typeface = 0;
  64809. ascent = 0;
  64810. }
  64811. }
  64812. void Font::setSizeAndStyle (const float newHeight,
  64813. const int newStyleFlags,
  64814. const float newHorizontalScale,
  64815. const float newKerningAmount) throw()
  64816. {
  64817. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  64818. horizontalScale = newHorizontalScale;
  64819. kerning = newKerningAmount;
  64820. setStyleFlags (newStyleFlags);
  64821. }
  64822. void Font::setHorizontalScale (const float scaleFactor) throw()
  64823. {
  64824. horizontalScale = scaleFactor;
  64825. }
  64826. void Font::setExtraKerningFactor (const float extraKerning) throw()
  64827. {
  64828. kerning = extraKerning;
  64829. }
  64830. void Font::setBold (const bool shouldBeBold) throw()
  64831. {
  64832. setStyleFlags (shouldBeBold ? (styleFlags | bold)
  64833. : (styleFlags & ~bold));
  64834. }
  64835. bool Font::isBold() const throw()
  64836. {
  64837. return (styleFlags & bold) != 0;
  64838. }
  64839. void Font::setItalic (const bool shouldBeItalic) throw()
  64840. {
  64841. setStyleFlags (shouldBeItalic ? (styleFlags | italic)
  64842. : (styleFlags & ~italic));
  64843. }
  64844. bool Font::isItalic() const throw()
  64845. {
  64846. return (styleFlags & italic) != 0;
  64847. }
  64848. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  64849. {
  64850. setStyleFlags (shouldBeUnderlined ? (styleFlags | underlined)
  64851. : (styleFlags & ~underlined));
  64852. }
  64853. bool Font::isUnderlined() const throw()
  64854. {
  64855. return (styleFlags & underlined) != 0;
  64856. }
  64857. float Font::getAscent() const throw()
  64858. {
  64859. if (ascent == 0)
  64860. ascent = getTypeface()->getAscent();
  64861. return height * ascent;
  64862. }
  64863. float Font::getDescent() const throw()
  64864. {
  64865. return height - getAscent();
  64866. }
  64867. int Font::getStringWidth (const String& text) const throw()
  64868. {
  64869. return roundFloatToInt (getStringWidthFloat (text));
  64870. }
  64871. float Font::getStringWidthFloat (const String& text) const throw()
  64872. {
  64873. float x = 0.0f;
  64874. if (text.isNotEmpty())
  64875. {
  64876. Typeface* const typeface = getTypeface();
  64877. const juce_wchar* t = (const juce_wchar*) text;
  64878. do
  64879. {
  64880. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (*t++);
  64881. if (glyph != 0)
  64882. x += kerning + glyph->getHorizontalSpacing (*t);
  64883. }
  64884. while (*t != 0);
  64885. x *= height;
  64886. x *= horizontalScale;
  64887. }
  64888. return x;
  64889. }
  64890. Typeface* Font::getTypeface() const throw()
  64891. {
  64892. if (typeface == 0)
  64893. typeface = Typeface::getTypefaceFor (*this);
  64894. return typeface;
  64895. }
  64896. void Font::findFonts (OwnedArray<Font>& destArray) throw()
  64897. {
  64898. const StringArray names (findAllTypefaceNames());
  64899. for (int i = 0; i < names.size(); ++i)
  64900. destArray.add (new Font (names[i], defaultFontHeight, Font::plain));
  64901. }
  64902. END_JUCE_NAMESPACE
  64903. /********* End of inlined file: juce_Font.cpp *********/
  64904. /********* Start of inlined file: juce_GlyphArrangement.cpp *********/
  64905. BEGIN_JUCE_NAMESPACE
  64906. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  64907. class FontGlyphAlphaMap
  64908. {
  64909. public:
  64910. bool draw (const Graphics& g, float x, const float y) const throw()
  64911. {
  64912. if (bitmap1 == 0)
  64913. return false;
  64914. x += xOrigin;
  64915. const float xFloor = floorf (x);
  64916. const int intX = (int) xFloor;
  64917. g.drawImageAt (((x - xFloor) >= 0.5f && bitmap2 != 0) ? bitmap2 : bitmap1,
  64918. intX, (int) floorf (y + yOrigin), true);
  64919. return true;
  64920. }
  64921. juce_UseDebuggingNewOperator
  64922. private:
  64923. Image* bitmap1;
  64924. Image* bitmap2;
  64925. float xOrigin, yOrigin;
  64926. int lastAccessCount;
  64927. Typeface::Ptr typeface;
  64928. float height, horizontalScale;
  64929. juce_wchar character;
  64930. friend class GlyphCache;
  64931. FontGlyphAlphaMap() throw()
  64932. : bitmap1 (0),
  64933. bitmap2 (0),
  64934. lastAccessCount (0),
  64935. height (0),
  64936. horizontalScale (0),
  64937. character (0)
  64938. {
  64939. }
  64940. ~FontGlyphAlphaMap() throw()
  64941. {
  64942. delete bitmap1;
  64943. delete bitmap2;
  64944. }
  64945. class AlphaBitmapRenderer
  64946. {
  64947. uint8* const data;
  64948. const int stride;
  64949. uint8* lineStart;
  64950. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  64951. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  64952. public:
  64953. AlphaBitmapRenderer (uint8* const data_,
  64954. const int stride_) throw()
  64955. : data (data_),
  64956. stride (stride_)
  64957. {
  64958. }
  64959. forcedinline void setEdgeTableYPos (const int y) throw()
  64960. {
  64961. lineStart = data + (stride * y);
  64962. }
  64963. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  64964. {
  64965. lineStart [x] = (uint8) alphaLevel;
  64966. }
  64967. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  64968. {
  64969. uint8* d = lineStart + x;
  64970. while (--width >= 0)
  64971. *d++ = (uint8) alphaLevel;
  64972. }
  64973. };
  64974. Image* createAlphaMapFromPath (const Path& path,
  64975. float& topLeftX, float& topLeftY,
  64976. float xScale, float yScale,
  64977. const float subPixelOffsetX) throw()
  64978. {
  64979. Image* im = 0;
  64980. float px, py, pw, ph;
  64981. path.getBounds (px, py, pw, ph);
  64982. topLeftX = floorf (px * xScale);
  64983. topLeftY = floorf (py * yScale);
  64984. int bitmapWidth = roundFloatToInt (pw * xScale) + 2;
  64985. int bitmapHeight = roundFloatToInt (ph * yScale) + 2;
  64986. im = new Image (Image::SingleChannel, bitmapWidth, bitmapHeight, true);
  64987. EdgeTable edgeTable (0, bitmapHeight, EdgeTable::Oversampling_16times);
  64988. edgeTable.addPath (path, AffineTransform::scale (xScale, yScale)
  64989. .translated (subPixelOffsetX - topLeftX, -topLeftY));
  64990. int stride, pixelStride;
  64991. uint8* const pixels = (uint8*) im->lockPixelDataReadWrite (0, 0, bitmapWidth, bitmapHeight, stride, pixelStride);
  64992. jassert (pixelStride == 1);
  64993. AlphaBitmapRenderer renderer (pixels, stride);
  64994. edgeTable.iterate (renderer, 0, 0, bitmapWidth, bitmapHeight, 0);
  64995. im->releasePixelDataReadWrite (pixels);
  64996. return im;
  64997. }
  64998. void generate (Typeface* const face,
  64999. const juce_wchar character_,
  65000. const float fontHeight,
  65001. const float fontHorizontalScale) throw()
  65002. {
  65003. character = character_;
  65004. typeface = face;
  65005. height = fontHeight;
  65006. horizontalScale = fontHorizontalScale;
  65007. const Path* const glyphPath = face->getOutlineForGlyph (character_);
  65008. deleteAndZero (bitmap1);
  65009. deleteAndZero (bitmap2);
  65010. const float fontHScale = fontHeight * fontHorizontalScale;
  65011. if (glyphPath != 0 && ! glyphPath->isEmpty())
  65012. {
  65013. bitmap1 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.0f);
  65014. if (fontHScale < 24.0f)
  65015. bitmap2 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.5f);
  65016. }
  65017. else
  65018. {
  65019. xOrigin = yOrigin = 0;
  65020. }
  65021. }
  65022. };
  65023. static const int defaultNumGlyphsToCache = 120;
  65024. class GlyphCache;
  65025. static GlyphCache* cacheInstance = 0;
  65026. class GlyphCache : private DeletedAtShutdown
  65027. {
  65028. public:
  65029. static GlyphCache* getInstance() throw()
  65030. {
  65031. if (cacheInstance == 0)
  65032. cacheInstance = new GlyphCache();
  65033. return cacheInstance;
  65034. }
  65035. const FontGlyphAlphaMap& getGlyphFor (Typeface* const typeface,
  65036. const float fontHeight,
  65037. const float fontHorizontalScale,
  65038. const juce_wchar character) throw()
  65039. {
  65040. ++accessCounter;
  65041. int oldestCounter = INT_MAX;
  65042. int oldestIndex = 0;
  65043. for (int i = numGlyphs; --i >= 0;)
  65044. {
  65045. FontGlyphAlphaMap& g = glyphs[i];
  65046. if (g.character == character
  65047. && g.height == fontHeight
  65048. && g.typeface->hashCode() == typeface->hashCode()
  65049. && g.horizontalScale == fontHorizontalScale)
  65050. {
  65051. g.lastAccessCount = accessCounter;
  65052. ++hits;
  65053. return g;
  65054. }
  65055. if (oldestCounter > g.lastAccessCount)
  65056. {
  65057. oldestCounter = g.lastAccessCount;
  65058. oldestIndex = i;
  65059. }
  65060. }
  65061. ++misses;
  65062. if (hits + misses > (numGlyphs << 4))
  65063. {
  65064. if (misses * 2 > hits)
  65065. setCacheSize (numGlyphs + 32);
  65066. hits = 0;
  65067. misses = 0;
  65068. oldestIndex = 0;
  65069. }
  65070. FontGlyphAlphaMap& oldest = glyphs [oldestIndex];
  65071. oldest.lastAccessCount = accessCounter;
  65072. oldest.generate (typeface,
  65073. character,
  65074. fontHeight,
  65075. fontHorizontalScale);
  65076. return oldest;
  65077. }
  65078. void setCacheSize (const int num) throw()
  65079. {
  65080. if (numGlyphs != num)
  65081. {
  65082. numGlyphs = num;
  65083. if (glyphs != 0)
  65084. delete[] glyphs;
  65085. glyphs = new FontGlyphAlphaMap [numGlyphs];
  65086. hits = 0;
  65087. misses = 0;
  65088. }
  65089. }
  65090. juce_UseDebuggingNewOperator
  65091. private:
  65092. FontGlyphAlphaMap* glyphs;
  65093. int numGlyphs, accessCounter;
  65094. int hits, misses;
  65095. GlyphCache() throw()
  65096. : glyphs (0),
  65097. numGlyphs (0),
  65098. accessCounter (0)
  65099. {
  65100. setCacheSize (defaultNumGlyphsToCache);
  65101. }
  65102. ~GlyphCache() throw()
  65103. {
  65104. delete[] glyphs;
  65105. jassert (cacheInstance == this);
  65106. cacheInstance = 0;
  65107. }
  65108. GlyphCache (const GlyphCache&);
  65109. const GlyphCache& operator= (const GlyphCache&);
  65110. };
  65111. PositionedGlyph::PositionedGlyph() throw()
  65112. {
  65113. }
  65114. void PositionedGlyph::draw (const Graphics& g) const throw()
  65115. {
  65116. if (! glyphInfo->isWhitespace())
  65117. {
  65118. if (fontHeight < 100.0f && fontHeight > 0.1f && ! g.isVectorDevice())
  65119. {
  65120. const FontGlyphAlphaMap& alphaMap
  65121. = GlyphCache::getInstance()->getGlyphFor (glyphInfo->getTypeface(),
  65122. fontHeight,
  65123. fontHorizontalScale,
  65124. getCharacter());
  65125. alphaMap.draw (g, x, y);
  65126. }
  65127. else
  65128. {
  65129. // that's a bit of a dodgy size, isn't it??
  65130. jassert (fontHeight > 0.0f && fontHeight < 4000.0f);
  65131. draw (g, AffineTransform::identity);
  65132. }
  65133. }
  65134. }
  65135. void PositionedGlyph::draw (const Graphics& g,
  65136. const AffineTransform& transform) const throw()
  65137. {
  65138. if (! glyphInfo->isWhitespace())
  65139. {
  65140. g.fillPath (glyphInfo->getPath(),
  65141. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  65142. .translated (x, y)
  65143. .followedBy (transform));
  65144. }
  65145. }
  65146. void PositionedGlyph::createPath (Path& path) const throw()
  65147. {
  65148. if (! glyphInfo->isWhitespace())
  65149. {
  65150. path.addPath (glyphInfo->getPath(),
  65151. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  65152. .translated (x, y));
  65153. }
  65154. }
  65155. bool PositionedGlyph::hitTest (float px, float py) const throw()
  65156. {
  65157. if (px >= getLeft() && px < getRight()
  65158. && py >= getTop() && py < getBottom()
  65159. && fontHeight > 0.0f
  65160. && ! glyphInfo->isWhitespace())
  65161. {
  65162. AffineTransform::translation (-x, -y)
  65163. .scaled (1.0f / (fontHeight * fontHorizontalScale), 1.0f / fontHeight)
  65164. .transformPoint (px, py);
  65165. return glyphInfo->getPath().contains (px, py);
  65166. }
  65167. return false;
  65168. }
  65169. void PositionedGlyph::moveBy (const float deltaX,
  65170. const float deltaY) throw()
  65171. {
  65172. x += deltaX;
  65173. y += deltaY;
  65174. }
  65175. GlyphArrangement::GlyphArrangement() throw()
  65176. : numGlyphs (0),
  65177. numAllocated (0),
  65178. glyphs (0)
  65179. {
  65180. }
  65181. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other) throw()
  65182. : numGlyphs (0),
  65183. numAllocated (0),
  65184. glyphs (0)
  65185. {
  65186. addGlyphArrangement (other);
  65187. }
  65188. const GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other) throw()
  65189. {
  65190. if (this != &other)
  65191. {
  65192. clear();
  65193. addGlyphArrangement (other);
  65194. }
  65195. return *this;
  65196. }
  65197. GlyphArrangement::~GlyphArrangement() throw()
  65198. {
  65199. clear();
  65200. juce_free (glyphs);
  65201. }
  65202. void GlyphArrangement::ensureNumGlyphsAllocated (const int minGlyphs) throw()
  65203. {
  65204. if (numAllocated <= minGlyphs)
  65205. {
  65206. numAllocated = minGlyphs + 2;
  65207. if (glyphs == 0)
  65208. glyphs = (PositionedGlyph*) juce_malloc (numAllocated * sizeof (PositionedGlyph));
  65209. else
  65210. glyphs = (PositionedGlyph*) juce_realloc (glyphs, numAllocated * sizeof (PositionedGlyph));
  65211. }
  65212. }
  65213. void GlyphArrangement::incGlyphRefCount (const int i) const throw()
  65214. {
  65215. jassert (((unsigned int) i) < (unsigned int) numGlyphs);
  65216. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  65217. glyphs[i].glyphInfo->getTypeface()->incReferenceCount();
  65218. }
  65219. void GlyphArrangement::decGlyphRefCount (const int i) const throw()
  65220. {
  65221. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  65222. glyphs[i].glyphInfo->getTypeface()->decReferenceCount();
  65223. }
  65224. void GlyphArrangement::clear() throw()
  65225. {
  65226. for (int i = numGlyphs; --i >= 0;)
  65227. decGlyphRefCount (i);
  65228. numGlyphs = 0;
  65229. }
  65230. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const throw()
  65231. {
  65232. jassert (((unsigned int) index) < (unsigned int) numGlyphs);
  65233. return glyphs [index];
  65234. }
  65235. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other) throw()
  65236. {
  65237. ensureNumGlyphsAllocated (numGlyphs + other.numGlyphs);
  65238. memcpy (glyphs + numGlyphs, other.glyphs,
  65239. other.numGlyphs * sizeof (PositionedGlyph));
  65240. for (int i = other.numGlyphs; --i >= 0;)
  65241. incGlyphRefCount (numGlyphs++);
  65242. }
  65243. void GlyphArrangement::removeLast() throw()
  65244. {
  65245. if (numGlyphs > 0)
  65246. decGlyphRefCount (--numGlyphs);
  65247. }
  65248. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num) throw()
  65249. {
  65250. jassert (startIndex >= 0);
  65251. if (startIndex < 0)
  65252. startIndex = 0;
  65253. if (num < 0 || startIndex + num >= numGlyphs)
  65254. {
  65255. while (numGlyphs > startIndex)
  65256. removeLast();
  65257. }
  65258. else if (num > 0)
  65259. {
  65260. int i;
  65261. for (i = startIndex; i < startIndex + num; ++i)
  65262. decGlyphRefCount (i);
  65263. for (i = numGlyphs - (startIndex + num); --i >= 0;)
  65264. {
  65265. glyphs [startIndex] = glyphs [startIndex + num];
  65266. ++startIndex;
  65267. }
  65268. numGlyphs -= num;
  65269. }
  65270. }
  65271. void GlyphArrangement::addLineOfText (const Font& font,
  65272. const String& text,
  65273. const float xOffset,
  65274. const float yOffset) throw()
  65275. {
  65276. addCurtailedLineOfText (font, text,
  65277. xOffset, yOffset,
  65278. 1.0e10f, false);
  65279. }
  65280. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  65281. const String& text,
  65282. float xOffset,
  65283. const float yOffset,
  65284. const float maxWidthPixels,
  65285. const bool useEllipsis) throw()
  65286. {
  65287. const int textLen = text.length();
  65288. if (textLen > 0)
  65289. {
  65290. ensureNumGlyphsAllocated (numGlyphs + textLen + 3); // extra chars for ellipsis
  65291. Typeface* const typeface = font.getTypeface();
  65292. const float fontHeight = font.getHeight();
  65293. const float ascent = font.getAscent();
  65294. const float fontHorizontalScale = font.getHorizontalScale();
  65295. const float heightTimesScale = fontHorizontalScale * fontHeight;
  65296. const float kerningFactor = font.getExtraKerningFactor();
  65297. const float startX = xOffset;
  65298. const juce_wchar* const unicodeText = (const juce_wchar*) text;
  65299. for (int i = 0; i < textLen; ++i)
  65300. {
  65301. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (unicodeText[i]);
  65302. if (glyph != 0)
  65303. {
  65304. jassert (numAllocated > numGlyphs);
  65305. ensureNumGlyphsAllocated (numGlyphs);
  65306. PositionedGlyph& pg = glyphs [numGlyphs];
  65307. pg.glyphInfo = glyph;
  65308. pg.x = xOffset;
  65309. pg.y = yOffset;
  65310. pg.w = heightTimesScale * glyph->getHorizontalSpacing (0);
  65311. pg.fontHeight = fontHeight;
  65312. pg.fontAscent = ascent;
  65313. pg.fontHorizontalScale = fontHorizontalScale;
  65314. pg.isUnderlined = font.isUnderlined();
  65315. xOffset += heightTimesScale * (kerningFactor + glyph->getHorizontalSpacing (unicodeText [i + 1]));
  65316. if (xOffset - startX > maxWidthPixels + 1.0f)
  65317. {
  65318. // curtail the string if it's too wide..
  65319. if (useEllipsis && textLen > 3 && numGlyphs >= 3)
  65320. appendEllipsis (font, startX + maxWidthPixels);
  65321. break;
  65322. }
  65323. else
  65324. {
  65325. if (glyph->getTypeface() != 0)
  65326. glyph->getTypeface()->incReferenceCount();
  65327. ++numGlyphs;
  65328. }
  65329. }
  65330. }
  65331. }
  65332. }
  65333. void GlyphArrangement::appendEllipsis (const Font& font, const float maxXPixels) throw()
  65334. {
  65335. const TypefaceGlyphInfo* const dotGlyph = font.getTypeface()->getGlyph (T('.'));
  65336. if (dotGlyph != 0)
  65337. {
  65338. if (numGlyphs > 0)
  65339. {
  65340. PositionedGlyph& glyph = glyphs [numGlyphs - 1];
  65341. const float fontHeight = glyph.fontHeight;
  65342. const float fontHorizontalScale = glyph.fontHorizontalScale;
  65343. const float fontAscent = glyph.fontAscent;
  65344. const float dx = fontHeight * fontHorizontalScale
  65345. * (font.getExtraKerningFactor() + dotGlyph->getHorizontalSpacing (T('.')));
  65346. float xOffset = 0.0f, yOffset = 0.0f;
  65347. for (int dotPos = 3; --dotPos >= 0 && numGlyphs > 0;)
  65348. {
  65349. removeLast();
  65350. jassert (numAllocated > numGlyphs);
  65351. PositionedGlyph& pg = glyphs [numGlyphs];
  65352. xOffset = pg.x;
  65353. yOffset = pg.y;
  65354. if (numGlyphs == 0 || xOffset + dx * 3 <= maxXPixels)
  65355. break;
  65356. }
  65357. for (int i = 3; --i >= 0;)
  65358. {
  65359. jassert (numAllocated > numGlyphs);
  65360. ensureNumGlyphsAllocated (numGlyphs);
  65361. PositionedGlyph& pg = glyphs [numGlyphs];
  65362. pg.glyphInfo = dotGlyph;
  65363. pg.x = xOffset;
  65364. pg.y = yOffset;
  65365. pg.w = dx;
  65366. pg.fontHeight = fontHeight;
  65367. pg.fontAscent = fontAscent;
  65368. pg.fontHorizontalScale = fontHorizontalScale;
  65369. pg.isUnderlined = font.isUnderlined();
  65370. xOffset += dx;
  65371. if (dotGlyph->getTypeface() != 0)
  65372. dotGlyph->getTypeface()->incReferenceCount();
  65373. ++numGlyphs;
  65374. }
  65375. }
  65376. }
  65377. }
  65378. void GlyphArrangement::addJustifiedText (const Font& font,
  65379. const String& text,
  65380. float x, float y,
  65381. const float maxLineWidth,
  65382. const Justification& horizontalLayout) throw()
  65383. {
  65384. int lineStartIndex = numGlyphs;
  65385. addLineOfText (font, text, x, y);
  65386. const float originalY = y;
  65387. while (lineStartIndex < numGlyphs)
  65388. {
  65389. int i = lineStartIndex;
  65390. if (glyphs[i].getCharacter() != T('\n') && glyphs[i].getCharacter() != T('\r'))
  65391. ++i;
  65392. const float lineMaxX = glyphs [lineStartIndex].getLeft() + maxLineWidth;
  65393. int lastWordBreakIndex = -1;
  65394. while (i < numGlyphs)
  65395. {
  65396. PositionedGlyph& pg = glyphs[i];
  65397. const juce_wchar c = pg.getCharacter();
  65398. if (c == T('\r') || c == T('\n'))
  65399. {
  65400. ++i;
  65401. if (c == T('\r') && i < numGlyphs && glyphs [i].getCharacter() == T('\n'))
  65402. ++i;
  65403. break;
  65404. }
  65405. else if (pg.isWhitespace())
  65406. {
  65407. lastWordBreakIndex = i + 1;
  65408. }
  65409. else if (SHOULD_WRAP (pg.getRight(), lineMaxX))
  65410. {
  65411. if (lastWordBreakIndex >= 0)
  65412. i = lastWordBreakIndex;
  65413. break;
  65414. }
  65415. ++i;
  65416. }
  65417. const float currentLineStartX = glyphs [lineStartIndex].getLeft();
  65418. float currentLineEndX = currentLineStartX;
  65419. for (int j = i; --j >= lineStartIndex;)
  65420. {
  65421. if (! glyphs[j].isWhitespace())
  65422. {
  65423. currentLineEndX = glyphs[j].getRight();
  65424. break;
  65425. }
  65426. }
  65427. float deltaX = 0.0f;
  65428. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  65429. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  65430. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  65431. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  65432. else if (horizontalLayout.testFlags (Justification::right))
  65433. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  65434. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  65435. x + deltaX - currentLineStartX, y - originalY);
  65436. lineStartIndex = i;
  65437. y += font.getHeight();
  65438. }
  65439. }
  65440. void GlyphArrangement::addFittedText (const Font& f,
  65441. const String& text,
  65442. float x, float y,
  65443. float width, float height,
  65444. const Justification& layout,
  65445. int maximumLines,
  65446. const float minimumHorizontalScale) throw()
  65447. {
  65448. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  65449. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  65450. if (text.containsAnyOf (T("\r\n")))
  65451. {
  65452. GlyphArrangement ga;
  65453. ga.addJustifiedText (f, text, x, y, width, layout);
  65454. float l, t, r, b;
  65455. ga.getBoundingBox (0, -1, l, t, r, b, false);
  65456. float dy = y - t;
  65457. if (layout.testFlags (Justification::verticallyCentred))
  65458. dy += (height - (b - t)) * 0.5f;
  65459. else if (layout.testFlags (Justification::bottom))
  65460. dy += height - (b - t);
  65461. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  65462. addGlyphArrangement (ga);
  65463. return;
  65464. }
  65465. int startIndex = numGlyphs;
  65466. addLineOfText (f, text.trim(), x, y);
  65467. if (numGlyphs > startIndex)
  65468. {
  65469. float lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  65470. if (lineWidth <= 0)
  65471. return;
  65472. if (lineWidth * minimumHorizontalScale < width)
  65473. {
  65474. if (lineWidth > width)
  65475. {
  65476. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex,
  65477. width / lineWidth);
  65478. }
  65479. justifyGlyphs (startIndex, numGlyphs - startIndex,
  65480. x, y, width, height, layout);
  65481. }
  65482. else if (maximumLines <= 1)
  65483. {
  65484. const float ratio = jmax (minimumHorizontalScale, width / lineWidth);
  65485. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex, ratio);
  65486. while (numGlyphs > 0 && glyphs [numGlyphs - 1].x + glyphs [numGlyphs - 1].w >= x + width)
  65487. removeLast();
  65488. appendEllipsis (f, x + width);
  65489. justifyGlyphs (startIndex, numGlyphs - startIndex,
  65490. x, y, width, height, layout);
  65491. }
  65492. else
  65493. {
  65494. Font font (f);
  65495. String txt (text.trim());
  65496. const int length = txt.length();
  65497. int numLines = 1;
  65498. const int originalStartIndex = startIndex;
  65499. if (length <= 12 && ! txt.containsAnyOf (T(" -\t\r\n")))
  65500. maximumLines = 1;
  65501. maximumLines = jmin (maximumLines, length);
  65502. while (numLines < maximumLines)
  65503. {
  65504. ++numLines;
  65505. const float newFontHeight = height / (float)numLines;
  65506. if (newFontHeight < 8.0f)
  65507. break;
  65508. if (newFontHeight < font.getHeight())
  65509. {
  65510. font.setHeight (newFontHeight);
  65511. while (numGlyphs > startIndex)
  65512. removeLast();
  65513. addLineOfText (font, txt, x, y);
  65514. lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  65515. }
  65516. if (numLines > lineWidth / width)
  65517. break;
  65518. }
  65519. if (numLines < 1)
  65520. numLines = 1;
  65521. float lineY = y;
  65522. float widthPerLine = lineWidth / numLines;
  65523. int lastLineStartIndex = 0;
  65524. for (int line = 0; line < numLines; ++line)
  65525. {
  65526. int i = startIndex;
  65527. lastLineStartIndex = i;
  65528. float lineStartX = glyphs[startIndex].getLeft();
  65529. while (i < numGlyphs)
  65530. {
  65531. lineWidth = (glyphs[i].getRight() - lineStartX);
  65532. if (lineWidth > widthPerLine)
  65533. {
  65534. // got to a point where the line's too long, so skip forward to find a
  65535. // good place to break it..
  65536. const int searchStartIndex = i;
  65537. while (i < numGlyphs)
  65538. {
  65539. if ((glyphs[i].getRight() - lineStartX) * minimumHorizontalScale < width)
  65540. {
  65541. if (glyphs[i].isWhitespace()
  65542. || glyphs[i].getCharacter() == T('-'))
  65543. {
  65544. ++i;
  65545. break;
  65546. }
  65547. }
  65548. else
  65549. {
  65550. // can't find a suitable break, so try looking backwards..
  65551. i = searchStartIndex;
  65552. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  65553. {
  65554. if (glyphs[i - back].isWhitespace()
  65555. || glyphs[i - back].getCharacter() == T('-'))
  65556. {
  65557. i -= back - 1;
  65558. break;
  65559. }
  65560. }
  65561. break;
  65562. }
  65563. ++i;
  65564. }
  65565. break;
  65566. }
  65567. ++i;
  65568. }
  65569. int wsStart = i;
  65570. while (wsStart > 0 && glyphs[wsStart - 1].isWhitespace())
  65571. --wsStart;
  65572. int wsEnd = i;
  65573. while (wsEnd < numGlyphs && glyphs[wsEnd].isWhitespace())
  65574. ++wsEnd;
  65575. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  65576. i = jmax (wsStart, startIndex + 1);
  65577. lineWidth = glyphs[i - 1].getRight() - lineStartX;
  65578. if (lineWidth > width)
  65579. {
  65580. stretchRangeOfGlyphs (startIndex, i - startIndex,
  65581. width / lineWidth);
  65582. }
  65583. justifyGlyphs (startIndex, i - startIndex,
  65584. x, lineY, width, font.getHeight(),
  65585. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  65586. startIndex = i;
  65587. lineY += font.getHeight();
  65588. if (startIndex >= numGlyphs)
  65589. break;
  65590. }
  65591. if (startIndex < numGlyphs)
  65592. {
  65593. while (numGlyphs > startIndex)
  65594. removeLast();
  65595. if (startIndex - originalStartIndex > 4)
  65596. {
  65597. const float lineStartX = glyphs[lastLineStartIndex].getLeft();
  65598. appendEllipsis (font, lineStartX + width);
  65599. lineWidth = glyphs[startIndex - 1].getRight() - lineStartX;
  65600. if (lineWidth > width)
  65601. {
  65602. stretchRangeOfGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  65603. width / lineWidth);
  65604. }
  65605. justifyGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  65606. x, lineY - font.getHeight(), width, font.getHeight(),
  65607. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  65608. }
  65609. startIndex = numGlyphs;
  65610. }
  65611. justifyGlyphs (originalStartIndex, startIndex - originalStartIndex,
  65612. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  65613. }
  65614. }
  65615. }
  65616. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  65617. const float dx, const float dy) throw()
  65618. {
  65619. jassert (startIndex >= 0);
  65620. if (dx != 0.0f || dy != 0.0f)
  65621. {
  65622. if (num < 0 || startIndex + num > numGlyphs)
  65623. num = numGlyphs - startIndex;
  65624. while (--num >= 0)
  65625. {
  65626. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  65627. glyphs [startIndex++].moveBy (dx, dy);
  65628. }
  65629. }
  65630. }
  65631. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  65632. const float horizontalScaleFactor) throw()
  65633. {
  65634. jassert (startIndex >= 0);
  65635. if (num < 0 || startIndex + num > numGlyphs)
  65636. num = numGlyphs - startIndex;
  65637. if (num > 0)
  65638. {
  65639. const float xAnchor = glyphs[startIndex].getLeft();
  65640. while (--num >= 0)
  65641. {
  65642. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  65643. PositionedGlyph& pg = glyphs[startIndex++];
  65644. pg.x = xAnchor + (pg.x - xAnchor) * horizontalScaleFactor;
  65645. pg.fontHorizontalScale *= horizontalScaleFactor;
  65646. pg.w *= horizontalScaleFactor;
  65647. }
  65648. }
  65649. }
  65650. void GlyphArrangement::getBoundingBox (int startIndex, int num,
  65651. float& left,
  65652. float& top,
  65653. float& right,
  65654. float& bottom,
  65655. const bool includeWhitespace) const throw()
  65656. {
  65657. jassert (startIndex >= 0);
  65658. if (num < 0 || startIndex + num > numGlyphs)
  65659. num = numGlyphs - startIndex;
  65660. left = 0.0f;
  65661. top = 0.0f;
  65662. right = 0.0f;
  65663. bottom = 0.0f;
  65664. bool isFirst = true;
  65665. while (--num >= 0)
  65666. {
  65667. const PositionedGlyph& pg = glyphs [startIndex++];
  65668. if (includeWhitespace || ! pg.isWhitespace())
  65669. {
  65670. if (isFirst)
  65671. {
  65672. isFirst = false;
  65673. left = pg.getLeft();
  65674. top = pg.getTop();
  65675. right = pg.getRight();
  65676. bottom = pg.getBottom();
  65677. }
  65678. else
  65679. {
  65680. left = jmin (left, pg.getLeft());
  65681. top = jmin (top, pg.getTop());
  65682. right = jmax (right, pg.getRight());
  65683. bottom = jmax (bottom, pg.getBottom());
  65684. }
  65685. }
  65686. }
  65687. }
  65688. void GlyphArrangement::justifyGlyphs (const int startIndex,
  65689. const int num,
  65690. const float x, const float y,
  65691. const float width, const float height,
  65692. const Justification& justification) throw()
  65693. {
  65694. jassert (num >= 0 && startIndex >= 0);
  65695. if (numGlyphs > 0 && num > 0)
  65696. {
  65697. float left, top, right, bottom;
  65698. getBoundingBox (startIndex, num, left, top, right, bottom,
  65699. ! justification.testFlags (Justification::horizontallyJustified
  65700. | Justification::horizontallyCentred));
  65701. float deltaX = 0.0f;
  65702. if (justification.testFlags (Justification::horizontallyJustified))
  65703. deltaX = x - left;
  65704. else if (justification.testFlags (Justification::horizontallyCentred))
  65705. deltaX = x + (width - (right - left)) * 0.5f - left;
  65706. else if (justification.testFlags (Justification::right))
  65707. deltaX = (x + width) - right;
  65708. else
  65709. deltaX = x - left;
  65710. float deltaY = 0.0f;
  65711. if (justification.testFlags (Justification::top))
  65712. deltaY = y - top;
  65713. else if (justification.testFlags (Justification::bottom))
  65714. deltaY = (y + height) - bottom;
  65715. else
  65716. deltaY = y + (height - (bottom - top)) * 0.5f - top;
  65717. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  65718. if (justification.testFlags (Justification::horizontallyJustified))
  65719. {
  65720. int lineStart = 0;
  65721. float baseY = glyphs [startIndex].getBaselineY();
  65722. int i;
  65723. for (i = 0; i < num; ++i)
  65724. {
  65725. const float glyphY = glyphs [startIndex + i].getBaselineY();
  65726. if (glyphY != baseY)
  65727. {
  65728. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  65729. lineStart = i;
  65730. baseY = glyphY;
  65731. }
  65732. }
  65733. if (i > lineStart)
  65734. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  65735. }
  65736. }
  65737. }
  65738. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth) throw()
  65739. {
  65740. if (start + num < numGlyphs
  65741. && glyphs [start + num - 1].getCharacter() != T('\r')
  65742. && glyphs [start + num - 1].getCharacter() != T('\n'))
  65743. {
  65744. int numSpaces = 0;
  65745. int spacesAtEnd = 0;
  65746. for (int i = 0; i < num; ++i)
  65747. {
  65748. if (glyphs [start + i].isWhitespace())
  65749. {
  65750. ++spacesAtEnd;
  65751. ++numSpaces;
  65752. }
  65753. else
  65754. {
  65755. spacesAtEnd = 0;
  65756. }
  65757. }
  65758. numSpaces -= spacesAtEnd;
  65759. if (numSpaces > 0)
  65760. {
  65761. const float startX = glyphs [start].getLeft();
  65762. const float endX = glyphs [start + num - 1 - spacesAtEnd].getRight();
  65763. const float extraPaddingBetweenWords
  65764. = (targetWidth - (endX - startX)) / (float) numSpaces;
  65765. float deltaX = 0.0f;
  65766. for (int i = 0; i < num; ++i)
  65767. {
  65768. glyphs [start + i].moveBy (deltaX, 0.0);
  65769. if (glyphs [start + i].isWhitespace())
  65770. deltaX += extraPaddingBetweenWords;
  65771. }
  65772. }
  65773. }
  65774. }
  65775. void GlyphArrangement::draw (const Graphics& g) const throw()
  65776. {
  65777. for (int i = 0; i < numGlyphs; ++i)
  65778. {
  65779. glyphs[i].draw (g);
  65780. if (glyphs[i].isUnderlined)
  65781. {
  65782. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  65783. juce_wchar nextChar = 0;
  65784. if (i < numGlyphs - 1
  65785. && glyphs[i + 1].y == glyphs[i].y)
  65786. {
  65787. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  65788. }
  65789. g.fillRect (glyphs[i].x,
  65790. glyphs[i].y + lineThickness * 2.0f,
  65791. glyphs[i].fontHeight
  65792. * glyphs[i].fontHorizontalScale
  65793. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  65794. lineThickness);
  65795. }
  65796. }
  65797. }
  65798. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const throw()
  65799. {
  65800. for (int i = 0; i < numGlyphs; ++i)
  65801. {
  65802. glyphs[i].draw (g, transform);
  65803. if (glyphs[i].isUnderlined)
  65804. {
  65805. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  65806. juce_wchar nextChar = 0;
  65807. if (i < numGlyphs - 1
  65808. && glyphs[i + 1].y == glyphs[i].y)
  65809. {
  65810. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  65811. }
  65812. Path p;
  65813. p.addLineSegment (glyphs[i].x,
  65814. glyphs[i].y + lineThickness * 2.5f,
  65815. glyphs[i].x + glyphs[i].fontHeight
  65816. * glyphs[i].fontHorizontalScale
  65817. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  65818. glyphs[i].y + lineThickness * 2.5f,
  65819. lineThickness);
  65820. g.fillPath (p, transform);
  65821. }
  65822. }
  65823. }
  65824. void GlyphArrangement::createPath (Path& path) const throw()
  65825. {
  65826. for (int i = 0; i < numGlyphs; ++i)
  65827. glyphs[i].createPath (path);
  65828. }
  65829. int GlyphArrangement::findGlyphIndexAt (float x, float y) const throw()
  65830. {
  65831. for (int i = 0; i < numGlyphs; ++i)
  65832. if (glyphs[i].hitTest (x, y))
  65833. return i;
  65834. return -1;
  65835. }
  65836. END_JUCE_NAMESPACE
  65837. /********* End of inlined file: juce_GlyphArrangement.cpp *********/
  65838. /********* Start of inlined file: juce_TextLayout.cpp *********/
  65839. BEGIN_JUCE_NAMESPACE
  65840. class TextLayoutToken
  65841. {
  65842. public:
  65843. String text;
  65844. Font font;
  65845. int x, y, w, h;
  65846. int line, lineHeight;
  65847. bool isWhitespace, isNewLine;
  65848. TextLayoutToken (const String& t,
  65849. const Font& f,
  65850. const bool isWhitespace_) throw()
  65851. : text (t),
  65852. font (f),
  65853. x(0),
  65854. y(0),
  65855. isWhitespace (isWhitespace_)
  65856. {
  65857. w = font.getStringWidth (t);
  65858. h = roundFloatToInt (f.getHeight());
  65859. isNewLine = t.containsAnyOf (T("\r\n"));
  65860. }
  65861. TextLayoutToken (const TextLayoutToken& other) throw()
  65862. : text (other.text),
  65863. font (other.font),
  65864. x (other.x),
  65865. y (other.y),
  65866. w (other.w),
  65867. h (other.h),
  65868. line (other.line),
  65869. lineHeight (other.lineHeight),
  65870. isWhitespace (other.isWhitespace),
  65871. isNewLine (other.isNewLine)
  65872. {
  65873. }
  65874. ~TextLayoutToken() throw()
  65875. {
  65876. }
  65877. void draw (Graphics& g,
  65878. const int xOffset,
  65879. const int yOffset) throw()
  65880. {
  65881. if (! isWhitespace)
  65882. {
  65883. g.setFont (font);
  65884. g.drawSingleLineText (text.trimEnd(),
  65885. xOffset + x,
  65886. yOffset + y + (lineHeight - h)
  65887. + roundFloatToInt (font.getAscent()));
  65888. }
  65889. }
  65890. juce_UseDebuggingNewOperator
  65891. };
  65892. TextLayout::TextLayout() throw()
  65893. : tokens (64),
  65894. totalLines (0)
  65895. {
  65896. }
  65897. TextLayout::TextLayout (const String& text,
  65898. const Font& font) throw()
  65899. : tokens (64),
  65900. totalLines (0)
  65901. {
  65902. appendText (text, font);
  65903. }
  65904. TextLayout::TextLayout (const TextLayout& other) throw()
  65905. : tokens (64),
  65906. totalLines (0)
  65907. {
  65908. *this = other;
  65909. }
  65910. const TextLayout& TextLayout::operator= (const TextLayout& other) throw()
  65911. {
  65912. if (this != &other)
  65913. {
  65914. clear();
  65915. totalLines = other.totalLines;
  65916. for (int i = 0; i < other.tokens.size(); ++i)
  65917. tokens.add (new TextLayoutToken (*(const TextLayoutToken*)(other.tokens.getUnchecked(i))));
  65918. }
  65919. return *this;
  65920. }
  65921. TextLayout::~TextLayout() throw()
  65922. {
  65923. clear();
  65924. }
  65925. void TextLayout::clear() throw()
  65926. {
  65927. for (int i = tokens.size(); --i >= 0;)
  65928. {
  65929. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  65930. delete t;
  65931. }
  65932. tokens.clear();
  65933. totalLines = 0;
  65934. }
  65935. void TextLayout::appendText (const String& text,
  65936. const Font& font) throw()
  65937. {
  65938. const tchar* t = text;
  65939. String currentString;
  65940. int lastCharType = 0;
  65941. for (;;)
  65942. {
  65943. const tchar c = *t++;
  65944. if (c == 0)
  65945. break;
  65946. int charType;
  65947. if (c == T('\r') || c == T('\n'))
  65948. {
  65949. charType = 0;
  65950. }
  65951. else if (CharacterFunctions::isWhitespace (c))
  65952. {
  65953. charType = 2;
  65954. }
  65955. else
  65956. {
  65957. charType = 1;
  65958. }
  65959. if (charType == 0 || charType != lastCharType)
  65960. {
  65961. if (currentString.isNotEmpty())
  65962. {
  65963. tokens.add (new TextLayoutToken (currentString, font,
  65964. lastCharType == 2 || lastCharType == 0));
  65965. }
  65966. currentString = String::charToString (c);
  65967. if (c == T('\r') && *t == T('\n'))
  65968. currentString += *t++;
  65969. }
  65970. else
  65971. {
  65972. currentString += c;
  65973. }
  65974. lastCharType = charType;
  65975. }
  65976. if (currentString.isNotEmpty())
  65977. tokens.add (new TextLayoutToken (currentString,
  65978. font,
  65979. lastCharType == 2));
  65980. }
  65981. void TextLayout::setText (const String& text, const Font& font) throw()
  65982. {
  65983. clear();
  65984. appendText (text, font);
  65985. }
  65986. void TextLayout::layout (int maxWidth,
  65987. const Justification& justification,
  65988. const bool attemptToBalanceLineLengths) throw()
  65989. {
  65990. if (attemptToBalanceLineLengths)
  65991. {
  65992. const int originalW = maxWidth;
  65993. int bestWidth = maxWidth;
  65994. float bestLineProportion = 0.0f;
  65995. while (maxWidth > originalW / 2)
  65996. {
  65997. layout (maxWidth, justification, false);
  65998. if (getNumLines() <= 1)
  65999. return;
  66000. const int lastLineW = getLineWidth (getNumLines() - 1);
  66001. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  66002. const float prop = lastLineW / (float) lastButOneLineW;
  66003. if (prop > 0.9f)
  66004. return;
  66005. if (prop > bestLineProportion)
  66006. {
  66007. bestLineProportion = prop;
  66008. bestWidth = maxWidth;
  66009. }
  66010. maxWidth -= 10;
  66011. }
  66012. layout (bestWidth, justification, false);
  66013. }
  66014. else
  66015. {
  66016. int x = 0;
  66017. int y = 0;
  66018. int h = 0;
  66019. totalLines = 0;
  66020. int i;
  66021. for (i = 0; i < tokens.size(); ++i)
  66022. {
  66023. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  66024. t->x = x;
  66025. t->y = y;
  66026. t->line = totalLines;
  66027. x += t->w;
  66028. h = jmax (h, t->h);
  66029. const TextLayoutToken* nextTok = (TextLayoutToken*) tokens [i + 1];
  66030. if (nextTok == 0)
  66031. break;
  66032. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  66033. {
  66034. // finished a line, so go back and update the heights of the things on it
  66035. for (int j = i; j >= 0; --j)
  66036. {
  66037. TextLayoutToken* const tok = (TextLayoutToken*)tokens.getUnchecked(j);
  66038. if (tok->line == totalLines)
  66039. tok->lineHeight = h;
  66040. else
  66041. break;
  66042. }
  66043. x = 0;
  66044. y += h;
  66045. h = 0;
  66046. ++totalLines;
  66047. }
  66048. }
  66049. // finished a line, so go back and update the heights of the things on it
  66050. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  66051. {
  66052. TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(j);
  66053. if (t->line == totalLines)
  66054. t->lineHeight = h;
  66055. else
  66056. break;
  66057. }
  66058. ++totalLines;
  66059. if (! justification.testFlags (Justification::left))
  66060. {
  66061. int totalW = getWidth();
  66062. for (i = totalLines; --i >= 0;)
  66063. {
  66064. const int lineW = getLineWidth (i);
  66065. int dx = 0;
  66066. if (justification.testFlags (Justification::horizontallyCentred))
  66067. dx = (totalW - lineW) / 2;
  66068. else if (justification.testFlags (Justification::right))
  66069. dx = totalW - lineW;
  66070. for (int j = tokens.size(); --j >= 0;)
  66071. {
  66072. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(j);
  66073. if (t->line == i)
  66074. t->x += dx;
  66075. }
  66076. }
  66077. }
  66078. }
  66079. }
  66080. int TextLayout::getLineWidth (const int lineNumber) const throw()
  66081. {
  66082. int maxW = 0;
  66083. for (int i = tokens.size(); --i >= 0;)
  66084. {
  66085. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  66086. if (t->line == lineNumber && ! t->isWhitespace)
  66087. maxW = jmax (maxW, t->x + t->w);
  66088. }
  66089. return maxW;
  66090. }
  66091. int TextLayout::getWidth() const throw()
  66092. {
  66093. int maxW = 0;
  66094. for (int i = tokens.size(); --i >= 0;)
  66095. {
  66096. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  66097. if (! t->isWhitespace)
  66098. maxW = jmax (maxW, t->x + t->w);
  66099. }
  66100. return maxW;
  66101. }
  66102. int TextLayout::getHeight() const throw()
  66103. {
  66104. int maxH = 0;
  66105. for (int i = tokens.size(); --i >= 0;)
  66106. {
  66107. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  66108. if (! t->isWhitespace)
  66109. maxH = jmax (maxH, t->y + t->h);
  66110. }
  66111. return maxH;
  66112. }
  66113. void TextLayout::draw (Graphics& g,
  66114. const int xOffset,
  66115. const int yOffset) const throw()
  66116. {
  66117. for (int i = tokens.size(); --i >= 0;)
  66118. ((TextLayoutToken*) tokens.getUnchecked(i))->draw (g, xOffset, yOffset);
  66119. }
  66120. void TextLayout::drawWithin (Graphics& g,
  66121. int x, int y, int w, int h,
  66122. const Justification& justification) const throw()
  66123. {
  66124. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  66125. x, y, w, h);
  66126. draw (g, x, y);
  66127. }
  66128. END_JUCE_NAMESPACE
  66129. /********* End of inlined file: juce_TextLayout.cpp *********/
  66130. /********* Start of inlined file: juce_Typeface.cpp *********/
  66131. BEGIN_JUCE_NAMESPACE
  66132. TypefaceGlyphInfo::TypefaceGlyphInfo (const juce_wchar character_,
  66133. const Path& shape,
  66134. const float horizontalSeparation,
  66135. Typeface* const typeface_) throw()
  66136. : character (character_),
  66137. path (shape),
  66138. width (horizontalSeparation),
  66139. typeface (typeface_)
  66140. {
  66141. }
  66142. TypefaceGlyphInfo::~TypefaceGlyphInfo() throw()
  66143. {
  66144. }
  66145. float TypefaceGlyphInfo::getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  66146. {
  66147. if (subsequentCharacter != 0)
  66148. {
  66149. const KerningPair* const pairs = (const KerningPair*) kerningPairs.getData();
  66150. const int numPairs = getNumKerningPairs();
  66151. for (int i = 0; i < numPairs; ++i)
  66152. if (pairs [i].character2 == subsequentCharacter)
  66153. return width + pairs [i].kerningAmount;
  66154. }
  66155. return width;
  66156. }
  66157. void TypefaceGlyphInfo::addKerningPair (const juce_wchar subsequentCharacter,
  66158. const float extraKerningAmount) throw()
  66159. {
  66160. const int numPairs = getNumKerningPairs();
  66161. kerningPairs.setSize ((numPairs + 1) * sizeof (KerningPair));
  66162. KerningPair& p = getKerningPair (numPairs);
  66163. p.character2 = subsequentCharacter;
  66164. p.kerningAmount = extraKerningAmount;
  66165. }
  66166. TypefaceGlyphInfo::KerningPair& TypefaceGlyphInfo::getKerningPair (const int index) const throw()
  66167. {
  66168. return ((KerningPair*) kerningPairs.getData()) [index];
  66169. }
  66170. int TypefaceGlyphInfo::getNumKerningPairs() const throw()
  66171. {
  66172. return kerningPairs.getSize() / sizeof (KerningPair);
  66173. }
  66174. Typeface::Typeface() throw()
  66175. : hash (0),
  66176. isFullyPopulated (false)
  66177. {
  66178. zeromem (lookupTable, sizeof (lookupTable));
  66179. }
  66180. Typeface::Typeface (const Typeface& other)
  66181. : typefaceName (other.typefaceName),
  66182. ascent (other.ascent),
  66183. bold (other.bold),
  66184. italic (other.italic),
  66185. isFullyPopulated (other.isFullyPopulated),
  66186. defaultCharacter (other.defaultCharacter)
  66187. {
  66188. zeromem (lookupTable, sizeof (lookupTable));
  66189. for (int i = 0; i < other.glyphs.size(); ++i)
  66190. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  66191. updateHashCode();
  66192. }
  66193. Typeface::Typeface (const String& faceName,
  66194. const bool bold,
  66195. const bool italic)
  66196. : isFullyPopulated (false)
  66197. {
  66198. zeromem (lookupTable, sizeof (lookupTable));
  66199. initialiseTypefaceCharacteristics (faceName, bold, italic, false);
  66200. updateHashCode();
  66201. }
  66202. Typeface::~Typeface()
  66203. {
  66204. clear();
  66205. }
  66206. const Typeface& Typeface::operator= (const Typeface& other) throw()
  66207. {
  66208. if (this != &other)
  66209. {
  66210. clear();
  66211. typefaceName = other.typefaceName;
  66212. ascent = other.ascent;
  66213. bold = other.bold;
  66214. italic = other.italic;
  66215. isFullyPopulated = other.isFullyPopulated;
  66216. defaultCharacter = other.defaultCharacter;
  66217. for (int i = 0; i < other.glyphs.size(); ++i)
  66218. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  66219. updateHashCode();
  66220. }
  66221. return *this;
  66222. }
  66223. void Typeface::updateHashCode() throw()
  66224. {
  66225. hash = typefaceName.hashCode();
  66226. if (bold)
  66227. hash ^= 0xffff;
  66228. if (italic)
  66229. hash ^= 0xffff0000;
  66230. }
  66231. void Typeface::clear() throw()
  66232. {
  66233. zeromem (lookupTable, sizeof (lookupTable));
  66234. typefaceName = String::empty;
  66235. bold = false;
  66236. italic = false;
  66237. for (int i = glyphs.size(); --i >= 0;)
  66238. {
  66239. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) (glyphs.getUnchecked(i));
  66240. delete g;
  66241. }
  66242. glyphs.clear();
  66243. updateHashCode();
  66244. }
  66245. Typeface::Typeface (InputStream& serialisedTypefaceStream)
  66246. {
  66247. zeromem (lookupTable, sizeof (lookupTable));
  66248. isFullyPopulated = true;
  66249. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  66250. BufferedInputStream in (&gzin, 32768, false);
  66251. typefaceName = in.readString();
  66252. bold = in.readBool();
  66253. italic = in.readBool();
  66254. ascent = in.readFloat();
  66255. defaultCharacter = (juce_wchar) in.readShort();
  66256. int i, numChars = in.readInt();
  66257. for (i = 0; i < numChars; ++i)
  66258. {
  66259. const juce_wchar c = (juce_wchar) in.readShort();
  66260. const float width = in.readFloat();
  66261. Path p;
  66262. p.loadPathFromStream (in);
  66263. addGlyph (c, p, width);
  66264. }
  66265. const int numKerningPairs = in.readInt();
  66266. for (i = 0; i < numKerningPairs; ++i)
  66267. {
  66268. const juce_wchar char1 = (juce_wchar) in.readShort();
  66269. const juce_wchar char2 = (juce_wchar) in.readShort();
  66270. addKerningPair (char1, char2, in.readFloat());
  66271. }
  66272. updateHashCode();
  66273. }
  66274. void Typeface::serialise (OutputStream& outputStream)
  66275. {
  66276. GZIPCompressorOutputStream out (&outputStream);
  66277. out.writeString (typefaceName);
  66278. out.writeBool (bold);
  66279. out.writeBool (italic);
  66280. out.writeFloat (ascent);
  66281. out.writeShort ((short) (unsigned short) defaultCharacter);
  66282. out.writeInt (glyphs.size());
  66283. int i, numKerningPairs = 0;
  66284. for (i = 0; i < glyphs.size(); ++i)
  66285. {
  66286. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  66287. out.writeShort ((short) (unsigned short) g.character);
  66288. out.writeFloat (g.width);
  66289. g.path.writePathToStream (out);
  66290. numKerningPairs += g.getNumKerningPairs();
  66291. }
  66292. out.writeInt (numKerningPairs);
  66293. for (i = 0; i < glyphs.size(); ++i)
  66294. {
  66295. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  66296. for (int j = 0; j < g.getNumKerningPairs(); ++j)
  66297. {
  66298. const TypefaceGlyphInfo::KerningPair& p = g.getKerningPair (j);
  66299. out.writeShort ((short) (unsigned short) g.character);
  66300. out.writeShort ((short) (unsigned short) p.character2);
  66301. out.writeFloat (p.kerningAmount);
  66302. }
  66303. }
  66304. }
  66305. const Path* Typeface::getOutlineForGlyph (const juce_wchar character) throw()
  66306. {
  66307. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) getGlyph (character);
  66308. if (g != 0)
  66309. return &(g->path);
  66310. else
  66311. return 0;
  66312. }
  66313. const TypefaceGlyphInfo* Typeface::getGlyph (const juce_wchar character) throw()
  66314. {
  66315. if (((unsigned int) character) < 128 && lookupTable [character] > 0)
  66316. return (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  66317. for (int i = 0; i < glyphs.size(); ++i)
  66318. {
  66319. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  66320. if (g->character == character)
  66321. return g;
  66322. }
  66323. if ((! isFullyPopulated)
  66324. && findAndAddSystemGlyph (character))
  66325. {
  66326. for (int i = 0; i < glyphs.size(); ++i)
  66327. {
  66328. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  66329. if (g->character == character)
  66330. return g;
  66331. }
  66332. }
  66333. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  66334. {
  66335. const TypefaceGlyphInfo* spaceGlyph = getGlyph (L' ');
  66336. if (spaceGlyph != 0)
  66337. {
  66338. // Add a copy of the empty glyph, mapped onto this character
  66339. addGlyph (character, spaceGlyph->getPath(), spaceGlyph->getHorizontalSpacing (0));
  66340. spaceGlyph = (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  66341. }
  66342. return spaceGlyph;
  66343. }
  66344. else if (character != defaultCharacter)
  66345. {
  66346. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  66347. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  66348. if (fallbackTypeface != 0 && fallbackTypeface != this)
  66349. return fallbackTypeface->getGlyph (character);
  66350. return getGlyph (defaultCharacter);
  66351. }
  66352. return 0;
  66353. }
  66354. void Typeface::addGlyph (const juce_wchar character,
  66355. const Path& path,
  66356. const float horizontalSpacing) throw()
  66357. {
  66358. #ifdef JUCE_DEBUG
  66359. for (int i = 0; i < glyphs.size(); ++i)
  66360. {
  66361. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  66362. if (g->character == character)
  66363. jassertfalse;
  66364. }
  66365. #endif
  66366. if (((unsigned int) character) < 128)
  66367. lookupTable [character] = (short) glyphs.size();
  66368. glyphs.add (new TypefaceGlyphInfo (character,
  66369. path,
  66370. horizontalSpacing,
  66371. this));
  66372. }
  66373. void Typeface::addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw()
  66374. {
  66375. if (glyphInfoToCopy != 0)
  66376. {
  66377. if (glyphInfoToCopy->character > 0 && glyphInfoToCopy->character < 128)
  66378. lookupTable [glyphInfoToCopy->character] = (short) glyphs.size();
  66379. TypefaceGlyphInfo* const newOne
  66380. = new TypefaceGlyphInfo (glyphInfoToCopy->character,
  66381. glyphInfoToCopy->path,
  66382. glyphInfoToCopy->width,
  66383. this);
  66384. newOne->kerningPairs = glyphInfoToCopy->kerningPairs;
  66385. glyphs.add (newOne);
  66386. }
  66387. }
  66388. void Typeface::addKerningPair (const juce_wchar char1,
  66389. const juce_wchar char2,
  66390. const float extraAmount) throw()
  66391. {
  66392. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) getGlyph (char1);
  66393. if (g != 0)
  66394. g->addKerningPair (char2, extraAmount);
  66395. }
  66396. void Typeface::setName (const String& name) throw()
  66397. {
  66398. typefaceName = name;
  66399. updateHashCode();
  66400. }
  66401. void Typeface::setAscent (const float newAscent) throw()
  66402. {
  66403. ascent = newAscent;
  66404. }
  66405. void Typeface::setDefaultCharacter (const juce_wchar newDefaultCharacter) throw()
  66406. {
  66407. defaultCharacter = newDefaultCharacter;
  66408. }
  66409. void Typeface::setBold (const bool shouldBeBold) throw()
  66410. {
  66411. bold = shouldBeBold;
  66412. updateHashCode();
  66413. }
  66414. void Typeface::setItalic (const bool shouldBeItalic) throw()
  66415. {
  66416. italic = shouldBeItalic;
  66417. updateHashCode();
  66418. }
  66419. class TypefaceCache;
  66420. static TypefaceCache* typefaceCacheInstance = 0;
  66421. void clearUpDefaultFontNames() throw(); // in juce_Font.cpp
  66422. class TypefaceCache : private DeletedAtShutdown
  66423. {
  66424. private:
  66425. struct CachedFace
  66426. {
  66427. CachedFace() throw()
  66428. : lastUsageCount (0),
  66429. flags (0)
  66430. {
  66431. }
  66432. String typefaceName;
  66433. int lastUsageCount;
  66434. int flags;
  66435. Typeface::Ptr typeFace;
  66436. };
  66437. int counter;
  66438. OwnedArray <CachedFace> faces;
  66439. TypefaceCache (const TypefaceCache&);
  66440. const TypefaceCache& operator= (const TypefaceCache&);
  66441. public:
  66442. TypefaceCache (int numToCache = 10)
  66443. : counter (1),
  66444. faces (2)
  66445. {
  66446. while (--numToCache >= 0)
  66447. {
  66448. CachedFace* const face = new CachedFace();
  66449. face->typeFace = new Typeface();
  66450. faces.add (face);
  66451. }
  66452. }
  66453. ~TypefaceCache()
  66454. {
  66455. faces.clear();
  66456. jassert (typefaceCacheInstance == this);
  66457. typefaceCacheInstance = 0;
  66458. // just a courtesy call to get avoid leaking these strings at shutdown
  66459. clearUpDefaultFontNames();
  66460. }
  66461. static TypefaceCache* getInstance() throw()
  66462. {
  66463. if (typefaceCacheInstance == 0)
  66464. typefaceCacheInstance = new TypefaceCache();
  66465. return typefaceCacheInstance;
  66466. }
  66467. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  66468. {
  66469. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  66470. int i;
  66471. for (i = faces.size(); --i >= 0;)
  66472. {
  66473. CachedFace* const face = faces.getUnchecked(i);
  66474. if (face->flags == flags
  66475. && face->typefaceName == font.getTypefaceName())
  66476. {
  66477. face->lastUsageCount = ++counter;
  66478. return face->typeFace;
  66479. }
  66480. }
  66481. int replaceIndex = 0;
  66482. int bestLastUsageCount = INT_MAX;
  66483. for (i = faces.size(); --i >= 0;)
  66484. {
  66485. const int lu = faces.getUnchecked(i)->lastUsageCount;
  66486. if (bestLastUsageCount > lu)
  66487. {
  66488. bestLastUsageCount = lu;
  66489. replaceIndex = i;
  66490. }
  66491. }
  66492. CachedFace* const face = faces.getUnchecked (replaceIndex);
  66493. face->typefaceName = font.getTypefaceName();
  66494. face->flags = flags;
  66495. face->lastUsageCount = ++counter;
  66496. face->typeFace = new Typeface (font.getTypefaceName(),
  66497. font.isBold(),
  66498. font.isItalic());
  66499. return face->typeFace;
  66500. }
  66501. };
  66502. const Typeface::Ptr Typeface::getTypefaceFor (const Font& font) throw()
  66503. {
  66504. return TypefaceCache::getInstance()->findTypefaceFor (font);
  66505. }
  66506. END_JUCE_NAMESPACE
  66507. /********* End of inlined file: juce_Typeface.cpp *********/
  66508. /********* Start of inlined file: juce_AffineTransform.cpp *********/
  66509. BEGIN_JUCE_NAMESPACE
  66510. AffineTransform::AffineTransform() throw()
  66511. : mat00 (1.0f),
  66512. mat01 (0),
  66513. mat02 (0),
  66514. mat10 (0),
  66515. mat11 (1.0f),
  66516. mat12 (0)
  66517. {
  66518. }
  66519. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  66520. : mat00 (other.mat00),
  66521. mat01 (other.mat01),
  66522. mat02 (other.mat02),
  66523. mat10 (other.mat10),
  66524. mat11 (other.mat11),
  66525. mat12 (other.mat12)
  66526. {
  66527. }
  66528. AffineTransform::AffineTransform (const float mat00_,
  66529. const float mat01_,
  66530. const float mat02_,
  66531. const float mat10_,
  66532. const float mat11_,
  66533. const float mat12_) throw()
  66534. : mat00 (mat00_),
  66535. mat01 (mat01_),
  66536. mat02 (mat02_),
  66537. mat10 (mat10_),
  66538. mat11 (mat11_),
  66539. mat12 (mat12_)
  66540. {
  66541. }
  66542. const AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  66543. {
  66544. mat00 = other.mat00;
  66545. mat01 = other.mat01;
  66546. mat02 = other.mat02;
  66547. mat10 = other.mat10;
  66548. mat11 = other.mat11;
  66549. mat12 = other.mat12;
  66550. return *this;
  66551. }
  66552. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  66553. {
  66554. return mat00 == other.mat00
  66555. && mat01 == other.mat01
  66556. && mat02 == other.mat02
  66557. && mat10 == other.mat10
  66558. && mat11 == other.mat11
  66559. && mat12 == other.mat12;
  66560. }
  66561. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  66562. {
  66563. return ! operator== (other);
  66564. }
  66565. bool AffineTransform::isIdentity() const throw()
  66566. {
  66567. return (mat01 == 0)
  66568. && (mat02 == 0)
  66569. && (mat10 == 0)
  66570. && (mat12 == 0)
  66571. && (mat00 == 1.0f)
  66572. && (mat11 == 1.0f);
  66573. }
  66574. const AffineTransform AffineTransform::identity;
  66575. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  66576. {
  66577. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  66578. other.mat00 * mat01 + other.mat01 * mat11,
  66579. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  66580. other.mat10 * mat00 + other.mat11 * mat10,
  66581. other.mat10 * mat01 + other.mat11 * mat11,
  66582. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  66583. }
  66584. const AffineTransform AffineTransform::followedBy (const float omat00,
  66585. const float omat01,
  66586. const float omat02,
  66587. const float omat10,
  66588. const float omat11,
  66589. const float omat12) const throw()
  66590. {
  66591. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  66592. omat00 * mat01 + omat01 * mat11,
  66593. omat00 * mat02 + omat01 * mat12 + omat02,
  66594. omat10 * mat00 + omat11 * mat10,
  66595. omat10 * mat01 + omat11 * mat11,
  66596. omat10 * mat02 + omat11 * mat12 + omat12);
  66597. }
  66598. const AffineTransform AffineTransform::translated (const float dx,
  66599. const float dy) const throw()
  66600. {
  66601. return followedBy (1.0f, 0, dx,
  66602. 0, 1.0f, dy);
  66603. }
  66604. const AffineTransform AffineTransform::translation (const float dx,
  66605. const float dy) throw()
  66606. {
  66607. return AffineTransform (1.0f, 0, dx,
  66608. 0, 1.0f, dy);
  66609. }
  66610. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  66611. {
  66612. const float cosRad = cosf (rad);
  66613. const float sinRad = sinf (rad);
  66614. return followedBy (cosRad, -sinRad, 0,
  66615. sinRad, cosRad, 0);
  66616. }
  66617. const AffineTransform AffineTransform::rotation (const float rad) throw()
  66618. {
  66619. const float cosRad = cosf (rad);
  66620. const float sinRad = sinf (rad);
  66621. return AffineTransform (cosRad, -sinRad, 0,
  66622. sinRad, cosRad, 0);
  66623. }
  66624. const AffineTransform AffineTransform::rotated (const float angle,
  66625. const float pivotX,
  66626. const float pivotY) const throw()
  66627. {
  66628. return translated (-pivotX, -pivotY)
  66629. .rotated (angle)
  66630. .translated (pivotX, pivotY);
  66631. }
  66632. const AffineTransform AffineTransform::rotation (const float angle,
  66633. const float pivotX,
  66634. const float pivotY) throw()
  66635. {
  66636. return translation (-pivotX, -pivotY)
  66637. .rotated (angle)
  66638. .translated (pivotX, pivotY);
  66639. }
  66640. const AffineTransform AffineTransform::scaled (const float factorX,
  66641. const float factorY) const throw()
  66642. {
  66643. return followedBy (factorX, 0, 0,
  66644. 0, factorY, 0);
  66645. }
  66646. const AffineTransform AffineTransform::scale (const float factorX,
  66647. const float factorY) throw()
  66648. {
  66649. return AffineTransform (factorX, 0, 0,
  66650. 0, factorY, 0);
  66651. }
  66652. const AffineTransform AffineTransform::sheared (const float shearX,
  66653. const float shearY) const throw()
  66654. {
  66655. return followedBy (1.0f, shearX, 0,
  66656. shearY, 1.0f, 0);
  66657. }
  66658. const AffineTransform AffineTransform::inverted() const throw()
  66659. {
  66660. double determinant = (mat00 * mat11 - mat10 * mat01);
  66661. if (determinant != 0.0)
  66662. {
  66663. determinant = 1.0 / determinant;
  66664. const float dst00 = (float) (mat11 * determinant);
  66665. const float dst10 = (float) (-mat10 * determinant);
  66666. const float dst01 = (float) (-mat01 * determinant);
  66667. const float dst11 = (float) (mat00 * determinant);
  66668. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  66669. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  66670. }
  66671. else
  66672. {
  66673. // singularity..
  66674. return *this;
  66675. }
  66676. }
  66677. bool AffineTransform::isSingularity() const throw()
  66678. {
  66679. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  66680. }
  66681. void AffineTransform::transformPoint (float& x,
  66682. float& y) const throw()
  66683. {
  66684. const float oldX = x;
  66685. x = mat00 * oldX + mat01 * y + mat02;
  66686. y = mat10 * oldX + mat11 * y + mat12;
  66687. }
  66688. void AffineTransform::transformPoint (double& x,
  66689. double& y) const throw()
  66690. {
  66691. const double oldX = x;
  66692. x = mat00 * oldX + mat01 * y + mat02;
  66693. y = mat10 * oldX + mat11 * y + mat12;
  66694. }
  66695. END_JUCE_NAMESPACE
  66696. /********* End of inlined file: juce_AffineTransform.cpp *********/
  66697. /********* Start of inlined file: juce_BorderSize.cpp *********/
  66698. BEGIN_JUCE_NAMESPACE
  66699. BorderSize::BorderSize() throw()
  66700. : top (0),
  66701. left (0),
  66702. bottom (0),
  66703. right (0)
  66704. {
  66705. }
  66706. BorderSize::BorderSize (const BorderSize& other) throw()
  66707. : top (other.top),
  66708. left (other.left),
  66709. bottom (other.bottom),
  66710. right (other.right)
  66711. {
  66712. }
  66713. BorderSize::BorderSize (const int topGap,
  66714. const int leftGap,
  66715. const int bottomGap,
  66716. const int rightGap) throw()
  66717. : top (topGap),
  66718. left (leftGap),
  66719. bottom (bottomGap),
  66720. right (rightGap)
  66721. {
  66722. }
  66723. BorderSize::BorderSize (const int allGaps) throw()
  66724. : top (allGaps),
  66725. left (allGaps),
  66726. bottom (allGaps),
  66727. right (allGaps)
  66728. {
  66729. }
  66730. BorderSize::~BorderSize() throw()
  66731. {
  66732. }
  66733. void BorderSize::setTop (const int newTopGap) throw()
  66734. {
  66735. top = newTopGap;
  66736. }
  66737. void BorderSize::setLeft (const int newLeftGap) throw()
  66738. {
  66739. left = newLeftGap;
  66740. }
  66741. void BorderSize::setBottom (const int newBottomGap) throw()
  66742. {
  66743. bottom = newBottomGap;
  66744. }
  66745. void BorderSize::setRight (const int newRightGap) throw()
  66746. {
  66747. right = newRightGap;
  66748. }
  66749. const Rectangle BorderSize::subtractedFrom (const Rectangle& r) const throw()
  66750. {
  66751. return Rectangle (r.getX() + left,
  66752. r.getY() + top,
  66753. r.getWidth() - (left + right),
  66754. r.getHeight() - (top + bottom));
  66755. }
  66756. void BorderSize::subtractFrom (Rectangle& r) const throw()
  66757. {
  66758. r.setBounds (r.getX() + left,
  66759. r.getY() + top,
  66760. r.getWidth() - (left + right),
  66761. r.getHeight() - (top + bottom));
  66762. }
  66763. const Rectangle BorderSize::addedTo (const Rectangle& r) const throw()
  66764. {
  66765. return Rectangle (r.getX() - left,
  66766. r.getY() - top,
  66767. r.getWidth() + (left + right),
  66768. r.getHeight() + (top + bottom));
  66769. }
  66770. void BorderSize::addTo (Rectangle& r) const throw()
  66771. {
  66772. r.setBounds (r.getX() - left,
  66773. r.getY() - top,
  66774. r.getWidth() + (left + right),
  66775. r.getHeight() + (top + bottom));
  66776. }
  66777. bool BorderSize::operator== (const BorderSize& other) const throw()
  66778. {
  66779. return top == other.top
  66780. && left == other.left
  66781. && bottom == other.bottom
  66782. && right == other.right;
  66783. }
  66784. bool BorderSize::operator!= (const BorderSize& other) const throw()
  66785. {
  66786. return ! operator== (other);
  66787. }
  66788. END_JUCE_NAMESPACE
  66789. /********* End of inlined file: juce_BorderSize.cpp *********/
  66790. /********* Start of inlined file: juce_Line.cpp *********/
  66791. BEGIN_JUCE_NAMESPACE
  66792. static bool juce_lineIntersection (const float x1, const float y1,
  66793. const float x2, const float y2,
  66794. const float x3, const float y3,
  66795. const float x4, const float y4,
  66796. float& intersectionX,
  66797. float& intersectionY) throw()
  66798. {
  66799. if (x2 != x3 || y2 != y3)
  66800. {
  66801. const float dx1 = x2 - x1;
  66802. const float dy1 = y2 - y1;
  66803. const float dx2 = x4 - x3;
  66804. const float dy2 = y4 - y3;
  66805. const float divisor = dx1 * dy2 - dx2 * dy1;
  66806. if (divisor == 0)
  66807. {
  66808. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  66809. {
  66810. if (dy1 == 0 && dy2 != 0)
  66811. {
  66812. const float along = (y1 - y3) / dy2;
  66813. intersectionX = x3 + along * dx2;
  66814. intersectionY = y1;
  66815. return along >= 0 && along <= 1.0f;
  66816. }
  66817. else if (dy2 == 0 && dy1 != 0)
  66818. {
  66819. const float along = (y3 - y1) / dy1;
  66820. intersectionX = x1 + along * dx1;
  66821. intersectionY = y3;
  66822. return along >= 0 && along <= 1.0f;
  66823. }
  66824. else if (dx1 == 0 && dx2 != 0)
  66825. {
  66826. const float along = (x1 - x3) / dx2;
  66827. intersectionX = x1;
  66828. intersectionY = y3 + along * dy2;
  66829. return along >= 0 && along <= 1.0f;
  66830. }
  66831. else if (dx2 == 0 && dx1 != 0)
  66832. {
  66833. const float along = (x3 - x1) / dx1;
  66834. intersectionX = x3;
  66835. intersectionY = y1 + along * dy1;
  66836. return along >= 0 && along <= 1.0f;
  66837. }
  66838. }
  66839. intersectionX = 0.5f * (x2 + x3);
  66840. intersectionY = 0.5f * (y2 + y3);
  66841. return false;
  66842. }
  66843. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  66844. intersectionX = x1 + along1 * dx1;
  66845. intersectionY = y1 + along1 * dy1;
  66846. if (along1 < 0 || along1 > 1.0f)
  66847. return false;
  66848. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1) / divisor;
  66849. return along2 >= 0 && along2 <= 1.0f;
  66850. }
  66851. intersectionX = x2;
  66852. intersectionY = y2;
  66853. return true;
  66854. }
  66855. Line::Line() throw()
  66856. : startX (0.0f),
  66857. startY (0.0f),
  66858. endX (0.0f),
  66859. endY (0.0f)
  66860. {
  66861. }
  66862. Line::Line (const Line& other) throw()
  66863. : startX (other.startX),
  66864. startY (other.startY),
  66865. endX (other.endX),
  66866. endY (other.endY)
  66867. {
  66868. }
  66869. Line::Line (const float startX_, const float startY_,
  66870. const float endX_, const float endY_) throw()
  66871. : startX (startX_),
  66872. startY (startY_),
  66873. endX (endX_),
  66874. endY (endY_)
  66875. {
  66876. }
  66877. Line::Line (const Point& start,
  66878. const Point& end) throw()
  66879. : startX (start.getX()),
  66880. startY (start.getY()),
  66881. endX (end.getX()),
  66882. endY (end.getY())
  66883. {
  66884. }
  66885. const Line& Line::operator= (const Line& other) throw()
  66886. {
  66887. startX = other.startX;
  66888. startY = other.startY;
  66889. endX = other.endX;
  66890. endY = other.endY;
  66891. return *this;
  66892. }
  66893. Line::~Line() throw()
  66894. {
  66895. }
  66896. const Point Line::getStart() const throw()
  66897. {
  66898. return Point (startX, startY);
  66899. }
  66900. const Point Line::getEnd() const throw()
  66901. {
  66902. return Point (endX, endY);
  66903. }
  66904. void Line::setStart (const float newStartX,
  66905. const float newStartY) throw()
  66906. {
  66907. startX = newStartX;
  66908. startY = newStartY;
  66909. }
  66910. void Line::setStart (const Point& newStart) throw()
  66911. {
  66912. startX = newStart.getX();
  66913. startY = newStart.getY();
  66914. }
  66915. void Line::setEnd (const float newEndX,
  66916. const float newEndY) throw()
  66917. {
  66918. endX = newEndX;
  66919. endY = newEndY;
  66920. }
  66921. void Line::setEnd (const Point& newEnd) throw()
  66922. {
  66923. endX = newEnd.getX();
  66924. endY = newEnd.getY();
  66925. }
  66926. bool Line::operator== (const Line& other) const throw()
  66927. {
  66928. return startX == other.startX
  66929. && startY == other.startY
  66930. && endX == other.endX
  66931. && endY == other.endY;
  66932. }
  66933. bool Line::operator!= (const Line& other) const throw()
  66934. {
  66935. return startX != other.startX
  66936. || startY != other.startY
  66937. || endX != other.endX
  66938. || endY != other.endY;
  66939. }
  66940. void Line::applyTransform (const AffineTransform& transform) throw()
  66941. {
  66942. transform.transformPoint (startX, startY);
  66943. transform.transformPoint (endX, endY);
  66944. }
  66945. float Line::getLength() const throw()
  66946. {
  66947. return (float) juce_hypot (startX - endX,
  66948. startY - endY);
  66949. }
  66950. float Line::getAngle() const throw()
  66951. {
  66952. return atan2f (endX - startX,
  66953. endY - startY);
  66954. }
  66955. const Point Line::getPointAlongLine (const float distanceFromStart) const throw()
  66956. {
  66957. const float alpha = distanceFromStart / getLength();
  66958. return Point (startX + (endX - startX) * alpha,
  66959. startY + (endY - startY) * alpha);
  66960. }
  66961. const Point Line::getPointAlongLine (const float offsetX,
  66962. const float offsetY) const throw()
  66963. {
  66964. const float dx = endX - startX;
  66965. const float dy = endY - startY;
  66966. const double length = juce_hypot (dx, dy);
  66967. if (length == 0)
  66968. return Point (startX, startY);
  66969. else
  66970. return Point (startX + (float) (((dx * offsetX) - (dy * offsetY)) / length),
  66971. startY + (float) (((dy * offsetX) + (dx * offsetY)) / length));
  66972. }
  66973. const Point Line::getPointAlongLineProportionally (const float alpha) const throw()
  66974. {
  66975. return Point (startX + (endX - startX) * alpha,
  66976. startY + (endY - startY) * alpha);
  66977. }
  66978. float Line::getDistanceFromLine (const float x,
  66979. const float y) const throw()
  66980. {
  66981. const double dx = endX - startX;
  66982. const double dy = endY - startY;
  66983. const double length = dx * dx + dy * dy;
  66984. if (length > 0)
  66985. {
  66986. const double prop = ((x - startX) * dx + (y - startY) * dy) / length;
  66987. if (prop >= 0.0f && prop < 1.0f)
  66988. {
  66989. return (float) juce_hypot (x - (startX + prop * dx),
  66990. y - (startY + prop * dy));
  66991. }
  66992. }
  66993. return (float) jmin (juce_hypot (x - startX, y - startY),
  66994. juce_hypot (x - endX, y - endY));
  66995. }
  66996. float Line::findNearestPointTo (const float x,
  66997. const float y) const throw()
  66998. {
  66999. const double dx = endX - startX;
  67000. const double dy = endY - startY;
  67001. const double length = dx * dx + dy * dy;
  67002. if (length <= 0.0)
  67003. return 0.0f;
  67004. return jlimit (0.0f, 1.0f,
  67005. (float) (((x - startX) * dx + (y - startY) * dy) / length));
  67006. }
  67007. const Line Line::withShortenedStart (const float distanceToShortenBy) const throw()
  67008. {
  67009. const float length = getLength();
  67010. return Line (getPointAlongLine (jmin (distanceToShortenBy, length)),
  67011. getEnd());
  67012. }
  67013. const Line Line::withShortenedEnd (const float distanceToShortenBy) const throw()
  67014. {
  67015. const float length = getLength();
  67016. return Line (getStart(),
  67017. getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  67018. }
  67019. bool Line::clipToPath (const Path& path,
  67020. const bool keepSectionOutsidePath) throw()
  67021. {
  67022. const bool startInside = path.contains (startX, startY);
  67023. const bool endInside = path.contains (endX, endY);
  67024. if (startInside == endInside)
  67025. {
  67026. if (keepSectionOutsidePath != startInside)
  67027. {
  67028. // entirely outside the path
  67029. return false;
  67030. }
  67031. else
  67032. {
  67033. // entirely inside the path
  67034. startX = 0.0f;
  67035. startY = 0.0f;
  67036. endX = 0.0f;
  67037. endY = 0.0f;
  67038. return true;
  67039. }
  67040. }
  67041. else
  67042. {
  67043. bool changed = false;
  67044. PathFlatteningIterator iter (path, AffineTransform::identity);
  67045. while (iter.next())
  67046. {
  67047. float ix, iy;
  67048. if (intersects (Line (iter.x1, iter.y1,
  67049. iter.x2, iter.y2),
  67050. ix, iy))
  67051. {
  67052. if ((startInside && keepSectionOutsidePath)
  67053. || (endInside && ! keepSectionOutsidePath))
  67054. {
  67055. setStart (ix, iy);
  67056. }
  67057. else
  67058. {
  67059. setEnd (ix, iy);
  67060. }
  67061. changed = true;
  67062. }
  67063. }
  67064. return changed;
  67065. }
  67066. }
  67067. bool Line::intersects (const Line& line,
  67068. float& intersectionX,
  67069. float& intersectionY) const throw()
  67070. {
  67071. return juce_lineIntersection (startX, startY,
  67072. endX, endY,
  67073. line.startX, line.startY,
  67074. line.endX, line.endY,
  67075. intersectionX,
  67076. intersectionY);
  67077. }
  67078. bool Line::isVertical() const throw()
  67079. {
  67080. return startX == endX;
  67081. }
  67082. bool Line::isHorizontal() const throw()
  67083. {
  67084. return startY == endY;
  67085. }
  67086. bool Line::isPointAbove (const float x, const float y) const throw()
  67087. {
  67088. return startX != endX
  67089. && y < ((endY - startY) * (x - startX)) / (endX - startX) + startY;
  67090. }
  67091. END_JUCE_NAMESPACE
  67092. /********* End of inlined file: juce_Line.cpp *********/
  67093. /********* Start of inlined file: juce_Path.cpp *********/
  67094. BEGIN_JUCE_NAMESPACE
  67095. // tests that some co-ords aren't NaNs
  67096. #define CHECK_COORDS_ARE_VALID(x, y) \
  67097. jassert (x == x && y == y);
  67098. const float Path::lineMarker = 100001.0f;
  67099. const float Path::moveMarker = 100002.0f;
  67100. const float Path::quadMarker = 100003.0f;
  67101. const float Path::cubicMarker = 100004.0f;
  67102. const float Path::closeSubPathMarker = 100005.0f;
  67103. static const int defaultGranularity = 32;
  67104. Path::Path() throw()
  67105. : ArrayAllocationBase <float> (defaultGranularity),
  67106. numElements (0),
  67107. pathXMin (0),
  67108. pathXMax (0),
  67109. pathYMin (0),
  67110. pathYMax (0),
  67111. useNonZeroWinding (true)
  67112. {
  67113. }
  67114. Path::~Path() throw()
  67115. {
  67116. }
  67117. Path::Path (const Path& other) throw()
  67118. : ArrayAllocationBase <float> (defaultGranularity),
  67119. numElements (other.numElements),
  67120. pathXMin (other.pathXMin),
  67121. pathXMax (other.pathXMax),
  67122. pathYMin (other.pathYMin),
  67123. pathYMax (other.pathYMax),
  67124. useNonZeroWinding (other.useNonZeroWinding)
  67125. {
  67126. if (numElements > 0)
  67127. {
  67128. setAllocatedSize (numElements);
  67129. memcpy (elements, other.elements, numElements * sizeof (float));
  67130. }
  67131. }
  67132. const Path& Path::operator= (const Path& other) throw()
  67133. {
  67134. if (this != &other)
  67135. {
  67136. ensureAllocatedSize (other.numElements);
  67137. numElements = other.numElements;
  67138. pathXMin = other.pathXMin;
  67139. pathXMax = other.pathXMax;
  67140. pathYMin = other.pathYMin;
  67141. pathYMax = other.pathYMax;
  67142. useNonZeroWinding = other.useNonZeroWinding;
  67143. if (numElements > 0)
  67144. memcpy (elements, other.elements, numElements * sizeof (float));
  67145. }
  67146. return *this;
  67147. }
  67148. void Path::clear() throw()
  67149. {
  67150. numElements = 0;
  67151. pathXMin = 0;
  67152. pathYMin = 0;
  67153. pathYMax = 0;
  67154. pathXMax = 0;
  67155. }
  67156. void Path::swapWithPath (Path& other)
  67157. {
  67158. swapVariables <int> (this->numAllocated, other.numAllocated);
  67159. swapVariables <float*> (this->elements, other.elements);
  67160. swapVariables <int> (this->numElements, other.numElements);
  67161. swapVariables <float> (this->pathXMin, other.pathXMin);
  67162. swapVariables <float> (this->pathXMax, other.pathXMax);
  67163. swapVariables <float> (this->pathYMin, other.pathYMin);
  67164. swapVariables <float> (this->pathYMax, other.pathYMax);
  67165. swapVariables <bool> (this->useNonZeroWinding, other.useNonZeroWinding);
  67166. }
  67167. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  67168. {
  67169. useNonZeroWinding = isNonZero;
  67170. }
  67171. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  67172. const bool preserveProportions) throw()
  67173. {
  67174. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  67175. }
  67176. bool Path::isEmpty() const throw()
  67177. {
  67178. int i = 0;
  67179. while (i < numElements)
  67180. {
  67181. const float type = elements [i++];
  67182. if (type == moveMarker)
  67183. {
  67184. i += 2;
  67185. }
  67186. else if (type == lineMarker
  67187. || type == quadMarker
  67188. || type == cubicMarker)
  67189. {
  67190. return false;
  67191. }
  67192. }
  67193. return true;
  67194. }
  67195. void Path::getBounds (float& x, float& y,
  67196. float& w, float& h) const throw()
  67197. {
  67198. x = pathXMin;
  67199. y = pathYMin;
  67200. w = pathXMax - pathXMin;
  67201. h = pathYMax - pathYMin;
  67202. }
  67203. void Path::getBoundsTransformed (const AffineTransform& transform,
  67204. float& x, float& y,
  67205. float& w, float& h) const throw()
  67206. {
  67207. float x1 = pathXMin;
  67208. float y1 = pathYMin;
  67209. transform.transformPoint (x1, y1);
  67210. float x2 = pathXMax;
  67211. float y2 = pathYMin;
  67212. transform.transformPoint (x2, y2);
  67213. float x3 = pathXMin;
  67214. float y3 = pathYMax;
  67215. transform.transformPoint (x3, y3);
  67216. float x4 = pathXMax;
  67217. float y4 = pathYMax;
  67218. transform.transformPoint (x4, y4);
  67219. x = jmin (x1, x2, x3, x4);
  67220. y = jmin (y1, y2, y3, y4);
  67221. w = jmax (x1, x2, x3, x4) - x;
  67222. h = jmax (y1, y2, y3, y4) - y;
  67223. }
  67224. void Path::startNewSubPath (const float x,
  67225. const float y) throw()
  67226. {
  67227. CHECK_COORDS_ARE_VALID (x, y);
  67228. if (numElements == 0)
  67229. {
  67230. pathXMin = pathXMax = x;
  67231. pathYMin = pathYMax = y;
  67232. }
  67233. else
  67234. {
  67235. pathXMin = jmin (pathXMin, x);
  67236. pathXMax = jmax (pathXMax, x);
  67237. pathYMin = jmin (pathYMin, y);
  67238. pathYMax = jmax (pathYMax, y);
  67239. }
  67240. ensureAllocatedSize (numElements + 3);
  67241. elements [numElements++] = moveMarker;
  67242. elements [numElements++] = x;
  67243. elements [numElements++] = y;
  67244. }
  67245. void Path::lineTo (const float x, const float y) throw()
  67246. {
  67247. CHECK_COORDS_ARE_VALID (x, y);
  67248. if (numElements == 0)
  67249. startNewSubPath (0, 0);
  67250. ensureAllocatedSize (numElements + 3);
  67251. elements [numElements++] = lineMarker;
  67252. elements [numElements++] = x;
  67253. elements [numElements++] = y;
  67254. pathXMin = jmin (pathXMin, x);
  67255. pathXMax = jmax (pathXMax, x);
  67256. pathYMin = jmin (pathYMin, y);
  67257. pathYMax = jmax (pathYMax, y);
  67258. }
  67259. void Path::quadraticTo (const float x1, const float y1,
  67260. const float x2, const float y2) throw()
  67261. {
  67262. CHECK_COORDS_ARE_VALID (x1, y1);
  67263. CHECK_COORDS_ARE_VALID (x2, y2);
  67264. if (numElements == 0)
  67265. startNewSubPath (0, 0);
  67266. ensureAllocatedSize (numElements + 5);
  67267. elements [numElements++] = quadMarker;
  67268. elements [numElements++] = x1;
  67269. elements [numElements++] = y1;
  67270. elements [numElements++] = x2;
  67271. elements [numElements++] = y2;
  67272. pathXMin = jmin (pathXMin, x1, x2);
  67273. pathXMax = jmax (pathXMax, x1, x2);
  67274. pathYMin = jmin (pathYMin, y1, y2);
  67275. pathYMax = jmax (pathYMax, y1, y2);
  67276. }
  67277. void Path::cubicTo (const float x1, const float y1,
  67278. const float x2, const float y2,
  67279. const float x3, const float y3) throw()
  67280. {
  67281. CHECK_COORDS_ARE_VALID (x1, y1);
  67282. CHECK_COORDS_ARE_VALID (x2, y2);
  67283. CHECK_COORDS_ARE_VALID (x3, y3);
  67284. if (numElements == 0)
  67285. startNewSubPath (0, 0);
  67286. ensureAllocatedSize (numElements + 7);
  67287. elements [numElements++] = cubicMarker;
  67288. elements [numElements++] = x1;
  67289. elements [numElements++] = y1;
  67290. elements [numElements++] = x2;
  67291. elements [numElements++] = y2;
  67292. elements [numElements++] = x3;
  67293. elements [numElements++] = y3;
  67294. pathXMin = jmin (pathXMin, x1, x2, x3);
  67295. pathXMax = jmax (pathXMax, x1, x2, x3);
  67296. pathYMin = jmin (pathYMin, y1, y2, y3);
  67297. pathYMax = jmax (pathYMax, y1, y2, y3);
  67298. }
  67299. void Path::closeSubPath() throw()
  67300. {
  67301. if (numElements > 0
  67302. && elements [numElements - 1] != closeSubPathMarker)
  67303. {
  67304. ensureAllocatedSize (numElements + 1);
  67305. elements [numElements++] = closeSubPathMarker;
  67306. }
  67307. }
  67308. const Point Path::getCurrentPosition() const
  67309. {
  67310. int i = numElements - 1;
  67311. if (i > 0 && elements[i] == closeSubPathMarker)
  67312. {
  67313. while (i >= 0)
  67314. {
  67315. if (elements[i] == moveMarker)
  67316. {
  67317. i += 2;
  67318. break;
  67319. }
  67320. --i;
  67321. }
  67322. }
  67323. if (i > 0)
  67324. return Point (elements [i - 1], elements [i]);
  67325. return Point (0.0f, 0.0f);
  67326. }
  67327. void Path::addRectangle (const float x, const float y,
  67328. const float w, const float h) throw()
  67329. {
  67330. startNewSubPath (x, y + h);
  67331. lineTo (x, y);
  67332. lineTo (x + w, y);
  67333. lineTo (x + w, y + h);
  67334. closeSubPath();
  67335. }
  67336. void Path::addRoundedRectangle (const float x, const float y,
  67337. const float w, const float h,
  67338. float csx,
  67339. float csy) throw()
  67340. {
  67341. csx = jmin (csx, w * 0.5f);
  67342. csy = jmin (csy, h * 0.5f);
  67343. const float cs45x = csx * 0.45f;
  67344. const float cs45y = csy * 0.45f;
  67345. const float x2 = x + w;
  67346. const float y2 = y + h;
  67347. startNewSubPath (x + csx, y);
  67348. lineTo (x2 - csx, y);
  67349. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  67350. lineTo (x2, y2 - csy);
  67351. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  67352. lineTo (x + csx, y2);
  67353. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  67354. lineTo (x, y + csy);
  67355. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  67356. closeSubPath();
  67357. }
  67358. void Path::addRoundedRectangle (const float x, const float y,
  67359. const float w, const float h,
  67360. float cs) throw()
  67361. {
  67362. addRoundedRectangle (x, y, w, h, cs, cs);
  67363. }
  67364. void Path::addTriangle (const float x1, const float y1,
  67365. const float x2, const float y2,
  67366. const float x3, const float y3) throw()
  67367. {
  67368. startNewSubPath (x1, y1);
  67369. lineTo (x2, y2);
  67370. lineTo (x3, y3);
  67371. closeSubPath();
  67372. }
  67373. void Path::addQuadrilateral (const float x1, const float y1,
  67374. const float x2, const float y2,
  67375. const float x3, const float y3,
  67376. const float x4, const float y4) throw()
  67377. {
  67378. startNewSubPath (x1, y1);
  67379. lineTo (x2, y2);
  67380. lineTo (x3, y3);
  67381. lineTo (x4, y4);
  67382. closeSubPath();
  67383. }
  67384. void Path::addEllipse (const float x, const float y,
  67385. const float w, const float h) throw()
  67386. {
  67387. const float hw = w * 0.5f;
  67388. const float hw55 = hw * 0.55f;
  67389. const float hh = h * 0.5f;
  67390. const float hh45 = hh * 0.55f;
  67391. const float cx = x + hw;
  67392. const float cy = y + hh;
  67393. startNewSubPath (cx, cy - hh);
  67394. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  67395. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  67396. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  67397. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  67398. closeSubPath();
  67399. }
  67400. void Path::addArc (const float x, const float y,
  67401. const float w, const float h,
  67402. const float fromRadians,
  67403. const float toRadians,
  67404. const bool startAsNewSubPath) throw()
  67405. {
  67406. const float radiusX = w / 2.0f;
  67407. const float radiusY = h / 2.0f;
  67408. addCentredArc (x + radiusX,
  67409. y + radiusY,
  67410. radiusX, radiusY,
  67411. 0.0f,
  67412. fromRadians, toRadians,
  67413. startAsNewSubPath);
  67414. }
  67415. static const float ellipseAngularIncrement = 0.05f;
  67416. void Path::addCentredArc (const float centreX, const float centreY,
  67417. const float radiusX, const float radiusY,
  67418. const float rotationOfEllipse,
  67419. const float fromRadians,
  67420. const float toRadians,
  67421. const bool startAsNewSubPath) throw()
  67422. {
  67423. if (radiusX > 0.0f && radiusY > 0.0f)
  67424. {
  67425. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  67426. float angle = fromRadians;
  67427. if (startAsNewSubPath)
  67428. {
  67429. float x = centreX + radiusX * sinf (angle);
  67430. float y = centreY - radiusY * cosf (angle);
  67431. if (rotationOfEllipse != 0)
  67432. rotation.transformPoint (x, y);
  67433. startNewSubPath (x, y);
  67434. }
  67435. if (fromRadians < toRadians)
  67436. {
  67437. if (startAsNewSubPath)
  67438. angle += ellipseAngularIncrement;
  67439. while (angle < toRadians)
  67440. {
  67441. float x = centreX + radiusX * sinf (angle);
  67442. float y = centreY - radiusY * cosf (angle);
  67443. if (rotationOfEllipse != 0)
  67444. rotation.transformPoint (x, y);
  67445. lineTo (x, y);
  67446. angle += ellipseAngularIncrement;
  67447. }
  67448. }
  67449. else
  67450. {
  67451. if (startAsNewSubPath)
  67452. angle -= ellipseAngularIncrement;
  67453. while (angle > toRadians)
  67454. {
  67455. float x = centreX + radiusX * sinf (angle);
  67456. float y = centreY - radiusY * cosf (angle);
  67457. if (rotationOfEllipse != 0)
  67458. rotation.transformPoint (x, y);
  67459. lineTo (x, y);
  67460. angle -= ellipseAngularIncrement;
  67461. }
  67462. }
  67463. float x = centreX + radiusX * sinf (toRadians);
  67464. float y = centreY - radiusY * cosf (toRadians);
  67465. if (rotationOfEllipse != 0)
  67466. rotation.transformPoint (x, y);
  67467. lineTo (x, y);
  67468. }
  67469. }
  67470. void Path::addPieSegment (const float x, const float y,
  67471. const float width, const float height,
  67472. const float fromRadians,
  67473. const float toRadians,
  67474. const float innerCircleProportionalSize)
  67475. {
  67476. float hw = width * 0.5f;
  67477. float hh = height * 0.5f;
  67478. const float centreX = x + hw;
  67479. const float centreY = y + hh;
  67480. startNewSubPath (centreX + hw * sinf (fromRadians),
  67481. centreY - hh * cosf (fromRadians));
  67482. addArc (x, y, width, height, fromRadians, toRadians);
  67483. if (fabs (fromRadians - toRadians) > float_Pi * 1.999f)
  67484. {
  67485. closeSubPath();
  67486. if (innerCircleProportionalSize > 0)
  67487. {
  67488. hw *= innerCircleProportionalSize;
  67489. hh *= innerCircleProportionalSize;
  67490. startNewSubPath (centreX + hw * sinf (toRadians),
  67491. centreY - hh * cosf (toRadians));
  67492. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  67493. toRadians, fromRadians);
  67494. }
  67495. }
  67496. else
  67497. {
  67498. if (innerCircleProportionalSize > 0)
  67499. {
  67500. hw *= innerCircleProportionalSize;
  67501. hh *= innerCircleProportionalSize;
  67502. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  67503. toRadians, fromRadians);
  67504. }
  67505. else
  67506. {
  67507. lineTo (centreX, centreY);
  67508. }
  67509. }
  67510. closeSubPath();
  67511. }
  67512. static void perpendicularOffset (const float x1, const float y1,
  67513. const float x2, const float y2,
  67514. const float offsetX, const float offsetY,
  67515. float& resultX, float& resultY) throw()
  67516. {
  67517. const float dx = x2 - x1;
  67518. const float dy = y2 - y1;
  67519. const float len = juce_hypotf (dx, dy);
  67520. if (len == 0)
  67521. {
  67522. resultX = x1;
  67523. resultY = y1;
  67524. }
  67525. else
  67526. {
  67527. resultX = x1 + ((dx * offsetX) - (dy * offsetY)) / len;
  67528. resultY = y1 + ((dy * offsetX) + (dx * offsetY)) / len;
  67529. }
  67530. }
  67531. void Path::addLineSegment (const float startX, const float startY,
  67532. const float endX, const float endY,
  67533. float lineThickness) throw()
  67534. {
  67535. lineThickness *= 0.5f;
  67536. float x, y;
  67537. perpendicularOffset (startX, startY, endX, endY,
  67538. 0, lineThickness, x, y);
  67539. startNewSubPath (x, y);
  67540. perpendicularOffset (startX, startY, endX, endY,
  67541. 0, -lineThickness, x, y);
  67542. lineTo (x, y);
  67543. perpendicularOffset (endX, endY, startX, startY,
  67544. 0, lineThickness, x, y);
  67545. lineTo (x, y);
  67546. perpendicularOffset (endX, endY, startX, startY,
  67547. 0, -lineThickness, x, y);
  67548. lineTo (x, y);
  67549. closeSubPath();
  67550. }
  67551. void Path::addArrow (const float startX, const float startY,
  67552. const float endX, const float endY,
  67553. float lineThickness,
  67554. float arrowheadWidth,
  67555. float arrowheadLength) throw()
  67556. {
  67557. lineThickness *= 0.5f;
  67558. arrowheadWidth *= 0.5f;
  67559. arrowheadLength = jmin (arrowheadLength, 0.8f * juce_hypotf (startX - endX,
  67560. startY - endY));
  67561. float x, y;
  67562. perpendicularOffset (startX, startY, endX, endY,
  67563. 0, lineThickness, x, y);
  67564. startNewSubPath (x, y);
  67565. perpendicularOffset (startX, startY, endX, endY,
  67566. 0, -lineThickness, x, y);
  67567. lineTo (x, y);
  67568. perpendicularOffset (endX, endY, startX, startY,
  67569. arrowheadLength, lineThickness, x, y);
  67570. lineTo (x, y);
  67571. perpendicularOffset (endX, endY, startX, startY,
  67572. arrowheadLength, arrowheadWidth, x, y);
  67573. lineTo (x, y);
  67574. perpendicularOffset (endX, endY, startX, startY,
  67575. 0, 0, x, y);
  67576. lineTo (x, y);
  67577. perpendicularOffset (endX, endY, startX, startY,
  67578. arrowheadLength, -arrowheadWidth, x, y);
  67579. lineTo (x, y);
  67580. perpendicularOffset (endX, endY, startX, startY,
  67581. arrowheadLength, -lineThickness, x, y);
  67582. lineTo (x, y);
  67583. closeSubPath();
  67584. }
  67585. void Path::addStar (const float centreX,
  67586. const float centreY,
  67587. const int numberOfPoints,
  67588. const float innerRadius,
  67589. const float outerRadius,
  67590. const float startAngle)
  67591. {
  67592. jassert (numberOfPoints > 1); // this would be silly.
  67593. if (numberOfPoints > 1)
  67594. {
  67595. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  67596. for (int i = 0; i < numberOfPoints; ++i)
  67597. {
  67598. float angle = startAngle + i * angleBetweenPoints;
  67599. const float x = centreX + outerRadius * sinf (angle);
  67600. const float y = centreY - outerRadius * cosf (angle);
  67601. if (i == 0)
  67602. startNewSubPath (x, y);
  67603. else
  67604. lineTo (x, y);
  67605. angle += angleBetweenPoints * 0.5f;
  67606. lineTo (centreX + innerRadius * sinf (angle),
  67607. centreY - innerRadius * cosf (angle));
  67608. }
  67609. closeSubPath();
  67610. }
  67611. }
  67612. void Path::addBubble (float x, float y,
  67613. float w, float h,
  67614. float cs,
  67615. float tipX,
  67616. float tipY,
  67617. int whichSide,
  67618. float arrowPos,
  67619. float arrowWidth)
  67620. {
  67621. if (w > 1.0f && h > 1.0f)
  67622. {
  67623. cs = jmin (cs, w * 0.5f, h * 0.5f);
  67624. const float cs2 = 2.0f * cs;
  67625. startNewSubPath (x + cs, y);
  67626. if (whichSide == 0)
  67627. {
  67628. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  67629. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  67630. lineTo (arrowX1, y);
  67631. lineTo (tipX, tipY);
  67632. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  67633. }
  67634. lineTo (x + w - cs, y);
  67635. if (cs > 0.0f)
  67636. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  67637. if (whichSide == 3)
  67638. {
  67639. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  67640. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  67641. lineTo (x + w, arrowY1);
  67642. lineTo (tipX, tipY);
  67643. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  67644. }
  67645. lineTo (x + w, y + h - cs);
  67646. if (cs > 0.0f)
  67647. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  67648. if (whichSide == 2)
  67649. {
  67650. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  67651. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  67652. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  67653. lineTo (tipX, tipY);
  67654. lineTo (arrowX1, y + h);
  67655. }
  67656. lineTo (x + cs, y + h);
  67657. if (cs > 0.0f)
  67658. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  67659. if (whichSide == 1)
  67660. {
  67661. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  67662. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  67663. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  67664. lineTo (tipX, tipY);
  67665. lineTo (x, arrowY1);
  67666. }
  67667. lineTo (x, y + cs);
  67668. if (cs > 0.0f)
  67669. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - ellipseAngularIncrement);
  67670. closeSubPath();
  67671. }
  67672. }
  67673. void Path::addPath (const Path& other) throw()
  67674. {
  67675. int i = 0;
  67676. while (i < other.numElements)
  67677. {
  67678. const float type = other.elements [i++];
  67679. if (type == moveMarker)
  67680. {
  67681. startNewSubPath (other.elements [i],
  67682. other.elements [i + 1]);
  67683. i += 2;
  67684. }
  67685. else if (type == lineMarker)
  67686. {
  67687. lineTo (other.elements [i],
  67688. other.elements [i + 1]);
  67689. i += 2;
  67690. }
  67691. else if (type == quadMarker)
  67692. {
  67693. quadraticTo (other.elements [i],
  67694. other.elements [i + 1],
  67695. other.elements [i + 2],
  67696. other.elements [i + 3]);
  67697. i += 4;
  67698. }
  67699. else if (type == cubicMarker)
  67700. {
  67701. cubicTo (other.elements [i],
  67702. other.elements [i + 1],
  67703. other.elements [i + 2],
  67704. other.elements [i + 3],
  67705. other.elements [i + 4],
  67706. other.elements [i + 5]);
  67707. i += 6;
  67708. }
  67709. else if (type == closeSubPathMarker)
  67710. {
  67711. closeSubPath();
  67712. }
  67713. else
  67714. {
  67715. // something's gone wrong with the element list!
  67716. jassertfalse
  67717. }
  67718. }
  67719. }
  67720. void Path::addPath (const Path& other,
  67721. const AffineTransform& transformToApply) throw()
  67722. {
  67723. int i = 0;
  67724. while (i < other.numElements)
  67725. {
  67726. const float type = other.elements [i++];
  67727. if (type == closeSubPathMarker)
  67728. {
  67729. closeSubPath();
  67730. }
  67731. else
  67732. {
  67733. float x = other.elements [i++];
  67734. float y = other.elements [i++];
  67735. transformToApply.transformPoint (x, y);
  67736. if (type == moveMarker)
  67737. {
  67738. startNewSubPath (x, y);
  67739. }
  67740. else if (type == lineMarker)
  67741. {
  67742. lineTo (x, y);
  67743. }
  67744. else if (type == quadMarker)
  67745. {
  67746. float x2 = other.elements [i++];
  67747. float y2 = other.elements [i++];
  67748. transformToApply.transformPoint (x2, y2);
  67749. quadraticTo (x, y, x2, y2);
  67750. }
  67751. else if (type == cubicMarker)
  67752. {
  67753. float x2 = other.elements [i++];
  67754. float y2 = other.elements [i++];
  67755. float x3 = other.elements [i++];
  67756. float y3 = other.elements [i++];
  67757. transformToApply.transformPoint (x2, y2);
  67758. transformToApply.transformPoint (x3, y3);
  67759. cubicTo (x, y, x2, y2, x3, y3);
  67760. }
  67761. else
  67762. {
  67763. // something's gone wrong with the element list!
  67764. jassertfalse
  67765. }
  67766. }
  67767. }
  67768. }
  67769. void Path::applyTransform (const AffineTransform& transform) throw()
  67770. {
  67771. int i = 0;
  67772. pathYMin = pathXMin = 0;
  67773. pathYMax = pathXMax = 0;
  67774. bool setMaxMin = false;
  67775. while (i < numElements)
  67776. {
  67777. const float type = elements [i++];
  67778. if (type == moveMarker)
  67779. {
  67780. transform.transformPoint (elements [i],
  67781. elements [i + 1]);
  67782. if (setMaxMin)
  67783. {
  67784. pathXMin = jmin (pathXMin, elements [i]);
  67785. pathXMax = jmax (pathXMax, elements [i]);
  67786. pathYMin = jmin (pathYMin, elements [i + 1]);
  67787. pathYMax = jmax (pathYMax, elements [i + 1]);
  67788. }
  67789. else
  67790. {
  67791. pathXMin = pathXMax = elements [i];
  67792. pathYMin = pathYMax = elements [i + 1];
  67793. setMaxMin = true;
  67794. }
  67795. i += 2;
  67796. }
  67797. else if (type == lineMarker)
  67798. {
  67799. transform.transformPoint (elements [i],
  67800. elements [i + 1]);
  67801. pathXMin = jmin (pathXMin, elements [i]);
  67802. pathXMax = jmax (pathXMax, elements [i]);
  67803. pathYMin = jmin (pathYMin, elements [i + 1]);
  67804. pathYMax = jmax (pathYMax, elements [i + 1]);
  67805. i += 2;
  67806. }
  67807. else if (type == quadMarker)
  67808. {
  67809. transform.transformPoint (elements [i],
  67810. elements [i + 1]);
  67811. transform.transformPoint (elements [i + 2],
  67812. elements [i + 3]);
  67813. pathXMin = jmin (pathXMin, elements [i], elements [i + 2]);
  67814. pathXMax = jmax (pathXMax, elements [i], elements [i + 2]);
  67815. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3]);
  67816. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3]);
  67817. i += 4;
  67818. }
  67819. else if (type == cubicMarker)
  67820. {
  67821. transform.transformPoint (elements [i],
  67822. elements [i + 1]);
  67823. transform.transformPoint (elements [i + 2],
  67824. elements [i + 3]);
  67825. transform.transformPoint (elements [i + 4],
  67826. elements [i + 5]);
  67827. pathXMin = jmin (pathXMin, elements [i], elements [i + 2], elements [i + 4]);
  67828. pathXMax = jmax (pathXMax, elements [i], elements [i + 2], elements [i + 4]);
  67829. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3], elements [i + 5]);
  67830. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3], elements [i + 5]);
  67831. i += 6;
  67832. }
  67833. }
  67834. }
  67835. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  67836. const float w, const float h,
  67837. const bool preserveProportions,
  67838. const Justification& justification) const throw()
  67839. {
  67840. float sx, sy, sw, sh;
  67841. getBounds (sx, sy, sw, sh);
  67842. if (preserveProportions)
  67843. {
  67844. if (w <= 0 || h <= 0 || sw <= 0 || sh <= 0)
  67845. return AffineTransform::identity;
  67846. float newW, newH;
  67847. const float srcRatio = sh / sw;
  67848. if (srcRatio > h / w)
  67849. {
  67850. newW = h / srcRatio;
  67851. newH = h;
  67852. }
  67853. else
  67854. {
  67855. newW = w;
  67856. newH = w * srcRatio;
  67857. }
  67858. float newXCentre = x;
  67859. float newYCentre = y;
  67860. if (justification.testFlags (Justification::left))
  67861. newXCentre += newW * 0.5f;
  67862. else if (justification.testFlags (Justification::right))
  67863. newXCentre += w - newW * 0.5f;
  67864. else
  67865. newXCentre += w * 0.5f;
  67866. if (justification.testFlags (Justification::top))
  67867. newYCentre += newH * 0.5f;
  67868. else if (justification.testFlags (Justification::bottom))
  67869. newYCentre += h - newH * 0.5f;
  67870. else
  67871. newYCentre += h * 0.5f;
  67872. return AffineTransform::translation (sw * -0.5f - sx, sh * -0.5f - sy)
  67873. .scaled (newW / sw, newH / sh)
  67874. .translated (newXCentre, newYCentre);
  67875. }
  67876. else
  67877. {
  67878. return AffineTransform::translation (-sx, -sy)
  67879. .scaled (w / sw, h / sh)
  67880. .translated (x, y);
  67881. }
  67882. }
  67883. static const float collisionDetectionTolerence = 20.0f;
  67884. bool Path::contains (const float x, const float y) const throw()
  67885. {
  67886. if (x <= pathXMin || x >= pathXMax
  67887. || y <= pathYMin || y >= pathYMax)
  67888. return false;
  67889. PathFlatteningIterator i (*this, AffineTransform::identity, collisionDetectionTolerence);
  67890. int positiveCrossings = 0;
  67891. int negativeCrossings = 0;
  67892. while (i.next())
  67893. {
  67894. if ((i.y1 <= y && i.y2 > y)
  67895. || (i.y2 <= y && i.y1 > y))
  67896. {
  67897. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  67898. if (intersectX <= x)
  67899. {
  67900. if (i.y1 < i.y2)
  67901. ++positiveCrossings;
  67902. else
  67903. ++negativeCrossings;
  67904. }
  67905. }
  67906. }
  67907. return (useNonZeroWinding) ? (negativeCrossings != positiveCrossings)
  67908. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  67909. }
  67910. bool Path::intersectsLine (const float x1, const float y1,
  67911. const float x2, const float y2) throw()
  67912. {
  67913. PathFlatteningIterator i (*this, AffineTransform::identity, collisionDetectionTolerence);
  67914. const Line line1 (x1, y1, x2, y2);
  67915. while (i.next())
  67916. {
  67917. const Line line2 (i.x1, i.y1, i.x2, i.y2);
  67918. float ix, iy;
  67919. if (line1.intersects (line2, ix, iy))
  67920. return true;
  67921. }
  67922. return false;
  67923. }
  67924. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const throw()
  67925. {
  67926. if (cornerRadius <= 0.01f)
  67927. return *this;
  67928. int indexOfPathStart = 0, indexOfPathStartThis = 0;
  67929. int n = 0;
  67930. bool lastWasLine = false, firstWasLine = false;
  67931. Path p;
  67932. while (n < numElements)
  67933. {
  67934. const float type = elements [n++];
  67935. if (type == moveMarker)
  67936. {
  67937. indexOfPathStart = p.numElements;
  67938. indexOfPathStartThis = n - 1;
  67939. const float x = elements [n++];
  67940. const float y = elements [n++];
  67941. p.startNewSubPath (x, y);
  67942. lastWasLine = false;
  67943. firstWasLine = (elements [n] == lineMarker);
  67944. }
  67945. else if (type == lineMarker || type == closeSubPathMarker)
  67946. {
  67947. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  67948. if (type == lineMarker)
  67949. {
  67950. endX = elements [n++];
  67951. endY = elements [n++];
  67952. if (n > 8)
  67953. {
  67954. startX = elements [n - 8];
  67955. startY = elements [n - 7];
  67956. joinX = elements [n - 5];
  67957. joinY = elements [n - 4];
  67958. }
  67959. }
  67960. else
  67961. {
  67962. endX = elements [indexOfPathStartThis + 1];
  67963. endY = elements [indexOfPathStartThis + 2];
  67964. if (n > 6)
  67965. {
  67966. startX = elements [n - 6];
  67967. startY = elements [n - 5];
  67968. joinX = elements [n - 3];
  67969. joinY = elements [n - 2];
  67970. }
  67971. }
  67972. if (lastWasLine)
  67973. {
  67974. const double len1 = juce_hypot (startX - joinX,
  67975. startY - joinY);
  67976. if (len1 > 0)
  67977. {
  67978. const double propNeeded = jmin (0.5, cornerRadius / len1);
  67979. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  67980. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  67981. }
  67982. const double len2 = juce_hypot (endX - joinX,
  67983. endY - joinY);
  67984. if (len2 > 0)
  67985. {
  67986. const double propNeeded = jmin (0.5, cornerRadius / len2);
  67987. p.quadraticTo (joinX, joinY,
  67988. (float) (joinX + (endX - joinX) * propNeeded),
  67989. (float) (joinY + (endY - joinY) * propNeeded));
  67990. }
  67991. p.lineTo (endX, endY);
  67992. }
  67993. else if (type == lineMarker)
  67994. {
  67995. p.lineTo (endX, endY);
  67996. lastWasLine = true;
  67997. }
  67998. if (type == closeSubPathMarker)
  67999. {
  68000. if (firstWasLine)
  68001. {
  68002. startX = elements [n - 3];
  68003. startY = elements [n - 2];
  68004. joinX = endX;
  68005. joinY = endY;
  68006. endX = elements [indexOfPathStartThis + 4];
  68007. endY = elements [indexOfPathStartThis + 5];
  68008. const double len1 = juce_hypot (startX - joinX,
  68009. startY - joinY);
  68010. if (len1 > 0)
  68011. {
  68012. const double propNeeded = jmin (0.5, cornerRadius / len1);
  68013. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  68014. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  68015. }
  68016. const double len2 = juce_hypot (endX - joinX,
  68017. endY - joinY);
  68018. if (len2 > 0)
  68019. {
  68020. const double propNeeded = jmin (0.5, cornerRadius / len2);
  68021. endX = (float) (joinX + (endX - joinX) * propNeeded);
  68022. endY = (float) (joinY + (endY - joinY) * propNeeded);
  68023. p.quadraticTo (joinX, joinY, endX, endY);
  68024. p.elements [indexOfPathStart + 1] = endX;
  68025. p.elements [indexOfPathStart + 2] = endY;
  68026. }
  68027. }
  68028. p.closeSubPath();
  68029. }
  68030. }
  68031. else if (type == quadMarker)
  68032. {
  68033. lastWasLine = false;
  68034. const float x1 = elements [n++];
  68035. const float y1 = elements [n++];
  68036. const float x2 = elements [n++];
  68037. const float y2 = elements [n++];
  68038. p.quadraticTo (x1, y1, x2, y2);
  68039. }
  68040. else if (type == cubicMarker)
  68041. {
  68042. lastWasLine = false;
  68043. const float x1 = elements [n++];
  68044. const float y1 = elements [n++];
  68045. const float x2 = elements [n++];
  68046. const float y2 = elements [n++];
  68047. const float x3 = elements [n++];
  68048. const float y3 = elements [n++];
  68049. p.cubicTo (x1, y1, x2, y2, x3, y3);
  68050. }
  68051. }
  68052. return p;
  68053. }
  68054. void Path::loadPathFromStream (InputStream& source)
  68055. {
  68056. while (! source.isExhausted())
  68057. {
  68058. switch (source.readByte())
  68059. {
  68060. case 'm':
  68061. {
  68062. const float x = source.readFloat();
  68063. const float y = source.readFloat();
  68064. startNewSubPath (x, y);
  68065. break;
  68066. }
  68067. case 'l':
  68068. {
  68069. const float x = source.readFloat();
  68070. const float y = source.readFloat();
  68071. lineTo (x, y);
  68072. break;
  68073. }
  68074. case 'q':
  68075. {
  68076. const float x1 = source.readFloat();
  68077. const float y1 = source.readFloat();
  68078. const float x2 = source.readFloat();
  68079. const float y2 = source.readFloat();
  68080. quadraticTo (x1, y1, x2, y2);
  68081. break;
  68082. }
  68083. case 'b':
  68084. {
  68085. const float x1 = source.readFloat();
  68086. const float y1 = source.readFloat();
  68087. const float x2 = source.readFloat();
  68088. const float y2 = source.readFloat();
  68089. const float x3 = source.readFloat();
  68090. const float y3 = source.readFloat();
  68091. cubicTo (x1, y1, x2, y2, x3, y3);
  68092. break;
  68093. }
  68094. case 'c':
  68095. closeSubPath();
  68096. break;
  68097. case 'n':
  68098. useNonZeroWinding = true;
  68099. break;
  68100. case 'z':
  68101. useNonZeroWinding = false;
  68102. break;
  68103. case 'e':
  68104. return; // end of path marker
  68105. default:
  68106. jassertfalse // illegal char in the stream
  68107. break;
  68108. }
  68109. }
  68110. }
  68111. void Path::loadPathFromData (const unsigned char* const data,
  68112. const int numberOfBytes) throw()
  68113. {
  68114. MemoryInputStream in ((const char*) data, numberOfBytes, false);
  68115. loadPathFromStream (in);
  68116. }
  68117. void Path::writePathToStream (OutputStream& dest) const
  68118. {
  68119. dest.writeByte ((useNonZeroWinding) ? 'n' : 'z');
  68120. int i = 0;
  68121. while (i < numElements)
  68122. {
  68123. const float type = elements [i++];
  68124. if (type == moveMarker)
  68125. {
  68126. dest.writeByte ('m');
  68127. dest.writeFloat (elements [i++]);
  68128. dest.writeFloat (elements [i++]);
  68129. }
  68130. else if (type == lineMarker)
  68131. {
  68132. dest.writeByte ('l');
  68133. dest.writeFloat (elements [i++]);
  68134. dest.writeFloat (elements [i++]);
  68135. }
  68136. else if (type == quadMarker)
  68137. {
  68138. dest.writeByte ('q');
  68139. dest.writeFloat (elements [i++]);
  68140. dest.writeFloat (elements [i++]);
  68141. dest.writeFloat (elements [i++]);
  68142. dest.writeFloat (elements [i++]);
  68143. }
  68144. else if (type == cubicMarker)
  68145. {
  68146. dest.writeByte ('b');
  68147. dest.writeFloat (elements [i++]);
  68148. dest.writeFloat (elements [i++]);
  68149. dest.writeFloat (elements [i++]);
  68150. dest.writeFloat (elements [i++]);
  68151. dest.writeFloat (elements [i++]);
  68152. dest.writeFloat (elements [i++]);
  68153. }
  68154. else if (type == closeSubPathMarker)
  68155. {
  68156. dest.writeByte ('c');
  68157. }
  68158. }
  68159. dest.writeByte ('e'); // marks the end-of-path
  68160. }
  68161. const String Path::toString() const
  68162. {
  68163. String s;
  68164. s.preallocateStorage (numElements * 4);
  68165. if (! useNonZeroWinding)
  68166. s << T("a ");
  68167. int i = 0;
  68168. float lastMarker = 0.0f;
  68169. while (i < numElements)
  68170. {
  68171. const float marker = elements [i++];
  68172. tchar markerChar = 0;
  68173. int numCoords = 0;
  68174. if (marker == moveMarker)
  68175. {
  68176. markerChar = T('m');
  68177. numCoords = 2;
  68178. }
  68179. else if (marker == lineMarker)
  68180. {
  68181. markerChar = T('l');
  68182. numCoords = 2;
  68183. }
  68184. else if (marker == quadMarker)
  68185. {
  68186. markerChar = T('q');
  68187. numCoords = 4;
  68188. }
  68189. else if (marker == cubicMarker)
  68190. {
  68191. markerChar = T('c');
  68192. numCoords = 6;
  68193. }
  68194. else
  68195. {
  68196. jassert (marker == closeSubPathMarker);
  68197. markerChar = T('z');
  68198. }
  68199. if (marker != lastMarker)
  68200. {
  68201. s << markerChar << T(' ');
  68202. lastMarker = marker;
  68203. }
  68204. while (--numCoords >= 0 && i < numElements)
  68205. {
  68206. String n (elements [i++], 3);
  68207. while (n.endsWithChar (T('0')))
  68208. n = n.dropLastCharacters (1);
  68209. if (n.endsWithChar (T('.')))
  68210. n = n.dropLastCharacters (1);
  68211. s << n << T(' ');
  68212. }
  68213. }
  68214. return s.trimEnd();
  68215. }
  68216. static const String nextToken (const tchar*& t)
  68217. {
  68218. while (*t == T(' '))
  68219. ++t;
  68220. const tchar* const start = t;
  68221. while (*t != 0 && *t != T(' '))
  68222. ++t;
  68223. const int length = (int) (t - start);
  68224. while (*t == T(' '))
  68225. ++t;
  68226. return String (start, length);
  68227. }
  68228. void Path::restoreFromString (const String& stringVersion)
  68229. {
  68230. clear();
  68231. setUsingNonZeroWinding (true);
  68232. const tchar* t = stringVersion;
  68233. tchar marker = T('m');
  68234. int numValues = 2;
  68235. float values [6];
  68236. while (*t != 0)
  68237. {
  68238. const String token (nextToken (t));
  68239. const tchar firstChar = token[0];
  68240. int startNum = 0;
  68241. if (firstChar == T('m') || firstChar == T('l'))
  68242. {
  68243. marker = firstChar;
  68244. numValues = 2;
  68245. }
  68246. else if (firstChar == T('q'))
  68247. {
  68248. marker = firstChar;
  68249. numValues = 4;
  68250. }
  68251. else if (firstChar == T('c'))
  68252. {
  68253. marker = firstChar;
  68254. numValues = 6;
  68255. }
  68256. else if (firstChar == T('z'))
  68257. {
  68258. marker = firstChar;
  68259. numValues = 0;
  68260. }
  68261. else if (firstChar == T('a'))
  68262. {
  68263. setUsingNonZeroWinding (false);
  68264. continue;
  68265. }
  68266. else
  68267. {
  68268. ++startNum;
  68269. values [0] = token.getFloatValue();
  68270. }
  68271. for (int i = startNum; i < numValues; ++i)
  68272. values [i] = nextToken (t).getFloatValue();
  68273. switch (marker)
  68274. {
  68275. case T('m'):
  68276. startNewSubPath (values[0], values[1]);
  68277. break;
  68278. case T('l'):
  68279. lineTo (values[0], values[1]);
  68280. break;
  68281. case T('q'):
  68282. quadraticTo (values[0], values[1],
  68283. values[2], values[3]);
  68284. break;
  68285. case T('c'):
  68286. cubicTo (values[0], values[1],
  68287. values[2], values[3],
  68288. values[4], values[5]);
  68289. break;
  68290. case T('z'):
  68291. closeSubPath();
  68292. break;
  68293. default:
  68294. jassertfalse // illegal string format?
  68295. break;
  68296. }
  68297. }
  68298. }
  68299. Path::Iterator::Iterator (const Path& path_)
  68300. : path (path_),
  68301. index (0)
  68302. {
  68303. }
  68304. Path::Iterator::~Iterator()
  68305. {
  68306. }
  68307. bool Path::Iterator::next()
  68308. {
  68309. const float* const elements = path.elements;
  68310. if (index < path.numElements)
  68311. {
  68312. const float type = elements [index++];
  68313. if (type == moveMarker)
  68314. {
  68315. elementType = startNewSubPath;
  68316. x1 = elements [index++];
  68317. y1 = elements [index++];
  68318. }
  68319. else if (type == lineMarker)
  68320. {
  68321. elementType = lineTo;
  68322. x1 = elements [index++];
  68323. y1 = elements [index++];
  68324. }
  68325. else if (type == quadMarker)
  68326. {
  68327. elementType = quadraticTo;
  68328. x1 = elements [index++];
  68329. y1 = elements [index++];
  68330. x2 = elements [index++];
  68331. y2 = elements [index++];
  68332. }
  68333. else if (type == cubicMarker)
  68334. {
  68335. elementType = cubicTo;
  68336. x1 = elements [index++];
  68337. y1 = elements [index++];
  68338. x2 = elements [index++];
  68339. y2 = elements [index++];
  68340. x3 = elements [index++];
  68341. y3 = elements [index++];
  68342. }
  68343. else if (type == closeSubPathMarker)
  68344. {
  68345. elementType = closePath;
  68346. }
  68347. return true;
  68348. }
  68349. return false;
  68350. }
  68351. END_JUCE_NAMESPACE
  68352. /********* End of inlined file: juce_Path.cpp *********/
  68353. /********* Start of inlined file: juce_PathIterator.cpp *********/
  68354. BEGIN_JUCE_NAMESPACE
  68355. #if JUCE_MSVC
  68356. #pragma optimize ("t", on)
  68357. #endif
  68358. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  68359. const AffineTransform& transform_,
  68360. float tolerence_) throw()
  68361. : x2 (0),
  68362. y2 (0),
  68363. closesSubPath (false),
  68364. subPathIndex (-1),
  68365. path (path_),
  68366. transform (transform_),
  68367. points (path_.elements),
  68368. tolerence (tolerence_ * tolerence_),
  68369. subPathCloseX (0),
  68370. subPathCloseY (0),
  68371. index (0),
  68372. stackSize (32)
  68373. {
  68374. stackBase = (float*) juce_malloc (stackSize * sizeof (float));
  68375. isIdentityTransform = transform.isIdentity();
  68376. stackPos = stackBase;
  68377. }
  68378. PathFlatteningIterator::~PathFlatteningIterator() throw()
  68379. {
  68380. juce_free (stackBase);
  68381. }
  68382. bool PathFlatteningIterator::next() throw()
  68383. {
  68384. x1 = x2;
  68385. y1 = y2;
  68386. float x3 = 0;
  68387. float y3 = 0;
  68388. float x4 = 0;
  68389. float y4 = 0;
  68390. float type;
  68391. for (;;)
  68392. {
  68393. if (stackPos == stackBase)
  68394. {
  68395. if (index >= path.numElements)
  68396. {
  68397. return false;
  68398. }
  68399. else
  68400. {
  68401. type = points [index++];
  68402. if (type != Path::closeSubPathMarker)
  68403. {
  68404. x2 = points [index++];
  68405. y2 = points [index++];
  68406. if (! isIdentityTransform)
  68407. transform.transformPoint (x2, y2);
  68408. if (type == Path::quadMarker)
  68409. {
  68410. x3 = points [index++];
  68411. y3 = points [index++];
  68412. if (! isIdentityTransform)
  68413. transform.transformPoint (x3, y3);
  68414. }
  68415. else if (type == Path::cubicMarker)
  68416. {
  68417. x3 = points [index++];
  68418. y3 = points [index++];
  68419. x4 = points [index++];
  68420. y4 = points [index++];
  68421. if (! isIdentityTransform)
  68422. {
  68423. transform.transformPoint (x3, y3);
  68424. transform.transformPoint (x4, y4);
  68425. }
  68426. }
  68427. }
  68428. }
  68429. }
  68430. else
  68431. {
  68432. type = *--stackPos;
  68433. if (type != Path::closeSubPathMarker)
  68434. {
  68435. x2 = *--stackPos;
  68436. y2 = *--stackPos;
  68437. if (type == Path::quadMarker)
  68438. {
  68439. x3 = *--stackPos;
  68440. y3 = *--stackPos;
  68441. }
  68442. else if (type == Path::cubicMarker)
  68443. {
  68444. x3 = *--stackPos;
  68445. y3 = *--stackPos;
  68446. x4 = *--stackPos;
  68447. y4 = *--stackPos;
  68448. }
  68449. }
  68450. }
  68451. if (type == Path::lineMarker)
  68452. {
  68453. ++subPathIndex;
  68454. closesSubPath = (stackPos == stackBase)
  68455. && (index < path.numElements)
  68456. && (points [index] == Path::closeSubPathMarker)
  68457. && x2 == subPathCloseX
  68458. && y2 == subPathCloseY;
  68459. return true;
  68460. }
  68461. else if (type == Path::quadMarker)
  68462. {
  68463. const int offset = (int) (stackPos - stackBase);
  68464. if (offset >= stackSize - 10)
  68465. {
  68466. stackSize <<= 1;
  68467. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  68468. stackPos = stackBase + offset;
  68469. }
  68470. const float dx1 = x1 - x2;
  68471. const float dy1 = y1 - y2;
  68472. const float dx2 = x2 - x3;
  68473. const float dy2 = y2 - y3;
  68474. const float m1x = (x1 + x2) * 0.5f;
  68475. const float m1y = (y1 + y2) * 0.5f;
  68476. const float m2x = (x2 + x3) * 0.5f;
  68477. const float m2y = (y2 + y3) * 0.5f;
  68478. const float m3x = (m1x + m2x) * 0.5f;
  68479. const float m3y = (m1y + m2y) * 0.5f;
  68480. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  68481. {
  68482. *stackPos++ = y3;
  68483. *stackPos++ = x3;
  68484. *stackPos++ = m2y;
  68485. *stackPos++ = m2x;
  68486. *stackPos++ = Path::quadMarker;
  68487. *stackPos++ = m3y;
  68488. *stackPos++ = m3x;
  68489. *stackPos++ = m1y;
  68490. *stackPos++ = m1x;
  68491. *stackPos++ = Path::quadMarker;
  68492. }
  68493. else
  68494. {
  68495. *stackPos++ = y3;
  68496. *stackPos++ = x3;
  68497. *stackPos++ = Path::lineMarker;
  68498. *stackPos++ = m3y;
  68499. *stackPos++ = m3x;
  68500. *stackPos++ = Path::lineMarker;
  68501. }
  68502. jassert (stackPos < stackBase + stackSize);
  68503. }
  68504. else if (type == Path::cubicMarker)
  68505. {
  68506. const int offset = (int) (stackPos - stackBase);
  68507. if (offset >= stackSize - 16)
  68508. {
  68509. stackSize <<= 1;
  68510. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  68511. stackPos = stackBase + offset;
  68512. }
  68513. const float dx1 = x1 - x2;
  68514. const float dy1 = y1 - y2;
  68515. const float dx2 = x2 - x3;
  68516. const float dy2 = y2 - y3;
  68517. const float dx3 = x3 - x4;
  68518. const float dy3 = y3 - y4;
  68519. const float m1x = (x1 + x2) * 0.5f;
  68520. const float m1y = (y1 + y2) * 0.5f;
  68521. const float m2x = (x3 + x2) * 0.5f;
  68522. const float m2y = (y3 + y2) * 0.5f;
  68523. const float m3x = (x3 + x4) * 0.5f;
  68524. const float m3y = (y3 + y4) * 0.5f;
  68525. const float m4x = (m1x + m2x) * 0.5f;
  68526. const float m4y = (m1y + m2y) * 0.5f;
  68527. const float m5x = (m3x + m2x) * 0.5f;
  68528. const float m5y = (m3y + m2y) * 0.5f;
  68529. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  68530. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  68531. {
  68532. *stackPos++ = y4;
  68533. *stackPos++ = x4;
  68534. *stackPos++ = m3y;
  68535. *stackPos++ = m3x;
  68536. *stackPos++ = m5y;
  68537. *stackPos++ = m5x;
  68538. *stackPos++ = Path::cubicMarker;
  68539. *stackPos++ = (m4y + m5y) * 0.5f;
  68540. *stackPos++ = (m4x + m5x) * 0.5f;
  68541. *stackPos++ = m4y;
  68542. *stackPos++ = m4x;
  68543. *stackPos++ = m1y;
  68544. *stackPos++ = m1x;
  68545. *stackPos++ = Path::cubicMarker;
  68546. }
  68547. else
  68548. {
  68549. *stackPos++ = y4;
  68550. *stackPos++ = x4;
  68551. *stackPos++ = Path::lineMarker;
  68552. *stackPos++ = m5y;
  68553. *stackPos++ = m5x;
  68554. *stackPos++ = Path::lineMarker;
  68555. *stackPos++ = m4y;
  68556. *stackPos++ = m4x;
  68557. *stackPos++ = Path::lineMarker;
  68558. }
  68559. }
  68560. else if (type == Path::closeSubPathMarker)
  68561. {
  68562. if (x2 != subPathCloseX || y2 != subPathCloseY)
  68563. {
  68564. x1 = x2;
  68565. y1 = y2;
  68566. x2 = subPathCloseX;
  68567. y2 = subPathCloseY;
  68568. closesSubPath = true;
  68569. return true;
  68570. }
  68571. }
  68572. else
  68573. {
  68574. subPathIndex = -1;
  68575. subPathCloseX = x1 = x2;
  68576. subPathCloseY = y1 = y2;
  68577. }
  68578. }
  68579. }
  68580. END_JUCE_NAMESPACE
  68581. /********* End of inlined file: juce_PathIterator.cpp *********/
  68582. /********* Start of inlined file: juce_PathStrokeType.cpp *********/
  68583. BEGIN_JUCE_NAMESPACE
  68584. PathStrokeType::PathStrokeType (const float strokeThickness,
  68585. const JointStyle jointStyle_,
  68586. const EndCapStyle endStyle_) throw()
  68587. : thickness (strokeThickness),
  68588. jointStyle (jointStyle_),
  68589. endStyle (endStyle_)
  68590. {
  68591. }
  68592. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  68593. : thickness (other.thickness),
  68594. jointStyle (other.jointStyle),
  68595. endStyle (other.endStyle)
  68596. {
  68597. }
  68598. const PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  68599. {
  68600. thickness = other.thickness;
  68601. jointStyle = other.jointStyle;
  68602. endStyle = other.endStyle;
  68603. return *this;
  68604. }
  68605. PathStrokeType::~PathStrokeType() throw()
  68606. {
  68607. }
  68608. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  68609. {
  68610. return thickness == other.thickness
  68611. && jointStyle == other.jointStyle
  68612. && endStyle == other.endStyle;
  68613. }
  68614. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  68615. {
  68616. return ! operator== (other);
  68617. }
  68618. static bool lineIntersection (const float x1, const float y1,
  68619. const float x2, const float y2,
  68620. const float x3, const float y3,
  68621. const float x4, const float y4,
  68622. float& intersectionX,
  68623. float& intersectionY,
  68624. float& distanceBeyondLine1EndSquared) throw()
  68625. {
  68626. if (x2 != x3 || y2 != y3)
  68627. {
  68628. const float dx1 = x2 - x1;
  68629. const float dy1 = y2 - y1;
  68630. const float dx2 = x4 - x3;
  68631. const float dy2 = y4 - y3;
  68632. const float divisor = dx1 * dy2 - dx2 * dy1;
  68633. if (divisor == 0)
  68634. {
  68635. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  68636. {
  68637. if (dy1 == 0 && dy2 != 0)
  68638. {
  68639. const float along = (y1 - y3) / dy2;
  68640. intersectionX = x3 + along * dx2;
  68641. intersectionY = y1;
  68642. distanceBeyondLine1EndSquared = intersectionX - x2;
  68643. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68644. if ((x2 > x1) == (intersectionX < x2))
  68645. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68646. return along >= 0 && along <= 1.0f;
  68647. }
  68648. else if (dy2 == 0 && dy1 != 0)
  68649. {
  68650. const float along = (y3 - y1) / dy1;
  68651. intersectionX = x1 + along * dx1;
  68652. intersectionY = y3;
  68653. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  68654. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68655. if (along < 1.0f)
  68656. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68657. return along >= 0 && along <= 1.0f;
  68658. }
  68659. else if (dx1 == 0 && dx2 != 0)
  68660. {
  68661. const float along = (x1 - x3) / dx2;
  68662. intersectionX = x1;
  68663. intersectionY = y3 + along * dy2;
  68664. distanceBeyondLine1EndSquared = intersectionY - y2;
  68665. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68666. if ((y2 > y1) == (intersectionY < y2))
  68667. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68668. return along >= 0 && along <= 1.0f;
  68669. }
  68670. else if (dx2 == 0 && dx1 != 0)
  68671. {
  68672. const float along = (x3 - x1) / dx1;
  68673. intersectionX = x3;
  68674. intersectionY = y1 + along * dy1;
  68675. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  68676. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68677. if (along < 1.0f)
  68678. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68679. return along >= 0 && along <= 1.0f;
  68680. }
  68681. }
  68682. intersectionX = 0.5f * (x2 + x3);
  68683. intersectionY = 0.5f * (y2 + y3);
  68684. distanceBeyondLine1EndSquared = 0.0f;
  68685. return false;
  68686. }
  68687. else
  68688. {
  68689. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  68690. intersectionX = x1 + along1 * dx1;
  68691. intersectionY = y1 + along1 * dy1;
  68692. if (along1 >= 0 && along1 <= 1.0f)
  68693. {
  68694. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  68695. if (along2 >= 0 && along2 <= divisor)
  68696. {
  68697. distanceBeyondLine1EndSquared = 0.0f;
  68698. return true;
  68699. }
  68700. }
  68701. distanceBeyondLine1EndSquared = along1 - 1.0f;
  68702. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68703. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  68704. if (along1 < 1.0f)
  68705. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68706. return false;
  68707. }
  68708. }
  68709. intersectionX = x2;
  68710. intersectionY = y2;
  68711. distanceBeyondLine1EndSquared = 0.0f;
  68712. return true;
  68713. }
  68714. // part of stroke drawing stuff
  68715. static void addEdgeAndJoint (Path& destPath,
  68716. const PathStrokeType::JointStyle style,
  68717. const float maxMiterExtensionSquared, const float width,
  68718. const float x1, const float y1,
  68719. const float x2, const float y2,
  68720. const float x3, const float y3,
  68721. const float x4, const float y4,
  68722. const float midX, const float midY) throw()
  68723. {
  68724. if (style == PathStrokeType::beveled
  68725. || (x3 == x4 && y3 == y4)
  68726. || (x1 == x2 && y1 == y2))
  68727. {
  68728. destPath.lineTo (x2, y2);
  68729. destPath.lineTo (x3, y3);
  68730. }
  68731. else
  68732. {
  68733. float jx, jy, distanceBeyondLine1EndSquared;
  68734. // if they intersect, use this point..
  68735. if (lineIntersection (x1, y1, x2, y2,
  68736. x3, y3, x4, y4,
  68737. jx, jy, distanceBeyondLine1EndSquared))
  68738. {
  68739. destPath.lineTo (jx, jy);
  68740. }
  68741. else
  68742. {
  68743. if (style == PathStrokeType::mitered)
  68744. {
  68745. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  68746. && distanceBeyondLine1EndSquared > 0.0f)
  68747. {
  68748. destPath.lineTo (jx, jy);
  68749. }
  68750. else
  68751. {
  68752. // the end sticks out too far, so just use a blunt joint
  68753. destPath.lineTo (x2, y2);
  68754. destPath.lineTo (x3, y3);
  68755. }
  68756. }
  68757. else
  68758. {
  68759. // curved joints
  68760. float angle = atan2f (x2 - midX, y2 - midY);
  68761. float angle2 = atan2f (x3 - midX, y3 - midY);
  68762. while (angle < angle2 - 0.01f)
  68763. angle2 -= float_Pi * 2.0f;
  68764. destPath.lineTo (x2, y2);
  68765. while (angle > angle2)
  68766. {
  68767. destPath.lineTo (midX + width * sinf (angle),
  68768. midY + width * cosf (angle));
  68769. angle -= 0.1f;
  68770. }
  68771. destPath.lineTo (x3, y3);
  68772. }
  68773. }
  68774. }
  68775. }
  68776. static inline void addLineEnd (Path& destPath,
  68777. const PathStrokeType::EndCapStyle style,
  68778. const float x1, const float y1,
  68779. const float x2, const float y2,
  68780. const float width) throw()
  68781. {
  68782. if (style == PathStrokeType::butt)
  68783. {
  68784. destPath.lineTo (x2, y2);
  68785. }
  68786. else
  68787. {
  68788. float offx1, offy1, offx2, offy2;
  68789. float dx = x2 - x1;
  68790. float dy = y2 - y1;
  68791. const float len = juce_hypotf (dx, dy);
  68792. if (len == 0)
  68793. {
  68794. offx1 = offx2 = x1;
  68795. offy1 = offy2 = y1;
  68796. }
  68797. else
  68798. {
  68799. const float offset = width / len;
  68800. dx *= offset;
  68801. dy *= offset;
  68802. offx1 = x1 + dy;
  68803. offy1 = y1 - dx;
  68804. offx2 = x2 + dy;
  68805. offy2 = y2 - dx;
  68806. }
  68807. if (style == PathStrokeType::square)
  68808. {
  68809. // sqaure ends
  68810. destPath.lineTo (offx1, offy1);
  68811. destPath.lineTo (offx2, offy2);
  68812. destPath.lineTo (x2, y2);
  68813. }
  68814. else
  68815. {
  68816. // rounded ends
  68817. const float midx = (offx1 + offx2) * 0.5f;
  68818. const float midy = (offy1 + offy2) * 0.5f;
  68819. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  68820. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  68821. midx, midy);
  68822. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  68823. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  68824. x2, y2);
  68825. }
  68826. }
  68827. }
  68828. struct LineSection
  68829. {
  68830. LineSection() throw() {}
  68831. LineSection (int) throw() {}
  68832. float x1, y1, x2, y2; // original line
  68833. float lx1, ly1, lx2, ly2; // the left-hand stroke
  68834. float rx1, ry1, rx2, ry2; // the right-hand stroke
  68835. };
  68836. static void addSubPath (Path& destPath, const Array <LineSection>& subPath,
  68837. const bool isClosed,
  68838. const float width, const float maxMiterExtensionSquared,
  68839. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle) throw()
  68840. {
  68841. jassert (subPath.size() > 0);
  68842. const LineSection& firstLine = subPath.getReference (0);
  68843. float lastX1 = firstLine.lx1;
  68844. float lastY1 = firstLine.ly1;
  68845. float lastX2 = firstLine.lx2;
  68846. float lastY2 = firstLine.ly2;
  68847. if (isClosed)
  68848. {
  68849. destPath.startNewSubPath (lastX1, lastY1);
  68850. }
  68851. else
  68852. {
  68853. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  68854. addLineEnd (destPath, endStyle,
  68855. firstLine.rx2, firstLine.ry2,
  68856. lastX1, lastY1,
  68857. width);
  68858. }
  68859. int i;
  68860. for (i = 1; i < subPath.size(); ++i)
  68861. {
  68862. const LineSection& l = subPath.getReference (i);
  68863. addEdgeAndJoint (destPath, jointStyle,
  68864. maxMiterExtensionSquared, width,
  68865. lastX1, lastY1, lastX2, lastY2,
  68866. l.lx1, l.ly1, l.lx2, l.ly2,
  68867. l.x1, l.y1);
  68868. lastX1 = l.lx1;
  68869. lastY1 = l.ly1;
  68870. lastX2 = l.lx2;
  68871. lastY2 = l.ly2;
  68872. }
  68873. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  68874. if (isClosed)
  68875. {
  68876. const LineSection& l = subPath.getReference (0);
  68877. addEdgeAndJoint (destPath, jointStyle,
  68878. maxMiterExtensionSquared, width,
  68879. lastX1, lastY1, lastX2, lastY2,
  68880. l.lx1, l.ly1, l.lx2, l.ly2,
  68881. l.x1, l.y1);
  68882. destPath.closeSubPath();
  68883. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  68884. }
  68885. else
  68886. {
  68887. destPath.lineTo (lastX2, lastY2);
  68888. addLineEnd (destPath, endStyle,
  68889. lastX2, lastY2,
  68890. lastLine.rx1, lastLine.ry1,
  68891. width);
  68892. }
  68893. lastX1 = lastLine.rx1;
  68894. lastY1 = lastLine.ry1;
  68895. lastX2 = lastLine.rx2;
  68896. lastY2 = lastLine.ry2;
  68897. for (i = subPath.size() - 1; --i >= 0;)
  68898. {
  68899. const LineSection& l = subPath.getReference (i);
  68900. addEdgeAndJoint (destPath, jointStyle,
  68901. maxMiterExtensionSquared, width,
  68902. lastX1, lastY1, lastX2, lastY2,
  68903. l.rx1, l.ry1, l.rx2, l.ry2,
  68904. l.x2, l.y2);
  68905. lastX1 = l.rx1;
  68906. lastY1 = l.ry1;
  68907. lastX2 = l.rx2;
  68908. lastY2 = l.ry2;
  68909. }
  68910. if (isClosed)
  68911. {
  68912. addEdgeAndJoint (destPath, jointStyle,
  68913. maxMiterExtensionSquared, width,
  68914. lastX1, lastY1, lastX2, lastY2,
  68915. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  68916. lastLine.x2, lastLine.y2);
  68917. }
  68918. else
  68919. {
  68920. // do the last line
  68921. destPath.lineTo (lastX2, lastY2);
  68922. }
  68923. destPath.closeSubPath();
  68924. }
  68925. void PathStrokeType::createStrokedPath (Path& destPath,
  68926. const Path& source,
  68927. const AffineTransform& transform,
  68928. const float extraAccuracy) const throw()
  68929. {
  68930. if (thickness <= 0)
  68931. {
  68932. destPath.clear();
  68933. return;
  68934. }
  68935. const Path* sourcePath = &source;
  68936. Path temp;
  68937. if (sourcePath == &destPath)
  68938. {
  68939. destPath.swapWithPath (temp);
  68940. sourcePath = &temp;
  68941. }
  68942. else
  68943. {
  68944. destPath.clear();
  68945. }
  68946. destPath.setUsingNonZeroWinding (true);
  68947. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  68948. const float width = 0.5f * thickness;
  68949. // Iterate the path, creating a list of the
  68950. // left/right-hand lines along either side of it...
  68951. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  68952. Array <LineSection> subPath;
  68953. LineSection l;
  68954. l.x1 = 0;
  68955. l.y1 = 0;
  68956. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  68957. while (it.next())
  68958. {
  68959. if (it.subPathIndex == 0)
  68960. {
  68961. if (subPath.size() > 0)
  68962. {
  68963. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  68964. subPath.clearQuick();
  68965. }
  68966. l.x1 = it.x1;
  68967. l.y1 = it.y1;
  68968. }
  68969. l.x2 = it.x2;
  68970. l.y2 = it.y2;
  68971. float dx = l.x2 - l.x1;
  68972. float dy = l.y2 - l.y1;
  68973. const float hypotSquared = dx*dx + dy*dy;
  68974. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  68975. {
  68976. const float len = sqrtf (hypotSquared);
  68977. if (len == 0)
  68978. {
  68979. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  68980. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  68981. }
  68982. else
  68983. {
  68984. const float offset = width / len;
  68985. dx *= offset;
  68986. dy *= offset;
  68987. l.rx2 = l.x1 - dy;
  68988. l.ry2 = l.y1 + dx;
  68989. l.lx1 = l.x1 + dy;
  68990. l.ly1 = l.y1 - dx;
  68991. l.lx2 = l.x2 + dy;
  68992. l.ly2 = l.y2 - dx;
  68993. l.rx1 = l.x2 - dy;
  68994. l.ry1 = l.y2 + dx;
  68995. }
  68996. subPath.add (l);
  68997. if (it.closesSubPath)
  68998. {
  68999. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle);
  69000. subPath.clearQuick();
  69001. }
  69002. else
  69003. {
  69004. l.x1 = it.x2;
  69005. l.y1 = it.y2;
  69006. }
  69007. }
  69008. }
  69009. if (subPath.size() > 0)
  69010. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  69011. }
  69012. void PathStrokeType::createDashedStroke (Path& destPath,
  69013. const Path& sourcePath,
  69014. const float* dashLengths,
  69015. int numDashLengths,
  69016. const AffineTransform& transform,
  69017. const float extraAccuracy) const throw()
  69018. {
  69019. if (thickness <= 0)
  69020. return;
  69021. // this should really be an even number..
  69022. jassert ((numDashLengths & 1) == 0);
  69023. Path newDestPath;
  69024. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  69025. bool first = true;
  69026. int dashNum = 0;
  69027. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  69028. float dx = 0.0f, dy = 0.0f;
  69029. for (;;)
  69030. {
  69031. const bool isSolid = ((dashNum & 1) == 0);
  69032. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  69033. jassert (dashLen > 0); // must be a positive increment!
  69034. if (dashLen <= 0)
  69035. break;
  69036. pos += dashLen;
  69037. while (pos > lineEndPos)
  69038. {
  69039. if (! it.next())
  69040. {
  69041. if (isSolid && ! first)
  69042. newDestPath.lineTo (it.x2, it.y2);
  69043. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  69044. return;
  69045. }
  69046. if (isSolid && ! first)
  69047. {
  69048. newDestPath.lineTo (it.x1, it.y1);
  69049. }
  69050. else
  69051. {
  69052. newDestPath.startNewSubPath (it.x1, it.y1);
  69053. first = false;
  69054. }
  69055. dx = it.x2 - it.x1;
  69056. dy = it.y2 - it.y1;
  69057. lineLen = juce_hypotf (dx, dy);
  69058. lineEndPos += lineLen;
  69059. }
  69060. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  69061. if (isSolid)
  69062. newDestPath.lineTo (it.x1 + dx * alpha,
  69063. it.y1 + dy * alpha);
  69064. else
  69065. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  69066. it.y1 + dy * alpha);
  69067. }
  69068. }
  69069. END_JUCE_NAMESPACE
  69070. /********* End of inlined file: juce_PathStrokeType.cpp *********/
  69071. /********* Start of inlined file: juce_Point.cpp *********/
  69072. BEGIN_JUCE_NAMESPACE
  69073. Point::Point() throw()
  69074. : x (0.0f),
  69075. y (0.0f)
  69076. {
  69077. }
  69078. Point::Point (const Point& other) throw()
  69079. : x (other.x),
  69080. y (other.y)
  69081. {
  69082. }
  69083. const Point& Point::operator= (const Point& other) throw()
  69084. {
  69085. x = other.x;
  69086. y = other.y;
  69087. return *this;
  69088. }
  69089. Point::Point (const float x_,
  69090. const float y_) throw()
  69091. : x (x_),
  69092. y (y_)
  69093. {
  69094. }
  69095. Point::~Point() throw()
  69096. {
  69097. }
  69098. void Point::setXY (const float x_,
  69099. const float y_) throw()
  69100. {
  69101. x = x_;
  69102. y = y_;
  69103. }
  69104. void Point::applyTransform (const AffineTransform& transform) throw()
  69105. {
  69106. transform.transformPoint (x, y);
  69107. }
  69108. END_JUCE_NAMESPACE
  69109. /********* End of inlined file: juce_Point.cpp *********/
  69110. /********* Start of inlined file: juce_PositionedRectangle.cpp *********/
  69111. BEGIN_JUCE_NAMESPACE
  69112. PositionedRectangle::PositionedRectangle() throw()
  69113. : x (0.0),
  69114. y (0.0),
  69115. w (0.0),
  69116. h (0.0),
  69117. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  69118. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  69119. wMode (absoluteSize),
  69120. hMode (absoluteSize)
  69121. {
  69122. }
  69123. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  69124. : x (other.x),
  69125. y (other.y),
  69126. w (other.w),
  69127. h (other.h),
  69128. xMode (other.xMode),
  69129. yMode (other.yMode),
  69130. wMode (other.wMode),
  69131. hMode (other.hMode)
  69132. {
  69133. }
  69134. const PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  69135. {
  69136. if (this != &other)
  69137. {
  69138. x = other.x;
  69139. y = other.y;
  69140. w = other.w;
  69141. h = other.h;
  69142. xMode = other.xMode;
  69143. yMode = other.yMode;
  69144. wMode = other.wMode;
  69145. hMode = other.hMode;
  69146. }
  69147. return *this;
  69148. }
  69149. PositionedRectangle::~PositionedRectangle() throw()
  69150. {
  69151. }
  69152. const bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  69153. {
  69154. return x == other.x
  69155. && y == other.y
  69156. && w == other.w
  69157. && h == other.h
  69158. && xMode == other.xMode
  69159. && yMode == other.yMode
  69160. && wMode == other.wMode
  69161. && hMode == other.hMode;
  69162. }
  69163. const bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  69164. {
  69165. return ! operator== (other);
  69166. }
  69167. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  69168. {
  69169. StringArray tokens;
  69170. tokens.addTokens (stringVersion, false);
  69171. decodePosString (tokens [0], xMode, x);
  69172. decodePosString (tokens [1], yMode, y);
  69173. decodeSizeString (tokens [2], wMode, w);
  69174. decodeSizeString (tokens [3], hMode, h);
  69175. }
  69176. const String PositionedRectangle::toString() const throw()
  69177. {
  69178. String s;
  69179. s.preallocateStorage (12);
  69180. addPosDescription (s, xMode, x);
  69181. s << T(' ');
  69182. addPosDescription (s, yMode, y);
  69183. s << T(' ');
  69184. addSizeDescription (s, wMode, w);
  69185. s << T(' ');
  69186. addSizeDescription (s, hMode, h);
  69187. return s;
  69188. }
  69189. const Rectangle PositionedRectangle::getRectangle (const Rectangle& target) const throw()
  69190. {
  69191. jassert (! target.isEmpty());
  69192. double x_, y_, w_, h_;
  69193. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  69194. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  69195. return Rectangle (roundDoubleToInt (x_), roundDoubleToInt (y_),
  69196. roundDoubleToInt (w_), roundDoubleToInt (h_));
  69197. }
  69198. void PositionedRectangle::getRectangleDouble (const Rectangle& target,
  69199. double& x_, double& y_,
  69200. double& w_, double& h_) const throw()
  69201. {
  69202. jassert (! target.isEmpty());
  69203. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  69204. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  69205. }
  69206. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  69207. {
  69208. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  69209. }
  69210. void PositionedRectangle::updateFrom (const Rectangle& rectangle,
  69211. const Rectangle& target) throw()
  69212. {
  69213. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  69214. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  69215. }
  69216. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  69217. const double newW, const double newH,
  69218. const Rectangle& target) throw()
  69219. {
  69220. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  69221. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  69222. }
  69223. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  69224. {
  69225. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  69226. updateFrom (comp.getBounds(), Rectangle());
  69227. else
  69228. updateFrom (comp.getBounds(), Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  69229. }
  69230. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  69231. {
  69232. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  69233. }
  69234. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  69235. {
  69236. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  69237. | absoluteFromParentBottomRight
  69238. | absoluteFromParentCentre
  69239. | proportionOfParentSize));
  69240. }
  69241. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  69242. {
  69243. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  69244. }
  69245. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  69246. {
  69247. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  69248. | absoluteFromParentBottomRight
  69249. | absoluteFromParentCentre
  69250. | proportionOfParentSize));
  69251. }
  69252. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  69253. {
  69254. return (SizeMode) wMode;
  69255. }
  69256. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  69257. {
  69258. return (SizeMode) hMode;
  69259. }
  69260. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  69261. const PositionMode xMode_,
  69262. const AnchorPoint yAnchor,
  69263. const PositionMode yMode_,
  69264. const SizeMode widthMode,
  69265. const SizeMode heightMode,
  69266. const Rectangle& target) throw()
  69267. {
  69268. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  69269. {
  69270. double tx, tw;
  69271. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  69272. xMode = (uint8) (xAnchor | xMode_);
  69273. wMode = (uint8) widthMode;
  69274. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  69275. }
  69276. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  69277. {
  69278. double ty, th;
  69279. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  69280. yMode = (uint8) (yAnchor | yMode_);
  69281. hMode = (uint8) heightMode;
  69282. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  69283. }
  69284. }
  69285. bool PositionedRectangle::isPositionAbsolute() const throw()
  69286. {
  69287. return xMode == absoluteFromParentTopLeft
  69288. && yMode == absoluteFromParentTopLeft
  69289. && wMode == absoluteSize
  69290. && hMode == absoluteSize;
  69291. }
  69292. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  69293. {
  69294. if ((mode & proportionOfParentSize) != 0)
  69295. {
  69296. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  69297. }
  69298. else
  69299. {
  69300. s << (roundDoubleToInt (value * 100.0) / 100.0);
  69301. if ((mode & absoluteFromParentBottomRight) != 0)
  69302. s << T('R');
  69303. else if ((mode & absoluteFromParentCentre) != 0)
  69304. s << T('C');
  69305. }
  69306. if ((mode & anchorAtRightOrBottom) != 0)
  69307. s << T('r');
  69308. else if ((mode & anchorAtCentre) != 0)
  69309. s << T('c');
  69310. }
  69311. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  69312. {
  69313. if (mode == proportionalSize)
  69314. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  69315. else if (mode == parentSizeMinusAbsolute)
  69316. s << (roundDoubleToInt (value * 100.0) / 100.0) << T('M');
  69317. else
  69318. s << (roundDoubleToInt (value * 100.0) / 100.0);
  69319. }
  69320. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  69321. {
  69322. if (s.containsChar (T('r')))
  69323. mode = anchorAtRightOrBottom;
  69324. else if (s.containsChar (T('c')))
  69325. mode = anchorAtCentre;
  69326. else
  69327. mode = anchorAtLeftOrTop;
  69328. if (s.containsChar (T('%')))
  69329. {
  69330. mode |= proportionOfParentSize;
  69331. value = s.removeCharacters (T("%rcRC")).getDoubleValue() / 100.0;
  69332. }
  69333. else
  69334. {
  69335. if (s.containsChar (T('R')))
  69336. mode |= absoluteFromParentBottomRight;
  69337. else if (s.containsChar (T('C')))
  69338. mode |= absoluteFromParentCentre;
  69339. else
  69340. mode |= absoluteFromParentTopLeft;
  69341. value = s.removeCharacters (T("rcRC")).getDoubleValue();
  69342. }
  69343. }
  69344. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  69345. {
  69346. if (s.containsChar (T('%')))
  69347. {
  69348. mode = proportionalSize;
  69349. value = s.upToFirstOccurrenceOf (T("%"), false, false).getDoubleValue() / 100.0;
  69350. }
  69351. else if (s.containsChar (T('M')))
  69352. {
  69353. mode = parentSizeMinusAbsolute;
  69354. value = s.getDoubleValue();
  69355. }
  69356. else
  69357. {
  69358. mode = absoluteSize;
  69359. value = s.getDoubleValue();
  69360. }
  69361. }
  69362. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  69363. const double x, const double w,
  69364. const uint8 xMode, const uint8 wMode,
  69365. const int parentPos,
  69366. const int parentSize) const throw()
  69367. {
  69368. if (wMode == proportionalSize)
  69369. wOut = roundDoubleToInt (w * parentSize);
  69370. else if (wMode == parentSizeMinusAbsolute)
  69371. wOut = jmax (0, parentSize - roundDoubleToInt (w));
  69372. else
  69373. wOut = roundDoubleToInt (w);
  69374. if ((xMode & proportionOfParentSize) != 0)
  69375. xOut = parentPos + x * parentSize;
  69376. else if ((xMode & absoluteFromParentBottomRight) != 0)
  69377. xOut = (parentPos + parentSize) - x;
  69378. else if ((xMode & absoluteFromParentCentre) != 0)
  69379. xOut = x + (parentPos + parentSize / 2);
  69380. else
  69381. xOut = x + parentPos;
  69382. if ((xMode & anchorAtRightOrBottom) != 0)
  69383. xOut -= wOut;
  69384. else if ((xMode & anchorAtCentre) != 0)
  69385. xOut -= wOut / 2;
  69386. }
  69387. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  69388. double x, const double w,
  69389. const uint8 xMode, const uint8 wMode,
  69390. const int parentPos,
  69391. const int parentSize) const throw()
  69392. {
  69393. if (wMode == proportionalSize)
  69394. {
  69395. if (parentSize > 0)
  69396. wOut = w / parentSize;
  69397. }
  69398. else if (wMode == parentSizeMinusAbsolute)
  69399. wOut = parentSize - w;
  69400. else
  69401. wOut = w;
  69402. if ((xMode & anchorAtRightOrBottom) != 0)
  69403. x += w;
  69404. else if ((xMode & anchorAtCentre) != 0)
  69405. x += w / 2;
  69406. if ((xMode & proportionOfParentSize) != 0)
  69407. {
  69408. if (parentSize > 0)
  69409. xOut = (x - parentPos) / parentSize;
  69410. }
  69411. else if ((xMode & absoluteFromParentBottomRight) != 0)
  69412. xOut = (parentPos + parentSize) - x;
  69413. else if ((xMode & absoluteFromParentCentre) != 0)
  69414. xOut = x - (parentPos + parentSize / 2);
  69415. else
  69416. xOut = x - parentPos;
  69417. }
  69418. END_JUCE_NAMESPACE
  69419. /********* End of inlined file: juce_PositionedRectangle.cpp *********/
  69420. /********* Start of inlined file: juce_Rectangle.cpp *********/
  69421. BEGIN_JUCE_NAMESPACE
  69422. Rectangle::Rectangle() throw()
  69423. : x (0),
  69424. y (0),
  69425. w (0),
  69426. h (0)
  69427. {
  69428. }
  69429. Rectangle::Rectangle (const int x_, const int y_,
  69430. const int w_, const int h_) throw()
  69431. : x (x_),
  69432. y (y_),
  69433. w (w_),
  69434. h (h_)
  69435. {
  69436. }
  69437. Rectangle::Rectangle (const int w_, const int h_) throw()
  69438. : x (0),
  69439. y (0),
  69440. w (w_),
  69441. h (h_)
  69442. {
  69443. }
  69444. Rectangle::Rectangle (const Rectangle& other) throw()
  69445. : x (other.x),
  69446. y (other.y),
  69447. w (other.w),
  69448. h (other.h)
  69449. {
  69450. }
  69451. Rectangle::~Rectangle() throw()
  69452. {
  69453. }
  69454. bool Rectangle::isEmpty() const throw()
  69455. {
  69456. return w <= 0 || h <= 0;
  69457. }
  69458. void Rectangle::setBounds (const int x_,
  69459. const int y_,
  69460. const int w_,
  69461. const int h_) throw()
  69462. {
  69463. x = x_;
  69464. y = y_;
  69465. w = w_;
  69466. h = h_;
  69467. }
  69468. void Rectangle::setPosition (const int x_,
  69469. const int y_) throw()
  69470. {
  69471. x = x_;
  69472. y = y_;
  69473. }
  69474. void Rectangle::setSize (const int w_,
  69475. const int h_) throw()
  69476. {
  69477. w = w_;
  69478. h = h_;
  69479. }
  69480. void Rectangle::translate (const int dx,
  69481. const int dy) throw()
  69482. {
  69483. x += dx;
  69484. y += dy;
  69485. }
  69486. const Rectangle Rectangle::translated (const int dx,
  69487. const int dy) const throw()
  69488. {
  69489. return Rectangle (x + dx, y + dy, w, h);
  69490. }
  69491. void Rectangle::expand (const int deltaX,
  69492. const int deltaY) throw()
  69493. {
  69494. const int nw = jmax (0, w + deltaX + deltaX);
  69495. const int nh = jmax (0, h + deltaY + deltaY);
  69496. setBounds (x - deltaX,
  69497. y - deltaY,
  69498. nw, nh);
  69499. }
  69500. const Rectangle Rectangle::expanded (const int deltaX,
  69501. const int deltaY) const throw()
  69502. {
  69503. const int nw = jmax (0, w + deltaX + deltaX);
  69504. const int nh = jmax (0, h + deltaY + deltaY);
  69505. return Rectangle (x - deltaX,
  69506. y - deltaY,
  69507. nw, nh);
  69508. }
  69509. void Rectangle::reduce (const int deltaX,
  69510. const int deltaY) throw()
  69511. {
  69512. expand (-deltaX, -deltaY);
  69513. }
  69514. const Rectangle Rectangle::reduced (const int deltaX,
  69515. const int deltaY) const throw()
  69516. {
  69517. return expanded (-deltaX, -deltaY);
  69518. }
  69519. bool Rectangle::operator== (const Rectangle& other) const throw()
  69520. {
  69521. return x == other.x
  69522. && y == other.y
  69523. && w == other.w
  69524. && h == other.h;
  69525. }
  69526. bool Rectangle::operator!= (const Rectangle& other) const throw()
  69527. {
  69528. return x != other.x
  69529. || y != other.y
  69530. || w != other.w
  69531. || h != other.h;
  69532. }
  69533. bool Rectangle::contains (const int px,
  69534. const int py) const throw()
  69535. {
  69536. return px >= x
  69537. && py >= y
  69538. && px < x + w
  69539. && py < y + h;
  69540. }
  69541. bool Rectangle::contains (const Rectangle& other) const throw()
  69542. {
  69543. return x <= other.x
  69544. && y <= other.y
  69545. && x + w >= other.x + other.w
  69546. && y + h >= other.y + other.h;
  69547. }
  69548. bool Rectangle::intersects (const Rectangle& other) const throw()
  69549. {
  69550. return x + w > other.x
  69551. && y + h > other.y
  69552. && x < other.x + other.w
  69553. && y < other.y + other.h
  69554. && w > 0
  69555. && h > 0;
  69556. }
  69557. const Rectangle Rectangle::getIntersection (const Rectangle& other) const throw()
  69558. {
  69559. const int nx = jmax (x, other.x);
  69560. const int ny = jmax (y, other.y);
  69561. const int nw = jmin (x + w, other.x + other.w) - nx;
  69562. const int nh = jmin (y + h, other.y + other.h) - ny;
  69563. if (nw >= 0 && nh >= 0)
  69564. return Rectangle (nx, ny, nw, nh);
  69565. else
  69566. return Rectangle();
  69567. }
  69568. bool Rectangle::intersectRectangle (int& x1, int& y1, int& w1, int& h1) const throw()
  69569. {
  69570. const int maxX = jmax (x1, x);
  69571. w1 = jmin (x1 + w1, x + w) - maxX;
  69572. if (w1 > 0)
  69573. {
  69574. const int maxY = jmax (y1, y);
  69575. h1 = jmin (y1 + h1, y + h) - maxY;
  69576. if (h1 > 0)
  69577. {
  69578. x1 = maxX;
  69579. y1 = maxY;
  69580. return true;
  69581. }
  69582. }
  69583. return false;
  69584. }
  69585. bool Rectangle::intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  69586. int x2, int y2, int w2, int h2) throw()
  69587. {
  69588. const int x = jmax (x1, x2);
  69589. w1 = jmin (x1 + w1, x2 + w2) - x;
  69590. if (w1 > 0)
  69591. {
  69592. const int y = jmax (y1, y2);
  69593. h1 = jmin (y1 + h1, y2 + h2) - y;
  69594. if (h1 > 0)
  69595. {
  69596. x1 = x;
  69597. y1 = y;
  69598. return true;
  69599. }
  69600. }
  69601. return false;
  69602. }
  69603. const Rectangle Rectangle::getUnion (const Rectangle& other) const throw()
  69604. {
  69605. const int newX = jmin (x, other.x);
  69606. const int newY = jmin (y, other.y);
  69607. return Rectangle (newX, newY,
  69608. jmax (x + w, other.x + other.w) - newX,
  69609. jmax (y + h, other.y + other.h) - newY);
  69610. }
  69611. bool Rectangle::enlargeIfAdjacent (const Rectangle& other) throw()
  69612. {
  69613. if (x == other.x && getRight() == other.getRight()
  69614. && (other.getBottom() >= y && other.y <= getBottom()))
  69615. {
  69616. const int newY = jmin (y, other.y);
  69617. h = jmax (getBottom(), other.getBottom()) - newY;
  69618. y = newY;
  69619. return true;
  69620. }
  69621. else if (y == other.y && getBottom() == other.getBottom()
  69622. && (other.getRight() >= x && other.x <= getRight()))
  69623. {
  69624. const int newX = jmin (x, other.x);
  69625. w = jmax (getRight(), other.getRight()) - newX;
  69626. x = newX;
  69627. return true;
  69628. }
  69629. return false;
  69630. }
  69631. bool Rectangle::reduceIfPartlyContainedIn (const Rectangle& other) throw()
  69632. {
  69633. int inside = 0;
  69634. const int otherR = other.getRight();
  69635. if (x >= other.x && x < otherR)
  69636. inside = 1;
  69637. const int otherB = other.getBottom();
  69638. if (y >= other.y && y < otherB)
  69639. inside |= 2;
  69640. const int r = x + w;
  69641. if (r >= other.x && r < otherR)
  69642. inside |= 4;
  69643. const int b = y + h;
  69644. if (b >= other.y && b < otherB)
  69645. inside |= 8;
  69646. switch (inside)
  69647. {
  69648. case 1 + 2 + 8:
  69649. w = r - otherR;
  69650. x = otherR;
  69651. return true;
  69652. case 1 + 2 + 4:
  69653. h = b - otherB;
  69654. y = otherB;
  69655. return true;
  69656. case 2 + 4 + 8:
  69657. w = other.x - x;
  69658. return true;
  69659. case 1 + 4 + 8:
  69660. h = other.y - y;
  69661. return true;
  69662. }
  69663. return false;
  69664. }
  69665. const String Rectangle::toString() const throw()
  69666. {
  69667. String s;
  69668. s.preallocateStorage (16);
  69669. s << x << T(' ')
  69670. << y << T(' ')
  69671. << w << T(' ')
  69672. << h;
  69673. return s;
  69674. }
  69675. const Rectangle Rectangle::fromString (const String& stringVersion)
  69676. {
  69677. StringArray toks;
  69678. toks.addTokens (stringVersion.trim(), T(",; \t\r\n"), 0);
  69679. return Rectangle (toks[0].trim().getIntValue(),
  69680. toks[1].trim().getIntValue(),
  69681. toks[2].trim().getIntValue(),
  69682. toks[3].trim().getIntValue());
  69683. }
  69684. END_JUCE_NAMESPACE
  69685. /********* End of inlined file: juce_Rectangle.cpp *********/
  69686. /********* Start of inlined file: juce_RectangleList.cpp *********/
  69687. BEGIN_JUCE_NAMESPACE
  69688. RectangleList::RectangleList() throw()
  69689. {
  69690. }
  69691. RectangleList::RectangleList (const Rectangle& rect) throw()
  69692. {
  69693. if (! rect.isEmpty())
  69694. rects.add (rect);
  69695. }
  69696. RectangleList::RectangleList (const RectangleList& other) throw()
  69697. : rects (other.rects)
  69698. {
  69699. }
  69700. const RectangleList& RectangleList::operator= (const RectangleList& other) throw()
  69701. {
  69702. if (this != &other)
  69703. rects = other.rects;
  69704. return *this;
  69705. }
  69706. RectangleList::~RectangleList() throw()
  69707. {
  69708. }
  69709. void RectangleList::clear() throw()
  69710. {
  69711. rects.clearQuick();
  69712. }
  69713. const Rectangle RectangleList::getRectangle (const int index) const throw()
  69714. {
  69715. if (((unsigned int) index) < (unsigned int) rects.size())
  69716. return rects.getReference (index);
  69717. return Rectangle();
  69718. }
  69719. bool RectangleList::isEmpty() const throw()
  69720. {
  69721. return rects.size() == 0;
  69722. }
  69723. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  69724. : current (0),
  69725. owner (list),
  69726. index (list.rects.size())
  69727. {
  69728. }
  69729. RectangleList::Iterator::~Iterator() throw()
  69730. {
  69731. }
  69732. bool RectangleList::Iterator::next() throw()
  69733. {
  69734. if (--index >= 0)
  69735. {
  69736. current = & (owner.rects.getReference (index));
  69737. return true;
  69738. }
  69739. return false;
  69740. }
  69741. void RectangleList::add (const Rectangle& rect) throw()
  69742. {
  69743. if (! rect.isEmpty())
  69744. {
  69745. if (rects.size() == 0)
  69746. {
  69747. rects.add (rect);
  69748. }
  69749. else
  69750. {
  69751. bool anyOverlaps = false;
  69752. int i;
  69753. for (i = rects.size(); --i >= 0;)
  69754. {
  69755. Rectangle& ourRect = rects.getReference (i);
  69756. if (rect.intersects (ourRect))
  69757. {
  69758. if (rect.contains (ourRect))
  69759. rects.remove (i);
  69760. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  69761. anyOverlaps = true;
  69762. }
  69763. }
  69764. if (anyOverlaps && rects.size() > 0)
  69765. {
  69766. RectangleList r (rect);
  69767. for (i = rects.size(); --i >= 0;)
  69768. {
  69769. const Rectangle& ourRect = rects.getReference (i);
  69770. if (rect.intersects (ourRect))
  69771. {
  69772. r.subtract (ourRect);
  69773. if (r.rects.size() == 0)
  69774. return;
  69775. }
  69776. }
  69777. for (i = r.getNumRectangles(); --i >= 0;)
  69778. rects.add (r.rects.getReference (i));
  69779. }
  69780. else
  69781. {
  69782. rects.add (rect);
  69783. }
  69784. }
  69785. }
  69786. }
  69787. void RectangleList::addWithoutMerging (const Rectangle& rect) throw()
  69788. {
  69789. rects.add (rect);
  69790. }
  69791. void RectangleList::add (const int x, const int y, const int w, const int h) throw()
  69792. {
  69793. if (rects.size() == 0)
  69794. {
  69795. if (w > 0 && h > 0)
  69796. rects.add (Rectangle (x, y, w, h));
  69797. }
  69798. else
  69799. {
  69800. add (Rectangle (x, y, w, h));
  69801. }
  69802. }
  69803. void RectangleList::add (const RectangleList& other) throw()
  69804. {
  69805. for (int i = 0; i < other.rects.size(); ++i)
  69806. add (other.rects.getReference (i));
  69807. }
  69808. void RectangleList::subtract (const Rectangle& rect) throw()
  69809. {
  69810. const int originalNumRects = rects.size();
  69811. if (originalNumRects > 0)
  69812. {
  69813. const int x1 = rect.x;
  69814. const int y1 = rect.y;
  69815. const int x2 = x1 + rect.w;
  69816. const int y2 = y1 + rect.h;
  69817. for (int i = getNumRectangles(); --i >= 0;)
  69818. {
  69819. Rectangle& r = rects.getReference (i);
  69820. const int rx1 = r.x;
  69821. const int ry1 = r.y;
  69822. const int rx2 = rx1 + r.w;
  69823. const int ry2 = ry1 + r.h;
  69824. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  69825. {
  69826. if (x1 > rx1 && x1 < rx2)
  69827. {
  69828. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  69829. {
  69830. r.w = x1 - rx1;
  69831. }
  69832. else
  69833. {
  69834. r.x = x1;
  69835. r.w = rx2 - x1;
  69836. rects.insert (i + 1, Rectangle (rx1, ry1, x1 - rx1, ry2 - ry1));
  69837. i += 2;
  69838. }
  69839. }
  69840. else if (x2 > rx1 && x2 < rx2)
  69841. {
  69842. r.x = x2;
  69843. r.w = rx2 - x2;
  69844. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  69845. {
  69846. rects.insert (i + 1, Rectangle (rx1, ry1, x2 - rx1, ry2 - ry1));
  69847. i += 2;
  69848. }
  69849. }
  69850. else if (y1 > ry1 && y1 < ry2)
  69851. {
  69852. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  69853. {
  69854. r.h = y1 - ry1;
  69855. }
  69856. else
  69857. {
  69858. r.y = y1;
  69859. r.h = ry2 - y1;
  69860. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y1 - ry1));
  69861. i += 2;
  69862. }
  69863. }
  69864. else if (y2 > ry1 && y2 < ry2)
  69865. {
  69866. r.y = y2;
  69867. r.h = ry2 - y2;
  69868. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  69869. {
  69870. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y2 - ry1));
  69871. i += 2;
  69872. }
  69873. }
  69874. else
  69875. {
  69876. rects.remove (i);
  69877. }
  69878. }
  69879. }
  69880. if (rects.size() > originalNumRects + 10)
  69881. consolidate();
  69882. }
  69883. }
  69884. void RectangleList::subtract (const RectangleList& otherList) throw()
  69885. {
  69886. for (int i = otherList.rects.size(); --i >= 0;)
  69887. subtract (otherList.rects.getReference (i));
  69888. }
  69889. bool RectangleList::clipTo (const Rectangle& rect) throw()
  69890. {
  69891. bool notEmpty = false;
  69892. if (rect.isEmpty())
  69893. {
  69894. clear();
  69895. }
  69896. else
  69897. {
  69898. for (int i = rects.size(); --i >= 0;)
  69899. {
  69900. Rectangle& r = rects.getReference (i);
  69901. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  69902. rects.remove (i);
  69903. else
  69904. notEmpty = true;
  69905. }
  69906. }
  69907. return notEmpty;
  69908. }
  69909. bool RectangleList::clipTo (const RectangleList& other) throw()
  69910. {
  69911. if (rects.size() == 0)
  69912. return false;
  69913. RectangleList result;
  69914. for (int j = 0; j < rects.size(); ++j)
  69915. {
  69916. const Rectangle& rect = rects.getReference (j);
  69917. for (int i = other.rects.size(); --i >= 0;)
  69918. {
  69919. Rectangle r (other.rects.getReference (i));
  69920. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  69921. result.rects.add (r);
  69922. }
  69923. }
  69924. swapWith (result);
  69925. return ! isEmpty();
  69926. }
  69927. bool RectangleList::getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw()
  69928. {
  69929. destRegion.clear();
  69930. if (! rect.isEmpty())
  69931. {
  69932. for (int i = rects.size(); --i >= 0;)
  69933. {
  69934. Rectangle r (rects.getReference (i));
  69935. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  69936. destRegion.rects.add (r);
  69937. }
  69938. }
  69939. return destRegion.rects.size() > 0;
  69940. }
  69941. void RectangleList::swapWith (RectangleList& otherList) throw()
  69942. {
  69943. rects.swapWithArray (otherList.rects);
  69944. }
  69945. void RectangleList::consolidate() throw()
  69946. {
  69947. int i;
  69948. for (i = 0; i < getNumRectangles() - 1; ++i)
  69949. {
  69950. Rectangle& r = rects.getReference (i);
  69951. const int rx1 = r.x;
  69952. const int ry1 = r.y;
  69953. const int rx2 = rx1 + r.w;
  69954. const int ry2 = ry1 + r.h;
  69955. for (int j = rects.size(); --j > i;)
  69956. {
  69957. Rectangle& r2 = rects.getReference (j);
  69958. const int jrx1 = r2.x;
  69959. const int jry1 = r2.y;
  69960. const int jrx2 = jrx1 + r2.w;
  69961. const int jry2 = jry1 + r2.h;
  69962. // if the vertical edges of any blocks are touching and their horizontals don't
  69963. // line up, split them horizontally..
  69964. if (jrx1 == rx2 || jrx2 == rx1)
  69965. {
  69966. if (jry1 > ry1 && jry1 < ry2)
  69967. {
  69968. r.h = jry1 - ry1;
  69969. rects.add (Rectangle (rx1, jry1, rx2 - rx1, ry2 - jry1));
  69970. i = -1;
  69971. break;
  69972. }
  69973. if (jry2 > ry1 && jry2 < ry2)
  69974. {
  69975. r.h = jry2 - ry1;
  69976. rects.add (Rectangle (rx1, jry2, rx2 - rx1, ry2 - jry2));
  69977. i = -1;
  69978. break;
  69979. }
  69980. else if (ry1 > jry1 && ry1 < jry2)
  69981. {
  69982. r2.h = ry1 - jry1;
  69983. rects.add (Rectangle (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  69984. i = -1;
  69985. break;
  69986. }
  69987. else if (ry2 > jry1 && ry2 < jry2)
  69988. {
  69989. r2.h = ry2 - jry1;
  69990. rects.add (Rectangle (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  69991. i = -1;
  69992. break;
  69993. }
  69994. }
  69995. }
  69996. }
  69997. for (i = 0; i < rects.size() - 1; ++i)
  69998. {
  69999. Rectangle& r = rects.getReference (i);
  70000. for (int j = rects.size(); --j > i;)
  70001. {
  70002. if (r.enlargeIfAdjacent (rects.getReference (j)))
  70003. {
  70004. rects.remove (j);
  70005. i = -1;
  70006. break;
  70007. }
  70008. }
  70009. }
  70010. }
  70011. bool RectangleList::containsPoint (const int x, const int y) const throw()
  70012. {
  70013. for (int i = getNumRectangles(); --i >= 0;)
  70014. if (rects.getReference (i).contains (x, y))
  70015. return true;
  70016. return false;
  70017. }
  70018. bool RectangleList::containsRectangle (const Rectangle& rectangleToCheck) const throw()
  70019. {
  70020. if (rects.size() > 1)
  70021. {
  70022. RectangleList r (rectangleToCheck);
  70023. for (int i = rects.size(); --i >= 0;)
  70024. {
  70025. r.subtract (rects.getReference (i));
  70026. if (r.rects.size() == 0)
  70027. return true;
  70028. }
  70029. }
  70030. else if (rects.size() > 0)
  70031. {
  70032. return rects.getReference (0).contains (rectangleToCheck);
  70033. }
  70034. return false;
  70035. }
  70036. bool RectangleList::intersectsRectangle (const Rectangle& rectangleToCheck) const throw()
  70037. {
  70038. for (int i = rects.size(); --i >= 0;)
  70039. if (rects.getReference (i).intersects (rectangleToCheck))
  70040. return true;
  70041. return false;
  70042. }
  70043. bool RectangleList::intersects (const RectangleList& other) const throw()
  70044. {
  70045. for (int i = rects.size(); --i >= 0;)
  70046. if (other.intersectsRectangle (rects.getReference (i)))
  70047. return true;
  70048. return false;
  70049. }
  70050. const Rectangle RectangleList::getBounds() const throw()
  70051. {
  70052. if (rects.size() <= 1)
  70053. {
  70054. if (rects.size() == 0)
  70055. return Rectangle();
  70056. else
  70057. return rects.getReference (0);
  70058. }
  70059. else
  70060. {
  70061. const Rectangle& r = rects.getReference (0);
  70062. int minX = r.x;
  70063. int minY = r.y;
  70064. int maxX = minX + r.w;
  70065. int maxY = minY + r.h;
  70066. for (int i = rects.size(); --i > 0;)
  70067. {
  70068. const Rectangle& r2 = rects.getReference (i);
  70069. minX = jmin (minX, r2.x);
  70070. minY = jmin (minY, r2.y);
  70071. maxX = jmax (maxX, r2.getRight());
  70072. maxY = jmax (maxY, r2.getBottom());
  70073. }
  70074. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  70075. }
  70076. }
  70077. void RectangleList::offsetAll (const int dx, const int dy) throw()
  70078. {
  70079. for (int i = rects.size(); --i >= 0;)
  70080. {
  70081. Rectangle& r = rects.getReference (i);
  70082. r.x += dx;
  70083. r.y += dy;
  70084. }
  70085. }
  70086. const Path RectangleList::toPath() const throw()
  70087. {
  70088. Path p;
  70089. for (int i = rects.size(); --i >= 0;)
  70090. {
  70091. const Rectangle& r = rects.getReference (i);
  70092. p.addRectangle ((float) r.x,
  70093. (float) r.y,
  70094. (float) r.w,
  70095. (float) r.h);
  70096. }
  70097. return p;
  70098. }
  70099. END_JUCE_NAMESPACE
  70100. /********* End of inlined file: juce_RectangleList.cpp *********/
  70101. /********* Start of inlined file: juce_Image.cpp *********/
  70102. BEGIN_JUCE_NAMESPACE
  70103. static const int fullAlphaThreshold = 253;
  70104. Image::Image (const PixelFormat format_,
  70105. const int imageWidth_,
  70106. const int imageHeight_)
  70107. : format (format_),
  70108. imageWidth (imageWidth_),
  70109. imageHeight (imageHeight_),
  70110. imageData (0)
  70111. {
  70112. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  70113. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  70114. // actual image will be at least 1x1.
  70115. }
  70116. Image::Image (const PixelFormat format_,
  70117. const int imageWidth_,
  70118. const int imageHeight_,
  70119. const bool clearImage)
  70120. : format (format_),
  70121. imageWidth (imageWidth_),
  70122. imageHeight (imageHeight_)
  70123. {
  70124. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  70125. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  70126. // actual image will be at least 1x1.
  70127. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  70128. lineStride = (pixelStride * jmax (1, imageWidth_) + 3) & ~3;
  70129. const int dataSize = lineStride * jmax (1, imageHeight_);
  70130. imageData = (uint8*) (clearImage ? juce_calloc (dataSize)
  70131. : juce_malloc (dataSize));
  70132. }
  70133. Image::Image (const Image& other)
  70134. : format (other.format),
  70135. imageWidth (other.imageWidth),
  70136. imageHeight (other.imageHeight)
  70137. {
  70138. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  70139. lineStride = (pixelStride * jmax (1, imageWidth) + 3) & ~3;
  70140. const int dataSize = lineStride * jmax (1, imageHeight);
  70141. imageData = (uint8*) juce_malloc (dataSize);
  70142. int ls, ps;
  70143. const uint8* srcData = other.lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  70144. setPixelData (0, 0, imageWidth, imageHeight, srcData, ls);
  70145. other.releasePixelDataReadOnly (srcData);
  70146. }
  70147. Image::~Image()
  70148. {
  70149. juce_free (imageData);
  70150. }
  70151. LowLevelGraphicsContext* Image::createLowLevelContext()
  70152. {
  70153. return new LowLevelGraphicsSoftwareRenderer (*this);
  70154. }
  70155. uint8* Image::lockPixelDataReadWrite (int x, int y, int w, int h, int& ls, int& ps)
  70156. {
  70157. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  70158. w = w;
  70159. h = h;
  70160. ls = lineStride;
  70161. ps = pixelStride;
  70162. return imageData + x * pixelStride + y * lineStride;
  70163. }
  70164. void Image::releasePixelDataReadWrite (void*)
  70165. {
  70166. }
  70167. const uint8* Image::lockPixelDataReadOnly (int x, int y, int w, int h, int& ls, int& ps) const
  70168. {
  70169. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  70170. w = w;
  70171. h = h;
  70172. ls = lineStride;
  70173. ps = pixelStride;
  70174. return imageData + x * pixelStride + y * lineStride;
  70175. }
  70176. void Image::releasePixelDataReadOnly (const void*) const
  70177. {
  70178. }
  70179. void Image::setPixelData (int x, int y, int w, int h,
  70180. const uint8* sourcePixelData, int sourceLineStride)
  70181. {
  70182. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  70183. if (Rectangle::intersectRectangles (x, y, w, h, 0, 0, imageWidth, imageHeight))
  70184. {
  70185. int ls, ps;
  70186. uint8* dest = lockPixelDataReadWrite (x, y, w, h, ls, ps);
  70187. for (int i = 0; i < h; ++i)
  70188. {
  70189. memcpy (dest + ls * i,
  70190. sourcePixelData + sourceLineStride * i,
  70191. w * pixelStride);
  70192. }
  70193. releasePixelDataReadWrite (dest);
  70194. }
  70195. }
  70196. void Image::clear (int dx, int dy, int dw, int dh,
  70197. const Colour& colourToClearTo)
  70198. {
  70199. const PixelARGB col (colourToClearTo.getPixelARGB());
  70200. int ls, ps;
  70201. uint8* dstData = lockPixelDataReadWrite (dx, dy, dw, dh, ls, ps);
  70202. uint8* dest = dstData;
  70203. while (--dh >= 0)
  70204. {
  70205. uint8* line = dest;
  70206. dest += ls;
  70207. if (isARGB())
  70208. {
  70209. for (int x = dw; --x >= 0;)
  70210. {
  70211. ((PixelARGB*) line)->set (col);
  70212. line += ps;
  70213. }
  70214. }
  70215. else if (isRGB())
  70216. {
  70217. for (int x = dw; --x >= 0;)
  70218. {
  70219. ((PixelRGB*) line)->set (col);
  70220. line += ps;
  70221. }
  70222. }
  70223. else
  70224. {
  70225. for (int x = dw; --x >= 0;)
  70226. {
  70227. *line = col.getAlpha();
  70228. line += ps;
  70229. }
  70230. }
  70231. }
  70232. releasePixelDataReadWrite (dstData);
  70233. }
  70234. Image* Image::createCopy (int newWidth, int newHeight,
  70235. const Graphics::ResamplingQuality quality) const
  70236. {
  70237. if (newWidth < 0)
  70238. newWidth = imageWidth;
  70239. if (newHeight < 0)
  70240. newHeight = imageHeight;
  70241. Image* const newImage = new Image (format, newWidth, newHeight, true);
  70242. Graphics g (*newImage);
  70243. g.setImageResamplingQuality (quality);
  70244. g.drawImage (this,
  70245. 0, 0, newWidth, newHeight,
  70246. 0, 0, imageWidth, imageHeight,
  70247. false);
  70248. return newImage;
  70249. }
  70250. const Colour Image::getPixelAt (const int x, const int y) const
  70251. {
  70252. Colour c;
  70253. if (((unsigned int) x) < (unsigned int) imageWidth
  70254. && ((unsigned int) y) < (unsigned int) imageHeight)
  70255. {
  70256. int ls, ps;
  70257. const uint8* const pixels = lockPixelDataReadOnly (x, y, 1, 1, ls, ps);
  70258. if (isARGB())
  70259. {
  70260. PixelARGB p (*(const PixelARGB*) pixels);
  70261. p.unpremultiply();
  70262. c = Colour (p.getARGB());
  70263. }
  70264. else if (isRGB())
  70265. c = Colour (((const PixelRGB*) pixels)->getARGB());
  70266. else
  70267. c = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixels);
  70268. releasePixelDataReadOnly (pixels);
  70269. }
  70270. return c;
  70271. }
  70272. void Image::setPixelAt (const int x, const int y,
  70273. const Colour& colour)
  70274. {
  70275. if (((unsigned int) x) < (unsigned int) imageWidth
  70276. && ((unsigned int) y) < (unsigned int) imageHeight)
  70277. {
  70278. int ls, ps;
  70279. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  70280. const PixelARGB col (colour.getPixelARGB());
  70281. if (isARGB())
  70282. ((PixelARGB*) pixels)->set (col);
  70283. else if (isRGB())
  70284. ((PixelRGB*) pixels)->set (col);
  70285. else
  70286. *pixels = col.getAlpha();
  70287. releasePixelDataReadWrite (pixels);
  70288. }
  70289. }
  70290. void Image::multiplyAlphaAt (const int x, const int y,
  70291. const float multiplier)
  70292. {
  70293. if (((unsigned int) x) < (unsigned int) imageWidth
  70294. && ((unsigned int) y) < (unsigned int) imageHeight
  70295. && hasAlphaChannel())
  70296. {
  70297. int ls, ps;
  70298. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  70299. if (isARGB())
  70300. ((PixelARGB*) pixels)->multiplyAlpha (multiplier);
  70301. else
  70302. *pixels = (uint8) (*pixels * multiplier);
  70303. releasePixelDataReadWrite (pixels);
  70304. }
  70305. }
  70306. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  70307. {
  70308. if (hasAlphaChannel())
  70309. {
  70310. int ls, ps;
  70311. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  70312. if (isARGB())
  70313. {
  70314. for (int y = 0; y < imageHeight; ++y)
  70315. {
  70316. uint8* p = pixels + y * ls;
  70317. for (int x = 0; x < imageWidth; ++x)
  70318. {
  70319. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  70320. p += ps;
  70321. }
  70322. }
  70323. }
  70324. else
  70325. {
  70326. for (int y = 0; y < imageHeight; ++y)
  70327. {
  70328. uint8* p = pixels + y * ls;
  70329. for (int x = 0; x < imageWidth; ++x)
  70330. {
  70331. *p = (uint8) (*p * amountToMultiplyBy);
  70332. p += ps;
  70333. }
  70334. }
  70335. }
  70336. releasePixelDataReadWrite (pixels);
  70337. }
  70338. else
  70339. {
  70340. jassertfalse // can't do this without an alpha-channel!
  70341. }
  70342. }
  70343. void Image::desaturate()
  70344. {
  70345. if (isARGB() || isRGB())
  70346. {
  70347. int ls, ps;
  70348. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  70349. if (isARGB())
  70350. {
  70351. for (int y = 0; y < imageHeight; ++y)
  70352. {
  70353. uint8* p = pixels + y * ls;
  70354. for (int x = 0; x < imageWidth; ++x)
  70355. {
  70356. ((PixelARGB*) p)->desaturate();
  70357. p += ps;
  70358. }
  70359. }
  70360. }
  70361. else
  70362. {
  70363. for (int y = 0; y < imageHeight; ++y)
  70364. {
  70365. uint8* p = pixels + y * ls;
  70366. for (int x = 0; x < imageWidth; ++x)
  70367. {
  70368. ((PixelRGB*) p)->desaturate();
  70369. p += ps;
  70370. }
  70371. }
  70372. }
  70373. releasePixelDataReadWrite (pixels);
  70374. }
  70375. }
  70376. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  70377. {
  70378. if (hasAlphaChannel())
  70379. {
  70380. const uint8 threshold = (uint8) jlimit (0, 255, roundFloatToInt (alphaThreshold * 255.0f));
  70381. SparseSet <int> pixelsOnRow;
  70382. int ls, ps;
  70383. const uint8* const pixels = lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  70384. for (int y = 0; y < imageHeight; ++y)
  70385. {
  70386. pixelsOnRow.clear();
  70387. const uint8* lineData = pixels + ls * y;
  70388. if (isARGB())
  70389. {
  70390. for (int x = 0; x < imageWidth; ++x)
  70391. {
  70392. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  70393. pixelsOnRow.addRange (x, 1);
  70394. lineData += ps;
  70395. }
  70396. }
  70397. else
  70398. {
  70399. for (int x = 0; x < imageWidth; ++x)
  70400. {
  70401. if (*lineData >= threshold)
  70402. pixelsOnRow.addRange (x, 1);
  70403. lineData += ps;
  70404. }
  70405. }
  70406. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  70407. {
  70408. int x, w;
  70409. if (pixelsOnRow.getRange (i, x, w))
  70410. result.add (Rectangle (x, y, w, 1));
  70411. }
  70412. result.consolidate();
  70413. }
  70414. releasePixelDataReadOnly (pixels);
  70415. }
  70416. else
  70417. {
  70418. result.add (0, 0, imageWidth, imageHeight);
  70419. }
  70420. }
  70421. void Image::moveImageSection (int dx, int dy,
  70422. int sx, int sy,
  70423. int w, int h)
  70424. {
  70425. if (dx < 0)
  70426. {
  70427. w += dx;
  70428. sx -= dx;
  70429. dx = 0;
  70430. }
  70431. if (dy < 0)
  70432. {
  70433. h += dy;
  70434. sy -= dy;
  70435. dy = 0;
  70436. }
  70437. if (sx < 0)
  70438. {
  70439. w += sx;
  70440. dx -= sx;
  70441. sx = 0;
  70442. }
  70443. if (sy < 0)
  70444. {
  70445. h += sy;
  70446. dy -= sy;
  70447. sy = 0;
  70448. }
  70449. const int minX = jmin (dx, sx);
  70450. const int minY = jmin (dy, sy);
  70451. w = jmin (w, getWidth() - jmax (sx, dx));
  70452. h = jmin (h, getHeight() - jmax (sy, dy));
  70453. if (w > 0 && h > 0)
  70454. {
  70455. const int maxX = jmax (dx, sx) + w;
  70456. const int maxY = jmax (dy, sy) + h;
  70457. int ls, ps;
  70458. uint8* const pixels = lockPixelDataReadWrite (minX, minY, maxX - minX, maxY - minY, ls, ps);
  70459. uint8* dst = pixels + ls * (dy - minY) + ps * (dx - minX);
  70460. const uint8* src = pixels + ls * (sy - minY) + ps * (sx - minX);
  70461. const int lineSize = ps * w;
  70462. if (dy > sy)
  70463. {
  70464. while (--h >= 0)
  70465. {
  70466. const int offset = h * ls;
  70467. memmove (dst + offset, src + offset, lineSize);
  70468. }
  70469. }
  70470. else if (dst != src)
  70471. {
  70472. while (--h >= 0)
  70473. {
  70474. memmove (dst, src, lineSize);
  70475. dst += ls;
  70476. src += ls;
  70477. }
  70478. }
  70479. releasePixelDataReadWrite (pixels);
  70480. }
  70481. }
  70482. END_JUCE_NAMESPACE
  70483. /********* End of inlined file: juce_Image.cpp *********/
  70484. /********* Start of inlined file: juce_ImageCache.cpp *********/
  70485. BEGIN_JUCE_NAMESPACE
  70486. struct CachedImageInfo
  70487. {
  70488. Image* image;
  70489. int64 hashCode;
  70490. int refCount;
  70491. unsigned int releaseTime;
  70492. juce_UseDebuggingNewOperator
  70493. };
  70494. static ImageCache* instance = 0;
  70495. static int cacheTimeout = 5000;
  70496. ImageCache::ImageCache() throw()
  70497. : images (4)
  70498. {
  70499. }
  70500. ImageCache::~ImageCache()
  70501. {
  70502. const ScopedLock sl (lock);
  70503. for (int i = images.size(); --i >= 0;)
  70504. {
  70505. CachedImageInfo* const ci = (CachedImageInfo*)(images.getUnchecked(i));
  70506. delete ci->image;
  70507. delete ci;
  70508. }
  70509. images.clear();
  70510. jassert (instance == this);
  70511. instance = 0;
  70512. }
  70513. Image* ImageCache::getFromHashCode (const int64 hashCode)
  70514. {
  70515. if (instance != 0)
  70516. {
  70517. const ScopedLock sl (instance->lock);
  70518. for (int i = instance->images.size(); --i >= 0;)
  70519. {
  70520. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  70521. if (ci->hashCode == hashCode)
  70522. {
  70523. atomicIncrement (ci->refCount);
  70524. return ci->image;
  70525. }
  70526. }
  70527. }
  70528. return 0;
  70529. }
  70530. void ImageCache::addImageToCache (Image* const image,
  70531. const int64 hashCode)
  70532. {
  70533. if (image != 0)
  70534. {
  70535. if (instance == 0)
  70536. instance = new ImageCache();
  70537. CachedImageInfo* const newC = new CachedImageInfo();
  70538. newC->hashCode = hashCode;
  70539. newC->image = image;
  70540. newC->refCount = 1;
  70541. newC->releaseTime = 0;
  70542. const ScopedLock sl (instance->lock);
  70543. instance->images.add (newC);
  70544. }
  70545. }
  70546. void ImageCache::release (Image* const imageToRelease)
  70547. {
  70548. if (imageToRelease != 0 && instance != 0)
  70549. {
  70550. const ScopedLock sl (instance->lock);
  70551. for (int i = instance->images.size(); --i >= 0;)
  70552. {
  70553. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  70554. if (ci->image == imageToRelease)
  70555. {
  70556. if (--(ci->refCount) == 0)
  70557. ci->releaseTime = Time::getApproximateMillisecondCounter();
  70558. if (! instance->isTimerRunning())
  70559. instance->startTimer (999);
  70560. break;
  70561. }
  70562. }
  70563. }
  70564. }
  70565. bool ImageCache::isImageInCache (Image* const imageToLookFor)
  70566. {
  70567. if (instance != 0)
  70568. {
  70569. const ScopedLock sl (instance->lock);
  70570. for (int i = instance->images.size(); --i >= 0;)
  70571. if (((const CachedImageInfo*) instance->images.getUnchecked(i))->image == imageToLookFor)
  70572. return true;
  70573. }
  70574. return false;
  70575. }
  70576. void ImageCache::incReferenceCount (Image* const image)
  70577. {
  70578. if (instance != 0)
  70579. {
  70580. const ScopedLock sl (instance->lock);
  70581. for (int i = instance->images.size(); --i >= 0;)
  70582. {
  70583. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  70584. if (ci->image == image)
  70585. {
  70586. ci->refCount++;
  70587. return;
  70588. }
  70589. }
  70590. }
  70591. jassertfalse // (trying to inc the ref count of an image that's not in the cache)
  70592. }
  70593. void ImageCache::timerCallback()
  70594. {
  70595. int numberStillNeedingReleasing = 0;
  70596. const unsigned int now = Time::getApproximateMillisecondCounter();
  70597. const ScopedLock sl (lock);
  70598. for (int i = images.size(); --i >= 0;)
  70599. {
  70600. CachedImageInfo* const ci = (CachedImageInfo*) images.getUnchecked(i);
  70601. if (ci->refCount <= 0)
  70602. {
  70603. if (now > ci->releaseTime + cacheTimeout
  70604. || now < ci->releaseTime - 1000)
  70605. {
  70606. images.remove (i);
  70607. delete ci->image;
  70608. delete ci;
  70609. }
  70610. else
  70611. {
  70612. ++numberStillNeedingReleasing;
  70613. }
  70614. }
  70615. }
  70616. if (numberStillNeedingReleasing == 0)
  70617. stopTimer();
  70618. }
  70619. Image* ImageCache::getFromFile (const File& file)
  70620. {
  70621. const int64 hashCode = file.getFullPathName().hashCode64();
  70622. Image* image = getFromHashCode (hashCode);
  70623. if (image == 0)
  70624. {
  70625. image = ImageFileFormat::loadFrom (file);
  70626. addImageToCache (image, hashCode);
  70627. }
  70628. return image;
  70629. }
  70630. Image* ImageCache::getFromMemory (const void* imageData,
  70631. const int dataSize)
  70632. {
  70633. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  70634. Image* image = getFromHashCode (hashCode);
  70635. if (image == 0)
  70636. {
  70637. image = ImageFileFormat::loadFrom (imageData, dataSize);
  70638. addImageToCache (image, hashCode);
  70639. }
  70640. return image;
  70641. }
  70642. void ImageCache::setCacheTimeout (const int millisecs)
  70643. {
  70644. cacheTimeout = millisecs;
  70645. }
  70646. END_JUCE_NAMESPACE
  70647. /********* End of inlined file: juce_ImageCache.cpp *********/
  70648. /********* Start of inlined file: juce_ImageConvolutionKernel.cpp *********/
  70649. BEGIN_JUCE_NAMESPACE
  70650. ImageConvolutionKernel::ImageConvolutionKernel (const int size_) throw()
  70651. : size (size_)
  70652. {
  70653. values = new float* [size];
  70654. for (int i = size; --i >= 0;)
  70655. values[i] = new float [size];
  70656. clear();
  70657. }
  70658. ImageConvolutionKernel::~ImageConvolutionKernel() throw()
  70659. {
  70660. for (int i = size; --i >= 0;)
  70661. delete[] values[i];
  70662. delete[] values;
  70663. }
  70664. void ImageConvolutionKernel::setKernelValue (const int x,
  70665. const int y,
  70666. const float value) throw()
  70667. {
  70668. if (((unsigned int) x) < (unsigned int) size
  70669. && ((unsigned int) y) < (unsigned int) size)
  70670. {
  70671. values[x][y] = value;
  70672. }
  70673. else
  70674. {
  70675. jassertfalse
  70676. }
  70677. }
  70678. void ImageConvolutionKernel::clear() throw()
  70679. {
  70680. for (int y = size; --y >= 0;)
  70681. for (int x = size; --x >= 0;)
  70682. values[x][y] = 0;
  70683. }
  70684. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum) throw()
  70685. {
  70686. double currentTotal = 0.0;
  70687. for (int y = size; --y >= 0;)
  70688. for (int x = size; --x >= 0;)
  70689. currentTotal += values[x][y];
  70690. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  70691. }
  70692. void ImageConvolutionKernel::rescaleAllValues (const float multiplier) throw()
  70693. {
  70694. for (int y = size; --y >= 0;)
  70695. for (int x = size; --x >= 0;)
  70696. values[x][y] *= multiplier;
  70697. }
  70698. void ImageConvolutionKernel::createGaussianBlur (const float radius) throw()
  70699. {
  70700. const double radiusFactor = -1.0 / (radius * radius * 2);
  70701. const int centre = size >> 1;
  70702. for (int y = size; --y >= 0;)
  70703. {
  70704. for (int x = size; --x >= 0;)
  70705. {
  70706. const int cx = x - centre;
  70707. const int cy = y - centre;
  70708. values[x][y] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  70709. }
  70710. }
  70711. setOverallSum (1.0f);
  70712. }
  70713. void ImageConvolutionKernel::applyToImage (Image& destImage,
  70714. const Image* sourceImage,
  70715. int dx,
  70716. int dy,
  70717. int dw,
  70718. int dh) const
  70719. {
  70720. Image* imageCreated = 0;
  70721. if (sourceImage == 0)
  70722. {
  70723. sourceImage = imageCreated = destImage.createCopy();
  70724. }
  70725. else
  70726. {
  70727. jassert (sourceImage->getWidth() == destImage.getWidth()
  70728. && sourceImage->getHeight() == destImage.getHeight()
  70729. && sourceImage->getFormat() == destImage.getFormat());
  70730. if (sourceImage->getWidth() != destImage.getWidth()
  70731. || sourceImage->getHeight() != destImage.getHeight()
  70732. || sourceImage->getFormat() != destImage.getFormat())
  70733. return;
  70734. }
  70735. const int imageWidth = destImage.getWidth();
  70736. const int imageHeight = destImage.getHeight();
  70737. if (dx >= imageWidth || dy >= imageHeight)
  70738. return;
  70739. if (dx + dw > imageWidth)
  70740. dw = imageWidth - dx;
  70741. if (dy + dh > imageHeight)
  70742. dh = imageHeight - dy;
  70743. const int dx2 = dx + dw;
  70744. const int dy2 = dy + dh;
  70745. int lineStride, pixelStride;
  70746. uint8* pixels = destImage.lockPixelDataReadWrite (dx, dy, dw, dh, lineStride, pixelStride);
  70747. uint8* line = pixels;
  70748. int srcLineStride, srcPixelStride;
  70749. const uint8* srcPixels = sourceImage->lockPixelDataReadOnly (0, 0, sourceImage->getWidth(), sourceImage->getHeight(), srcLineStride, srcPixelStride);
  70750. if (pixelStride == 4)
  70751. {
  70752. for (int y = dy; y < dy2; ++y)
  70753. {
  70754. uint8* dest = line;
  70755. line += lineStride;
  70756. for (int x = dx; x < dx2; ++x)
  70757. {
  70758. float c1 = 0;
  70759. float c2 = 0;
  70760. float c3 = 0;
  70761. float c4 = 0;
  70762. for (int yy = 0; yy < size; ++yy)
  70763. {
  70764. const int sy = y + yy - (size >> 1);
  70765. if (sy >= imageHeight)
  70766. break;
  70767. if (sy >= 0)
  70768. {
  70769. int sx = x - (size >> 1);
  70770. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  70771. for (int xx = 0; xx < size; ++xx)
  70772. {
  70773. if (sx >= imageWidth)
  70774. break;
  70775. if (sx >= 0)
  70776. {
  70777. const float kernelMult = values[xx][yy];
  70778. c1 += kernelMult * *src++;
  70779. c2 += kernelMult * *src++;
  70780. c3 += kernelMult * *src++;
  70781. c4 += kernelMult * *src++;
  70782. }
  70783. else
  70784. {
  70785. src += 4;
  70786. }
  70787. ++sx;
  70788. }
  70789. }
  70790. }
  70791. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c1));
  70792. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c2));
  70793. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c3));
  70794. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c4));
  70795. }
  70796. }
  70797. }
  70798. else if (pixelStride == 3)
  70799. {
  70800. for (int y = dy; y < dy2; ++y)
  70801. {
  70802. uint8* dest = line;
  70803. line += lineStride;
  70804. for (int x = dx; x < dx2; ++x)
  70805. {
  70806. float c1 = 0;
  70807. float c2 = 0;
  70808. float c3 = 0;
  70809. for (int yy = 0; yy < size; ++yy)
  70810. {
  70811. const int sy = y + yy - (size >> 1);
  70812. if (sy >= imageHeight)
  70813. break;
  70814. if (sy >= 0)
  70815. {
  70816. int sx = x - (size >> 1);
  70817. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  70818. for (int xx = 0; xx < size; ++xx)
  70819. {
  70820. if (sx >= imageWidth)
  70821. break;
  70822. if (sx >= 0)
  70823. {
  70824. const float kernelMult = values[xx][yy];
  70825. c1 += kernelMult * *src++;
  70826. c2 += kernelMult * *src++;
  70827. c3 += kernelMult * *src++;
  70828. }
  70829. else
  70830. {
  70831. src += 3;
  70832. }
  70833. ++sx;
  70834. }
  70835. }
  70836. }
  70837. *dest++ = (uint8) roundFloatToInt (c1);
  70838. *dest++ = (uint8) roundFloatToInt (c2);
  70839. *dest++ = (uint8) roundFloatToInt (c3);
  70840. }
  70841. }
  70842. }
  70843. sourceImage->releasePixelDataReadOnly (srcPixels);
  70844. destImage.releasePixelDataReadWrite (pixels);
  70845. if (imageCreated != 0)
  70846. delete imageCreated;
  70847. }
  70848. END_JUCE_NAMESPACE
  70849. /********* End of inlined file: juce_ImageConvolutionKernel.cpp *********/
  70850. /********* Start of inlined file: juce_ImageFileFormat.cpp *********/
  70851. BEGIN_JUCE_NAMESPACE
  70852. /********* Start of inlined file: juce_GIFLoader.h *********/
  70853. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  70854. #define __JUCE_GIFLOADER_JUCEHEADER__
  70855. #ifndef DOXYGEN
  70856. static const int maxGifCode = 1 << 12;
  70857. /**
  70858. Used internally by ImageFileFormat - don't use this class directly in your
  70859. application.
  70860. @see ImageFileFormat
  70861. */
  70862. class GIFLoader
  70863. {
  70864. public:
  70865. GIFLoader (InputStream& in);
  70866. ~GIFLoader() throw();
  70867. Image* getImage() const throw() { return image; }
  70868. private:
  70869. Image* image;
  70870. InputStream& input;
  70871. uint8 buffer [300];
  70872. uint8 palette [256][4];
  70873. bool dataBlockIsZero, fresh, finished;
  70874. int currentBit, lastBit, lastByteIndex;
  70875. int codeSize, setCodeSize;
  70876. int maxCode, maxCodeSize;
  70877. int firstcode, oldcode;
  70878. int clearCode, end_code;
  70879. int table [2] [maxGifCode];
  70880. int stack [2 * maxGifCode];
  70881. int *sp;
  70882. bool getSizeFromHeader (int& width, int& height);
  70883. bool readPalette (const int numCols);
  70884. int readDataBlock (unsigned char* dest);
  70885. int processExtension (int type, int& transparent);
  70886. int readLZWByte (bool initialise, int input_code_size);
  70887. int getCode (int code_size, bool initialise);
  70888. bool readImage (int width, int height,
  70889. int interlace, int transparent);
  70890. GIFLoader (const GIFLoader&);
  70891. const GIFLoader& operator= (const GIFLoader&);
  70892. };
  70893. #endif // DOXYGEN
  70894. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  70895. /********* End of inlined file: juce_GIFLoader.h *********/
  70896. Image* juce_loadPNGImageFromStream (InputStream& inputStream) throw();
  70897. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw();
  70898. PNGImageFormat::PNGImageFormat() throw() {}
  70899. PNGImageFormat::~PNGImageFormat() throw() {}
  70900. const String PNGImageFormat::getFormatName()
  70901. {
  70902. return T("PNG");
  70903. }
  70904. bool PNGImageFormat::canUnderstand (InputStream& in)
  70905. {
  70906. const int bytesNeeded = 4;
  70907. char header [bytesNeeded];
  70908. return in.read (header, bytesNeeded) == bytesNeeded
  70909. && header[1] == 'P'
  70910. && header[2] == 'N'
  70911. && header[3] == 'G';
  70912. }
  70913. Image* PNGImageFormat::decodeImage (InputStream& in)
  70914. {
  70915. return juce_loadPNGImageFromStream (in);
  70916. }
  70917. bool PNGImageFormat::writeImageToStream (const Image& sourceImage,
  70918. OutputStream& destStream)
  70919. {
  70920. return juce_writePNGImageToStream (sourceImage, destStream);
  70921. }
  70922. Image* juce_loadJPEGImageFromStream (InputStream& inputStream) throw();
  70923. bool juce_writeJPEGImageToStream (const Image& image, OutputStream& out, float quality) throw();
  70924. JPEGImageFormat::JPEGImageFormat() throw()
  70925. : quality (-1.0f)
  70926. {
  70927. }
  70928. JPEGImageFormat::~JPEGImageFormat() throw() {}
  70929. void JPEGImageFormat::setQuality (const float newQuality)
  70930. {
  70931. quality = newQuality;
  70932. }
  70933. const String JPEGImageFormat::getFormatName()
  70934. {
  70935. return T("JPEG");
  70936. }
  70937. bool JPEGImageFormat::canUnderstand (InputStream& in)
  70938. {
  70939. const int bytesNeeded = 10;
  70940. uint8 header [bytesNeeded];
  70941. if (in.read (header, bytesNeeded) == bytesNeeded)
  70942. {
  70943. return header[0] == 0xff
  70944. && header[1] == 0xd8
  70945. && header[2] == 0xff
  70946. && (header[3] == 0xe0 || header[3] == 0xe1);
  70947. }
  70948. return false;
  70949. }
  70950. Image* JPEGImageFormat::decodeImage (InputStream& in)
  70951. {
  70952. return juce_loadJPEGImageFromStream (in);
  70953. }
  70954. bool JPEGImageFormat::writeImageToStream (const Image& sourceImage,
  70955. OutputStream& destStream)
  70956. {
  70957. return juce_writeJPEGImageToStream (sourceImage, destStream, quality);
  70958. }
  70959. class GIFImageFormat : public ImageFileFormat
  70960. {
  70961. public:
  70962. GIFImageFormat() throw() {}
  70963. ~GIFImageFormat() throw() {}
  70964. const String getFormatName()
  70965. {
  70966. return T("GIF");
  70967. }
  70968. bool canUnderstand (InputStream& in)
  70969. {
  70970. const int bytesNeeded = 4;
  70971. char header [bytesNeeded];
  70972. return (in.read (header, bytesNeeded) == bytesNeeded)
  70973. && header[0] == 'G'
  70974. && header[1] == 'I'
  70975. && header[2] == 'F';
  70976. }
  70977. Image* decodeImage (InputStream& in)
  70978. {
  70979. GIFLoader* const loader = new GIFLoader (in);
  70980. Image* const im = loader->getImage();
  70981. delete loader;
  70982. return im;
  70983. }
  70984. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  70985. {
  70986. return false;
  70987. }
  70988. };
  70989. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  70990. {
  70991. static PNGImageFormat png;
  70992. static JPEGImageFormat jpg;
  70993. static GIFImageFormat gif;
  70994. ImageFileFormat* formats[4];
  70995. int numFormats = 0;
  70996. formats [numFormats++] = &png;
  70997. formats [numFormats++] = &jpg;
  70998. formats [numFormats++] = &gif;
  70999. const int64 streamPos = input.getPosition();
  71000. for (int i = 0; i < numFormats; ++i)
  71001. {
  71002. const bool found = formats[i]->canUnderstand (input);
  71003. input.setPosition (streamPos);
  71004. if (found)
  71005. return formats[i];
  71006. }
  71007. return 0;
  71008. }
  71009. Image* ImageFileFormat::loadFrom (InputStream& input)
  71010. {
  71011. ImageFileFormat* const format = findImageFormatForStream (input);
  71012. if (format != 0)
  71013. return format->decodeImage (input);
  71014. return 0;
  71015. }
  71016. Image* ImageFileFormat::loadFrom (const File& file)
  71017. {
  71018. InputStream* const in = file.createInputStream();
  71019. if (in != 0)
  71020. {
  71021. BufferedInputStream b (in, 8192, true);
  71022. return loadFrom (b);
  71023. }
  71024. return 0;
  71025. }
  71026. Image* ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  71027. {
  71028. if (rawData != 0 && numBytes > 4)
  71029. {
  71030. MemoryInputStream stream (rawData, numBytes, false);
  71031. return loadFrom (stream);
  71032. }
  71033. return 0;
  71034. }
  71035. END_JUCE_NAMESPACE
  71036. /********* End of inlined file: juce_ImageFileFormat.cpp *********/
  71037. /********* Start of inlined file: juce_GIFLoader.cpp *********/
  71038. BEGIN_JUCE_NAMESPACE
  71039. static inline int makeWord (const unsigned char a, const unsigned char b) throw()
  71040. {
  71041. return (b << 8) | a;
  71042. }
  71043. GIFLoader::GIFLoader (InputStream& in)
  71044. : image (0),
  71045. input (in),
  71046. dataBlockIsZero (false),
  71047. fresh (false),
  71048. finished (false)
  71049. {
  71050. currentBit = lastBit = lastByteIndex = 0;
  71051. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  71052. firstcode = oldcode = 0;
  71053. clearCode = end_code = 0;
  71054. int imageWidth, imageHeight;
  71055. int transparent = -1;
  71056. if (! getSizeFromHeader (imageWidth, imageHeight))
  71057. return;
  71058. if ((imageWidth <= 0) || (imageHeight <= 0))
  71059. return;
  71060. unsigned char buf [16];
  71061. if (in.read (buf, 3) != 3)
  71062. return;
  71063. int numColours = 2 << (buf[0] & 7);
  71064. if ((buf[0] & 0x80) != 0)
  71065. readPalette (numColours);
  71066. for (;;)
  71067. {
  71068. if (input.read (buf, 1) != 1)
  71069. break;
  71070. if (buf[0] == ';')
  71071. break;
  71072. if (buf[0] == '!')
  71073. {
  71074. if (input.read (buf, 1) != 1)
  71075. break;
  71076. if (processExtension (buf[0], transparent) < 0)
  71077. break;
  71078. continue;
  71079. }
  71080. if (buf[0] != ',')
  71081. continue;
  71082. if (input.read (buf, 9) != 9)
  71083. break;
  71084. imageWidth = makeWord (buf[4], buf[5]);
  71085. imageHeight = makeWord (buf[6], buf[7]);
  71086. numColours = 2 << (buf[8] & 7);
  71087. if ((buf[8] & 0x80) != 0)
  71088. if (! readPalette (numColours))
  71089. break;
  71090. image = new Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  71091. imageWidth, imageHeight, (transparent >= 0));
  71092. readImage (imageWidth, imageHeight,
  71093. (buf[8] & 0x40) != 0,
  71094. transparent);
  71095. break;
  71096. }
  71097. }
  71098. GIFLoader::~GIFLoader() throw()
  71099. {
  71100. }
  71101. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  71102. {
  71103. unsigned char b [8];
  71104. if (input.read (b, 6) == 6)
  71105. {
  71106. if ((strncmp ("GIF87a", (char*) b, 6) == 0)
  71107. || (strncmp ("GIF89a", (char*) b, 6) == 0))
  71108. {
  71109. if (input.read (b, 4) == 4)
  71110. {
  71111. w = makeWord (b[0], b[1]);
  71112. h = makeWord (b[2], b[3]);
  71113. return true;
  71114. }
  71115. }
  71116. }
  71117. return false;
  71118. }
  71119. bool GIFLoader::readPalette (const int numCols)
  71120. {
  71121. unsigned char rgb[4];
  71122. for (int i = 0; i < numCols; ++i)
  71123. {
  71124. input.read (rgb, 3);
  71125. palette [i][0] = rgb[0];
  71126. palette [i][1] = rgb[1];
  71127. palette [i][2] = rgb[2];
  71128. palette [i][3] = 0xff;
  71129. }
  71130. return true;
  71131. }
  71132. int GIFLoader::readDataBlock (unsigned char* const dest)
  71133. {
  71134. unsigned char n;
  71135. if (input.read (&n, 1) == 1)
  71136. {
  71137. dataBlockIsZero = (n == 0);
  71138. if (dataBlockIsZero || (input.read (dest, n) == n))
  71139. return n;
  71140. }
  71141. return -1;
  71142. }
  71143. int GIFLoader::processExtension (const int type, int& transparent)
  71144. {
  71145. unsigned char b [300];
  71146. int n = 0;
  71147. if (type == 0xf9)
  71148. {
  71149. n = readDataBlock (b);
  71150. if (n < 0)
  71151. return 1;
  71152. if ((b[0] & 0x1) != 0)
  71153. transparent = b[3];
  71154. }
  71155. do
  71156. {
  71157. n = readDataBlock (b);
  71158. }
  71159. while (n > 0);
  71160. return n;
  71161. }
  71162. int GIFLoader::getCode (const int codeSize, const bool initialise)
  71163. {
  71164. if (initialise)
  71165. {
  71166. currentBit = 0;
  71167. lastBit = 0;
  71168. finished = false;
  71169. return 0;
  71170. }
  71171. if ((currentBit + codeSize) >= lastBit)
  71172. {
  71173. if (finished)
  71174. return -1;
  71175. buffer[0] = buffer [lastByteIndex - 2];
  71176. buffer[1] = buffer [lastByteIndex - 1];
  71177. const int n = readDataBlock (&buffer[2]);
  71178. if (n == 0)
  71179. finished = true;
  71180. lastByteIndex = 2 + n;
  71181. currentBit = (currentBit - lastBit) + 16;
  71182. lastBit = (2 + n) * 8 ;
  71183. }
  71184. int result = 0;
  71185. int i = currentBit;
  71186. for (int j = 0; j < codeSize; ++j)
  71187. {
  71188. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  71189. ++i;
  71190. }
  71191. currentBit += codeSize;
  71192. return result;
  71193. }
  71194. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  71195. {
  71196. int code, incode, i;
  71197. if (initialise)
  71198. {
  71199. setCodeSize = inputCodeSize;
  71200. codeSize = setCodeSize + 1;
  71201. clearCode = 1 << setCodeSize;
  71202. end_code = clearCode + 1;
  71203. maxCodeSize = 2 * clearCode;
  71204. maxCode = clearCode + 2;
  71205. getCode (0, true);
  71206. fresh = true;
  71207. for (i = 0; i < clearCode; ++i)
  71208. {
  71209. table[0][i] = 0;
  71210. table[1][i] = i;
  71211. }
  71212. for (; i < maxGifCode; ++i)
  71213. {
  71214. table[0][i] = 0;
  71215. table[1][i] = 0;
  71216. }
  71217. sp = stack;
  71218. return 0;
  71219. }
  71220. else if (fresh)
  71221. {
  71222. fresh = false;
  71223. do
  71224. {
  71225. firstcode = oldcode
  71226. = getCode (codeSize, false);
  71227. }
  71228. while (firstcode == clearCode);
  71229. return firstcode;
  71230. }
  71231. if (sp > stack)
  71232. return *--sp;
  71233. while ((code = getCode (codeSize, false)) >= 0)
  71234. {
  71235. if (code == clearCode)
  71236. {
  71237. for (i = 0; i < clearCode; ++i)
  71238. {
  71239. table[0][i] = 0;
  71240. table[1][i] = i;
  71241. }
  71242. for (; i < maxGifCode; ++i)
  71243. {
  71244. table[0][i] = 0;
  71245. table[1][i] = 0;
  71246. }
  71247. codeSize = setCodeSize + 1;
  71248. maxCodeSize = 2 * clearCode;
  71249. maxCode = clearCode + 2;
  71250. sp = stack;
  71251. firstcode = oldcode = getCode (codeSize, false);
  71252. return firstcode;
  71253. }
  71254. else if (code == end_code)
  71255. {
  71256. if (dataBlockIsZero)
  71257. return -2;
  71258. unsigned char buf [260];
  71259. int n;
  71260. while ((n = readDataBlock (buf)) > 0)
  71261. {}
  71262. if (n != 0)
  71263. return -2;
  71264. }
  71265. incode = code;
  71266. if (code >= maxCode)
  71267. {
  71268. *sp++ = firstcode;
  71269. code = oldcode;
  71270. }
  71271. while (code >= clearCode)
  71272. {
  71273. *sp++ = table[1][code];
  71274. if (code == table[0][code])
  71275. return -2;
  71276. code = table[0][code];
  71277. }
  71278. *sp++ = firstcode = table[1][code];
  71279. if ((code = maxCode) < maxGifCode)
  71280. {
  71281. table[0][code] = oldcode;
  71282. table[1][code] = firstcode;
  71283. ++maxCode;
  71284. if ((maxCode >= maxCodeSize)
  71285. && (maxCodeSize < maxGifCode))
  71286. {
  71287. maxCodeSize <<= 1;
  71288. ++codeSize;
  71289. }
  71290. }
  71291. oldcode = incode;
  71292. if (sp > stack)
  71293. return *--sp;
  71294. }
  71295. return code;
  71296. }
  71297. bool GIFLoader::readImage (const int width, const int height,
  71298. const int interlace, const int transparent)
  71299. {
  71300. unsigned char c;
  71301. if (input.read (&c, 1) != 1
  71302. || readLZWByte (true, c) < 0)
  71303. return false;
  71304. if (transparent >= 0)
  71305. {
  71306. palette [transparent][0] = 0;
  71307. palette [transparent][1] = 0;
  71308. palette [transparent][2] = 0;
  71309. palette [transparent][3] = 0;
  71310. }
  71311. int index;
  71312. int xpos = 0, ypos = 0, pass = 0;
  71313. int stride, pixelStride;
  71314. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  71315. uint8* p = pixels;
  71316. const bool hasAlpha = image->hasAlphaChannel();
  71317. while ((index = readLZWByte (false, c)) >= 0)
  71318. {
  71319. const uint8* const paletteEntry = palette [index];
  71320. if (hasAlpha)
  71321. {
  71322. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  71323. paletteEntry[0],
  71324. paletteEntry[1],
  71325. paletteEntry[2]);
  71326. ((PixelARGB*) p)->premultiply();
  71327. p += pixelStride;
  71328. }
  71329. else
  71330. {
  71331. ((PixelRGB*) p)->setARGB (0,
  71332. paletteEntry[0],
  71333. paletteEntry[1],
  71334. paletteEntry[2]);
  71335. p += pixelStride;
  71336. }
  71337. ++xpos;
  71338. if (xpos == width)
  71339. {
  71340. xpos = 0;
  71341. if (interlace)
  71342. {
  71343. switch (pass)
  71344. {
  71345. case 0:
  71346. case 1:
  71347. ypos += 8;
  71348. break;
  71349. case 2:
  71350. ypos += 4;
  71351. break;
  71352. case 3:
  71353. ypos += 2;
  71354. break;
  71355. }
  71356. while (ypos >= height)
  71357. {
  71358. ++pass;
  71359. switch (pass)
  71360. {
  71361. case 1:
  71362. ypos = 4;
  71363. break;
  71364. case 2:
  71365. ypos = 2;
  71366. break;
  71367. case 3:
  71368. ypos = 1;
  71369. break;
  71370. default:
  71371. return true;
  71372. }
  71373. }
  71374. }
  71375. else
  71376. {
  71377. ++ypos;
  71378. }
  71379. p = pixels + xpos * pixelStride + ypos * stride;
  71380. }
  71381. if (ypos >= height)
  71382. break;
  71383. }
  71384. image->releasePixelDataReadWrite (pixels);
  71385. return true;
  71386. }
  71387. END_JUCE_NAMESPACE
  71388. /********* End of inlined file: juce_GIFLoader.cpp *********/
  71389. #endif
  71390. //==============================================================================
  71391. // some files include lots of library code, so leave them to the end to avoid cluttering
  71392. // up the build for the clean files.
  71393. /********* Start of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  71394. namespace zlibNamespace
  71395. {
  71396. #undef OS_CODE
  71397. #undef fdopen
  71398. /********* Start of inlined file: zlib.h *********/
  71399. #ifndef ZLIB_H
  71400. #define ZLIB_H
  71401. /********* Start of inlined file: zconf.h *********/
  71402. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  71403. #ifndef ZCONF_H
  71404. #define ZCONF_H
  71405. // *** Just a few hacks here to make it compile nicely with Juce..
  71406. #define Z_PREFIX 1
  71407. #undef __MACTYPES__
  71408. #ifdef _MSC_VER
  71409. #pragma warning (disable : 4131 4127 4244 4267)
  71410. #endif
  71411. /*
  71412. * If you *really* need a unique prefix for all types and library functions,
  71413. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  71414. */
  71415. #ifdef Z_PREFIX
  71416. # define deflateInit_ z_deflateInit_
  71417. # define deflate z_deflate
  71418. # define deflateEnd z_deflateEnd
  71419. # define inflateInit_ z_inflateInit_
  71420. # define inflate z_inflate
  71421. # define inflateEnd z_inflateEnd
  71422. # define deflateInit2_ z_deflateInit2_
  71423. # define deflateSetDictionary z_deflateSetDictionary
  71424. # define deflateCopy z_deflateCopy
  71425. # define deflateReset z_deflateReset
  71426. # define deflateParams z_deflateParams
  71427. # define deflateBound z_deflateBound
  71428. # define deflatePrime z_deflatePrime
  71429. # define inflateInit2_ z_inflateInit2_
  71430. # define inflateSetDictionary z_inflateSetDictionary
  71431. # define inflateSync z_inflateSync
  71432. # define inflateSyncPoint z_inflateSyncPoint
  71433. # define inflateCopy z_inflateCopy
  71434. # define inflateReset z_inflateReset
  71435. # define inflateBack z_inflateBack
  71436. # define inflateBackEnd z_inflateBackEnd
  71437. # define compress z_compress
  71438. # define compress2 z_compress2
  71439. # define compressBound z_compressBound
  71440. # define uncompress z_uncompress
  71441. # define adler32 z_adler32
  71442. # define crc32 z_crc32
  71443. # define get_crc_table z_get_crc_table
  71444. # define zError z_zError
  71445. # define alloc_func z_alloc_func
  71446. # define free_func z_free_func
  71447. # define in_func z_in_func
  71448. # define out_func z_out_func
  71449. # define Byte z_Byte
  71450. # define uInt z_uInt
  71451. # define uLong z_uLong
  71452. # define Bytef z_Bytef
  71453. # define charf z_charf
  71454. # define intf z_intf
  71455. # define uIntf z_uIntf
  71456. # define uLongf z_uLongf
  71457. # define voidpf z_voidpf
  71458. # define voidp z_voidp
  71459. #endif
  71460. #if defined(__MSDOS__) && !defined(MSDOS)
  71461. # define MSDOS
  71462. #endif
  71463. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  71464. # define OS2
  71465. #endif
  71466. #if defined(_WINDOWS) && !defined(WINDOWS)
  71467. # define WINDOWS
  71468. #endif
  71469. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  71470. # ifndef WIN32
  71471. # define WIN32
  71472. # endif
  71473. #endif
  71474. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  71475. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  71476. # ifndef SYS16BIT
  71477. # define SYS16BIT
  71478. # endif
  71479. # endif
  71480. #endif
  71481. /*
  71482. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  71483. * than 64k bytes at a time (needed on systems with 16-bit int).
  71484. */
  71485. #ifdef SYS16BIT
  71486. # define MAXSEG_64K
  71487. #endif
  71488. #ifdef MSDOS
  71489. # define UNALIGNED_OK
  71490. #endif
  71491. #ifdef __STDC_VERSION__
  71492. # ifndef STDC
  71493. # define STDC
  71494. # endif
  71495. # if __STDC_VERSION__ >= 199901L
  71496. # ifndef STDC99
  71497. # define STDC99
  71498. # endif
  71499. # endif
  71500. #endif
  71501. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  71502. # define STDC
  71503. #endif
  71504. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  71505. # define STDC
  71506. #endif
  71507. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  71508. # define STDC
  71509. #endif
  71510. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  71511. # define STDC
  71512. #endif
  71513. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  71514. # define STDC
  71515. #endif
  71516. #ifndef STDC
  71517. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  71518. # define const /* note: need a more gentle solution here */
  71519. # endif
  71520. #endif
  71521. /* Some Mac compilers merge all .h files incorrectly: */
  71522. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  71523. # define NO_DUMMY_DECL
  71524. #endif
  71525. /* Maximum value for memLevel in deflateInit2 */
  71526. #ifndef MAX_MEM_LEVEL
  71527. # ifdef MAXSEG_64K
  71528. # define MAX_MEM_LEVEL 8
  71529. # else
  71530. # define MAX_MEM_LEVEL 9
  71531. # endif
  71532. #endif
  71533. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  71534. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  71535. * created by gzip. (Files created by minigzip can still be extracted by
  71536. * gzip.)
  71537. */
  71538. #ifndef MAX_WBITS
  71539. # define MAX_WBITS 15 /* 32K LZ77 window */
  71540. #endif
  71541. /* The memory requirements for deflate are (in bytes):
  71542. (1 << (windowBits+2)) + (1 << (memLevel+9))
  71543. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  71544. plus a few kilobytes for small objects. For example, if you want to reduce
  71545. the default memory requirements from 256K to 128K, compile with
  71546. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  71547. Of course this will generally degrade compression (there's no free lunch).
  71548. The memory requirements for inflate are (in bytes) 1 << windowBits
  71549. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  71550. for small objects.
  71551. */
  71552. /* Type declarations */
  71553. #ifndef OF /* function prototypes */
  71554. # ifdef STDC
  71555. # define OF(args) args
  71556. # else
  71557. # define OF(args) ()
  71558. # endif
  71559. #endif
  71560. /* The following definitions for FAR are needed only for MSDOS mixed
  71561. * model programming (small or medium model with some far allocations).
  71562. * This was tested only with MSC; for other MSDOS compilers you may have
  71563. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  71564. * just define FAR to be empty.
  71565. */
  71566. #ifdef SYS16BIT
  71567. # if defined(M_I86SM) || defined(M_I86MM)
  71568. /* MSC small or medium model */
  71569. # define SMALL_MEDIUM
  71570. # ifdef _MSC_VER
  71571. # define FAR _far
  71572. # else
  71573. # define FAR far
  71574. # endif
  71575. # endif
  71576. # if (defined(__SMALL__) || defined(__MEDIUM__))
  71577. /* Turbo C small or medium model */
  71578. # define SMALL_MEDIUM
  71579. # ifdef __BORLANDC__
  71580. # define FAR _far
  71581. # else
  71582. # define FAR far
  71583. # endif
  71584. # endif
  71585. #endif
  71586. #if defined(WINDOWS) || defined(WIN32)
  71587. /* If building or using zlib as a DLL, define ZLIB_DLL.
  71588. * This is not mandatory, but it offers a little performance increase.
  71589. */
  71590. # ifdef ZLIB_DLL
  71591. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  71592. # ifdef ZLIB_INTERNAL
  71593. # define ZEXTERN extern __declspec(dllexport)
  71594. # else
  71595. # define ZEXTERN extern __declspec(dllimport)
  71596. # endif
  71597. # endif
  71598. # endif /* ZLIB_DLL */
  71599. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  71600. * define ZLIB_WINAPI.
  71601. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  71602. */
  71603. # ifdef ZLIB_WINAPI
  71604. # ifdef FAR
  71605. # undef FAR
  71606. # endif
  71607. # include <windows.h>
  71608. /* No need for _export, use ZLIB.DEF instead. */
  71609. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  71610. # define ZEXPORT WINAPI
  71611. # ifdef WIN32
  71612. # define ZEXPORTVA WINAPIV
  71613. # else
  71614. # define ZEXPORTVA FAR CDECL
  71615. # endif
  71616. # endif
  71617. #endif
  71618. #if defined (__BEOS__)
  71619. # ifdef ZLIB_DLL
  71620. # ifdef ZLIB_INTERNAL
  71621. # define ZEXPORT __declspec(dllexport)
  71622. # define ZEXPORTVA __declspec(dllexport)
  71623. # else
  71624. # define ZEXPORT __declspec(dllimport)
  71625. # define ZEXPORTVA __declspec(dllimport)
  71626. # endif
  71627. # endif
  71628. #endif
  71629. #ifndef ZEXTERN
  71630. # define ZEXTERN extern
  71631. #endif
  71632. #ifndef ZEXPORT
  71633. # define ZEXPORT
  71634. #endif
  71635. #ifndef ZEXPORTVA
  71636. # define ZEXPORTVA
  71637. #endif
  71638. #ifndef FAR
  71639. # define FAR
  71640. #endif
  71641. #if !defined(__MACTYPES__)
  71642. typedef unsigned char Byte; /* 8 bits */
  71643. #endif
  71644. typedef unsigned int uInt; /* 16 bits or more */
  71645. typedef unsigned long uLong; /* 32 bits or more */
  71646. #ifdef SMALL_MEDIUM
  71647. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  71648. # define Bytef Byte FAR
  71649. #else
  71650. typedef Byte FAR Bytef;
  71651. #endif
  71652. typedef char FAR charf;
  71653. typedef int FAR intf;
  71654. typedef uInt FAR uIntf;
  71655. typedef uLong FAR uLongf;
  71656. #ifdef STDC
  71657. typedef void const *voidpc;
  71658. typedef void FAR *voidpf;
  71659. typedef void *voidp;
  71660. #else
  71661. typedef Byte const *voidpc;
  71662. typedef Byte FAR *voidpf;
  71663. typedef Byte *voidp;
  71664. #endif
  71665. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  71666. # include <sys/types.h> /* for off_t */
  71667. # include <unistd.h> /* for SEEK_* and off_t */
  71668. # ifdef VMS
  71669. # include <unixio.h> /* for off_t */
  71670. # endif
  71671. # define z_off_t off_t
  71672. #endif
  71673. #ifndef SEEK_SET
  71674. # define SEEK_SET 0 /* Seek from beginning of file. */
  71675. # define SEEK_CUR 1 /* Seek from current position. */
  71676. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  71677. #endif
  71678. #ifndef z_off_t
  71679. # define z_off_t long
  71680. #endif
  71681. #if defined(__OS400__)
  71682. # define NO_vsnprintf
  71683. #endif
  71684. #if defined(__MVS__)
  71685. # define NO_vsnprintf
  71686. # ifdef FAR
  71687. # undef FAR
  71688. # endif
  71689. #endif
  71690. /* MVS linker does not support external names larger than 8 bytes */
  71691. #if defined(__MVS__)
  71692. # pragma map(deflateInit_,"DEIN")
  71693. # pragma map(deflateInit2_,"DEIN2")
  71694. # pragma map(deflateEnd,"DEEND")
  71695. # pragma map(deflateBound,"DEBND")
  71696. # pragma map(inflateInit_,"ININ")
  71697. # pragma map(inflateInit2_,"ININ2")
  71698. # pragma map(inflateEnd,"INEND")
  71699. # pragma map(inflateSync,"INSY")
  71700. # pragma map(inflateSetDictionary,"INSEDI")
  71701. # pragma map(compressBound,"CMBND")
  71702. # pragma map(inflate_table,"INTABL")
  71703. # pragma map(inflate_fast,"INFA")
  71704. # pragma map(inflate_copyright,"INCOPY")
  71705. #endif
  71706. #endif /* ZCONF_H */
  71707. /********* End of inlined file: zconf.h *********/
  71708. #ifdef __cplusplus
  71709. extern "C" {
  71710. #endif
  71711. #define ZLIB_VERSION "1.2.3"
  71712. #define ZLIB_VERNUM 0x1230
  71713. /*
  71714. The 'zlib' compression library provides in-memory compression and
  71715. decompression functions, including integrity checks of the uncompressed
  71716. data. This version of the library supports only one compression method
  71717. (deflation) but other algorithms will be added later and will have the same
  71718. stream interface.
  71719. Compression can be done in a single step if the buffers are large
  71720. enough (for example if an input file is mmap'ed), or can be done by
  71721. repeated calls of the compression function. In the latter case, the
  71722. application must provide more input and/or consume the output
  71723. (providing more output space) before each call.
  71724. The compressed data format used by default by the in-memory functions is
  71725. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  71726. around a deflate stream, which is itself documented in RFC 1951.
  71727. The library also supports reading and writing files in gzip (.gz) format
  71728. with an interface similar to that of stdio using the functions that start
  71729. with "gz". The gzip format is different from the zlib format. gzip is a
  71730. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  71731. This library can optionally read and write gzip streams in memory as well.
  71732. The zlib format was designed to be compact and fast for use in memory
  71733. and on communications channels. The gzip format was designed for single-
  71734. file compression on file systems, has a larger header than zlib to maintain
  71735. directory information, and uses a different, slower check method than zlib.
  71736. The library does not install any signal handler. The decoder checks
  71737. the consistency of the compressed data, so the library should never
  71738. crash even in case of corrupted input.
  71739. */
  71740. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  71741. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  71742. struct internal_state;
  71743. typedef struct z_stream_s {
  71744. Bytef *next_in; /* next input byte */
  71745. uInt avail_in; /* number of bytes available at next_in */
  71746. uLong total_in; /* total nb of input bytes read so far */
  71747. Bytef *next_out; /* next output byte should be put there */
  71748. uInt avail_out; /* remaining free space at next_out */
  71749. uLong total_out; /* total nb of bytes output so far */
  71750. char *msg; /* last error message, NULL if no error */
  71751. struct internal_state FAR *state; /* not visible by applications */
  71752. alloc_func zalloc; /* used to allocate the internal state */
  71753. free_func zfree; /* used to free the internal state */
  71754. voidpf opaque; /* private data object passed to zalloc and zfree */
  71755. int data_type; /* best guess about the data type: binary or text */
  71756. uLong adler; /* adler32 value of the uncompressed data */
  71757. uLong reserved; /* reserved for future use */
  71758. } z_stream;
  71759. typedef z_stream FAR *z_streamp;
  71760. /*
  71761. gzip header information passed to and from zlib routines. See RFC 1952
  71762. for more details on the meanings of these fields.
  71763. */
  71764. typedef struct gz_header_s {
  71765. int text; /* true if compressed data believed to be text */
  71766. uLong time; /* modification time */
  71767. int xflags; /* extra flags (not used when writing a gzip file) */
  71768. int os; /* operating system */
  71769. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  71770. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  71771. uInt extra_max; /* space at extra (only when reading header) */
  71772. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  71773. uInt name_max; /* space at name (only when reading header) */
  71774. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  71775. uInt comm_max; /* space at comment (only when reading header) */
  71776. int hcrc; /* true if there was or will be a header crc */
  71777. int done; /* true when done reading gzip header (not used
  71778. when writing a gzip file) */
  71779. } gz_header;
  71780. typedef gz_header FAR *gz_headerp;
  71781. /*
  71782. The application must update next_in and avail_in when avail_in has
  71783. dropped to zero. It must update next_out and avail_out when avail_out
  71784. has dropped to zero. The application must initialize zalloc, zfree and
  71785. opaque before calling the init function. All other fields are set by the
  71786. compression library and must not be updated by the application.
  71787. The opaque value provided by the application will be passed as the first
  71788. parameter for calls of zalloc and zfree. This can be useful for custom
  71789. memory management. The compression library attaches no meaning to the
  71790. opaque value.
  71791. zalloc must return Z_NULL if there is not enough memory for the object.
  71792. If zlib is used in a multi-threaded application, zalloc and zfree must be
  71793. thread safe.
  71794. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  71795. exactly 65536 bytes, but will not be required to allocate more than this
  71796. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  71797. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  71798. have their offset normalized to zero. The default allocation function
  71799. provided by this library ensures this (see zutil.c). To reduce memory
  71800. requirements and avoid any allocation of 64K objects, at the expense of
  71801. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  71802. The fields total_in and total_out can be used for statistics or
  71803. progress reports. After compression, total_in holds the total size of
  71804. the uncompressed data and may be saved for use in the decompressor
  71805. (particularly if the decompressor wants to decompress everything in
  71806. a single step).
  71807. */
  71808. /* constants */
  71809. #define Z_NO_FLUSH 0
  71810. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  71811. #define Z_SYNC_FLUSH 2
  71812. #define Z_FULL_FLUSH 3
  71813. #define Z_FINISH 4
  71814. #define Z_BLOCK 5
  71815. /* Allowed flush values; see deflate() and inflate() below for details */
  71816. #define Z_OK 0
  71817. #define Z_STREAM_END 1
  71818. #define Z_NEED_DICT 2
  71819. #define Z_ERRNO (-1)
  71820. #define Z_STREAM_ERROR (-2)
  71821. #define Z_DATA_ERROR (-3)
  71822. #define Z_MEM_ERROR (-4)
  71823. #define Z_BUF_ERROR (-5)
  71824. #define Z_VERSION_ERROR (-6)
  71825. /* Return codes for the compression/decompression functions. Negative
  71826. * values are errors, positive values are used for special but normal events.
  71827. */
  71828. #define Z_NO_COMPRESSION 0
  71829. #define Z_BEST_SPEED 1
  71830. #define Z_BEST_COMPRESSION 9
  71831. #define Z_DEFAULT_COMPRESSION (-1)
  71832. /* compression levels */
  71833. #define Z_FILTERED 1
  71834. #define Z_HUFFMAN_ONLY 2
  71835. #define Z_RLE 3
  71836. #define Z_FIXED 4
  71837. #define Z_DEFAULT_STRATEGY 0
  71838. /* compression strategy; see deflateInit2() below for details */
  71839. #define Z_BINARY 0
  71840. #define Z_TEXT 1
  71841. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  71842. #define Z_UNKNOWN 2
  71843. /* Possible values of the data_type field (though see inflate()) */
  71844. #define Z_DEFLATED 8
  71845. /* The deflate compression method (the only one supported in this version) */
  71846. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  71847. #define zlib_version zlibVersion()
  71848. /* for compatibility with versions < 1.0.2 */
  71849. /* basic functions */
  71850. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  71851. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  71852. If the first character differs, the library code actually used is
  71853. not compatible with the zlib.h header file used by the application.
  71854. This check is automatically made by deflateInit and inflateInit.
  71855. */
  71856. /*
  71857. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  71858. Initializes the internal stream state for compression. The fields
  71859. zalloc, zfree and opaque must be initialized before by the caller.
  71860. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  71861. use default allocation functions.
  71862. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  71863. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  71864. all (the input data is simply copied a block at a time).
  71865. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  71866. compression (currently equivalent to level 6).
  71867. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  71868. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  71869. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  71870. with the version assumed by the caller (ZLIB_VERSION).
  71871. msg is set to null if there is no error message. deflateInit does not
  71872. perform any compression: this will be done by deflate().
  71873. */
  71874. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  71875. /*
  71876. deflate compresses as much data as possible, and stops when the input
  71877. buffer becomes empty or the output buffer becomes full. It may introduce some
  71878. output latency (reading input without producing any output) except when
  71879. forced to flush.
  71880. The detailed semantics are as follows. deflate performs one or both of the
  71881. following actions:
  71882. - Compress more input starting at next_in and update next_in and avail_in
  71883. accordingly. If not all input can be processed (because there is not
  71884. enough room in the output buffer), next_in and avail_in are updated and
  71885. processing will resume at this point for the next call of deflate().
  71886. - Provide more output starting at next_out and update next_out and avail_out
  71887. accordingly. This action is forced if the parameter flush is non zero.
  71888. Forcing flush frequently degrades the compression ratio, so this parameter
  71889. should be set only when necessary (in interactive applications).
  71890. Some output may be provided even if flush is not set.
  71891. Before the call of deflate(), the application should ensure that at least
  71892. one of the actions is possible, by providing more input and/or consuming
  71893. more output, and updating avail_in or avail_out accordingly; avail_out
  71894. should never be zero before the call. The application can consume the
  71895. compressed output when it wants, for example when the output buffer is full
  71896. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  71897. and with zero avail_out, it must be called again after making room in the
  71898. output buffer because there might be more output pending.
  71899. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  71900. decide how much data to accumualte before producing output, in order to
  71901. maximize compression.
  71902. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  71903. flushed to the output buffer and the output is aligned on a byte boundary, so
  71904. that the decompressor can get all input data available so far. (In particular
  71905. avail_in is zero after the call if enough output space has been provided
  71906. before the call.) Flushing may degrade compression for some compression
  71907. algorithms and so it should be used only when necessary.
  71908. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  71909. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  71910. restart from this point if previous compressed data has been damaged or if
  71911. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  71912. compression.
  71913. If deflate returns with avail_out == 0, this function must be called again
  71914. with the same value of the flush parameter and more output space (updated
  71915. avail_out), until the flush is complete (deflate returns with non-zero
  71916. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  71917. avail_out is greater than six to avoid repeated flush markers due to
  71918. avail_out == 0 on return.
  71919. If the parameter flush is set to Z_FINISH, pending input is processed,
  71920. pending output is flushed and deflate returns with Z_STREAM_END if there
  71921. was enough output space; if deflate returns with Z_OK, this function must be
  71922. called again with Z_FINISH and more output space (updated avail_out) but no
  71923. more input data, until it returns with Z_STREAM_END or an error. After
  71924. deflate has returned Z_STREAM_END, the only possible operations on the
  71925. stream are deflateReset or deflateEnd.
  71926. Z_FINISH can be used immediately after deflateInit if all the compression
  71927. is to be done in a single step. In this case, avail_out must be at least
  71928. the value returned by deflateBound (see below). If deflate does not return
  71929. Z_STREAM_END, then it must be called again as described above.
  71930. deflate() sets strm->adler to the adler32 checksum of all input read
  71931. so far (that is, total_in bytes).
  71932. deflate() may update strm->data_type if it can make a good guess about
  71933. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  71934. binary. This field is only for information purposes and does not affect
  71935. the compression algorithm in any manner.
  71936. deflate() returns Z_OK if some progress has been made (more input
  71937. processed or more output produced), Z_STREAM_END if all input has been
  71938. consumed and all output has been produced (only when flush is set to
  71939. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  71940. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  71941. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  71942. fatal, and deflate() can be called again with more input and more output
  71943. space to continue compressing.
  71944. */
  71945. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  71946. /*
  71947. All dynamically allocated data structures for this stream are freed.
  71948. This function discards any unprocessed input and does not flush any
  71949. pending output.
  71950. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  71951. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  71952. prematurely (some input or output was discarded). In the error case,
  71953. msg may be set but then points to a static string (which must not be
  71954. deallocated).
  71955. */
  71956. /*
  71957. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  71958. Initializes the internal stream state for decompression. The fields
  71959. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  71960. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  71961. value depends on the compression method), inflateInit determines the
  71962. compression method from the zlib header and allocates all data structures
  71963. accordingly; otherwise the allocation will be deferred to the first call of
  71964. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  71965. use default allocation functions.
  71966. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  71967. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  71968. version assumed by the caller. msg is set to null if there is no error
  71969. message. inflateInit does not perform any decompression apart from reading
  71970. the zlib header if present: this will be done by inflate(). (So next_in and
  71971. avail_in may be modified, but next_out and avail_out are unchanged.)
  71972. */
  71973. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  71974. /*
  71975. inflate decompresses as much data as possible, and stops when the input
  71976. buffer becomes empty or the output buffer becomes full. It may introduce
  71977. some output latency (reading input without producing any output) except when
  71978. forced to flush.
  71979. The detailed semantics are as follows. inflate performs one or both of the
  71980. following actions:
  71981. - Decompress more input starting at next_in and update next_in and avail_in
  71982. accordingly. If not all input can be processed (because there is not
  71983. enough room in the output buffer), next_in is updated and processing
  71984. will resume at this point for the next call of inflate().
  71985. - Provide more output starting at next_out and update next_out and avail_out
  71986. accordingly. inflate() provides as much output as possible, until there
  71987. is no more input data or no more space in the output buffer (see below
  71988. about the flush parameter).
  71989. Before the call of inflate(), the application should ensure that at least
  71990. one of the actions is possible, by providing more input and/or consuming
  71991. more output, and updating the next_* and avail_* values accordingly.
  71992. The application can consume the uncompressed output when it wants, for
  71993. example when the output buffer is full (avail_out == 0), or after each
  71994. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  71995. must be called again after making room in the output buffer because there
  71996. might be more output pending.
  71997. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  71998. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  71999. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  72000. if and when it gets to the next deflate block boundary. When decoding the
  72001. zlib or gzip format, this will cause inflate() to return immediately after
  72002. the header and before the first block. When doing a raw inflate, inflate()
  72003. will go ahead and process the first block, and will return when it gets to
  72004. the end of that block, or when it runs out of data.
  72005. The Z_BLOCK option assists in appending to or combining deflate streams.
  72006. Also to assist in this, on return inflate() will set strm->data_type to the
  72007. number of unused bits in the last byte taken from strm->next_in, plus 64
  72008. if inflate() is currently decoding the last block in the deflate stream,
  72009. plus 128 if inflate() returned immediately after decoding an end-of-block
  72010. code or decoding the complete header up to just before the first byte of the
  72011. deflate stream. The end-of-block will not be indicated until all of the
  72012. uncompressed data from that block has been written to strm->next_out. The
  72013. number of unused bits may in general be greater than seven, except when
  72014. bit 7 of data_type is set, in which case the number of unused bits will be
  72015. less than eight.
  72016. inflate() should normally be called until it returns Z_STREAM_END or an
  72017. error. However if all decompression is to be performed in a single step
  72018. (a single call of inflate), the parameter flush should be set to
  72019. Z_FINISH. In this case all pending input is processed and all pending
  72020. output is flushed; avail_out must be large enough to hold all the
  72021. uncompressed data. (The size of the uncompressed data may have been saved
  72022. by the compressor for this purpose.) The next operation on this stream must
  72023. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  72024. is never required, but can be used to inform inflate that a faster approach
  72025. may be used for the single inflate() call.
  72026. In this implementation, inflate() always flushes as much output as
  72027. possible to the output buffer, and always uses the faster approach on the
  72028. first call. So the only effect of the flush parameter in this implementation
  72029. is on the return value of inflate(), as noted below, or when it returns early
  72030. because Z_BLOCK is used.
  72031. If a preset dictionary is needed after this call (see inflateSetDictionary
  72032. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  72033. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  72034. strm->adler to the adler32 checksum of all output produced so far (that is,
  72035. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  72036. below. At the end of the stream, inflate() checks that its computed adler32
  72037. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  72038. only if the checksum is correct.
  72039. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  72040. deflate data. The header type is detected automatically. Any information
  72041. contained in the gzip header is not retained, so applications that need that
  72042. information should instead use raw inflate, see inflateInit2() below, or
  72043. inflateBack() and perform their own processing of the gzip header and
  72044. trailer.
  72045. inflate() returns Z_OK if some progress has been made (more input processed
  72046. or more output produced), Z_STREAM_END if the end of the compressed data has
  72047. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  72048. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  72049. corrupted (input stream not conforming to the zlib format or incorrect check
  72050. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  72051. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  72052. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  72053. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  72054. inflate() can be called again with more input and more output space to
  72055. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  72056. call inflateSync() to look for a good compression block if a partial recovery
  72057. of the data is desired.
  72058. */
  72059. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  72060. /*
  72061. All dynamically allocated data structures for this stream are freed.
  72062. This function discards any unprocessed input and does not flush any
  72063. pending output.
  72064. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  72065. was inconsistent. In the error case, msg may be set but then points to a
  72066. static string (which must not be deallocated).
  72067. */
  72068. /* Advanced functions */
  72069. /*
  72070. The following functions are needed only in some special applications.
  72071. */
  72072. /*
  72073. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  72074. int level,
  72075. int method,
  72076. int windowBits,
  72077. int memLevel,
  72078. int strategy));
  72079. This is another version of deflateInit with more compression options. The
  72080. fields next_in, zalloc, zfree and opaque must be initialized before by
  72081. the caller.
  72082. The method parameter is the compression method. It must be Z_DEFLATED in
  72083. this version of the library.
  72084. The windowBits parameter is the base two logarithm of the window size
  72085. (the size of the history buffer). It should be in the range 8..15 for this
  72086. version of the library. Larger values of this parameter result in better
  72087. compression at the expense of memory usage. The default value is 15 if
  72088. deflateInit is used instead.
  72089. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  72090. determines the window size. deflate() will then generate raw deflate data
  72091. with no zlib header or trailer, and will not compute an adler32 check value.
  72092. windowBits can also be greater than 15 for optional gzip encoding. Add
  72093. 16 to windowBits to write a simple gzip header and trailer around the
  72094. compressed data instead of a zlib wrapper. The gzip header will have no
  72095. file name, no extra data, no comment, no modification time (set to zero),
  72096. no header crc, and the operating system will be set to 255 (unknown). If a
  72097. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  72098. The memLevel parameter specifies how much memory should be allocated
  72099. for the internal compression state. memLevel=1 uses minimum memory but
  72100. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  72101. for optimal speed. The default value is 8. See zconf.h for total memory
  72102. usage as a function of windowBits and memLevel.
  72103. The strategy parameter is used to tune the compression algorithm. Use the
  72104. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  72105. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  72106. string match), or Z_RLE to limit match distances to one (run-length
  72107. encoding). Filtered data consists mostly of small values with a somewhat
  72108. random distribution. In this case, the compression algorithm is tuned to
  72109. compress them better. The effect of Z_FILTERED is to force more Huffman
  72110. coding and less string matching; it is somewhat intermediate between
  72111. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  72112. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  72113. parameter only affects the compression ratio but not the correctness of the
  72114. compressed output even if it is not set appropriately. Z_FIXED prevents the
  72115. use of dynamic Huffman codes, allowing for a simpler decoder for special
  72116. applications.
  72117. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  72118. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  72119. method). msg is set to null if there is no error message. deflateInit2 does
  72120. not perform any compression: this will be done by deflate().
  72121. */
  72122. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  72123. const Bytef *dictionary,
  72124. uInt dictLength));
  72125. /*
  72126. Initializes the compression dictionary from the given byte sequence
  72127. without producing any compressed output. This function must be called
  72128. immediately after deflateInit, deflateInit2 or deflateReset, before any
  72129. call of deflate. The compressor and decompressor must use exactly the same
  72130. dictionary (see inflateSetDictionary).
  72131. The dictionary should consist of strings (byte sequences) that are likely
  72132. to be encountered later in the data to be compressed, with the most commonly
  72133. used strings preferably put towards the end of the dictionary. Using a
  72134. dictionary is most useful when the data to be compressed is short and can be
  72135. predicted with good accuracy; the data can then be compressed better than
  72136. with the default empty dictionary.
  72137. Depending on the size of the compression data structures selected by
  72138. deflateInit or deflateInit2, a part of the dictionary may in effect be
  72139. discarded, for example if the dictionary is larger than the window size in
  72140. deflate or deflate2. Thus the strings most likely to be useful should be
  72141. put at the end of the dictionary, not at the front. In addition, the
  72142. current implementation of deflate will use at most the window size minus
  72143. 262 bytes of the provided dictionary.
  72144. Upon return of this function, strm->adler is set to the adler32 value
  72145. of the dictionary; the decompressor may later use this value to determine
  72146. which dictionary has been used by the compressor. (The adler32 value
  72147. applies to the whole dictionary even if only a subset of the dictionary is
  72148. actually used by the compressor.) If a raw deflate was requested, then the
  72149. adler32 value is not computed and strm->adler is not set.
  72150. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  72151. parameter is invalid (such as NULL dictionary) or the stream state is
  72152. inconsistent (for example if deflate has already been called for this stream
  72153. or if the compression method is bsort). deflateSetDictionary does not
  72154. perform any compression: this will be done by deflate().
  72155. */
  72156. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  72157. z_streamp source));
  72158. /*
  72159. Sets the destination stream as a complete copy of the source stream.
  72160. This function can be useful when several compression strategies will be
  72161. tried, for example when there are several ways of pre-processing the input
  72162. data with a filter. The streams that will be discarded should then be freed
  72163. by calling deflateEnd. Note that deflateCopy duplicates the internal
  72164. compression state which can be quite large, so this strategy is slow and
  72165. can consume lots of memory.
  72166. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  72167. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  72168. (such as zalloc being NULL). msg is left unchanged in both source and
  72169. destination.
  72170. */
  72171. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  72172. /*
  72173. This function is equivalent to deflateEnd followed by deflateInit,
  72174. but does not free and reallocate all the internal compression state.
  72175. The stream will keep the same compression level and any other attributes
  72176. that may have been set by deflateInit2.
  72177. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  72178. stream state was inconsistent (such as zalloc or state being NULL).
  72179. */
  72180. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  72181. int level,
  72182. int strategy));
  72183. /*
  72184. Dynamically update the compression level and compression strategy. The
  72185. interpretation of level and strategy is as in deflateInit2. This can be
  72186. used to switch between compression and straight copy of the input data, or
  72187. to switch to a different kind of input data requiring a different
  72188. strategy. If the compression level is changed, the input available so far
  72189. is compressed with the old level (and may be flushed); the new level will
  72190. take effect only at the next call of deflate().
  72191. Before the call of deflateParams, the stream state must be set as for
  72192. a call of deflate(), since the currently available input may have to
  72193. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  72194. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  72195. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  72196. if strm->avail_out was zero.
  72197. */
  72198. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  72199. int good_length,
  72200. int max_lazy,
  72201. int nice_length,
  72202. int max_chain));
  72203. /*
  72204. Fine tune deflate's internal compression parameters. This should only be
  72205. used by someone who understands the algorithm used by zlib's deflate for
  72206. searching for the best matching string, and even then only by the most
  72207. fanatic optimizer trying to squeeze out the last compressed bit for their
  72208. specific input data. Read the deflate.c source code for the meaning of the
  72209. max_lazy, good_length, nice_length, and max_chain parameters.
  72210. deflateTune() can be called after deflateInit() or deflateInit2(), and
  72211. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  72212. */
  72213. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  72214. uLong sourceLen));
  72215. /*
  72216. deflateBound() returns an upper bound on the compressed size after
  72217. deflation of sourceLen bytes. It must be called after deflateInit()
  72218. or deflateInit2(). This would be used to allocate an output buffer
  72219. for deflation in a single pass, and so would be called before deflate().
  72220. */
  72221. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  72222. int bits,
  72223. int value));
  72224. /*
  72225. deflatePrime() inserts bits in the deflate output stream. The intent
  72226. is that this function is used to start off the deflate output with the
  72227. bits leftover from a previous deflate stream when appending to it. As such,
  72228. this function can only be used for raw deflate, and must be used before the
  72229. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  72230. less than or equal to 16, and that many of the least significant bits of
  72231. value will be inserted in the output.
  72232. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  72233. stream state was inconsistent.
  72234. */
  72235. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  72236. gz_headerp head));
  72237. /*
  72238. deflateSetHeader() provides gzip header information for when a gzip
  72239. stream is requested by deflateInit2(). deflateSetHeader() may be called
  72240. after deflateInit2() or deflateReset() and before the first call of
  72241. deflate(). The text, time, os, extra field, name, and comment information
  72242. in the provided gz_header structure are written to the gzip header (xflag is
  72243. ignored -- the extra flags are set according to the compression level). The
  72244. caller must assure that, if not Z_NULL, name and comment are terminated with
  72245. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  72246. available there. If hcrc is true, a gzip header crc is included. Note that
  72247. the current versions of the command-line version of gzip (up through version
  72248. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  72249. gzip file" and give up.
  72250. If deflateSetHeader is not used, the default gzip header has text false,
  72251. the time set to zero, and os set to 255, with no extra, name, or comment
  72252. fields. The gzip header is returned to the default state by deflateReset().
  72253. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  72254. stream state was inconsistent.
  72255. */
  72256. /*
  72257. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  72258. int windowBits));
  72259. This is another version of inflateInit with an extra parameter. The
  72260. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  72261. before by the caller.
  72262. The windowBits parameter is the base two logarithm of the maximum window
  72263. size (the size of the history buffer). It should be in the range 8..15 for
  72264. this version of the library. The default value is 15 if inflateInit is used
  72265. instead. windowBits must be greater than or equal to the windowBits value
  72266. provided to deflateInit2() while compressing, or it must be equal to 15 if
  72267. deflateInit2() was not used. If a compressed stream with a larger window
  72268. size is given as input, inflate() will return with the error code
  72269. Z_DATA_ERROR instead of trying to allocate a larger window.
  72270. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  72271. determines the window size. inflate() will then process raw deflate data,
  72272. not looking for a zlib or gzip header, not generating a check value, and not
  72273. looking for any check values for comparison at the end of the stream. This
  72274. is for use with other formats that use the deflate compressed data format
  72275. such as zip. Those formats provide their own check values. If a custom
  72276. format is developed using the raw deflate format for compressed data, it is
  72277. recommended that a check value such as an adler32 or a crc32 be applied to
  72278. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  72279. most applications, the zlib format should be used as is. Note that comments
  72280. above on the use in deflateInit2() applies to the magnitude of windowBits.
  72281. windowBits can also be greater than 15 for optional gzip decoding. Add
  72282. 32 to windowBits to enable zlib and gzip decoding with automatic header
  72283. detection, or add 16 to decode only the gzip format (the zlib format will
  72284. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  72285. a crc32 instead of an adler32.
  72286. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  72287. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  72288. is set to null if there is no error message. inflateInit2 does not perform
  72289. any decompression apart from reading the zlib header if present: this will
  72290. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  72291. and avail_out are unchanged.)
  72292. */
  72293. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  72294. const Bytef *dictionary,
  72295. uInt dictLength));
  72296. /*
  72297. Initializes the decompression dictionary from the given uncompressed byte
  72298. sequence. This function must be called immediately after a call of inflate,
  72299. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  72300. can be determined from the adler32 value returned by that call of inflate.
  72301. The compressor and decompressor must use exactly the same dictionary (see
  72302. deflateSetDictionary). For raw inflate, this function can be called
  72303. immediately after inflateInit2() or inflateReset() and before any call of
  72304. inflate() to set the dictionary. The application must insure that the
  72305. dictionary that was used for compression is provided.
  72306. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  72307. parameter is invalid (such as NULL dictionary) or the stream state is
  72308. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  72309. expected one (incorrect adler32 value). inflateSetDictionary does not
  72310. perform any decompression: this will be done by subsequent calls of
  72311. inflate().
  72312. */
  72313. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  72314. /*
  72315. Skips invalid compressed data until a full flush point (see above the
  72316. description of deflate with Z_FULL_FLUSH) can be found, or until all
  72317. available input is skipped. No output is provided.
  72318. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  72319. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  72320. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  72321. case, the application may save the current current value of total_in which
  72322. indicates where valid compressed data was found. In the error case, the
  72323. application may repeatedly call inflateSync, providing more input each time,
  72324. until success or end of the input data.
  72325. */
  72326. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  72327. z_streamp source));
  72328. /*
  72329. Sets the destination stream as a complete copy of the source stream.
  72330. This function can be useful when randomly accessing a large stream. The
  72331. first pass through the stream can periodically record the inflate state,
  72332. allowing restarting inflate at those points when randomly accessing the
  72333. stream.
  72334. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  72335. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  72336. (such as zalloc being NULL). msg is left unchanged in both source and
  72337. destination.
  72338. */
  72339. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  72340. /*
  72341. This function is equivalent to inflateEnd followed by inflateInit,
  72342. but does not free and reallocate all the internal decompression state.
  72343. The stream will keep attributes that may have been set by inflateInit2.
  72344. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  72345. stream state was inconsistent (such as zalloc or state being NULL).
  72346. */
  72347. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  72348. int bits,
  72349. int value));
  72350. /*
  72351. This function inserts bits in the inflate input stream. The intent is
  72352. that this function is used to start inflating at a bit position in the
  72353. middle of a byte. The provided bits will be used before any bytes are used
  72354. from next_in. This function should only be used with raw inflate, and
  72355. should be used before the first inflate() call after inflateInit2() or
  72356. inflateReset(). bits must be less than or equal to 16, and that many of the
  72357. least significant bits of value will be inserted in the input.
  72358. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  72359. stream state was inconsistent.
  72360. */
  72361. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  72362. gz_headerp head));
  72363. /*
  72364. inflateGetHeader() requests that gzip header information be stored in the
  72365. provided gz_header structure. inflateGetHeader() may be called after
  72366. inflateInit2() or inflateReset(), and before the first call of inflate().
  72367. As inflate() processes the gzip stream, head->done is zero until the header
  72368. is completed, at which time head->done is set to one. If a zlib stream is
  72369. being decoded, then head->done is set to -1 to indicate that there will be
  72370. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  72371. force inflate() to return immediately after header processing is complete
  72372. and before any actual data is decompressed.
  72373. The text, time, xflags, and os fields are filled in with the gzip header
  72374. contents. hcrc is set to true if there is a header CRC. (The header CRC
  72375. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  72376. contains the maximum number of bytes to write to extra. Once done is true,
  72377. extra_len contains the actual extra field length, and extra contains the
  72378. extra field, or that field truncated if extra_max is less than extra_len.
  72379. If name is not Z_NULL, then up to name_max characters are written there,
  72380. terminated with a zero unless the length is greater than name_max. If
  72381. comment is not Z_NULL, then up to comm_max characters are written there,
  72382. terminated with a zero unless the length is greater than comm_max. When
  72383. any of extra, name, or comment are not Z_NULL and the respective field is
  72384. not present in the header, then that field is set to Z_NULL to signal its
  72385. absence. This allows the use of deflateSetHeader() with the returned
  72386. structure to duplicate the header. However if those fields are set to
  72387. allocated memory, then the application will need to save those pointers
  72388. elsewhere so that they can be eventually freed.
  72389. If inflateGetHeader is not used, then the header information is simply
  72390. discarded. The header is always checked for validity, including the header
  72391. CRC if present. inflateReset() will reset the process to discard the header
  72392. information. The application would need to call inflateGetHeader() again to
  72393. retrieve the header from the next gzip stream.
  72394. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  72395. stream state was inconsistent.
  72396. */
  72397. /*
  72398. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  72399. unsigned char FAR *window));
  72400. Initialize the internal stream state for decompression using inflateBack()
  72401. calls. The fields zalloc, zfree and opaque in strm must be initialized
  72402. before the call. If zalloc and zfree are Z_NULL, then the default library-
  72403. derived memory allocation routines are used. windowBits is the base two
  72404. logarithm of the window size, in the range 8..15. window is a caller
  72405. supplied buffer of that size. Except for special applications where it is
  72406. assured that deflate was used with small window sizes, windowBits must be 15
  72407. and a 32K byte window must be supplied to be able to decompress general
  72408. deflate streams.
  72409. See inflateBack() for the usage of these routines.
  72410. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  72411. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  72412. be allocated, or Z_VERSION_ERROR if the version of the library does not
  72413. match the version of the header file.
  72414. */
  72415. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  72416. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  72417. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  72418. in_func in, void FAR *in_desc,
  72419. out_func out, void FAR *out_desc));
  72420. /*
  72421. inflateBack() does a raw inflate with a single call using a call-back
  72422. interface for input and output. This is more efficient than inflate() for
  72423. file i/o applications in that it avoids copying between the output and the
  72424. sliding window by simply making the window itself the output buffer. This
  72425. function trusts the application to not change the output buffer passed by
  72426. the output function, at least until inflateBack() returns.
  72427. inflateBackInit() must be called first to allocate the internal state
  72428. and to initialize the state with the user-provided window buffer.
  72429. inflateBack() may then be used multiple times to inflate a complete, raw
  72430. deflate stream with each call. inflateBackEnd() is then called to free
  72431. the allocated state.
  72432. A raw deflate stream is one with no zlib or gzip header or trailer.
  72433. This routine would normally be used in a utility that reads zip or gzip
  72434. files and writes out uncompressed files. The utility would decode the
  72435. header and process the trailer on its own, hence this routine expects
  72436. only the raw deflate stream to decompress. This is different from the
  72437. normal behavior of inflate(), which expects either a zlib or gzip header and
  72438. trailer around the deflate stream.
  72439. inflateBack() uses two subroutines supplied by the caller that are then
  72440. called by inflateBack() for input and output. inflateBack() calls those
  72441. routines until it reads a complete deflate stream and writes out all of the
  72442. uncompressed data, or until it encounters an error. The function's
  72443. parameters and return types are defined above in the in_func and out_func
  72444. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  72445. number of bytes of provided input, and a pointer to that input in buf. If
  72446. there is no input available, in() must return zero--buf is ignored in that
  72447. case--and inflateBack() will return a buffer error. inflateBack() will call
  72448. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  72449. should return zero on success, or non-zero on failure. If out() returns
  72450. non-zero, inflateBack() will return with an error. Neither in() nor out()
  72451. are permitted to change the contents of the window provided to
  72452. inflateBackInit(), which is also the buffer that out() uses to write from.
  72453. The length written by out() will be at most the window size. Any non-zero
  72454. amount of input may be provided by in().
  72455. For convenience, inflateBack() can be provided input on the first call by
  72456. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  72457. in() will be called. Therefore strm->next_in must be initialized before
  72458. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  72459. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  72460. must also be initialized, and then if strm->avail_in is not zero, input will
  72461. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  72462. The in_desc and out_desc parameters of inflateBack() is passed as the
  72463. first parameter of in() and out() respectively when they are called. These
  72464. descriptors can be optionally used to pass any information that the caller-
  72465. supplied in() and out() functions need to do their job.
  72466. On return, inflateBack() will set strm->next_in and strm->avail_in to
  72467. pass back any unused input that was provided by the last in() call. The
  72468. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  72469. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  72470. error in the deflate stream (in which case strm->msg is set to indicate the
  72471. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  72472. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  72473. distinguished using strm->next_in which will be Z_NULL only if in() returned
  72474. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  72475. out() returning non-zero. (in() will always be called before out(), so
  72476. strm->next_in is assured to be defined if out() returns non-zero.) Note
  72477. that inflateBack() cannot return Z_OK.
  72478. */
  72479. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  72480. /*
  72481. All memory allocated by inflateBackInit() is freed.
  72482. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  72483. state was inconsistent.
  72484. */
  72485. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  72486. /* Return flags indicating compile-time options.
  72487. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  72488. 1.0: size of uInt
  72489. 3.2: size of uLong
  72490. 5.4: size of voidpf (pointer)
  72491. 7.6: size of z_off_t
  72492. Compiler, assembler, and debug options:
  72493. 8: DEBUG
  72494. 9: ASMV or ASMINF -- use ASM code
  72495. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  72496. 11: 0 (reserved)
  72497. One-time table building (smaller code, but not thread-safe if true):
  72498. 12: BUILDFIXED -- build static block decoding tables when needed
  72499. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  72500. 14,15: 0 (reserved)
  72501. Library content (indicates missing functionality):
  72502. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  72503. deflate code when not needed)
  72504. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  72505. and decode gzip streams (to avoid linking crc code)
  72506. 18-19: 0 (reserved)
  72507. Operation variations (changes in library functionality):
  72508. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  72509. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  72510. 22,23: 0 (reserved)
  72511. The sprintf variant used by gzprintf (zero is best):
  72512. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  72513. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  72514. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  72515. Remainder:
  72516. 27-31: 0 (reserved)
  72517. */
  72518. /* utility functions */
  72519. /*
  72520. The following utility functions are implemented on top of the
  72521. basic stream-oriented functions. To simplify the interface, some
  72522. default options are assumed (compression level and memory usage,
  72523. standard memory allocation functions). The source code of these
  72524. utility functions can easily be modified if you need special options.
  72525. */
  72526. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  72527. const Bytef *source, uLong sourceLen));
  72528. /*
  72529. Compresses the source buffer into the destination buffer. sourceLen is
  72530. the byte length of the source buffer. Upon entry, destLen is the total
  72531. size of the destination buffer, which must be at least the value returned
  72532. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  72533. compressed buffer.
  72534. This function can be used to compress a whole file at once if the
  72535. input file is mmap'ed.
  72536. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  72537. enough memory, Z_BUF_ERROR if there was not enough room in the output
  72538. buffer.
  72539. */
  72540. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  72541. const Bytef *source, uLong sourceLen,
  72542. int level));
  72543. /*
  72544. Compresses the source buffer into the destination buffer. The level
  72545. parameter has the same meaning as in deflateInit. sourceLen is the byte
  72546. length of the source buffer. Upon entry, destLen is the total size of the
  72547. destination buffer, which must be at least the value returned by
  72548. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  72549. compressed buffer.
  72550. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  72551. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  72552. Z_STREAM_ERROR if the level parameter is invalid.
  72553. */
  72554. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  72555. /*
  72556. compressBound() returns an upper bound on the compressed size after
  72557. compress() or compress2() on sourceLen bytes. It would be used before
  72558. a compress() or compress2() call to allocate the destination buffer.
  72559. */
  72560. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  72561. const Bytef *source, uLong sourceLen));
  72562. /*
  72563. Decompresses the source buffer into the destination buffer. sourceLen is
  72564. the byte length of the source buffer. Upon entry, destLen is the total
  72565. size of the destination buffer, which must be large enough to hold the
  72566. entire uncompressed data. (The size of the uncompressed data must have
  72567. been saved previously by the compressor and transmitted to the decompressor
  72568. by some mechanism outside the scope of this compression library.)
  72569. Upon exit, destLen is the actual size of the compressed buffer.
  72570. This function can be used to decompress a whole file at once if the
  72571. input file is mmap'ed.
  72572. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  72573. enough memory, Z_BUF_ERROR if there was not enough room in the output
  72574. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  72575. */
  72576. typedef voidp gzFile;
  72577. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  72578. /*
  72579. Opens a gzip (.gz) file for reading or writing. The mode parameter
  72580. is as in fopen ("rb" or "wb") but can also include a compression level
  72581. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  72582. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  72583. as in "wb1R". (See the description of deflateInit2 for more information
  72584. about the strategy parameter.)
  72585. gzopen can be used to read a file which is not in gzip format; in this
  72586. case gzread will directly read from the file without decompression.
  72587. gzopen returns NULL if the file could not be opened or if there was
  72588. insufficient memory to allocate the (de)compression state; errno
  72589. can be checked to distinguish the two cases (if errno is zero, the
  72590. zlib error is Z_MEM_ERROR). */
  72591. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  72592. /*
  72593. gzdopen() associates a gzFile with the file descriptor fd. File
  72594. descriptors are obtained from calls like open, dup, creat, pipe or
  72595. fileno (in the file has been previously opened with fopen).
  72596. The mode parameter is as in gzopen.
  72597. The next call of gzclose on the returned gzFile will also close the
  72598. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  72599. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  72600. gzdopen returns NULL if there was insufficient memory to allocate
  72601. the (de)compression state.
  72602. */
  72603. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  72604. /*
  72605. Dynamically update the compression level or strategy. See the description
  72606. of deflateInit2 for the meaning of these parameters.
  72607. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  72608. opened for writing.
  72609. */
  72610. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  72611. /*
  72612. Reads the given number of uncompressed bytes from the compressed file.
  72613. If the input file was not in gzip format, gzread copies the given number
  72614. of bytes into the buffer.
  72615. gzread returns the number of uncompressed bytes actually read (0 for
  72616. end of file, -1 for error). */
  72617. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  72618. voidpc buf, unsigned len));
  72619. /*
  72620. Writes the given number of uncompressed bytes into the compressed file.
  72621. gzwrite returns the number of uncompressed bytes actually written
  72622. (0 in case of error).
  72623. */
  72624. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  72625. /*
  72626. Converts, formats, and writes the args to the compressed file under
  72627. control of the format string, as in fprintf. gzprintf returns the number of
  72628. uncompressed bytes actually written (0 in case of error). The number of
  72629. uncompressed bytes written is limited to 4095. The caller should assure that
  72630. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  72631. return an error (0) with nothing written. In this case, there may also be a
  72632. buffer overflow with unpredictable consequences, which is possible only if
  72633. zlib was compiled with the insecure functions sprintf() or vsprintf()
  72634. because the secure snprintf() or vsnprintf() functions were not available.
  72635. */
  72636. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  72637. /*
  72638. Writes the given null-terminated string to the compressed file, excluding
  72639. the terminating null character.
  72640. gzputs returns the number of characters written, or -1 in case of error.
  72641. */
  72642. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  72643. /*
  72644. Reads bytes from the compressed file until len-1 characters are read, or
  72645. a newline character is read and transferred to buf, or an end-of-file
  72646. condition is encountered. The string is then terminated with a null
  72647. character.
  72648. gzgets returns buf, or Z_NULL in case of error.
  72649. */
  72650. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  72651. /*
  72652. Writes c, converted to an unsigned char, into the compressed file.
  72653. gzputc returns the value that was written, or -1 in case of error.
  72654. */
  72655. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  72656. /*
  72657. Reads one byte from the compressed file. gzgetc returns this byte
  72658. or -1 in case of end of file or error.
  72659. */
  72660. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  72661. /*
  72662. Push one character back onto the stream to be read again later.
  72663. Only one character of push-back is allowed. gzungetc() returns the
  72664. character pushed, or -1 on failure. gzungetc() will fail if a
  72665. character has been pushed but not read yet, or if c is -1. The pushed
  72666. character will be discarded if the stream is repositioned with gzseek()
  72667. or gzrewind().
  72668. */
  72669. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  72670. /*
  72671. Flushes all pending output into the compressed file. The parameter
  72672. flush is as in the deflate() function. The return value is the zlib
  72673. error number (see function gzerror below). gzflush returns Z_OK if
  72674. the flush parameter is Z_FINISH and all output could be flushed.
  72675. gzflush should be called only when strictly necessary because it can
  72676. degrade compression.
  72677. */
  72678. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  72679. z_off_t offset, int whence));
  72680. /*
  72681. Sets the starting position for the next gzread or gzwrite on the
  72682. given compressed file. The offset represents a number of bytes in the
  72683. uncompressed data stream. The whence parameter is defined as in lseek(2);
  72684. the value SEEK_END is not supported.
  72685. If the file is opened for reading, this function is emulated but can be
  72686. extremely slow. If the file is opened for writing, only forward seeks are
  72687. supported; gzseek then compresses a sequence of zeroes up to the new
  72688. starting position.
  72689. gzseek returns the resulting offset location as measured in bytes from
  72690. the beginning of the uncompressed stream, or -1 in case of error, in
  72691. particular if the file is opened for writing and the new starting position
  72692. would be before the current position.
  72693. */
  72694. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  72695. /*
  72696. Rewinds the given file. This function is supported only for reading.
  72697. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  72698. */
  72699. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  72700. /*
  72701. Returns the starting position for the next gzread or gzwrite on the
  72702. given compressed file. This position represents a number of bytes in the
  72703. uncompressed data stream.
  72704. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  72705. */
  72706. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  72707. /*
  72708. Returns 1 when EOF has previously been detected reading the given
  72709. input stream, otherwise zero.
  72710. */
  72711. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  72712. /*
  72713. Returns 1 if file is being read directly without decompression, otherwise
  72714. zero.
  72715. */
  72716. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  72717. /*
  72718. Flushes all pending output if necessary, closes the compressed file
  72719. and deallocates all the (de)compression state. The return value is the zlib
  72720. error number (see function gzerror below).
  72721. */
  72722. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  72723. /*
  72724. Returns the error message for the last error which occurred on the
  72725. given compressed file. errnum is set to zlib error number. If an
  72726. error occurred in the file system and not in the compression library,
  72727. errnum is set to Z_ERRNO and the application may consult errno
  72728. to get the exact error code.
  72729. */
  72730. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  72731. /*
  72732. Clears the error and end-of-file flags for file. This is analogous to the
  72733. clearerr() function in stdio. This is useful for continuing to read a gzip
  72734. file that is being written concurrently.
  72735. */
  72736. /* checksum functions */
  72737. /*
  72738. These functions are not related to compression but are exported
  72739. anyway because they might be useful in applications using the
  72740. compression library.
  72741. */
  72742. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  72743. /*
  72744. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  72745. return the updated checksum. If buf is NULL, this function returns
  72746. the required initial value for the checksum.
  72747. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  72748. much faster. Usage example:
  72749. uLong adler = adler32(0L, Z_NULL, 0);
  72750. while (read_buffer(buffer, length) != EOF) {
  72751. adler = adler32(adler, buffer, length);
  72752. }
  72753. if (adler != original_adler) error();
  72754. */
  72755. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  72756. z_off_t len2));
  72757. /*
  72758. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  72759. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  72760. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  72761. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  72762. */
  72763. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  72764. /*
  72765. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  72766. updated CRC-32. If buf is NULL, this function returns the required initial
  72767. value for the for the crc. Pre- and post-conditioning (one's complement) is
  72768. performed within this function so it shouldn't be done by the application.
  72769. Usage example:
  72770. uLong crc = crc32(0L, Z_NULL, 0);
  72771. while (read_buffer(buffer, length) != EOF) {
  72772. crc = crc32(crc, buffer, length);
  72773. }
  72774. if (crc != original_crc) error();
  72775. */
  72776. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  72777. /*
  72778. Combine two CRC-32 check values into one. For two sequences of bytes,
  72779. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  72780. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  72781. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  72782. len2.
  72783. */
  72784. /* various hacks, don't look :) */
  72785. /* deflateInit and inflateInit are macros to allow checking the zlib version
  72786. * and the compiler's view of z_stream:
  72787. */
  72788. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  72789. const char *version, int stream_size));
  72790. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  72791. const char *version, int stream_size));
  72792. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  72793. int windowBits, int memLevel,
  72794. int strategy, const char *version,
  72795. int stream_size));
  72796. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  72797. const char *version, int stream_size));
  72798. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  72799. unsigned char FAR *window,
  72800. const char *version,
  72801. int stream_size));
  72802. #define deflateInit(strm, level) \
  72803. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  72804. #define inflateInit(strm) \
  72805. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  72806. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  72807. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  72808. (strategy), ZLIB_VERSION, sizeof(z_stream))
  72809. #define inflateInit2(strm, windowBits) \
  72810. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  72811. #define inflateBackInit(strm, windowBits, window) \
  72812. inflateBackInit_((strm), (windowBits), (window), \
  72813. ZLIB_VERSION, sizeof(z_stream))
  72814. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  72815. struct internal_state {int dummy;}; /* hack for buggy compilers */
  72816. #endif
  72817. ZEXTERN const char * ZEXPORT zError OF((int));
  72818. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  72819. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  72820. #ifdef __cplusplus
  72821. }
  72822. #endif
  72823. #endif /* ZLIB_H */
  72824. /********* End of inlined file: zlib.h *********/
  72825. #undef OS_CODE
  72826. }
  72827. BEGIN_JUCE_NAMESPACE
  72828. using namespace zlibNamespace;
  72829. // internal helper object that holds the zlib structures so they don't have to be
  72830. // included publicly.
  72831. class GZIPCompressorHelper
  72832. {
  72833. private:
  72834. z_stream* stream;
  72835. uint8* data;
  72836. int dataSize, compLevel, strategy;
  72837. bool setParams;
  72838. public:
  72839. bool finished, shouldFinish;
  72840. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  72841. : data (0),
  72842. dataSize (0),
  72843. compLevel (compressionLevel),
  72844. strategy (0),
  72845. setParams (true),
  72846. finished (false),
  72847. shouldFinish (false)
  72848. {
  72849. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  72850. if (deflateInit2 (stream,
  72851. compLevel,
  72852. Z_DEFLATED,
  72853. nowrap ? -MAX_WBITS : MAX_WBITS,
  72854. 8,
  72855. strategy) != Z_OK)
  72856. {
  72857. juce_free (stream);
  72858. stream = 0;
  72859. }
  72860. }
  72861. ~GZIPCompressorHelper()
  72862. {
  72863. if (stream != 0)
  72864. {
  72865. deflateEnd (stream);
  72866. juce_free (stream);
  72867. }
  72868. }
  72869. bool needsInput() const throw()
  72870. {
  72871. return dataSize <= 0;
  72872. }
  72873. void setInput (uint8* const newData, const int size) throw()
  72874. {
  72875. data = newData;
  72876. dataSize = size;
  72877. }
  72878. int doNextBlock (uint8* const dest, const int destSize) throw()
  72879. {
  72880. if (stream != 0)
  72881. {
  72882. stream->next_in = data;
  72883. stream->next_out = dest;
  72884. stream->avail_in = dataSize;
  72885. stream->avail_out = destSize;
  72886. const int result = setParams ? deflateParams (stream, compLevel, strategy)
  72887. : deflate (stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  72888. setParams = false;
  72889. switch (result)
  72890. {
  72891. case Z_STREAM_END:
  72892. finished = true;
  72893. case Z_OK:
  72894. data += dataSize - stream->avail_in;
  72895. dataSize = stream->avail_in;
  72896. return destSize - stream->avail_out;
  72897. default:
  72898. break;
  72899. }
  72900. }
  72901. return 0;
  72902. }
  72903. };
  72904. const int gzipCompBufferSize = 32768;
  72905. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  72906. int compressionLevel,
  72907. const bool deleteDestStream_,
  72908. const bool noWrap)
  72909. : destStream (destStream_),
  72910. deleteDestStream (deleteDestStream_)
  72911. {
  72912. if (compressionLevel < 1 || compressionLevel > 9)
  72913. compressionLevel = -1;
  72914. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  72915. buffer = (uint8*) juce_malloc (gzipCompBufferSize);
  72916. }
  72917. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  72918. {
  72919. flush();
  72920. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  72921. delete h;
  72922. juce_free (buffer);
  72923. if (deleteDestStream)
  72924. delete destStream;
  72925. }
  72926. void GZIPCompressorOutputStream::flush()
  72927. {
  72928. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  72929. if (! h->finished)
  72930. {
  72931. h->shouldFinish = true;
  72932. while (! h->finished)
  72933. doNextBlock();
  72934. }
  72935. destStream->flush();
  72936. }
  72937. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  72938. {
  72939. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  72940. if (! h->finished)
  72941. {
  72942. h->setInput ((uint8*) destBuffer, howMany);
  72943. while (! h->needsInput())
  72944. {
  72945. if (! doNextBlock())
  72946. return false;
  72947. }
  72948. }
  72949. return true;
  72950. }
  72951. bool GZIPCompressorOutputStream::doNextBlock()
  72952. {
  72953. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  72954. const int len = h->doNextBlock (buffer, gzipCompBufferSize);
  72955. if (len > 0)
  72956. return destStream->write (buffer, len);
  72957. else
  72958. return true;
  72959. }
  72960. int64 GZIPCompressorOutputStream::getPosition()
  72961. {
  72962. return destStream->getPosition();
  72963. }
  72964. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  72965. {
  72966. jassertfalse // can't do it!
  72967. return false;
  72968. }
  72969. END_JUCE_NAMESPACE
  72970. /********* End of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  72971. /********* Start of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  72972. #if JUCE_MSVC
  72973. #pragma warning (push)
  72974. #pragma warning (disable: 4309 4305)
  72975. #endif
  72976. namespace zlibNamespace
  72977. {
  72978. extern "C"
  72979. {
  72980. #undef OS_CODE
  72981. #undef fdopen
  72982. #define ZLIB_INTERNAL
  72983. #define NO_DUMMY_DECL
  72984. /********* Start of inlined file: adler32.c *********/
  72985. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  72986. #define ZLIB_INTERNAL
  72987. #define BASE 65521UL /* largest prime smaller than 65536 */
  72988. #define NMAX 5552
  72989. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  72990. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  72991. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  72992. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  72993. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  72994. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  72995. /* use NO_DIVIDE if your processor does not do division in hardware */
  72996. #ifdef NO_DIVIDE
  72997. # define MOD(a) \
  72998. do { \
  72999. if (a >= (BASE << 16)) a -= (BASE << 16); \
  73000. if (a >= (BASE << 15)) a -= (BASE << 15); \
  73001. if (a >= (BASE << 14)) a -= (BASE << 14); \
  73002. if (a >= (BASE << 13)) a -= (BASE << 13); \
  73003. if (a >= (BASE << 12)) a -= (BASE << 12); \
  73004. if (a >= (BASE << 11)) a -= (BASE << 11); \
  73005. if (a >= (BASE << 10)) a -= (BASE << 10); \
  73006. if (a >= (BASE << 9)) a -= (BASE << 9); \
  73007. if (a >= (BASE << 8)) a -= (BASE << 8); \
  73008. if (a >= (BASE << 7)) a -= (BASE << 7); \
  73009. if (a >= (BASE << 6)) a -= (BASE << 6); \
  73010. if (a >= (BASE << 5)) a -= (BASE << 5); \
  73011. if (a >= (BASE << 4)) a -= (BASE << 4); \
  73012. if (a >= (BASE << 3)) a -= (BASE << 3); \
  73013. if (a >= (BASE << 2)) a -= (BASE << 2); \
  73014. if (a >= (BASE << 1)) a -= (BASE << 1); \
  73015. if (a >= BASE) a -= BASE; \
  73016. } while (0)
  73017. # define MOD4(a) \
  73018. do { \
  73019. if (a >= (BASE << 4)) a -= (BASE << 4); \
  73020. if (a >= (BASE << 3)) a -= (BASE << 3); \
  73021. if (a >= (BASE << 2)) a -= (BASE << 2); \
  73022. if (a >= (BASE << 1)) a -= (BASE << 1); \
  73023. if (a >= BASE) a -= BASE; \
  73024. } while (0)
  73025. #else
  73026. # define MOD(a) a %= BASE
  73027. # define MOD4(a) a %= BASE
  73028. #endif
  73029. /* ========================================================================= */
  73030. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  73031. {
  73032. unsigned long sum2;
  73033. unsigned n;
  73034. /* split Adler-32 into component sums */
  73035. sum2 = (adler >> 16) & 0xffff;
  73036. adler &= 0xffff;
  73037. /* in case user likes doing a byte at a time, keep it fast */
  73038. if (len == 1) {
  73039. adler += buf[0];
  73040. if (adler >= BASE)
  73041. adler -= BASE;
  73042. sum2 += adler;
  73043. if (sum2 >= BASE)
  73044. sum2 -= BASE;
  73045. return adler | (sum2 << 16);
  73046. }
  73047. /* initial Adler-32 value (deferred check for len == 1 speed) */
  73048. if (buf == Z_NULL)
  73049. return 1L;
  73050. /* in case short lengths are provided, keep it somewhat fast */
  73051. if (len < 16) {
  73052. while (len--) {
  73053. adler += *buf++;
  73054. sum2 += adler;
  73055. }
  73056. if (adler >= BASE)
  73057. adler -= BASE;
  73058. MOD4(sum2); /* only added so many BASE's */
  73059. return adler | (sum2 << 16);
  73060. }
  73061. /* do length NMAX blocks -- requires just one modulo operation */
  73062. while (len >= NMAX) {
  73063. len -= NMAX;
  73064. n = NMAX / 16; /* NMAX is divisible by 16 */
  73065. do {
  73066. DO16(buf); /* 16 sums unrolled */
  73067. buf += 16;
  73068. } while (--n);
  73069. MOD(adler);
  73070. MOD(sum2);
  73071. }
  73072. /* do remaining bytes (less than NMAX, still just one modulo) */
  73073. if (len) { /* avoid modulos if none remaining */
  73074. while (len >= 16) {
  73075. len -= 16;
  73076. DO16(buf);
  73077. buf += 16;
  73078. }
  73079. while (len--) {
  73080. adler += *buf++;
  73081. sum2 += adler;
  73082. }
  73083. MOD(adler);
  73084. MOD(sum2);
  73085. }
  73086. /* return recombined sums */
  73087. return adler | (sum2 << 16);
  73088. }
  73089. /* ========================================================================= */
  73090. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  73091. {
  73092. unsigned long sum1;
  73093. unsigned long sum2;
  73094. unsigned rem;
  73095. /* the derivation of this formula is left as an exercise for the reader */
  73096. rem = (unsigned)(len2 % BASE);
  73097. sum1 = adler1 & 0xffff;
  73098. sum2 = rem * sum1;
  73099. MOD(sum2);
  73100. sum1 += (adler2 & 0xffff) + BASE - 1;
  73101. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  73102. if (sum1 > BASE) sum1 -= BASE;
  73103. if (sum1 > BASE) sum1 -= BASE;
  73104. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  73105. if (sum2 > BASE) sum2 -= BASE;
  73106. return sum1 | (sum2 << 16);
  73107. }
  73108. /********* End of inlined file: adler32.c *********/
  73109. /********* Start of inlined file: compress.c *********/
  73110. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73111. #define ZLIB_INTERNAL
  73112. /* ===========================================================================
  73113. Compresses the source buffer into the destination buffer. The level
  73114. parameter has the same meaning as in deflateInit. sourceLen is the byte
  73115. length of the source buffer. Upon entry, destLen is the total size of the
  73116. destination buffer, which must be at least 0.1% larger than sourceLen plus
  73117. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  73118. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  73119. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  73120. Z_STREAM_ERROR if the level parameter is invalid.
  73121. */
  73122. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  73123. uLong sourceLen, int level)
  73124. {
  73125. z_stream stream;
  73126. int err;
  73127. stream.next_in = (Bytef*)source;
  73128. stream.avail_in = (uInt)sourceLen;
  73129. #ifdef MAXSEG_64K
  73130. /* Check for source > 64K on 16-bit machine: */
  73131. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  73132. #endif
  73133. stream.next_out = dest;
  73134. stream.avail_out = (uInt)*destLen;
  73135. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  73136. stream.zalloc = (alloc_func)0;
  73137. stream.zfree = (free_func)0;
  73138. stream.opaque = (voidpf)0;
  73139. err = deflateInit(&stream, level);
  73140. if (err != Z_OK) return err;
  73141. err = deflate(&stream, Z_FINISH);
  73142. if (err != Z_STREAM_END) {
  73143. deflateEnd(&stream);
  73144. return err == Z_OK ? Z_BUF_ERROR : err;
  73145. }
  73146. *destLen = stream.total_out;
  73147. err = deflateEnd(&stream);
  73148. return err;
  73149. }
  73150. /* ===========================================================================
  73151. */
  73152. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  73153. {
  73154. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  73155. }
  73156. /* ===========================================================================
  73157. If the default memLevel or windowBits for deflateInit() is changed, then
  73158. this function needs to be updated.
  73159. */
  73160. uLong ZEXPORT compressBound (uLong sourceLen)
  73161. {
  73162. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  73163. }
  73164. /********* End of inlined file: compress.c *********/
  73165. #undef DO1
  73166. #undef DO8
  73167. /********* Start of inlined file: crc32.c *********/
  73168. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73169. /*
  73170. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  73171. protection on the static variables used to control the first-use generation
  73172. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  73173. first call get_crc_table() to initialize the tables before allowing more than
  73174. one thread to use crc32().
  73175. */
  73176. #ifdef MAKECRCH
  73177. # include <stdio.h>
  73178. # ifndef DYNAMIC_CRC_TABLE
  73179. # define DYNAMIC_CRC_TABLE
  73180. # endif /* !DYNAMIC_CRC_TABLE */
  73181. #endif /* MAKECRCH */
  73182. /********* Start of inlined file: zutil.h *********/
  73183. /* WARNING: this file should *not* be used by applications. It is
  73184. part of the implementation of the compression library and is
  73185. subject to change. Applications should only use zlib.h.
  73186. */
  73187. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73188. #ifndef ZUTIL_H
  73189. #define ZUTIL_H
  73190. #define ZLIB_INTERNAL
  73191. #ifdef STDC
  73192. # ifndef _WIN32_WCE
  73193. # include <stddef.h>
  73194. # endif
  73195. # include <string.h>
  73196. # include <stdlib.h>
  73197. #endif
  73198. #ifdef NO_ERRNO_H
  73199. # ifdef _WIN32_WCE
  73200. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  73201. * errno. We define it as a global variable to simplify porting.
  73202. * Its value is always 0 and should not be used. We rename it to
  73203. * avoid conflict with other libraries that use the same workaround.
  73204. */
  73205. # define errno z_errno
  73206. # endif
  73207. extern int errno;
  73208. #else
  73209. # ifndef _WIN32_WCE
  73210. # include <errno.h>
  73211. # endif
  73212. #endif
  73213. #ifndef local
  73214. # define local static
  73215. #endif
  73216. /* compile with -Dlocal if your debugger can't find static symbols */
  73217. typedef unsigned char uch;
  73218. typedef uch FAR uchf;
  73219. typedef unsigned short ush;
  73220. typedef ush FAR ushf;
  73221. typedef unsigned long ulg;
  73222. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  73223. /* (size given to avoid silly warnings with Visual C++) */
  73224. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  73225. #define ERR_RETURN(strm,err) \
  73226. return (strm->msg = (char*)ERR_MSG(err), (err))
  73227. /* To be used only when the state is known to be valid */
  73228. /* common constants */
  73229. #ifndef DEF_WBITS
  73230. # define DEF_WBITS MAX_WBITS
  73231. #endif
  73232. /* default windowBits for decompression. MAX_WBITS is for compression only */
  73233. #if MAX_MEM_LEVEL >= 8
  73234. # define DEF_MEM_LEVEL 8
  73235. #else
  73236. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  73237. #endif
  73238. /* default memLevel */
  73239. #define STORED_BLOCK 0
  73240. #define STATIC_TREES 1
  73241. #define DYN_TREES 2
  73242. /* The three kinds of block type */
  73243. #define MIN_MATCH 3
  73244. #define MAX_MATCH 258
  73245. /* The minimum and maximum match lengths */
  73246. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  73247. /* target dependencies */
  73248. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  73249. # define OS_CODE 0x00
  73250. # if defined(__TURBOC__) || defined(__BORLANDC__)
  73251. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  73252. /* Allow compilation with ANSI keywords only enabled */
  73253. void _Cdecl farfree( void *block );
  73254. void *_Cdecl farmalloc( unsigned long nbytes );
  73255. # else
  73256. # include <alloc.h>
  73257. # endif
  73258. # else /* MSC or DJGPP */
  73259. # include <malloc.h>
  73260. # endif
  73261. #endif
  73262. #ifdef AMIGA
  73263. # define OS_CODE 0x01
  73264. #endif
  73265. #if defined(VAXC) || defined(VMS)
  73266. # define OS_CODE 0x02
  73267. # define F_OPEN(name, mode) \
  73268. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  73269. #endif
  73270. #if defined(ATARI) || defined(atarist)
  73271. # define OS_CODE 0x05
  73272. #endif
  73273. #ifdef OS2
  73274. # define OS_CODE 0x06
  73275. # ifdef M_I86
  73276. #include <malloc.h>
  73277. # endif
  73278. #endif
  73279. #if defined(MACOS) || TARGET_OS_MAC
  73280. # define OS_CODE 0x07
  73281. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  73282. # include <unix.h> /* for fdopen */
  73283. # else
  73284. # ifndef fdopen
  73285. # define fdopen(fd,mode) NULL /* No fdopen() */
  73286. # endif
  73287. # endif
  73288. #endif
  73289. #ifdef TOPS20
  73290. # define OS_CODE 0x0a
  73291. #endif
  73292. #ifdef WIN32
  73293. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  73294. # define OS_CODE 0x0b
  73295. # endif
  73296. #endif
  73297. #ifdef __50SERIES /* Prime/PRIMOS */
  73298. # define OS_CODE 0x0f
  73299. #endif
  73300. #if defined(_BEOS_) || defined(RISCOS)
  73301. # define fdopen(fd,mode) NULL /* No fdopen() */
  73302. #endif
  73303. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  73304. # if defined(_WIN32_WCE)
  73305. # define fdopen(fd,mode) NULL /* No fdopen() */
  73306. # ifndef _PTRDIFF_T_DEFINED
  73307. typedef int ptrdiff_t;
  73308. # define _PTRDIFF_T_DEFINED
  73309. # endif
  73310. # else
  73311. # define fdopen(fd,type) _fdopen(fd,type)
  73312. # endif
  73313. #endif
  73314. /* common defaults */
  73315. #ifndef OS_CODE
  73316. # define OS_CODE 0x03 /* assume Unix */
  73317. #endif
  73318. #ifndef F_OPEN
  73319. # define F_OPEN(name, mode) fopen((name), (mode))
  73320. #endif
  73321. /* functions */
  73322. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  73323. # ifndef HAVE_VSNPRINTF
  73324. # define HAVE_VSNPRINTF
  73325. # endif
  73326. #endif
  73327. #if defined(__CYGWIN__)
  73328. # ifndef HAVE_VSNPRINTF
  73329. # define HAVE_VSNPRINTF
  73330. # endif
  73331. #endif
  73332. #ifndef HAVE_VSNPRINTF
  73333. # ifdef MSDOS
  73334. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  73335. but for now we just assume it doesn't. */
  73336. # define NO_vsnprintf
  73337. # endif
  73338. # ifdef __TURBOC__
  73339. # define NO_vsnprintf
  73340. # endif
  73341. # ifdef WIN32
  73342. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  73343. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  73344. # define vsnprintf _vsnprintf
  73345. # endif
  73346. # endif
  73347. # ifdef __SASC
  73348. # define NO_vsnprintf
  73349. # endif
  73350. #endif
  73351. #ifdef VMS
  73352. # define NO_vsnprintf
  73353. #endif
  73354. #if defined(pyr)
  73355. # define NO_MEMCPY
  73356. #endif
  73357. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  73358. /* Use our own functions for small and medium model with MSC <= 5.0.
  73359. * You may have to use the same strategy for Borland C (untested).
  73360. * The __SC__ check is for Symantec.
  73361. */
  73362. # define NO_MEMCPY
  73363. #endif
  73364. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  73365. # define HAVE_MEMCPY
  73366. #endif
  73367. #ifdef HAVE_MEMCPY
  73368. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  73369. # define zmemcpy _fmemcpy
  73370. # define zmemcmp _fmemcmp
  73371. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  73372. # else
  73373. # define zmemcpy memcpy
  73374. # define zmemcmp memcmp
  73375. # define zmemzero(dest, len) memset(dest, 0, len)
  73376. # endif
  73377. #else
  73378. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  73379. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  73380. extern void zmemzero OF((Bytef* dest, uInt len));
  73381. #endif
  73382. /* Diagnostic functions */
  73383. #ifdef DEBUG
  73384. # include <stdio.h>
  73385. extern int z_verbose;
  73386. extern void z_error OF((char *m));
  73387. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  73388. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  73389. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  73390. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  73391. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  73392. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  73393. #else
  73394. # define Assert(cond,msg)
  73395. # define Trace(x)
  73396. # define Tracev(x)
  73397. # define Tracevv(x)
  73398. # define Tracec(c,x)
  73399. # define Tracecv(c,x)
  73400. #endif
  73401. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  73402. void zcfree OF((voidpf opaque, voidpf ptr));
  73403. #define ZALLOC(strm, items, size) \
  73404. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  73405. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  73406. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  73407. #endif /* ZUTIL_H */
  73408. /********* End of inlined file: zutil.h *********/
  73409. /* for STDC and FAR definitions */
  73410. #define local static
  73411. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  73412. #ifndef NOBYFOUR
  73413. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  73414. # include <limits.h>
  73415. # define BYFOUR
  73416. # if (UINT_MAX == 0xffffffffUL)
  73417. typedef unsigned int u4;
  73418. # else
  73419. # if (ULONG_MAX == 0xffffffffUL)
  73420. typedef unsigned long u4;
  73421. # else
  73422. # if (USHRT_MAX == 0xffffffffUL)
  73423. typedef unsigned short u4;
  73424. # else
  73425. # undef BYFOUR /* can't find a four-byte integer type! */
  73426. # endif
  73427. # endif
  73428. # endif
  73429. # endif /* STDC */
  73430. #endif /* !NOBYFOUR */
  73431. /* Definitions for doing the crc four data bytes at a time. */
  73432. #ifdef BYFOUR
  73433. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  73434. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  73435. local unsigned long crc32_little OF((unsigned long,
  73436. const unsigned char FAR *, unsigned));
  73437. local unsigned long crc32_big OF((unsigned long,
  73438. const unsigned char FAR *, unsigned));
  73439. # define TBLS 8
  73440. #else
  73441. # define TBLS 1
  73442. #endif /* BYFOUR */
  73443. /* Local functions for crc concatenation */
  73444. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  73445. unsigned long vec));
  73446. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  73447. #ifdef DYNAMIC_CRC_TABLE
  73448. local volatile int crc_table_empty = 1;
  73449. local unsigned long FAR crc_table[TBLS][256];
  73450. local void make_crc_table OF((void));
  73451. #ifdef MAKECRCH
  73452. local void write_table OF((FILE *, const unsigned long FAR *));
  73453. #endif /* MAKECRCH */
  73454. /*
  73455. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  73456. 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.
  73457. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  73458. with the lowest powers in the most significant bit. Then adding polynomials
  73459. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  73460. one. If we call the above polynomial p, and represent a byte as the
  73461. polynomial q, also with the lowest power in the most significant bit (so the
  73462. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  73463. where a mod b means the remainder after dividing a by b.
  73464. This calculation is done using the shift-register method of multiplying and
  73465. taking the remainder. The register is initialized to zero, and for each
  73466. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  73467. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  73468. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  73469. out is a one). We start with the highest power (least significant bit) of
  73470. q and repeat for all eight bits of q.
  73471. The first table is simply the CRC of all possible eight bit values. This is
  73472. all the information needed to generate CRCs on data a byte at a time for all
  73473. combinations of CRC register values and incoming bytes. The remaining tables
  73474. allow for word-at-a-time CRC calculation for both big-endian and little-
  73475. endian machines, where a word is four bytes.
  73476. */
  73477. local void make_crc_table()
  73478. {
  73479. unsigned long c;
  73480. int n, k;
  73481. unsigned long poly; /* polynomial exclusive-or pattern */
  73482. /* terms of polynomial defining this crc (except x^32): */
  73483. static volatile int first = 1; /* flag to limit concurrent making */
  73484. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  73485. /* See if another task is already doing this (not thread-safe, but better
  73486. than nothing -- significantly reduces duration of vulnerability in
  73487. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  73488. if (first) {
  73489. first = 0;
  73490. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  73491. poly = 0UL;
  73492. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  73493. poly |= 1UL << (31 - p[n]);
  73494. /* generate a crc for every 8-bit value */
  73495. for (n = 0; n < 256; n++) {
  73496. c = (unsigned long)n;
  73497. for (k = 0; k < 8; k++)
  73498. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  73499. crc_table[0][n] = c;
  73500. }
  73501. #ifdef BYFOUR
  73502. /* generate crc for each value followed by one, two, and three zeros,
  73503. and then the byte reversal of those as well as the first table */
  73504. for (n = 0; n < 256; n++) {
  73505. c = crc_table[0][n];
  73506. crc_table[4][n] = REV(c);
  73507. for (k = 1; k < 4; k++) {
  73508. c = crc_table[0][c & 0xff] ^ (c >> 8);
  73509. crc_table[k][n] = c;
  73510. crc_table[k + 4][n] = REV(c);
  73511. }
  73512. }
  73513. #endif /* BYFOUR */
  73514. crc_table_empty = 0;
  73515. }
  73516. else { /* not first */
  73517. /* wait for the other guy to finish (not efficient, but rare) */
  73518. while (crc_table_empty)
  73519. ;
  73520. }
  73521. #ifdef MAKECRCH
  73522. /* write out CRC tables to crc32.h */
  73523. {
  73524. FILE *out;
  73525. out = fopen("crc32.h", "w");
  73526. if (out == NULL) return;
  73527. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  73528. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  73529. fprintf(out, "local const unsigned long FAR ");
  73530. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  73531. write_table(out, crc_table[0]);
  73532. # ifdef BYFOUR
  73533. fprintf(out, "#ifdef BYFOUR\n");
  73534. for (k = 1; k < 8; k++) {
  73535. fprintf(out, " },\n {\n");
  73536. write_table(out, crc_table[k]);
  73537. }
  73538. fprintf(out, "#endif\n");
  73539. # endif /* BYFOUR */
  73540. fprintf(out, " }\n};\n");
  73541. fclose(out);
  73542. }
  73543. #endif /* MAKECRCH */
  73544. }
  73545. #ifdef MAKECRCH
  73546. local void write_table(out, table)
  73547. FILE *out;
  73548. const unsigned long FAR *table;
  73549. {
  73550. int n;
  73551. for (n = 0; n < 256; n++)
  73552. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  73553. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  73554. }
  73555. #endif /* MAKECRCH */
  73556. #else /* !DYNAMIC_CRC_TABLE */
  73557. /* ========================================================================
  73558. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  73559. */
  73560. /********* Start of inlined file: crc32.h *********/
  73561. local const unsigned long FAR crc_table[TBLS][256] =
  73562. {
  73563. {
  73564. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  73565. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  73566. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  73567. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  73568. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  73569. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  73570. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  73571. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  73572. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  73573. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  73574. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  73575. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  73576. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  73577. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  73578. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  73579. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  73580. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  73581. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  73582. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  73583. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  73584. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  73585. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  73586. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  73587. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  73588. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  73589. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  73590. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  73591. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  73592. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  73593. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  73594. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  73595. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  73596. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  73597. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  73598. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  73599. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  73600. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  73601. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  73602. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  73603. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  73604. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  73605. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  73606. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  73607. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  73608. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  73609. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  73610. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  73611. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  73612. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  73613. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  73614. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  73615. 0x2d02ef8dUL
  73616. #ifdef BYFOUR
  73617. },
  73618. {
  73619. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  73620. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  73621. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  73622. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  73623. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  73624. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  73625. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  73626. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  73627. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  73628. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  73629. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  73630. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  73631. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  73632. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  73633. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  73634. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  73635. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  73636. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  73637. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  73638. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  73639. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  73640. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  73641. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  73642. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  73643. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  73644. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  73645. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  73646. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  73647. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  73648. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  73649. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  73650. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  73651. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  73652. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  73653. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  73654. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  73655. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  73656. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  73657. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  73658. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  73659. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  73660. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  73661. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  73662. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  73663. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  73664. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  73665. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  73666. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  73667. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  73668. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  73669. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  73670. 0x9324fd72UL
  73671. },
  73672. {
  73673. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  73674. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  73675. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  73676. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  73677. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  73678. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  73679. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  73680. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  73681. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  73682. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  73683. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  73684. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  73685. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  73686. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  73687. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  73688. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  73689. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  73690. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  73691. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  73692. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  73693. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  73694. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  73695. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  73696. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  73697. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  73698. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  73699. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  73700. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  73701. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  73702. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  73703. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  73704. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  73705. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  73706. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  73707. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  73708. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  73709. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  73710. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  73711. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  73712. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  73713. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  73714. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  73715. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  73716. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  73717. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  73718. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  73719. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  73720. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  73721. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  73722. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  73723. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  73724. 0xbe9834edUL
  73725. },
  73726. {
  73727. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  73728. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  73729. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  73730. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  73731. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  73732. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  73733. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  73734. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  73735. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  73736. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  73737. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  73738. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  73739. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  73740. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  73741. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  73742. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  73743. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  73744. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  73745. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  73746. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  73747. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  73748. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  73749. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  73750. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  73751. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  73752. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  73753. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  73754. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  73755. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  73756. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  73757. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  73758. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  73759. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  73760. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  73761. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  73762. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  73763. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  73764. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  73765. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  73766. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  73767. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  73768. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  73769. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  73770. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  73771. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  73772. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  73773. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  73774. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  73775. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  73776. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  73777. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  73778. 0xde0506f1UL
  73779. },
  73780. {
  73781. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  73782. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  73783. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  73784. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  73785. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  73786. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  73787. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  73788. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  73789. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  73790. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  73791. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  73792. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  73793. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  73794. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  73795. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  73796. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  73797. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  73798. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  73799. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  73800. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  73801. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  73802. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  73803. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  73804. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  73805. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  73806. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  73807. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  73808. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  73809. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  73810. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  73811. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  73812. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  73813. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  73814. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  73815. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  73816. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  73817. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  73818. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  73819. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  73820. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  73821. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  73822. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  73823. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  73824. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  73825. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  73826. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  73827. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  73828. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  73829. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  73830. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  73831. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  73832. 0x8def022dUL
  73833. },
  73834. {
  73835. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  73836. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  73837. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  73838. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  73839. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  73840. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  73841. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  73842. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  73843. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  73844. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  73845. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  73846. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  73847. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  73848. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  73849. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  73850. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  73851. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  73852. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  73853. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  73854. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  73855. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  73856. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  73857. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  73858. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  73859. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  73860. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  73861. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  73862. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  73863. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  73864. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  73865. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  73866. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  73867. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  73868. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  73869. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  73870. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  73871. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  73872. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  73873. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  73874. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  73875. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  73876. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  73877. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  73878. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  73879. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  73880. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  73881. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  73882. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  73883. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  73884. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  73885. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  73886. 0x72fd2493UL
  73887. },
  73888. {
  73889. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  73890. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  73891. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  73892. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  73893. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  73894. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  73895. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  73896. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  73897. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  73898. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  73899. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  73900. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  73901. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  73902. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  73903. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  73904. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  73905. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  73906. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  73907. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  73908. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  73909. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  73910. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  73911. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  73912. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  73913. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  73914. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  73915. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  73916. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  73917. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  73918. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  73919. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  73920. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  73921. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  73922. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  73923. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  73924. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  73925. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  73926. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  73927. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  73928. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  73929. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  73930. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  73931. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  73932. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  73933. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  73934. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  73935. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  73936. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  73937. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  73938. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  73939. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  73940. 0xed3498beUL
  73941. },
  73942. {
  73943. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  73944. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  73945. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  73946. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  73947. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  73948. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  73949. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  73950. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  73951. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  73952. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  73953. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  73954. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  73955. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  73956. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  73957. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  73958. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  73959. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  73960. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  73961. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  73962. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  73963. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  73964. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  73965. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  73966. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  73967. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  73968. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  73969. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  73970. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  73971. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  73972. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  73973. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  73974. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  73975. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  73976. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  73977. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  73978. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  73979. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  73980. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  73981. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  73982. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  73983. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  73984. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  73985. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  73986. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  73987. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  73988. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  73989. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  73990. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  73991. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  73992. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  73993. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  73994. 0xf10605deUL
  73995. #endif
  73996. }
  73997. };
  73998. /********* End of inlined file: crc32.h *********/
  73999. #endif /* DYNAMIC_CRC_TABLE */
  74000. /* =========================================================================
  74001. * This function can be used by asm versions of crc32()
  74002. */
  74003. const unsigned long FAR * ZEXPORT get_crc_table()
  74004. {
  74005. #ifdef DYNAMIC_CRC_TABLE
  74006. if (crc_table_empty)
  74007. make_crc_table();
  74008. #endif /* DYNAMIC_CRC_TABLE */
  74009. return (const unsigned long FAR *)crc_table;
  74010. }
  74011. /* ========================================================================= */
  74012. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  74013. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  74014. /* ========================================================================= */
  74015. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  74016. {
  74017. if (buf == Z_NULL) return 0UL;
  74018. #ifdef DYNAMIC_CRC_TABLE
  74019. if (crc_table_empty)
  74020. make_crc_table();
  74021. #endif /* DYNAMIC_CRC_TABLE */
  74022. #ifdef BYFOUR
  74023. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  74024. u4 endian;
  74025. endian = 1;
  74026. if (*((unsigned char *)(&endian)))
  74027. return crc32_little(crc, buf, len);
  74028. else
  74029. return crc32_big(crc, buf, len);
  74030. }
  74031. #endif /* BYFOUR */
  74032. crc = crc ^ 0xffffffffUL;
  74033. while (len >= 8) {
  74034. DO8;
  74035. len -= 8;
  74036. }
  74037. if (len) do {
  74038. DO1;
  74039. } while (--len);
  74040. return crc ^ 0xffffffffUL;
  74041. }
  74042. #ifdef BYFOUR
  74043. /* ========================================================================= */
  74044. #define DOLIT4 c ^= *buf4++; \
  74045. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  74046. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  74047. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  74048. /* ========================================================================= */
  74049. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  74050. {
  74051. register u4 c;
  74052. register const u4 FAR *buf4;
  74053. c = (u4)crc;
  74054. c = ~c;
  74055. while (len && ((ptrdiff_t)buf & 3)) {
  74056. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  74057. len--;
  74058. }
  74059. buf4 = (const u4 FAR *)(const void FAR *)buf;
  74060. while (len >= 32) {
  74061. DOLIT32;
  74062. len -= 32;
  74063. }
  74064. while (len >= 4) {
  74065. DOLIT4;
  74066. len -= 4;
  74067. }
  74068. buf = (const unsigned char FAR *)buf4;
  74069. if (len) do {
  74070. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  74071. } while (--len);
  74072. c = ~c;
  74073. return (unsigned long)c;
  74074. }
  74075. /* ========================================================================= */
  74076. #define DOBIG4 c ^= *++buf4; \
  74077. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  74078. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  74079. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  74080. /* ========================================================================= */
  74081. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  74082. {
  74083. register u4 c;
  74084. register const u4 FAR *buf4;
  74085. c = REV((u4)crc);
  74086. c = ~c;
  74087. while (len && ((ptrdiff_t)buf & 3)) {
  74088. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  74089. len--;
  74090. }
  74091. buf4 = (const u4 FAR *)(const void FAR *)buf;
  74092. buf4--;
  74093. while (len >= 32) {
  74094. DOBIG32;
  74095. len -= 32;
  74096. }
  74097. while (len >= 4) {
  74098. DOBIG4;
  74099. len -= 4;
  74100. }
  74101. buf4++;
  74102. buf = (const unsigned char FAR *)buf4;
  74103. if (len) do {
  74104. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  74105. } while (--len);
  74106. c = ~c;
  74107. return (unsigned long)(REV(c));
  74108. }
  74109. #endif /* BYFOUR */
  74110. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  74111. /* ========================================================================= */
  74112. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  74113. {
  74114. unsigned long sum;
  74115. sum = 0;
  74116. while (vec) {
  74117. if (vec & 1)
  74118. sum ^= *mat;
  74119. vec >>= 1;
  74120. mat++;
  74121. }
  74122. return sum;
  74123. }
  74124. /* ========================================================================= */
  74125. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  74126. {
  74127. int n;
  74128. for (n = 0; n < GF2_DIM; n++)
  74129. square[n] = gf2_matrix_times(mat, mat[n]);
  74130. }
  74131. /* ========================================================================= */
  74132. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  74133. {
  74134. int n;
  74135. unsigned long row;
  74136. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  74137. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  74138. /* degenerate case */
  74139. if (len2 == 0)
  74140. return crc1;
  74141. /* put operator for one zero bit in odd */
  74142. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  74143. row = 1;
  74144. for (n = 1; n < GF2_DIM; n++) {
  74145. odd[n] = row;
  74146. row <<= 1;
  74147. }
  74148. /* put operator for two zero bits in even */
  74149. gf2_matrix_square(even, odd);
  74150. /* put operator for four zero bits in odd */
  74151. gf2_matrix_square(odd, even);
  74152. /* apply len2 zeros to crc1 (first square will put the operator for one
  74153. zero byte, eight zero bits, in even) */
  74154. do {
  74155. /* apply zeros operator for this bit of len2 */
  74156. gf2_matrix_square(even, odd);
  74157. if (len2 & 1)
  74158. crc1 = gf2_matrix_times(even, crc1);
  74159. len2 >>= 1;
  74160. /* if no more bits set, then done */
  74161. if (len2 == 0)
  74162. break;
  74163. /* another iteration of the loop with odd and even swapped */
  74164. gf2_matrix_square(odd, even);
  74165. if (len2 & 1)
  74166. crc1 = gf2_matrix_times(odd, crc1);
  74167. len2 >>= 1;
  74168. /* if no more bits set, then done */
  74169. } while (len2 != 0);
  74170. /* return combined crc */
  74171. crc1 ^= crc2;
  74172. return crc1;
  74173. }
  74174. /********* End of inlined file: crc32.c *********/
  74175. /********* Start of inlined file: deflate.c *********/
  74176. /*
  74177. * ALGORITHM
  74178. *
  74179. * The "deflation" process depends on being able to identify portions
  74180. * of the input text which are identical to earlier input (within a
  74181. * sliding window trailing behind the input currently being processed).
  74182. *
  74183. * The most straightforward technique turns out to be the fastest for
  74184. * most input files: try all possible matches and select the longest.
  74185. * The key feature of this algorithm is that insertions into the string
  74186. * dictionary are very simple and thus fast, and deletions are avoided
  74187. * completely. Insertions are performed at each input character, whereas
  74188. * string matches are performed only when the previous match ends. So it
  74189. * is preferable to spend more time in matches to allow very fast string
  74190. * insertions and avoid deletions. The matching algorithm for small
  74191. * strings is inspired from that of Rabin & Karp. A brute force approach
  74192. * is used to find longer strings when a small match has been found.
  74193. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  74194. * (by Leonid Broukhis).
  74195. * A previous version of this file used a more sophisticated algorithm
  74196. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  74197. * time, but has a larger average cost, uses more memory and is patented.
  74198. * However the F&G algorithm may be faster for some highly redundant
  74199. * files if the parameter max_chain_length (described below) is too large.
  74200. *
  74201. * ACKNOWLEDGEMENTS
  74202. *
  74203. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  74204. * I found it in 'freeze' written by Leonid Broukhis.
  74205. * Thanks to many people for bug reports and testing.
  74206. *
  74207. * REFERENCES
  74208. *
  74209. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  74210. * Available in http://www.ietf.org/rfc/rfc1951.txt
  74211. *
  74212. * A description of the Rabin and Karp algorithm is given in the book
  74213. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  74214. *
  74215. * Fiala,E.R., and Greene,D.H.
  74216. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  74217. *
  74218. */
  74219. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  74220. /********* Start of inlined file: deflate.h *********/
  74221. /* WARNING: this file should *not* be used by applications. It is
  74222. part of the implementation of the compression library and is
  74223. subject to change. Applications should only use zlib.h.
  74224. */
  74225. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  74226. #ifndef DEFLATE_H
  74227. #define DEFLATE_H
  74228. /* define NO_GZIP when compiling if you want to disable gzip header and
  74229. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  74230. the crc code when it is not needed. For shared libraries, gzip encoding
  74231. should be left enabled. */
  74232. #ifndef NO_GZIP
  74233. # define GZIP
  74234. #endif
  74235. #define NO_DUMMY_DECL
  74236. /* ===========================================================================
  74237. * Internal compression state.
  74238. */
  74239. #define LENGTH_CODES 29
  74240. /* number of length codes, not counting the special END_BLOCK code */
  74241. #define LITERALS 256
  74242. /* number of literal bytes 0..255 */
  74243. #define L_CODES (LITERALS+1+LENGTH_CODES)
  74244. /* number of Literal or Length codes, including the END_BLOCK code */
  74245. #define D_CODES 30
  74246. /* number of distance codes */
  74247. #define BL_CODES 19
  74248. /* number of codes used to transfer the bit lengths */
  74249. #define HEAP_SIZE (2*L_CODES+1)
  74250. /* maximum heap size */
  74251. #define MAX_BITS 15
  74252. /* All codes must not exceed MAX_BITS bits */
  74253. #define INIT_STATE 42
  74254. #define EXTRA_STATE 69
  74255. #define NAME_STATE 73
  74256. #define COMMENT_STATE 91
  74257. #define HCRC_STATE 103
  74258. #define BUSY_STATE 113
  74259. #define FINISH_STATE 666
  74260. /* Stream status */
  74261. /* Data structure describing a single value and its code string. */
  74262. typedef struct ct_data_s {
  74263. union {
  74264. ush freq; /* frequency count */
  74265. ush code; /* bit string */
  74266. } fc;
  74267. union {
  74268. ush dad; /* father node in Huffman tree */
  74269. ush len; /* length of bit string */
  74270. } dl;
  74271. } FAR ct_data;
  74272. #define Freq fc.freq
  74273. #define Code fc.code
  74274. #define Dad dl.dad
  74275. #define Len dl.len
  74276. typedef struct static_tree_desc_s static_tree_desc;
  74277. typedef struct tree_desc_s {
  74278. ct_data *dyn_tree; /* the dynamic tree */
  74279. int max_code; /* largest code with non zero frequency */
  74280. static_tree_desc *stat_desc; /* the corresponding static tree */
  74281. } FAR tree_desc;
  74282. typedef ush Pos;
  74283. typedef Pos FAR Posf;
  74284. typedef unsigned IPos;
  74285. /* A Pos is an index in the character window. We use short instead of int to
  74286. * save space in the various tables. IPos is used only for parameter passing.
  74287. */
  74288. typedef struct internal_state {
  74289. z_streamp strm; /* pointer back to this zlib stream */
  74290. int status; /* as the name implies */
  74291. Bytef *pending_buf; /* output still pending */
  74292. ulg pending_buf_size; /* size of pending_buf */
  74293. Bytef *pending_out; /* next pending byte to output to the stream */
  74294. uInt pending; /* nb of bytes in the pending buffer */
  74295. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  74296. gz_headerp gzhead; /* gzip header information to write */
  74297. uInt gzindex; /* where in extra, name, or comment */
  74298. Byte method; /* STORED (for zip only) or DEFLATED */
  74299. int last_flush; /* value of flush param for previous deflate call */
  74300. /* used by deflate.c: */
  74301. uInt w_size; /* LZ77 window size (32K by default) */
  74302. uInt w_bits; /* log2(w_size) (8..16) */
  74303. uInt w_mask; /* w_size - 1 */
  74304. Bytef *window;
  74305. /* Sliding window. Input bytes are read into the second half of the window,
  74306. * and move to the first half later to keep a dictionary of at least wSize
  74307. * bytes. With this organization, matches are limited to a distance of
  74308. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  74309. * performed with a length multiple of the block size. Also, it limits
  74310. * the window size to 64K, which is quite useful on MSDOS.
  74311. * To do: use the user input buffer as sliding window.
  74312. */
  74313. ulg window_size;
  74314. /* Actual size of window: 2*wSize, except when the user input buffer
  74315. * is directly used as sliding window.
  74316. */
  74317. Posf *prev;
  74318. /* Link to older string with same hash index. To limit the size of this
  74319. * array to 64K, this link is maintained only for the last 32K strings.
  74320. * An index in this array is thus a window index modulo 32K.
  74321. */
  74322. Posf *head; /* Heads of the hash chains or NIL. */
  74323. uInt ins_h; /* hash index of string to be inserted */
  74324. uInt hash_size; /* number of elements in hash table */
  74325. uInt hash_bits; /* log2(hash_size) */
  74326. uInt hash_mask; /* hash_size-1 */
  74327. uInt hash_shift;
  74328. /* Number of bits by which ins_h must be shifted at each input
  74329. * step. It must be such that after MIN_MATCH steps, the oldest
  74330. * byte no longer takes part in the hash key, that is:
  74331. * hash_shift * MIN_MATCH >= hash_bits
  74332. */
  74333. long block_start;
  74334. /* Window position at the beginning of the current output block. Gets
  74335. * negative when the window is moved backwards.
  74336. */
  74337. uInt match_length; /* length of best match */
  74338. IPos prev_match; /* previous match */
  74339. int match_available; /* set if previous match exists */
  74340. uInt strstart; /* start of string to insert */
  74341. uInt match_start; /* start of matching string */
  74342. uInt lookahead; /* number of valid bytes ahead in window */
  74343. uInt prev_length;
  74344. /* Length of the best match at previous step. Matches not greater than this
  74345. * are discarded. This is used in the lazy match evaluation.
  74346. */
  74347. uInt max_chain_length;
  74348. /* To speed up deflation, hash chains are never searched beyond this
  74349. * length. A higher limit improves compression ratio but degrades the
  74350. * speed.
  74351. */
  74352. uInt max_lazy_match;
  74353. /* Attempt to find a better match only when the current match is strictly
  74354. * smaller than this value. This mechanism is used only for compression
  74355. * levels >= 4.
  74356. */
  74357. # define max_insert_length max_lazy_match
  74358. /* Insert new strings in the hash table only if the match length is not
  74359. * greater than this length. This saves time but degrades compression.
  74360. * max_insert_length is used only for compression levels <= 3.
  74361. */
  74362. int level; /* compression level (1..9) */
  74363. int strategy; /* favor or force Huffman coding*/
  74364. uInt good_match;
  74365. /* Use a faster search when the previous match is longer than this */
  74366. int nice_match; /* Stop searching when current match exceeds this */
  74367. /* used by trees.c: */
  74368. /* Didn't use ct_data typedef below to supress compiler warning */
  74369. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  74370. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  74371. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  74372. struct tree_desc_s l_desc; /* desc. for literal tree */
  74373. struct tree_desc_s d_desc; /* desc. for distance tree */
  74374. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  74375. ush bl_count[MAX_BITS+1];
  74376. /* number of codes at each bit length for an optimal tree */
  74377. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  74378. int heap_len; /* number of elements in the heap */
  74379. int heap_max; /* element of largest frequency */
  74380. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  74381. * The same heap array is used to build all trees.
  74382. */
  74383. uch depth[2*L_CODES+1];
  74384. /* Depth of each subtree used as tie breaker for trees of equal frequency
  74385. */
  74386. uchf *l_buf; /* buffer for literals or lengths */
  74387. uInt lit_bufsize;
  74388. /* Size of match buffer for literals/lengths. There are 4 reasons for
  74389. * limiting lit_bufsize to 64K:
  74390. * - frequencies can be kept in 16 bit counters
  74391. * - if compression is not successful for the first block, all input
  74392. * data is still in the window so we can still emit a stored block even
  74393. * when input comes from standard input. (This can also be done for
  74394. * all blocks if lit_bufsize is not greater than 32K.)
  74395. * - if compression is not successful for a file smaller than 64K, we can
  74396. * even emit a stored file instead of a stored block (saving 5 bytes).
  74397. * This is applicable only for zip (not gzip or zlib).
  74398. * - creating new Huffman trees less frequently may not provide fast
  74399. * adaptation to changes in the input data statistics. (Take for
  74400. * example a binary file with poorly compressible code followed by
  74401. * a highly compressible string table.) Smaller buffer sizes give
  74402. * fast adaptation but have of course the overhead of transmitting
  74403. * trees more frequently.
  74404. * - I can't count above 4
  74405. */
  74406. uInt last_lit; /* running index in l_buf */
  74407. ushf *d_buf;
  74408. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  74409. * the same number of elements. To use different lengths, an extra flag
  74410. * array would be necessary.
  74411. */
  74412. ulg opt_len; /* bit length of current block with optimal trees */
  74413. ulg static_len; /* bit length of current block with static trees */
  74414. uInt matches; /* number of string matches in current block */
  74415. int last_eob_len; /* bit length of EOB code for last block */
  74416. #ifdef DEBUG
  74417. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  74418. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  74419. #endif
  74420. ush bi_buf;
  74421. /* Output buffer. bits are inserted starting at the bottom (least
  74422. * significant bits).
  74423. */
  74424. int bi_valid;
  74425. /* Number of valid bits in bi_buf. All bits above the last valid bit
  74426. * are always zero.
  74427. */
  74428. } FAR deflate_state;
  74429. /* Output a byte on the stream.
  74430. * IN assertion: there is enough room in pending_buf.
  74431. */
  74432. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  74433. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  74434. /* Minimum amount of lookahead, except at the end of the input file.
  74435. * See deflate.c for comments about the MIN_MATCH+1.
  74436. */
  74437. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  74438. /* In order to simplify the code, particularly on 16 bit machines, match
  74439. * distances are limited to MAX_DIST instead of WSIZE.
  74440. */
  74441. /* in trees.c */
  74442. void _tr_init OF((deflate_state *s));
  74443. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  74444. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  74445. int eof));
  74446. void _tr_align OF((deflate_state *s));
  74447. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  74448. int eof));
  74449. #define d_code(dist) \
  74450. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  74451. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  74452. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  74453. * used.
  74454. */
  74455. #ifndef DEBUG
  74456. /* Inline versions of _tr_tally for speed: */
  74457. #if defined(GEN_TREES_H) || !defined(STDC)
  74458. extern uch _length_code[];
  74459. extern uch _dist_code[];
  74460. #else
  74461. extern const uch _length_code[];
  74462. extern const uch _dist_code[];
  74463. #endif
  74464. # define _tr_tally_lit(s, c, flush) \
  74465. { uch cc = (c); \
  74466. s->d_buf[s->last_lit] = 0; \
  74467. s->l_buf[s->last_lit++] = cc; \
  74468. s->dyn_ltree[cc].Freq++; \
  74469. flush = (s->last_lit == s->lit_bufsize-1); \
  74470. }
  74471. # define _tr_tally_dist(s, distance, length, flush) \
  74472. { uch len = (length); \
  74473. ush dist = (distance); \
  74474. s->d_buf[s->last_lit] = dist; \
  74475. s->l_buf[s->last_lit++] = len; \
  74476. dist--; \
  74477. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  74478. s->dyn_dtree[d_code(dist)].Freq++; \
  74479. flush = (s->last_lit == s->lit_bufsize-1); \
  74480. }
  74481. #else
  74482. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  74483. # define _tr_tally_dist(s, distance, length, flush) \
  74484. flush = _tr_tally(s, distance, length)
  74485. #endif
  74486. #endif /* DEFLATE_H */
  74487. /********* End of inlined file: deflate.h *********/
  74488. const char deflate_copyright[] =
  74489. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  74490. /*
  74491. If you use the zlib library in a product, an acknowledgment is welcome
  74492. in the documentation of your product. If for some reason you cannot
  74493. include such an acknowledgment, I would appreciate that you keep this
  74494. copyright string in the executable of your product.
  74495. */
  74496. /* ===========================================================================
  74497. * Function prototypes.
  74498. */
  74499. typedef enum {
  74500. need_more, /* block not completed, need more input or more output */
  74501. block_done, /* block flush performed */
  74502. finish_started, /* finish started, need only more output at next deflate */
  74503. finish_done /* finish done, accept no more input or output */
  74504. } block_state;
  74505. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  74506. /* Compression function. Returns the block state after the call. */
  74507. local void fill_window OF((deflate_state *s));
  74508. local block_state deflate_stored OF((deflate_state *s, int flush));
  74509. local block_state deflate_fast OF((deflate_state *s, int flush));
  74510. #ifndef FASTEST
  74511. local block_state deflate_slow OF((deflate_state *s, int flush));
  74512. #endif
  74513. local void lm_init OF((deflate_state *s));
  74514. local void putShortMSB OF((deflate_state *s, uInt b));
  74515. local void flush_pending OF((z_streamp strm));
  74516. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  74517. #ifndef FASTEST
  74518. #ifdef ASMV
  74519. void match_init OF((void)); /* asm code initialization */
  74520. uInt longest_match OF((deflate_state *s, IPos cur_match));
  74521. #else
  74522. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  74523. #endif
  74524. #endif
  74525. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  74526. #ifdef DEBUG
  74527. local void check_match OF((deflate_state *s, IPos start, IPos match,
  74528. int length));
  74529. #endif
  74530. /* ===========================================================================
  74531. * Local data
  74532. */
  74533. #define NIL 0
  74534. /* Tail of hash chains */
  74535. #ifndef TOO_FAR
  74536. # define TOO_FAR 4096
  74537. #endif
  74538. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  74539. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  74540. /* Minimum amount of lookahead, except at the end of the input file.
  74541. * See deflate.c for comments about the MIN_MATCH+1.
  74542. */
  74543. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  74544. * the desired pack level (0..9). The values given below have been tuned to
  74545. * exclude worst case performance for pathological files. Better values may be
  74546. * found for specific files.
  74547. */
  74548. typedef struct config_s {
  74549. ush good_length; /* reduce lazy search above this match length */
  74550. ush max_lazy; /* do not perform lazy search above this match length */
  74551. ush nice_length; /* quit search above this match length */
  74552. ush max_chain;
  74553. compress_func func;
  74554. } config;
  74555. #ifdef FASTEST
  74556. local const config configuration_table[2] = {
  74557. /* good lazy nice chain */
  74558. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  74559. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  74560. #else
  74561. local const config configuration_table[10] = {
  74562. /* good lazy nice chain */
  74563. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  74564. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  74565. /* 2 */ {4, 5, 16, 8, deflate_fast},
  74566. /* 3 */ {4, 6, 32, 32, deflate_fast},
  74567. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  74568. /* 5 */ {8, 16, 32, 32, deflate_slow},
  74569. /* 6 */ {8, 16, 128, 128, deflate_slow},
  74570. /* 7 */ {8, 32, 128, 256, deflate_slow},
  74571. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  74572. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  74573. #endif
  74574. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  74575. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  74576. * meaning.
  74577. */
  74578. #define EQUAL 0
  74579. /* result of memcmp for equal strings */
  74580. #ifndef NO_DUMMY_DECL
  74581. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  74582. #endif
  74583. /* ===========================================================================
  74584. * Update a hash value with the given input byte
  74585. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  74586. * input characters, so that a running hash key can be computed from the
  74587. * previous key instead of complete recalculation each time.
  74588. */
  74589. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  74590. /* ===========================================================================
  74591. * Insert string str in the dictionary and set match_head to the previous head
  74592. * of the hash chain (the most recent string with same hash key). Return
  74593. * the previous length of the hash chain.
  74594. * If this file is compiled with -DFASTEST, the compression level is forced
  74595. * to 1, and no hash chains are maintained.
  74596. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  74597. * input characters and the first MIN_MATCH bytes of str are valid
  74598. * (except for the last MIN_MATCH-1 bytes of the input file).
  74599. */
  74600. #ifdef FASTEST
  74601. #define INSERT_STRING(s, str, match_head) \
  74602. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  74603. match_head = s->head[s->ins_h], \
  74604. s->head[s->ins_h] = (Pos)(str))
  74605. #else
  74606. #define INSERT_STRING(s, str, match_head) \
  74607. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  74608. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  74609. s->head[s->ins_h] = (Pos)(str))
  74610. #endif
  74611. /* ===========================================================================
  74612. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  74613. * prev[] will be initialized on the fly.
  74614. */
  74615. #define CLEAR_HASH(s) \
  74616. s->head[s->hash_size-1] = NIL; \
  74617. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  74618. /* ========================================================================= */
  74619. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  74620. {
  74621. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  74622. Z_DEFAULT_STRATEGY, version, stream_size);
  74623. /* To do: ignore strm->next_in if we use it as window */
  74624. }
  74625. /* ========================================================================= */
  74626. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  74627. {
  74628. deflate_state *s;
  74629. int wrap = 1;
  74630. static const char my_version[] = ZLIB_VERSION;
  74631. ushf *overlay;
  74632. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  74633. * output size for (length,distance) codes is <= 24 bits.
  74634. */
  74635. if (version == Z_NULL || version[0] != my_version[0] ||
  74636. stream_size != sizeof(z_stream)) {
  74637. return Z_VERSION_ERROR;
  74638. }
  74639. if (strm == Z_NULL) return Z_STREAM_ERROR;
  74640. strm->msg = Z_NULL;
  74641. if (strm->zalloc == (alloc_func)0) {
  74642. strm->zalloc = zcalloc;
  74643. strm->opaque = (voidpf)0;
  74644. }
  74645. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  74646. #ifdef FASTEST
  74647. if (level != 0) level = 1;
  74648. #else
  74649. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  74650. #endif
  74651. if (windowBits < 0) { /* suppress zlib wrapper */
  74652. wrap = 0;
  74653. windowBits = -windowBits;
  74654. }
  74655. #ifdef GZIP
  74656. else if (windowBits > 15) {
  74657. wrap = 2; /* write gzip wrapper instead */
  74658. windowBits -= 16;
  74659. }
  74660. #endif
  74661. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  74662. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  74663. strategy < 0 || strategy > Z_FIXED) {
  74664. return Z_STREAM_ERROR;
  74665. }
  74666. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  74667. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  74668. if (s == Z_NULL) return Z_MEM_ERROR;
  74669. strm->state = (struct internal_state FAR *)s;
  74670. s->strm = strm;
  74671. s->wrap = wrap;
  74672. s->gzhead = Z_NULL;
  74673. s->w_bits = windowBits;
  74674. s->w_size = 1 << s->w_bits;
  74675. s->w_mask = s->w_size - 1;
  74676. s->hash_bits = memLevel + 7;
  74677. s->hash_size = 1 << s->hash_bits;
  74678. s->hash_mask = s->hash_size - 1;
  74679. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  74680. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  74681. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  74682. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  74683. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  74684. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  74685. s->pending_buf = (uchf *) overlay;
  74686. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  74687. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  74688. s->pending_buf == Z_NULL) {
  74689. s->status = FINISH_STATE;
  74690. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  74691. deflateEnd (strm);
  74692. return Z_MEM_ERROR;
  74693. }
  74694. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  74695. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  74696. s->level = level;
  74697. s->strategy = strategy;
  74698. s->method = (Byte)method;
  74699. return deflateReset(strm);
  74700. }
  74701. /* ========================================================================= */
  74702. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  74703. {
  74704. deflate_state *s;
  74705. uInt length = dictLength;
  74706. uInt n;
  74707. IPos hash_head = 0;
  74708. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  74709. strm->state->wrap == 2 ||
  74710. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  74711. return Z_STREAM_ERROR;
  74712. s = strm->state;
  74713. if (s->wrap)
  74714. strm->adler = adler32(strm->adler, dictionary, dictLength);
  74715. if (length < MIN_MATCH) return Z_OK;
  74716. if (length > MAX_DIST(s)) {
  74717. length = MAX_DIST(s);
  74718. dictionary += dictLength - length; /* use the tail of the dictionary */
  74719. }
  74720. zmemcpy(s->window, dictionary, length);
  74721. s->strstart = length;
  74722. s->block_start = (long)length;
  74723. /* Insert all strings in the hash table (except for the last two bytes).
  74724. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  74725. * call of fill_window.
  74726. */
  74727. s->ins_h = s->window[0];
  74728. UPDATE_HASH(s, s->ins_h, s->window[1]);
  74729. for (n = 0; n <= length - MIN_MATCH; n++) {
  74730. INSERT_STRING(s, n, hash_head);
  74731. }
  74732. if (hash_head) hash_head = 0; /* to make compiler happy */
  74733. return Z_OK;
  74734. }
  74735. /* ========================================================================= */
  74736. int ZEXPORT deflateReset (z_streamp strm)
  74737. {
  74738. deflate_state *s;
  74739. if (strm == Z_NULL || strm->state == Z_NULL ||
  74740. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  74741. return Z_STREAM_ERROR;
  74742. }
  74743. strm->total_in = strm->total_out = 0;
  74744. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  74745. strm->data_type = Z_UNKNOWN;
  74746. s = (deflate_state *)strm->state;
  74747. s->pending = 0;
  74748. s->pending_out = s->pending_buf;
  74749. if (s->wrap < 0) {
  74750. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  74751. }
  74752. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  74753. strm->adler =
  74754. #ifdef GZIP
  74755. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  74756. #endif
  74757. adler32(0L, Z_NULL, 0);
  74758. s->last_flush = Z_NO_FLUSH;
  74759. _tr_init(s);
  74760. lm_init(s);
  74761. return Z_OK;
  74762. }
  74763. /* ========================================================================= */
  74764. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  74765. {
  74766. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74767. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  74768. strm->state->gzhead = head;
  74769. return Z_OK;
  74770. }
  74771. /* ========================================================================= */
  74772. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  74773. {
  74774. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74775. strm->state->bi_valid = bits;
  74776. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  74777. return Z_OK;
  74778. }
  74779. /* ========================================================================= */
  74780. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  74781. {
  74782. deflate_state *s;
  74783. compress_func func;
  74784. int err = Z_OK;
  74785. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74786. s = strm->state;
  74787. #ifdef FASTEST
  74788. if (level != 0) level = 1;
  74789. #else
  74790. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  74791. #endif
  74792. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  74793. return Z_STREAM_ERROR;
  74794. }
  74795. func = configuration_table[s->level].func;
  74796. if (func != configuration_table[level].func && strm->total_in != 0) {
  74797. /* Flush the last buffer: */
  74798. err = deflate(strm, Z_PARTIAL_FLUSH);
  74799. }
  74800. if (s->level != level) {
  74801. s->level = level;
  74802. s->max_lazy_match = configuration_table[level].max_lazy;
  74803. s->good_match = configuration_table[level].good_length;
  74804. s->nice_match = configuration_table[level].nice_length;
  74805. s->max_chain_length = configuration_table[level].max_chain;
  74806. }
  74807. s->strategy = strategy;
  74808. return err;
  74809. }
  74810. /* ========================================================================= */
  74811. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  74812. {
  74813. deflate_state *s;
  74814. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74815. s = strm->state;
  74816. s->good_match = good_length;
  74817. s->max_lazy_match = max_lazy;
  74818. s->nice_match = nice_length;
  74819. s->max_chain_length = max_chain;
  74820. return Z_OK;
  74821. }
  74822. /* =========================================================================
  74823. * For the default windowBits of 15 and memLevel of 8, this function returns
  74824. * a close to exact, as well as small, upper bound on the compressed size.
  74825. * They are coded as constants here for a reason--if the #define's are
  74826. * changed, then this function needs to be changed as well. The return
  74827. * value for 15 and 8 only works for those exact settings.
  74828. *
  74829. * For any setting other than those defaults for windowBits and memLevel,
  74830. * the value returned is a conservative worst case for the maximum expansion
  74831. * resulting from using fixed blocks instead of stored blocks, which deflate
  74832. * can emit on compressed data for some combinations of the parameters.
  74833. *
  74834. * This function could be more sophisticated to provide closer upper bounds
  74835. * for every combination of windowBits and memLevel, as well as wrap.
  74836. * But even the conservative upper bound of about 14% expansion does not
  74837. * seem onerous for output buffer allocation.
  74838. */
  74839. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  74840. {
  74841. deflate_state *s;
  74842. uLong destLen;
  74843. /* conservative upper bound */
  74844. destLen = sourceLen +
  74845. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  74846. /* if can't get parameters, return conservative bound */
  74847. if (strm == Z_NULL || strm->state == Z_NULL)
  74848. return destLen;
  74849. /* if not default parameters, return conservative bound */
  74850. s = strm->state;
  74851. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  74852. return destLen;
  74853. /* default settings: return tight bound for that case */
  74854. return compressBound(sourceLen);
  74855. }
  74856. /* =========================================================================
  74857. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  74858. * IN assertion: the stream state is correct and there is enough room in
  74859. * pending_buf.
  74860. */
  74861. local void putShortMSB (deflate_state *s, uInt b)
  74862. {
  74863. put_byte(s, (Byte)(b >> 8));
  74864. put_byte(s, (Byte)(b & 0xff));
  74865. }
  74866. /* =========================================================================
  74867. * Flush as much pending output as possible. All deflate() output goes
  74868. * through this function so some applications may wish to modify it
  74869. * to avoid allocating a large strm->next_out buffer and copying into it.
  74870. * (See also read_buf()).
  74871. */
  74872. local void flush_pending (z_streamp strm)
  74873. {
  74874. unsigned len = strm->state->pending;
  74875. if (len > strm->avail_out) len = strm->avail_out;
  74876. if (len == 0) return;
  74877. zmemcpy(strm->next_out, strm->state->pending_out, len);
  74878. strm->next_out += len;
  74879. strm->state->pending_out += len;
  74880. strm->total_out += len;
  74881. strm->avail_out -= len;
  74882. strm->state->pending -= len;
  74883. if (strm->state->pending == 0) {
  74884. strm->state->pending_out = strm->state->pending_buf;
  74885. }
  74886. }
  74887. /* ========================================================================= */
  74888. int ZEXPORT deflate (z_streamp strm, int flush)
  74889. {
  74890. int old_flush; /* value of flush param for previous deflate call */
  74891. deflate_state *s;
  74892. if (strm == Z_NULL || strm->state == Z_NULL ||
  74893. flush > Z_FINISH || flush < 0) {
  74894. return Z_STREAM_ERROR;
  74895. }
  74896. s = strm->state;
  74897. if (strm->next_out == Z_NULL ||
  74898. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  74899. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  74900. ERR_RETURN(strm, Z_STREAM_ERROR);
  74901. }
  74902. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  74903. s->strm = strm; /* just in case */
  74904. old_flush = s->last_flush;
  74905. s->last_flush = flush;
  74906. /* Write the header */
  74907. if (s->status == INIT_STATE) {
  74908. #ifdef GZIP
  74909. if (s->wrap == 2) {
  74910. strm->adler = crc32(0L, Z_NULL, 0);
  74911. put_byte(s, 31);
  74912. put_byte(s, 139);
  74913. put_byte(s, 8);
  74914. if (s->gzhead == NULL) {
  74915. put_byte(s, 0);
  74916. put_byte(s, 0);
  74917. put_byte(s, 0);
  74918. put_byte(s, 0);
  74919. put_byte(s, 0);
  74920. put_byte(s, s->level == 9 ? 2 :
  74921. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  74922. 4 : 0));
  74923. put_byte(s, OS_CODE);
  74924. s->status = BUSY_STATE;
  74925. }
  74926. else {
  74927. put_byte(s, (s->gzhead->text ? 1 : 0) +
  74928. (s->gzhead->hcrc ? 2 : 0) +
  74929. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  74930. (s->gzhead->name == Z_NULL ? 0 : 8) +
  74931. (s->gzhead->comment == Z_NULL ? 0 : 16)
  74932. );
  74933. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  74934. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  74935. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  74936. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  74937. put_byte(s, s->level == 9 ? 2 :
  74938. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  74939. 4 : 0));
  74940. put_byte(s, s->gzhead->os & 0xff);
  74941. if (s->gzhead->extra != NULL) {
  74942. put_byte(s, s->gzhead->extra_len & 0xff);
  74943. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  74944. }
  74945. if (s->gzhead->hcrc)
  74946. strm->adler = crc32(strm->adler, s->pending_buf,
  74947. s->pending);
  74948. s->gzindex = 0;
  74949. s->status = EXTRA_STATE;
  74950. }
  74951. }
  74952. else
  74953. #endif
  74954. {
  74955. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  74956. uInt level_flags;
  74957. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  74958. level_flags = 0;
  74959. else if (s->level < 6)
  74960. level_flags = 1;
  74961. else if (s->level == 6)
  74962. level_flags = 2;
  74963. else
  74964. level_flags = 3;
  74965. header |= (level_flags << 6);
  74966. if (s->strstart != 0) header |= PRESET_DICT;
  74967. header += 31 - (header % 31);
  74968. s->status = BUSY_STATE;
  74969. putShortMSB(s, header);
  74970. /* Save the adler32 of the preset dictionary: */
  74971. if (s->strstart != 0) {
  74972. putShortMSB(s, (uInt)(strm->adler >> 16));
  74973. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  74974. }
  74975. strm->adler = adler32(0L, Z_NULL, 0);
  74976. }
  74977. }
  74978. #ifdef GZIP
  74979. if (s->status == EXTRA_STATE) {
  74980. if (s->gzhead->extra != NULL) {
  74981. uInt beg = s->pending; /* start of bytes to update crc */
  74982. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  74983. if (s->pending == s->pending_buf_size) {
  74984. if (s->gzhead->hcrc && s->pending > beg)
  74985. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  74986. s->pending - beg);
  74987. flush_pending(strm);
  74988. beg = s->pending;
  74989. if (s->pending == s->pending_buf_size)
  74990. break;
  74991. }
  74992. put_byte(s, s->gzhead->extra[s->gzindex]);
  74993. s->gzindex++;
  74994. }
  74995. if (s->gzhead->hcrc && s->pending > beg)
  74996. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  74997. s->pending - beg);
  74998. if (s->gzindex == s->gzhead->extra_len) {
  74999. s->gzindex = 0;
  75000. s->status = NAME_STATE;
  75001. }
  75002. }
  75003. else
  75004. s->status = NAME_STATE;
  75005. }
  75006. if (s->status == NAME_STATE) {
  75007. if (s->gzhead->name != NULL) {
  75008. uInt beg = s->pending; /* start of bytes to update crc */
  75009. int val;
  75010. do {
  75011. if (s->pending == s->pending_buf_size) {
  75012. if (s->gzhead->hcrc && s->pending > beg)
  75013. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75014. s->pending - beg);
  75015. flush_pending(strm);
  75016. beg = s->pending;
  75017. if (s->pending == s->pending_buf_size) {
  75018. val = 1;
  75019. break;
  75020. }
  75021. }
  75022. val = s->gzhead->name[s->gzindex++];
  75023. put_byte(s, val);
  75024. } while (val != 0);
  75025. if (s->gzhead->hcrc && s->pending > beg)
  75026. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75027. s->pending - beg);
  75028. if (val == 0) {
  75029. s->gzindex = 0;
  75030. s->status = COMMENT_STATE;
  75031. }
  75032. }
  75033. else
  75034. s->status = COMMENT_STATE;
  75035. }
  75036. if (s->status == COMMENT_STATE) {
  75037. if (s->gzhead->comment != NULL) {
  75038. uInt beg = s->pending; /* start of bytes to update crc */
  75039. int val;
  75040. do {
  75041. if (s->pending == s->pending_buf_size) {
  75042. if (s->gzhead->hcrc && s->pending > beg)
  75043. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75044. s->pending - beg);
  75045. flush_pending(strm);
  75046. beg = s->pending;
  75047. if (s->pending == s->pending_buf_size) {
  75048. val = 1;
  75049. break;
  75050. }
  75051. }
  75052. val = s->gzhead->comment[s->gzindex++];
  75053. put_byte(s, val);
  75054. } while (val != 0);
  75055. if (s->gzhead->hcrc && s->pending > beg)
  75056. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75057. s->pending - beg);
  75058. if (val == 0)
  75059. s->status = HCRC_STATE;
  75060. }
  75061. else
  75062. s->status = HCRC_STATE;
  75063. }
  75064. if (s->status == HCRC_STATE) {
  75065. if (s->gzhead->hcrc) {
  75066. if (s->pending + 2 > s->pending_buf_size)
  75067. flush_pending(strm);
  75068. if (s->pending + 2 <= s->pending_buf_size) {
  75069. put_byte(s, (Byte)(strm->adler & 0xff));
  75070. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  75071. strm->adler = crc32(0L, Z_NULL, 0);
  75072. s->status = BUSY_STATE;
  75073. }
  75074. }
  75075. else
  75076. s->status = BUSY_STATE;
  75077. }
  75078. #endif
  75079. /* Flush as much pending output as possible */
  75080. if (s->pending != 0) {
  75081. flush_pending(strm);
  75082. if (strm->avail_out == 0) {
  75083. /* Since avail_out is 0, deflate will be called again with
  75084. * more output space, but possibly with both pending and
  75085. * avail_in equal to zero. There won't be anything to do,
  75086. * but this is not an error situation so make sure we
  75087. * return OK instead of BUF_ERROR at next call of deflate:
  75088. */
  75089. s->last_flush = -1;
  75090. return Z_OK;
  75091. }
  75092. /* Make sure there is something to do and avoid duplicate consecutive
  75093. * flushes. For repeated and useless calls with Z_FINISH, we keep
  75094. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  75095. */
  75096. } else if (strm->avail_in == 0 && flush <= old_flush &&
  75097. flush != Z_FINISH) {
  75098. ERR_RETURN(strm, Z_BUF_ERROR);
  75099. }
  75100. /* User must not provide more input after the first FINISH: */
  75101. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  75102. ERR_RETURN(strm, Z_BUF_ERROR);
  75103. }
  75104. /* Start a new block or continue the current one.
  75105. */
  75106. if (strm->avail_in != 0 || s->lookahead != 0 ||
  75107. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  75108. block_state bstate;
  75109. bstate = (*(configuration_table[s->level].func))(s, flush);
  75110. if (bstate == finish_started || bstate == finish_done) {
  75111. s->status = FINISH_STATE;
  75112. }
  75113. if (bstate == need_more || bstate == finish_started) {
  75114. if (strm->avail_out == 0) {
  75115. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  75116. }
  75117. return Z_OK;
  75118. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  75119. * of deflate should use the same flush parameter to make sure
  75120. * that the flush is complete. So we don't have to output an
  75121. * empty block here, this will be done at next call. This also
  75122. * ensures that for a very small output buffer, we emit at most
  75123. * one empty block.
  75124. */
  75125. }
  75126. if (bstate == block_done) {
  75127. if (flush == Z_PARTIAL_FLUSH) {
  75128. _tr_align(s);
  75129. } else { /* FULL_FLUSH or SYNC_FLUSH */
  75130. _tr_stored_block(s, (char*)0, 0L, 0);
  75131. /* For a full flush, this empty block will be recognized
  75132. * as a special marker by inflate_sync().
  75133. */
  75134. if (flush == Z_FULL_FLUSH) {
  75135. CLEAR_HASH(s); /* forget history */
  75136. }
  75137. }
  75138. flush_pending(strm);
  75139. if (strm->avail_out == 0) {
  75140. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  75141. return Z_OK;
  75142. }
  75143. }
  75144. }
  75145. Assert(strm->avail_out > 0, "bug2");
  75146. if (flush != Z_FINISH) return Z_OK;
  75147. if (s->wrap <= 0) return Z_STREAM_END;
  75148. /* Write the trailer */
  75149. #ifdef GZIP
  75150. if (s->wrap == 2) {
  75151. put_byte(s, (Byte)(strm->adler & 0xff));
  75152. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  75153. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  75154. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  75155. put_byte(s, (Byte)(strm->total_in & 0xff));
  75156. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  75157. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  75158. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  75159. }
  75160. else
  75161. #endif
  75162. {
  75163. putShortMSB(s, (uInt)(strm->adler >> 16));
  75164. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  75165. }
  75166. flush_pending(strm);
  75167. /* If avail_out is zero, the application will call deflate again
  75168. * to flush the rest.
  75169. */
  75170. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  75171. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  75172. }
  75173. /* ========================================================================= */
  75174. int ZEXPORT deflateEnd (z_streamp strm)
  75175. {
  75176. int status;
  75177. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  75178. status = strm->state->status;
  75179. if (status != INIT_STATE &&
  75180. status != EXTRA_STATE &&
  75181. status != NAME_STATE &&
  75182. status != COMMENT_STATE &&
  75183. status != HCRC_STATE &&
  75184. status != BUSY_STATE &&
  75185. status != FINISH_STATE) {
  75186. return Z_STREAM_ERROR;
  75187. }
  75188. /* Deallocate in reverse order of allocations: */
  75189. TRY_FREE(strm, strm->state->pending_buf);
  75190. TRY_FREE(strm, strm->state->head);
  75191. TRY_FREE(strm, strm->state->prev);
  75192. TRY_FREE(strm, strm->state->window);
  75193. ZFREE(strm, strm->state);
  75194. strm->state = Z_NULL;
  75195. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  75196. }
  75197. /* =========================================================================
  75198. * Copy the source state to the destination state.
  75199. * To simplify the source, this is not supported for 16-bit MSDOS (which
  75200. * doesn't have enough memory anyway to duplicate compression states).
  75201. */
  75202. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  75203. {
  75204. #ifdef MAXSEG_64K
  75205. return Z_STREAM_ERROR;
  75206. #else
  75207. deflate_state *ds;
  75208. deflate_state *ss;
  75209. ushf *overlay;
  75210. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  75211. return Z_STREAM_ERROR;
  75212. }
  75213. ss = source->state;
  75214. zmemcpy(dest, source, sizeof(z_stream));
  75215. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  75216. if (ds == Z_NULL) return Z_MEM_ERROR;
  75217. dest->state = (struct internal_state FAR *) ds;
  75218. zmemcpy(ds, ss, sizeof(deflate_state));
  75219. ds->strm = dest;
  75220. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  75221. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  75222. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  75223. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  75224. ds->pending_buf = (uchf *) overlay;
  75225. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  75226. ds->pending_buf == Z_NULL) {
  75227. deflateEnd (dest);
  75228. return Z_MEM_ERROR;
  75229. }
  75230. /* following zmemcpy do not work for 16-bit MSDOS */
  75231. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  75232. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  75233. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  75234. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  75235. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  75236. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  75237. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  75238. ds->l_desc.dyn_tree = ds->dyn_ltree;
  75239. ds->d_desc.dyn_tree = ds->dyn_dtree;
  75240. ds->bl_desc.dyn_tree = ds->bl_tree;
  75241. return Z_OK;
  75242. #endif /* MAXSEG_64K */
  75243. }
  75244. /* ===========================================================================
  75245. * Read a new buffer from the current input stream, update the adler32
  75246. * and total number of bytes read. All deflate() input goes through
  75247. * this function so some applications may wish to modify it to avoid
  75248. * allocating a large strm->next_in buffer and copying from it.
  75249. * (See also flush_pending()).
  75250. */
  75251. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  75252. {
  75253. unsigned len = strm->avail_in;
  75254. if (len > size) len = size;
  75255. if (len == 0) return 0;
  75256. strm->avail_in -= len;
  75257. if (strm->state->wrap == 1) {
  75258. strm->adler = adler32(strm->adler, strm->next_in, len);
  75259. }
  75260. #ifdef GZIP
  75261. else if (strm->state->wrap == 2) {
  75262. strm->adler = crc32(strm->adler, strm->next_in, len);
  75263. }
  75264. #endif
  75265. zmemcpy(buf, strm->next_in, len);
  75266. strm->next_in += len;
  75267. strm->total_in += len;
  75268. return (int)len;
  75269. }
  75270. /* ===========================================================================
  75271. * Initialize the "longest match" routines for a new zlib stream
  75272. */
  75273. local void lm_init (deflate_state *s)
  75274. {
  75275. s->window_size = (ulg)2L*s->w_size;
  75276. CLEAR_HASH(s);
  75277. /* Set the default configuration parameters:
  75278. */
  75279. s->max_lazy_match = configuration_table[s->level].max_lazy;
  75280. s->good_match = configuration_table[s->level].good_length;
  75281. s->nice_match = configuration_table[s->level].nice_length;
  75282. s->max_chain_length = configuration_table[s->level].max_chain;
  75283. s->strstart = 0;
  75284. s->block_start = 0L;
  75285. s->lookahead = 0;
  75286. s->match_length = s->prev_length = MIN_MATCH-1;
  75287. s->match_available = 0;
  75288. s->ins_h = 0;
  75289. #ifndef FASTEST
  75290. #ifdef ASMV
  75291. match_init(); /* initialize the asm code */
  75292. #endif
  75293. #endif
  75294. }
  75295. #ifndef FASTEST
  75296. /* ===========================================================================
  75297. * Set match_start to the longest match starting at the given string and
  75298. * return its length. Matches shorter or equal to prev_length are discarded,
  75299. * in which case the result is equal to prev_length and match_start is
  75300. * garbage.
  75301. * IN assertions: cur_match is the head of the hash chain for the current
  75302. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  75303. * OUT assertion: the match length is not greater than s->lookahead.
  75304. */
  75305. #ifndef ASMV
  75306. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  75307. * match.S. The code will be functionally equivalent.
  75308. */
  75309. local uInt longest_match(deflate_state *s, IPos cur_match)
  75310. {
  75311. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  75312. register Bytef *scan = s->window + s->strstart; /* current string */
  75313. register Bytef *match; /* matched string */
  75314. register int len; /* length of current match */
  75315. int best_len = s->prev_length; /* best match length so far */
  75316. int nice_match = s->nice_match; /* stop if match long enough */
  75317. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  75318. s->strstart - (IPos)MAX_DIST(s) : NIL;
  75319. /* Stop when cur_match becomes <= limit. To simplify the code,
  75320. * we prevent matches with the string of window index 0.
  75321. */
  75322. Posf *prev = s->prev;
  75323. uInt wmask = s->w_mask;
  75324. #ifdef UNALIGNED_OK
  75325. /* Compare two bytes at a time. Note: this is not always beneficial.
  75326. * Try with and without -DUNALIGNED_OK to check.
  75327. */
  75328. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  75329. register ush scan_start = *(ushf*)scan;
  75330. register ush scan_end = *(ushf*)(scan+best_len-1);
  75331. #else
  75332. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  75333. register Byte scan_end1 = scan[best_len-1];
  75334. register Byte scan_end = scan[best_len];
  75335. #endif
  75336. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  75337. * It is easy to get rid of this optimization if necessary.
  75338. */
  75339. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  75340. /* Do not waste too much time if we already have a good match: */
  75341. if (s->prev_length >= s->good_match) {
  75342. chain_length >>= 2;
  75343. }
  75344. /* Do not look for matches beyond the end of the input. This is necessary
  75345. * to make deflate deterministic.
  75346. */
  75347. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  75348. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  75349. do {
  75350. Assert(cur_match < s->strstart, "no future");
  75351. match = s->window + cur_match;
  75352. /* Skip to next match if the match length cannot increase
  75353. * or if the match length is less than 2. Note that the checks below
  75354. * for insufficient lookahead only occur occasionally for performance
  75355. * reasons. Therefore uninitialized memory will be accessed, and
  75356. * conditional jumps will be made that depend on those values.
  75357. * However the length of the match is limited to the lookahead, so
  75358. * the output of deflate is not affected by the uninitialized values.
  75359. */
  75360. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  75361. /* This code assumes sizeof(unsigned short) == 2. Do not use
  75362. * UNALIGNED_OK if your compiler uses a different size.
  75363. */
  75364. if (*(ushf*)(match+best_len-1) != scan_end ||
  75365. *(ushf*)match != scan_start) continue;
  75366. /* It is not necessary to compare scan[2] and match[2] since they are
  75367. * always equal when the other bytes match, given that the hash keys
  75368. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  75369. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  75370. * lookahead only every 4th comparison; the 128th check will be made
  75371. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  75372. * necessary to put more guard bytes at the end of the window, or
  75373. * to check more often for insufficient lookahead.
  75374. */
  75375. Assert(scan[2] == match[2], "scan[2]?");
  75376. scan++, match++;
  75377. do {
  75378. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  75379. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  75380. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  75381. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  75382. scan < strend);
  75383. /* The funny "do {}" generates better code on most compilers */
  75384. /* Here, scan <= window+strstart+257 */
  75385. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  75386. if (*scan == *match) scan++;
  75387. len = (MAX_MATCH - 1) - (int)(strend-scan);
  75388. scan = strend - (MAX_MATCH-1);
  75389. #else /* UNALIGNED_OK */
  75390. if (match[best_len] != scan_end ||
  75391. match[best_len-1] != scan_end1 ||
  75392. *match != *scan ||
  75393. *++match != scan[1]) continue;
  75394. /* The check at best_len-1 can be removed because it will be made
  75395. * again later. (This heuristic is not always a win.)
  75396. * It is not necessary to compare scan[2] and match[2] since they
  75397. * are always equal when the other bytes match, given that
  75398. * the hash keys are equal and that HASH_BITS >= 8.
  75399. */
  75400. scan += 2, match++;
  75401. Assert(*scan == *match, "match[2]?");
  75402. /* We check for insufficient lookahead only every 8th comparison;
  75403. * the 256th check will be made at strstart+258.
  75404. */
  75405. do {
  75406. } while (*++scan == *++match && *++scan == *++match &&
  75407. *++scan == *++match && *++scan == *++match &&
  75408. *++scan == *++match && *++scan == *++match &&
  75409. *++scan == *++match && *++scan == *++match &&
  75410. scan < strend);
  75411. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  75412. len = MAX_MATCH - (int)(strend - scan);
  75413. scan = strend - MAX_MATCH;
  75414. #endif /* UNALIGNED_OK */
  75415. if (len > best_len) {
  75416. s->match_start = cur_match;
  75417. best_len = len;
  75418. if (len >= nice_match) break;
  75419. #ifdef UNALIGNED_OK
  75420. scan_end = *(ushf*)(scan+best_len-1);
  75421. #else
  75422. scan_end1 = scan[best_len-1];
  75423. scan_end = scan[best_len];
  75424. #endif
  75425. }
  75426. } while ((cur_match = prev[cur_match & wmask]) > limit
  75427. && --chain_length != 0);
  75428. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  75429. return s->lookahead;
  75430. }
  75431. #endif /* ASMV */
  75432. #endif /* FASTEST */
  75433. /* ---------------------------------------------------------------------------
  75434. * Optimized version for level == 1 or strategy == Z_RLE only
  75435. */
  75436. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  75437. {
  75438. register Bytef *scan = s->window + s->strstart; /* current string */
  75439. register Bytef *match; /* matched string */
  75440. register int len; /* length of current match */
  75441. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  75442. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  75443. * It is easy to get rid of this optimization if necessary.
  75444. */
  75445. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  75446. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  75447. Assert(cur_match < s->strstart, "no future");
  75448. match = s->window + cur_match;
  75449. /* Return failure if the match length is less than 2:
  75450. */
  75451. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  75452. /* The check at best_len-1 can be removed because it will be made
  75453. * again later. (This heuristic is not always a win.)
  75454. * It is not necessary to compare scan[2] and match[2] since they
  75455. * are always equal when the other bytes match, given that
  75456. * the hash keys are equal and that HASH_BITS >= 8.
  75457. */
  75458. scan += 2, match += 2;
  75459. Assert(*scan == *match, "match[2]?");
  75460. /* We check for insufficient lookahead only every 8th comparison;
  75461. * the 256th check will be made at strstart+258.
  75462. */
  75463. do {
  75464. } while (*++scan == *++match && *++scan == *++match &&
  75465. *++scan == *++match && *++scan == *++match &&
  75466. *++scan == *++match && *++scan == *++match &&
  75467. *++scan == *++match && *++scan == *++match &&
  75468. scan < strend);
  75469. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  75470. len = MAX_MATCH - (int)(strend - scan);
  75471. if (len < MIN_MATCH) return MIN_MATCH - 1;
  75472. s->match_start = cur_match;
  75473. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  75474. }
  75475. #ifdef DEBUG
  75476. /* ===========================================================================
  75477. * Check that the match at match_start is indeed a match.
  75478. */
  75479. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  75480. {
  75481. /* check that the match is indeed a match */
  75482. if (zmemcmp(s->window + match,
  75483. s->window + start, length) != EQUAL) {
  75484. fprintf(stderr, " start %u, match %u, length %d\n",
  75485. start, match, length);
  75486. do {
  75487. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  75488. } while (--length != 0);
  75489. z_error("invalid match");
  75490. }
  75491. if (z_verbose > 1) {
  75492. fprintf(stderr,"\\[%d,%d]", start-match, length);
  75493. do { putc(s->window[start++], stderr); } while (--length != 0);
  75494. }
  75495. }
  75496. #else
  75497. # define check_match(s, start, match, length)
  75498. #endif /* DEBUG */
  75499. /* ===========================================================================
  75500. * Fill the window when the lookahead becomes insufficient.
  75501. * Updates strstart and lookahead.
  75502. *
  75503. * IN assertion: lookahead < MIN_LOOKAHEAD
  75504. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  75505. * At least one byte has been read, or avail_in == 0; reads are
  75506. * performed for at least two bytes (required for the zip translate_eol
  75507. * option -- not supported here).
  75508. */
  75509. local void fill_window (deflate_state *s)
  75510. {
  75511. register unsigned n, m;
  75512. register Posf *p;
  75513. unsigned more; /* Amount of free space at the end of the window. */
  75514. uInt wsize = s->w_size;
  75515. do {
  75516. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  75517. /* Deal with !@#$% 64K limit: */
  75518. if (sizeof(int) <= 2) {
  75519. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  75520. more = wsize;
  75521. } else if (more == (unsigned)(-1)) {
  75522. /* Very unlikely, but possible on 16 bit machine if
  75523. * strstart == 0 && lookahead == 1 (input done a byte at time)
  75524. */
  75525. more--;
  75526. }
  75527. }
  75528. /* If the window is almost full and there is insufficient lookahead,
  75529. * move the upper half to the lower one to make room in the upper half.
  75530. */
  75531. if (s->strstart >= wsize+MAX_DIST(s)) {
  75532. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  75533. s->match_start -= wsize;
  75534. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  75535. s->block_start -= (long) wsize;
  75536. /* Slide the hash table (could be avoided with 32 bit values
  75537. at the expense of memory usage). We slide even when level == 0
  75538. to keep the hash table consistent if we switch back to level > 0
  75539. later. (Using level 0 permanently is not an optimal usage of
  75540. zlib, so we don't care about this pathological case.)
  75541. */
  75542. /* %%% avoid this when Z_RLE */
  75543. n = s->hash_size;
  75544. p = &s->head[n];
  75545. do {
  75546. m = *--p;
  75547. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  75548. } while (--n);
  75549. n = wsize;
  75550. #ifndef FASTEST
  75551. p = &s->prev[n];
  75552. do {
  75553. m = *--p;
  75554. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  75555. /* If n is not on any hash chain, prev[n] is garbage but
  75556. * its value will never be used.
  75557. */
  75558. } while (--n);
  75559. #endif
  75560. more += wsize;
  75561. }
  75562. if (s->strm->avail_in == 0) return;
  75563. /* If there was no sliding:
  75564. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  75565. * more == window_size - lookahead - strstart
  75566. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  75567. * => more >= window_size - 2*WSIZE + 2
  75568. * In the BIG_MEM or MMAP case (not yet supported),
  75569. * window_size == input_size + MIN_LOOKAHEAD &&
  75570. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  75571. * Otherwise, window_size == 2*WSIZE so more >= 2.
  75572. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  75573. */
  75574. Assert(more >= 2, "more < 2");
  75575. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  75576. s->lookahead += n;
  75577. /* Initialize the hash value now that we have some input: */
  75578. if (s->lookahead >= MIN_MATCH) {
  75579. s->ins_h = s->window[s->strstart];
  75580. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  75581. #if MIN_MATCH != 3
  75582. Call UPDATE_HASH() MIN_MATCH-3 more times
  75583. #endif
  75584. }
  75585. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  75586. * but this is not important since only literal bytes will be emitted.
  75587. */
  75588. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  75589. }
  75590. /* ===========================================================================
  75591. * Flush the current block, with given end-of-file flag.
  75592. * IN assertion: strstart is set to the end of the current match.
  75593. */
  75594. #define FLUSH_BLOCK_ONLY(s, eof) { \
  75595. _tr_flush_block(s, (s->block_start >= 0L ? \
  75596. (charf *)&s->window[(unsigned)s->block_start] : \
  75597. (charf *)Z_NULL), \
  75598. (ulg)((long)s->strstart - s->block_start), \
  75599. (eof)); \
  75600. s->block_start = s->strstart; \
  75601. flush_pending(s->strm); \
  75602. Tracev((stderr,"[FLUSH]")); \
  75603. }
  75604. /* Same but force premature exit if necessary. */
  75605. #define FLUSH_BLOCK(s, eof) { \
  75606. FLUSH_BLOCK_ONLY(s, eof); \
  75607. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  75608. }
  75609. /* ===========================================================================
  75610. * Copy without compression as much as possible from the input stream, return
  75611. * the current block state.
  75612. * This function does not insert new strings in the dictionary since
  75613. * uncompressible data is probably not useful. This function is used
  75614. * only for the level=0 compression option.
  75615. * NOTE: this function should be optimized to avoid extra copying from
  75616. * window to pending_buf.
  75617. */
  75618. local block_state deflate_stored(deflate_state *s, int flush)
  75619. {
  75620. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  75621. * to pending_buf_size, and each stored block has a 5 byte header:
  75622. */
  75623. ulg max_block_size = 0xffff;
  75624. ulg max_start;
  75625. if (max_block_size > s->pending_buf_size - 5) {
  75626. max_block_size = s->pending_buf_size - 5;
  75627. }
  75628. /* Copy as much as possible from input to output: */
  75629. for (;;) {
  75630. /* Fill the window as much as possible: */
  75631. if (s->lookahead <= 1) {
  75632. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  75633. s->block_start >= (long)s->w_size, "slide too late");
  75634. fill_window(s);
  75635. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  75636. if (s->lookahead == 0) break; /* flush the current block */
  75637. }
  75638. Assert(s->block_start >= 0L, "block gone");
  75639. s->strstart += s->lookahead;
  75640. s->lookahead = 0;
  75641. /* Emit a stored block if pending_buf will be full: */
  75642. max_start = s->block_start + max_block_size;
  75643. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  75644. /* strstart == 0 is possible when wraparound on 16-bit machine */
  75645. s->lookahead = (uInt)(s->strstart - max_start);
  75646. s->strstart = (uInt)max_start;
  75647. FLUSH_BLOCK(s, 0);
  75648. }
  75649. /* Flush if we may have to slide, otherwise block_start may become
  75650. * negative and the data will be gone:
  75651. */
  75652. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  75653. FLUSH_BLOCK(s, 0);
  75654. }
  75655. }
  75656. FLUSH_BLOCK(s, flush == Z_FINISH);
  75657. return flush == Z_FINISH ? finish_done : block_done;
  75658. }
  75659. /* ===========================================================================
  75660. * Compress as much as possible from the input stream, return the current
  75661. * block state.
  75662. * This function does not perform lazy evaluation of matches and inserts
  75663. * new strings in the dictionary only for unmatched strings or for short
  75664. * matches. It is used only for the fast compression options.
  75665. */
  75666. local block_state deflate_fast(deflate_state *s, int flush)
  75667. {
  75668. IPos hash_head = NIL; /* head of the hash chain */
  75669. int bflush; /* set if current block must be flushed */
  75670. for (;;) {
  75671. /* Make sure that we always have enough lookahead, except
  75672. * at the end of the input file. We need MAX_MATCH bytes
  75673. * for the next match, plus MIN_MATCH bytes to insert the
  75674. * string following the next match.
  75675. */
  75676. if (s->lookahead < MIN_LOOKAHEAD) {
  75677. fill_window(s);
  75678. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  75679. return need_more;
  75680. }
  75681. if (s->lookahead == 0) break; /* flush the current block */
  75682. }
  75683. /* Insert the string window[strstart .. strstart+2] in the
  75684. * dictionary, and set hash_head to the head of the hash chain:
  75685. */
  75686. if (s->lookahead >= MIN_MATCH) {
  75687. INSERT_STRING(s, s->strstart, hash_head);
  75688. }
  75689. /* Find the longest match, discarding those <= prev_length.
  75690. * At this point we have always match_length < MIN_MATCH
  75691. */
  75692. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  75693. /* To simplify the code, we prevent matches with the string
  75694. * of window index 0 (in particular we have to avoid a match
  75695. * of the string with itself at the start of the input file).
  75696. */
  75697. #ifdef FASTEST
  75698. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  75699. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  75700. s->match_length = longest_match_fast (s, hash_head);
  75701. }
  75702. #else
  75703. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  75704. s->match_length = longest_match (s, hash_head);
  75705. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  75706. s->match_length = longest_match_fast (s, hash_head);
  75707. }
  75708. #endif
  75709. /* longest_match() or longest_match_fast() sets match_start */
  75710. }
  75711. if (s->match_length >= MIN_MATCH) {
  75712. check_match(s, s->strstart, s->match_start, s->match_length);
  75713. _tr_tally_dist(s, s->strstart - s->match_start,
  75714. s->match_length - MIN_MATCH, bflush);
  75715. s->lookahead -= s->match_length;
  75716. /* Insert new strings in the hash table only if the match length
  75717. * is not too large. This saves time but degrades compression.
  75718. */
  75719. #ifndef FASTEST
  75720. if (s->match_length <= s->max_insert_length &&
  75721. s->lookahead >= MIN_MATCH) {
  75722. s->match_length--; /* string at strstart already in table */
  75723. do {
  75724. s->strstart++;
  75725. INSERT_STRING(s, s->strstart, hash_head);
  75726. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  75727. * always MIN_MATCH bytes ahead.
  75728. */
  75729. } while (--s->match_length != 0);
  75730. s->strstart++;
  75731. } else
  75732. #endif
  75733. {
  75734. s->strstart += s->match_length;
  75735. s->match_length = 0;
  75736. s->ins_h = s->window[s->strstart];
  75737. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  75738. #if MIN_MATCH != 3
  75739. Call UPDATE_HASH() MIN_MATCH-3 more times
  75740. #endif
  75741. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  75742. * matter since it will be recomputed at next deflate call.
  75743. */
  75744. }
  75745. } else {
  75746. /* No match, output a literal byte */
  75747. Tracevv((stderr,"%c", s->window[s->strstart]));
  75748. _tr_tally_lit (s, s->window[s->strstart], bflush);
  75749. s->lookahead--;
  75750. s->strstart++;
  75751. }
  75752. if (bflush) FLUSH_BLOCK(s, 0);
  75753. }
  75754. FLUSH_BLOCK(s, flush == Z_FINISH);
  75755. return flush == Z_FINISH ? finish_done : block_done;
  75756. }
  75757. #ifndef FASTEST
  75758. /* ===========================================================================
  75759. * Same as above, but achieves better compression. We use a lazy
  75760. * evaluation for matches: a match is finally adopted only if there is
  75761. * no better match at the next window position.
  75762. */
  75763. local block_state deflate_slow(deflate_state *s, int flush)
  75764. {
  75765. IPos hash_head = NIL; /* head of hash chain */
  75766. int bflush; /* set if current block must be flushed */
  75767. /* Process the input block. */
  75768. for (;;) {
  75769. /* Make sure that we always have enough lookahead, except
  75770. * at the end of the input file. We need MAX_MATCH bytes
  75771. * for the next match, plus MIN_MATCH bytes to insert the
  75772. * string following the next match.
  75773. */
  75774. if (s->lookahead < MIN_LOOKAHEAD) {
  75775. fill_window(s);
  75776. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  75777. return need_more;
  75778. }
  75779. if (s->lookahead == 0) break; /* flush the current block */
  75780. }
  75781. /* Insert the string window[strstart .. strstart+2] in the
  75782. * dictionary, and set hash_head to the head of the hash chain:
  75783. */
  75784. if (s->lookahead >= MIN_MATCH) {
  75785. INSERT_STRING(s, s->strstart, hash_head);
  75786. }
  75787. /* Find the longest match, discarding those <= prev_length.
  75788. */
  75789. s->prev_length = s->match_length, s->prev_match = s->match_start;
  75790. s->match_length = MIN_MATCH-1;
  75791. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  75792. s->strstart - hash_head <= MAX_DIST(s)) {
  75793. /* To simplify the code, we prevent matches with the string
  75794. * of window index 0 (in particular we have to avoid a match
  75795. * of the string with itself at the start of the input file).
  75796. */
  75797. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  75798. s->match_length = longest_match (s, hash_head);
  75799. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  75800. s->match_length = longest_match_fast (s, hash_head);
  75801. }
  75802. /* longest_match() or longest_match_fast() sets match_start */
  75803. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  75804. #if TOO_FAR <= 32767
  75805. || (s->match_length == MIN_MATCH &&
  75806. s->strstart - s->match_start > TOO_FAR)
  75807. #endif
  75808. )) {
  75809. /* If prev_match is also MIN_MATCH, match_start is garbage
  75810. * but we will ignore the current match anyway.
  75811. */
  75812. s->match_length = MIN_MATCH-1;
  75813. }
  75814. }
  75815. /* If there was a match at the previous step and the current
  75816. * match is not better, output the previous match:
  75817. */
  75818. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  75819. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  75820. /* Do not insert strings in hash table beyond this. */
  75821. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  75822. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  75823. s->prev_length - MIN_MATCH, bflush);
  75824. /* Insert in hash table all strings up to the end of the match.
  75825. * strstart-1 and strstart are already inserted. If there is not
  75826. * enough lookahead, the last two strings are not inserted in
  75827. * the hash table.
  75828. */
  75829. s->lookahead -= s->prev_length-1;
  75830. s->prev_length -= 2;
  75831. do {
  75832. if (++s->strstart <= max_insert) {
  75833. INSERT_STRING(s, s->strstart, hash_head);
  75834. }
  75835. } while (--s->prev_length != 0);
  75836. s->match_available = 0;
  75837. s->match_length = MIN_MATCH-1;
  75838. s->strstart++;
  75839. if (bflush) FLUSH_BLOCK(s, 0);
  75840. } else if (s->match_available) {
  75841. /* If there was no match at the previous position, output a
  75842. * single literal. If there was a match but the current match
  75843. * is longer, truncate the previous match to a single literal.
  75844. */
  75845. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  75846. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  75847. if (bflush) {
  75848. FLUSH_BLOCK_ONLY(s, 0);
  75849. }
  75850. s->strstart++;
  75851. s->lookahead--;
  75852. if (s->strm->avail_out == 0) return need_more;
  75853. } else {
  75854. /* There is no previous match to compare with, wait for
  75855. * the next step to decide.
  75856. */
  75857. s->match_available = 1;
  75858. s->strstart++;
  75859. s->lookahead--;
  75860. }
  75861. }
  75862. Assert (flush != Z_NO_FLUSH, "no flush?");
  75863. if (s->match_available) {
  75864. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  75865. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  75866. s->match_available = 0;
  75867. }
  75868. FLUSH_BLOCK(s, flush == Z_FINISH);
  75869. return flush == Z_FINISH ? finish_done : block_done;
  75870. }
  75871. #endif /* FASTEST */
  75872. #if 0
  75873. /* ===========================================================================
  75874. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  75875. * one. Do not maintain a hash table. (It will be regenerated if this run of
  75876. * deflate switches away from Z_RLE.)
  75877. */
  75878. local block_state deflate_rle(s, flush)
  75879. deflate_state *s;
  75880. int flush;
  75881. {
  75882. int bflush; /* set if current block must be flushed */
  75883. uInt run; /* length of run */
  75884. uInt max; /* maximum length of run */
  75885. uInt prev; /* byte at distance one to match */
  75886. Bytef *scan; /* scan for end of run */
  75887. for (;;) {
  75888. /* Make sure that we always have enough lookahead, except
  75889. * at the end of the input file. We need MAX_MATCH bytes
  75890. * for the longest encodable run.
  75891. */
  75892. if (s->lookahead < MAX_MATCH) {
  75893. fill_window(s);
  75894. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  75895. return need_more;
  75896. }
  75897. if (s->lookahead == 0) break; /* flush the current block */
  75898. }
  75899. /* See how many times the previous byte repeats */
  75900. run = 0;
  75901. if (s->strstart > 0) { /* if there is a previous byte, that is */
  75902. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  75903. scan = s->window + s->strstart - 1;
  75904. prev = *scan++;
  75905. do {
  75906. if (*scan++ != prev)
  75907. break;
  75908. } while (++run < max);
  75909. }
  75910. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  75911. if (run >= MIN_MATCH) {
  75912. check_match(s, s->strstart, s->strstart - 1, run);
  75913. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  75914. s->lookahead -= run;
  75915. s->strstart += run;
  75916. } else {
  75917. /* No match, output a literal byte */
  75918. Tracevv((stderr,"%c", s->window[s->strstart]));
  75919. _tr_tally_lit (s, s->window[s->strstart], bflush);
  75920. s->lookahead--;
  75921. s->strstart++;
  75922. }
  75923. if (bflush) FLUSH_BLOCK(s, 0);
  75924. }
  75925. FLUSH_BLOCK(s, flush == Z_FINISH);
  75926. return flush == Z_FINISH ? finish_done : block_done;
  75927. }
  75928. #endif
  75929. /********* End of inlined file: deflate.c *********/
  75930. /********* Start of inlined file: infback.c *********/
  75931. /*
  75932. This code is largely copied from inflate.c. Normally either infback.o or
  75933. inflate.o would be linked into an application--not both. The interface
  75934. with inffast.c is retained so that optimized assembler-coded versions of
  75935. inflate_fast() can be used with either inflate.c or infback.c.
  75936. */
  75937. /********* Start of inlined file: inftrees.h *********/
  75938. /* WARNING: this file should *not* be used by applications. It is
  75939. part of the implementation of the compression library and is
  75940. subject to change. Applications should only use zlib.h.
  75941. */
  75942. #ifndef _INFTREES_H_
  75943. #define _INFTREES_H_
  75944. /* Structure for decoding tables. Each entry provides either the
  75945. information needed to do the operation requested by the code that
  75946. indexed that table entry, or it provides a pointer to another
  75947. table that indexes more bits of the code. op indicates whether
  75948. the entry is a pointer to another table, a literal, a length or
  75949. distance, an end-of-block, or an invalid code. For a table
  75950. pointer, the low four bits of op is the number of index bits of
  75951. that table. For a length or distance, the low four bits of op
  75952. is the number of extra bits to get after the code. bits is
  75953. the number of bits in this code or part of the code to drop off
  75954. of the bit buffer. val is the actual byte to output in the case
  75955. of a literal, the base length or distance, or the offset from
  75956. the current table to the next table. Each entry is four bytes. */
  75957. typedef struct {
  75958. unsigned char op; /* operation, extra bits, table bits */
  75959. unsigned char bits; /* bits in this part of the code */
  75960. unsigned short val; /* offset in table or code value */
  75961. } code;
  75962. /* op values as set by inflate_table():
  75963. 00000000 - literal
  75964. 0000tttt - table link, tttt != 0 is the number of table index bits
  75965. 0001eeee - length or distance, eeee is the number of extra bits
  75966. 01100000 - end of block
  75967. 01000000 - invalid code
  75968. */
  75969. /* Maximum size of dynamic tree. The maximum found in a long but non-
  75970. exhaustive search was 1444 code structures (852 for length/literals
  75971. and 592 for distances, the latter actually the result of an
  75972. exhaustive search). The true maximum is not known, but the value
  75973. below is more than safe. */
  75974. #define ENOUGH 2048
  75975. #define MAXD 592
  75976. /* Type of code to build for inftable() */
  75977. typedef enum {
  75978. CODES,
  75979. LENS,
  75980. DISTS
  75981. } codetype;
  75982. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  75983. unsigned codes, code FAR * FAR *table,
  75984. unsigned FAR *bits, unsigned short FAR *work));
  75985. #endif
  75986. /********* End of inlined file: inftrees.h *********/
  75987. /********* Start of inlined file: inflate.h *********/
  75988. /* WARNING: this file should *not* be used by applications. It is
  75989. part of the implementation of the compression library and is
  75990. subject to change. Applications should only use zlib.h.
  75991. */
  75992. #ifndef _INFLATE_H_
  75993. #define _INFLATE_H_
  75994. /* define NO_GZIP when compiling if you want to disable gzip header and
  75995. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  75996. the crc code when it is not needed. For shared libraries, gzip decoding
  75997. should be left enabled. */
  75998. #ifndef NO_GZIP
  75999. # define GUNZIP
  76000. #endif
  76001. /* Possible inflate modes between inflate() calls */
  76002. typedef enum {
  76003. HEAD, /* i: waiting for magic header */
  76004. FLAGS, /* i: waiting for method and flags (gzip) */
  76005. TIME, /* i: waiting for modification time (gzip) */
  76006. OS, /* i: waiting for extra flags and operating system (gzip) */
  76007. EXLEN, /* i: waiting for extra length (gzip) */
  76008. EXTRA, /* i: waiting for extra bytes (gzip) */
  76009. NAME, /* i: waiting for end of file name (gzip) */
  76010. COMMENT, /* i: waiting for end of comment (gzip) */
  76011. HCRC, /* i: waiting for header crc (gzip) */
  76012. DICTID, /* i: waiting for dictionary check value */
  76013. DICT, /* waiting for inflateSetDictionary() call */
  76014. TYPE, /* i: waiting for type bits, including last-flag bit */
  76015. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  76016. STORED, /* i: waiting for stored size (length and complement) */
  76017. COPY, /* i/o: waiting for input or output to copy stored block */
  76018. TABLE, /* i: waiting for dynamic block table lengths */
  76019. LENLENS, /* i: waiting for code length code lengths */
  76020. CODELENS, /* i: waiting for length/lit and distance code lengths */
  76021. LEN, /* i: waiting for length/lit code */
  76022. LENEXT, /* i: waiting for length extra bits */
  76023. DIST, /* i: waiting for distance code */
  76024. DISTEXT, /* i: waiting for distance extra bits */
  76025. MATCH, /* o: waiting for output space to copy string */
  76026. LIT, /* o: waiting for output space to write literal */
  76027. CHECK, /* i: waiting for 32-bit check value */
  76028. LENGTH, /* i: waiting for 32-bit length (gzip) */
  76029. DONE, /* finished check, done -- remain here until reset */
  76030. BAD, /* got a data error -- remain here until reset */
  76031. MEM, /* got an inflate() memory error -- remain here until reset */
  76032. SYNC /* looking for synchronization bytes to restart inflate() */
  76033. } inflate_mode;
  76034. /*
  76035. State transitions between above modes -
  76036. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  76037. Process header:
  76038. HEAD -> (gzip) or (zlib)
  76039. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  76040. NAME -> COMMENT -> HCRC -> TYPE
  76041. (zlib) -> DICTID or TYPE
  76042. DICTID -> DICT -> TYPE
  76043. Read deflate blocks:
  76044. TYPE -> STORED or TABLE or LEN or CHECK
  76045. STORED -> COPY -> TYPE
  76046. TABLE -> LENLENS -> CODELENS -> LEN
  76047. Read deflate codes:
  76048. LEN -> LENEXT or LIT or TYPE
  76049. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  76050. LIT -> LEN
  76051. Process trailer:
  76052. CHECK -> LENGTH -> DONE
  76053. */
  76054. /* state maintained between inflate() calls. Approximately 7K bytes. */
  76055. struct inflate_state {
  76056. inflate_mode mode; /* current inflate mode */
  76057. int last; /* true if processing last block */
  76058. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  76059. int havedict; /* true if dictionary provided */
  76060. int flags; /* gzip header method and flags (0 if zlib) */
  76061. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  76062. unsigned long check; /* protected copy of check value */
  76063. unsigned long total; /* protected copy of output count */
  76064. gz_headerp head; /* where to save gzip header information */
  76065. /* sliding window */
  76066. unsigned wbits; /* log base 2 of requested window size */
  76067. unsigned wsize; /* window size or zero if not using window */
  76068. unsigned whave; /* valid bytes in the window */
  76069. unsigned write; /* window write index */
  76070. unsigned char FAR *window; /* allocated sliding window, if needed */
  76071. /* bit accumulator */
  76072. unsigned long hold; /* input bit accumulator */
  76073. unsigned bits; /* number of bits in "in" */
  76074. /* for string and stored block copying */
  76075. unsigned length; /* literal or length of data to copy */
  76076. unsigned offset; /* distance back to copy string from */
  76077. /* for table and code decoding */
  76078. unsigned extra; /* extra bits needed */
  76079. /* fixed and dynamic code tables */
  76080. code const FAR *lencode; /* starting table for length/literal codes */
  76081. code const FAR *distcode; /* starting table for distance codes */
  76082. unsigned lenbits; /* index bits for lencode */
  76083. unsigned distbits; /* index bits for distcode */
  76084. /* dynamic table building */
  76085. unsigned ncode; /* number of code length code lengths */
  76086. unsigned nlen; /* number of length code lengths */
  76087. unsigned ndist; /* number of distance code lengths */
  76088. unsigned have; /* number of code lengths in lens[] */
  76089. code FAR *next; /* next available space in codes[] */
  76090. unsigned short lens[320]; /* temporary storage for code lengths */
  76091. unsigned short work[288]; /* work area for code table building */
  76092. code codes[ENOUGH]; /* space for code tables */
  76093. };
  76094. #endif
  76095. /********* End of inlined file: inflate.h *********/
  76096. /********* Start of inlined file: inffast.h *********/
  76097. /* WARNING: this file should *not* be used by applications. It is
  76098. part of the implementation of the compression library and is
  76099. subject to change. Applications should only use zlib.h.
  76100. */
  76101. void inflate_fast OF((z_streamp strm, unsigned start));
  76102. /********* End of inlined file: inffast.h *********/
  76103. /* function prototypes */
  76104. local void fixedtables1 OF((struct inflate_state FAR *state));
  76105. /*
  76106. strm provides memory allocation functions in zalloc and zfree, or
  76107. Z_NULL to use the library memory allocation functions.
  76108. windowBits is in the range 8..15, and window is a user-supplied
  76109. window and output buffer that is 2**windowBits bytes.
  76110. */
  76111. int ZEXPORT inflateBackInit_(z_streamp strm, int windowBits, unsigned char FAR *window, const char *version, int stream_size)
  76112. {
  76113. struct inflate_state FAR *state;
  76114. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  76115. stream_size != (int)(sizeof(z_stream)))
  76116. return Z_VERSION_ERROR;
  76117. if (strm == Z_NULL || window == Z_NULL ||
  76118. windowBits < 8 || windowBits > 15)
  76119. return Z_STREAM_ERROR;
  76120. strm->msg = Z_NULL; /* in case we return an error */
  76121. if (strm->zalloc == (alloc_func)0) {
  76122. strm->zalloc = zcalloc;
  76123. strm->opaque = (voidpf)0;
  76124. }
  76125. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  76126. state = (struct inflate_state FAR *)ZALLOC(strm, 1,
  76127. sizeof(struct inflate_state));
  76128. if (state == Z_NULL) return Z_MEM_ERROR;
  76129. Tracev((stderr, "inflate: allocated\n"));
  76130. strm->state = (struct internal_state FAR *)state;
  76131. state->dmax = 32768U;
  76132. state->wbits = windowBits;
  76133. state->wsize = 1U << windowBits;
  76134. state->window = window;
  76135. state->write = 0;
  76136. state->whave = 0;
  76137. return Z_OK;
  76138. }
  76139. /*
  76140. Return state with length and distance decoding tables and index sizes set to
  76141. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  76142. If BUILDFIXED is defined, then instead this routine builds the tables the
  76143. first time it's called, and returns those tables the first time and
  76144. thereafter. This reduces the size of the code by about 2K bytes, in
  76145. exchange for a little execution time. However, BUILDFIXED should not be
  76146. used for threaded applications, since the rewriting of the tables and virgin
  76147. may not be thread-safe.
  76148. */
  76149. local void fixedtables1 (struct inflate_state FAR *state)
  76150. {
  76151. #ifdef BUILDFIXED
  76152. static int virgin = 1;
  76153. static code *lenfix, *distfix;
  76154. static code fixed[544];
  76155. /* build fixed huffman tables if first call (may not be thread safe) */
  76156. if (virgin) {
  76157. unsigned sym, bits;
  76158. static code *next;
  76159. /* literal/length table */
  76160. sym = 0;
  76161. while (sym < 144) state->lens[sym++] = 8;
  76162. while (sym < 256) state->lens[sym++] = 9;
  76163. while (sym < 280) state->lens[sym++] = 7;
  76164. while (sym < 288) state->lens[sym++] = 8;
  76165. next = fixed;
  76166. lenfix = next;
  76167. bits = 9;
  76168. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  76169. /* distance table */
  76170. sym = 0;
  76171. while (sym < 32) state->lens[sym++] = 5;
  76172. distfix = next;
  76173. bits = 5;
  76174. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  76175. /* do this just once */
  76176. virgin = 0;
  76177. }
  76178. #else /* !BUILDFIXED */
  76179. /********* Start of inlined file: inffixed.h *********/
  76180. /* inffixed.h -- table for decoding fixed codes
  76181. * Generated automatically by makefixed().
  76182. */
  76183. /* WARNING: this file should *not* be used by applications. It
  76184. is part of the implementation of the compression library and
  76185. is subject to change. Applications should only use zlib.h.
  76186. */
  76187. static const code lenfix[512] = {
  76188. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  76189. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  76190. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  76191. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  76192. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  76193. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  76194. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  76195. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  76196. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  76197. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  76198. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  76199. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  76200. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  76201. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  76202. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  76203. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  76204. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  76205. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  76206. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  76207. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  76208. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  76209. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  76210. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  76211. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  76212. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  76213. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  76214. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  76215. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  76216. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  76217. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  76218. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  76219. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  76220. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  76221. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  76222. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  76223. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  76224. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  76225. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  76226. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  76227. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  76228. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  76229. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  76230. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  76231. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  76232. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  76233. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  76234. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  76235. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  76236. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  76237. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  76238. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  76239. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  76240. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  76241. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  76242. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  76243. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  76244. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  76245. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  76246. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  76247. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  76248. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  76249. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  76250. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  76251. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  76252. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  76253. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  76254. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  76255. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  76256. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  76257. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  76258. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  76259. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  76260. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  76261. {0,9,255}
  76262. };
  76263. static const code distfix[32] = {
  76264. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  76265. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  76266. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  76267. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  76268. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  76269. {22,5,193},{64,5,0}
  76270. };
  76271. /********* End of inlined file: inffixed.h *********/
  76272. #endif /* BUILDFIXED */
  76273. state->lencode = lenfix;
  76274. state->lenbits = 9;
  76275. state->distcode = distfix;
  76276. state->distbits = 5;
  76277. }
  76278. /* Macros for inflateBack(): */
  76279. /* Load returned state from inflate_fast() */
  76280. #define LOAD() \
  76281. do { \
  76282. put = strm->next_out; \
  76283. left = strm->avail_out; \
  76284. next = strm->next_in; \
  76285. have = strm->avail_in; \
  76286. hold = state->hold; \
  76287. bits = state->bits; \
  76288. } while (0)
  76289. /* Set state from registers for inflate_fast() */
  76290. #define RESTORE() \
  76291. do { \
  76292. strm->next_out = put; \
  76293. strm->avail_out = left; \
  76294. strm->next_in = next; \
  76295. strm->avail_in = have; \
  76296. state->hold = hold; \
  76297. state->bits = bits; \
  76298. } while (0)
  76299. /* Clear the input bit accumulator */
  76300. #define INITBITS() \
  76301. do { \
  76302. hold = 0; \
  76303. bits = 0; \
  76304. } while (0)
  76305. /* Assure that some input is available. If input is requested, but denied,
  76306. then return a Z_BUF_ERROR from inflateBack(). */
  76307. #define PULL() \
  76308. do { \
  76309. if (have == 0) { \
  76310. have = in(in_desc, &next); \
  76311. if (have == 0) { \
  76312. next = Z_NULL; \
  76313. ret = Z_BUF_ERROR; \
  76314. goto inf_leave; \
  76315. } \
  76316. } \
  76317. } while (0)
  76318. /* Get a byte of input into the bit accumulator, or return from inflateBack()
  76319. with an error if there is no input available. */
  76320. #define PULLBYTE() \
  76321. do { \
  76322. PULL(); \
  76323. have--; \
  76324. hold += (unsigned long)(*next++) << bits; \
  76325. bits += 8; \
  76326. } while (0)
  76327. /* Assure that there are at least n bits in the bit accumulator. If there is
  76328. not enough available input to do that, then return from inflateBack() with
  76329. an error. */
  76330. #define NEEDBITS(n) \
  76331. do { \
  76332. while (bits < (unsigned)(n)) \
  76333. PULLBYTE(); \
  76334. } while (0)
  76335. /* Return the low n bits of the bit accumulator (n < 16) */
  76336. #define BITS(n) \
  76337. ((unsigned)hold & ((1U << (n)) - 1))
  76338. /* Remove n bits from the bit accumulator */
  76339. #define DROPBITS(n) \
  76340. do { \
  76341. hold >>= (n); \
  76342. bits -= (unsigned)(n); \
  76343. } while (0)
  76344. /* Remove zero to seven bits as needed to go to a byte boundary */
  76345. #define BYTEBITS() \
  76346. do { \
  76347. hold >>= bits & 7; \
  76348. bits -= bits & 7; \
  76349. } while (0)
  76350. /* Assure that some output space is available, by writing out the window
  76351. if it's full. If the write fails, return from inflateBack() with a
  76352. Z_BUF_ERROR. */
  76353. #define ROOM() \
  76354. do { \
  76355. if (left == 0) { \
  76356. put = state->window; \
  76357. left = state->wsize; \
  76358. state->whave = left; \
  76359. if (out(out_desc, put, left)) { \
  76360. ret = Z_BUF_ERROR; \
  76361. goto inf_leave; \
  76362. } \
  76363. } \
  76364. } while (0)
  76365. /*
  76366. strm provides the memory allocation functions and window buffer on input,
  76367. and provides information on the unused input on return. For Z_DATA_ERROR
  76368. returns, strm will also provide an error message.
  76369. in() and out() are the call-back input and output functions. When
  76370. inflateBack() needs more input, it calls in(). When inflateBack() has
  76371. filled the window with output, or when it completes with data in the
  76372. window, it calls out() to write out the data. The application must not
  76373. change the provided input until in() is called again or inflateBack()
  76374. returns. The application must not change the window/output buffer until
  76375. inflateBack() returns.
  76376. in() and out() are called with a descriptor parameter provided in the
  76377. inflateBack() call. This parameter can be a structure that provides the
  76378. information required to do the read or write, as well as accumulated
  76379. information on the input and output such as totals and check values.
  76380. in() should return zero on failure. out() should return non-zero on
  76381. failure. If either in() or out() fails, than inflateBack() returns a
  76382. Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it
  76383. was in() or out() that caused in the error. Otherwise, inflateBack()
  76384. returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format
  76385. error, or Z_MEM_ERROR if it could not allocate memory for the state.
  76386. inflateBack() can also return Z_STREAM_ERROR if the input parameters
  76387. are not correct, i.e. strm is Z_NULL or the state was not initialized.
  76388. */
  76389. int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc, out_func out, void FAR *out_desc)
  76390. {
  76391. struct inflate_state FAR *state;
  76392. unsigned char FAR *next; /* next input */
  76393. unsigned char FAR *put; /* next output */
  76394. unsigned have, left; /* available input and output */
  76395. unsigned long hold; /* bit buffer */
  76396. unsigned bits; /* bits in bit buffer */
  76397. unsigned copy; /* number of stored or match bytes to copy */
  76398. unsigned char FAR *from; /* where to copy match bytes from */
  76399. code thisx; /* current decoding table entry */
  76400. code last; /* parent table entry */
  76401. unsigned len; /* length to copy for repeats, bits to drop */
  76402. int ret; /* return code */
  76403. static const unsigned short order[19] = /* permutation of code lengths */
  76404. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  76405. /* Check that the strm exists and that the state was initialized */
  76406. if (strm == Z_NULL || strm->state == Z_NULL)
  76407. return Z_STREAM_ERROR;
  76408. state = (struct inflate_state FAR *)strm->state;
  76409. /* Reset the state */
  76410. strm->msg = Z_NULL;
  76411. state->mode = TYPE;
  76412. state->last = 0;
  76413. state->whave = 0;
  76414. next = strm->next_in;
  76415. have = next != Z_NULL ? strm->avail_in : 0;
  76416. hold = 0;
  76417. bits = 0;
  76418. put = state->window;
  76419. left = state->wsize;
  76420. /* Inflate until end of block marked as last */
  76421. for (;;)
  76422. switch (state->mode) {
  76423. case TYPE:
  76424. /* determine and dispatch block type */
  76425. if (state->last) {
  76426. BYTEBITS();
  76427. state->mode = DONE;
  76428. break;
  76429. }
  76430. NEEDBITS(3);
  76431. state->last = BITS(1);
  76432. DROPBITS(1);
  76433. switch (BITS(2)) {
  76434. case 0: /* stored block */
  76435. Tracev((stderr, "inflate: stored block%s\n",
  76436. state->last ? " (last)" : ""));
  76437. state->mode = STORED;
  76438. break;
  76439. case 1: /* fixed block */
  76440. fixedtables1(state);
  76441. Tracev((stderr, "inflate: fixed codes block%s\n",
  76442. state->last ? " (last)" : ""));
  76443. state->mode = LEN; /* decode codes */
  76444. break;
  76445. case 2: /* dynamic block */
  76446. Tracev((stderr, "inflate: dynamic codes block%s\n",
  76447. state->last ? " (last)" : ""));
  76448. state->mode = TABLE;
  76449. break;
  76450. case 3:
  76451. strm->msg = (char *)"invalid block type";
  76452. state->mode = BAD;
  76453. }
  76454. DROPBITS(2);
  76455. break;
  76456. case STORED:
  76457. /* get and verify stored block length */
  76458. BYTEBITS(); /* go to byte boundary */
  76459. NEEDBITS(32);
  76460. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  76461. strm->msg = (char *)"invalid stored block lengths";
  76462. state->mode = BAD;
  76463. break;
  76464. }
  76465. state->length = (unsigned)hold & 0xffff;
  76466. Tracev((stderr, "inflate: stored length %u\n",
  76467. state->length));
  76468. INITBITS();
  76469. /* copy stored block from input to output */
  76470. while (state->length != 0) {
  76471. copy = state->length;
  76472. PULL();
  76473. ROOM();
  76474. if (copy > have) copy = have;
  76475. if (copy > left) copy = left;
  76476. zmemcpy(put, next, copy);
  76477. have -= copy;
  76478. next += copy;
  76479. left -= copy;
  76480. put += copy;
  76481. state->length -= copy;
  76482. }
  76483. Tracev((stderr, "inflate: stored end\n"));
  76484. state->mode = TYPE;
  76485. break;
  76486. case TABLE:
  76487. /* get dynamic table entries descriptor */
  76488. NEEDBITS(14);
  76489. state->nlen = BITS(5) + 257;
  76490. DROPBITS(5);
  76491. state->ndist = BITS(5) + 1;
  76492. DROPBITS(5);
  76493. state->ncode = BITS(4) + 4;
  76494. DROPBITS(4);
  76495. #ifndef PKZIP_BUG_WORKAROUND
  76496. if (state->nlen > 286 || state->ndist > 30) {
  76497. strm->msg = (char *)"too many length or distance symbols";
  76498. state->mode = BAD;
  76499. break;
  76500. }
  76501. #endif
  76502. Tracev((stderr, "inflate: table sizes ok\n"));
  76503. /* get code length code lengths (not a typo) */
  76504. state->have = 0;
  76505. while (state->have < state->ncode) {
  76506. NEEDBITS(3);
  76507. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  76508. DROPBITS(3);
  76509. }
  76510. while (state->have < 19)
  76511. state->lens[order[state->have++]] = 0;
  76512. state->next = state->codes;
  76513. state->lencode = (code const FAR *)(state->next);
  76514. state->lenbits = 7;
  76515. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  76516. &(state->lenbits), state->work);
  76517. if (ret) {
  76518. strm->msg = (char *)"invalid code lengths set";
  76519. state->mode = BAD;
  76520. break;
  76521. }
  76522. Tracev((stderr, "inflate: code lengths ok\n"));
  76523. /* get length and distance code code lengths */
  76524. state->have = 0;
  76525. while (state->have < state->nlen + state->ndist) {
  76526. for (;;) {
  76527. thisx = state->lencode[BITS(state->lenbits)];
  76528. if ((unsigned)(thisx.bits) <= bits) break;
  76529. PULLBYTE();
  76530. }
  76531. if (thisx.val < 16) {
  76532. NEEDBITS(thisx.bits);
  76533. DROPBITS(thisx.bits);
  76534. state->lens[state->have++] = thisx.val;
  76535. }
  76536. else {
  76537. if (thisx.val == 16) {
  76538. NEEDBITS(thisx.bits + 2);
  76539. DROPBITS(thisx.bits);
  76540. if (state->have == 0) {
  76541. strm->msg = (char *)"invalid bit length repeat";
  76542. state->mode = BAD;
  76543. break;
  76544. }
  76545. len = (unsigned)(state->lens[state->have - 1]);
  76546. copy = 3 + BITS(2);
  76547. DROPBITS(2);
  76548. }
  76549. else if (thisx.val == 17) {
  76550. NEEDBITS(thisx.bits + 3);
  76551. DROPBITS(thisx.bits);
  76552. len = 0;
  76553. copy = 3 + BITS(3);
  76554. DROPBITS(3);
  76555. }
  76556. else {
  76557. NEEDBITS(thisx.bits + 7);
  76558. DROPBITS(thisx.bits);
  76559. len = 0;
  76560. copy = 11 + BITS(7);
  76561. DROPBITS(7);
  76562. }
  76563. if (state->have + copy > state->nlen + state->ndist) {
  76564. strm->msg = (char *)"invalid bit length repeat";
  76565. state->mode = BAD;
  76566. break;
  76567. }
  76568. while (copy--)
  76569. state->lens[state->have++] = (unsigned short)len;
  76570. }
  76571. }
  76572. /* handle error breaks in while */
  76573. if (state->mode == BAD) break;
  76574. /* build code tables */
  76575. state->next = state->codes;
  76576. state->lencode = (code const FAR *)(state->next);
  76577. state->lenbits = 9;
  76578. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  76579. &(state->lenbits), state->work);
  76580. if (ret) {
  76581. strm->msg = (char *)"invalid literal/lengths set";
  76582. state->mode = BAD;
  76583. break;
  76584. }
  76585. state->distcode = (code const FAR *)(state->next);
  76586. state->distbits = 6;
  76587. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  76588. &(state->next), &(state->distbits), state->work);
  76589. if (ret) {
  76590. strm->msg = (char *)"invalid distances set";
  76591. state->mode = BAD;
  76592. break;
  76593. }
  76594. Tracev((stderr, "inflate: codes ok\n"));
  76595. state->mode = LEN;
  76596. case LEN:
  76597. /* use inflate_fast() if we have enough input and output */
  76598. if (have >= 6 && left >= 258) {
  76599. RESTORE();
  76600. if (state->whave < state->wsize)
  76601. state->whave = state->wsize - left;
  76602. inflate_fast(strm, state->wsize);
  76603. LOAD();
  76604. break;
  76605. }
  76606. /* get a literal, length, or end-of-block code */
  76607. for (;;) {
  76608. thisx = state->lencode[BITS(state->lenbits)];
  76609. if ((unsigned)(thisx.bits) <= bits) break;
  76610. PULLBYTE();
  76611. }
  76612. if (thisx.op && (thisx.op & 0xf0) == 0) {
  76613. last = thisx;
  76614. for (;;) {
  76615. thisx = state->lencode[last.val +
  76616. (BITS(last.bits + last.op) >> last.bits)];
  76617. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  76618. PULLBYTE();
  76619. }
  76620. DROPBITS(last.bits);
  76621. }
  76622. DROPBITS(thisx.bits);
  76623. state->length = (unsigned)thisx.val;
  76624. /* process literal */
  76625. if (thisx.op == 0) {
  76626. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  76627. "inflate: literal '%c'\n" :
  76628. "inflate: literal 0x%02x\n", thisx.val));
  76629. ROOM();
  76630. *put++ = (unsigned char)(state->length);
  76631. left--;
  76632. state->mode = LEN;
  76633. break;
  76634. }
  76635. /* process end of block */
  76636. if (thisx.op & 32) {
  76637. Tracevv((stderr, "inflate: end of block\n"));
  76638. state->mode = TYPE;
  76639. break;
  76640. }
  76641. /* invalid code */
  76642. if (thisx.op & 64) {
  76643. strm->msg = (char *)"invalid literal/length code";
  76644. state->mode = BAD;
  76645. break;
  76646. }
  76647. /* length code -- get extra bits, if any */
  76648. state->extra = (unsigned)(thisx.op) & 15;
  76649. if (state->extra != 0) {
  76650. NEEDBITS(state->extra);
  76651. state->length += BITS(state->extra);
  76652. DROPBITS(state->extra);
  76653. }
  76654. Tracevv((stderr, "inflate: length %u\n", state->length));
  76655. /* get distance code */
  76656. for (;;) {
  76657. thisx = state->distcode[BITS(state->distbits)];
  76658. if ((unsigned)(thisx.bits) <= bits) break;
  76659. PULLBYTE();
  76660. }
  76661. if ((thisx.op & 0xf0) == 0) {
  76662. last = thisx;
  76663. for (;;) {
  76664. thisx = state->distcode[last.val +
  76665. (BITS(last.bits + last.op) >> last.bits)];
  76666. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  76667. PULLBYTE();
  76668. }
  76669. DROPBITS(last.bits);
  76670. }
  76671. DROPBITS(thisx.bits);
  76672. if (thisx.op & 64) {
  76673. strm->msg = (char *)"invalid distance code";
  76674. state->mode = BAD;
  76675. break;
  76676. }
  76677. state->offset = (unsigned)thisx.val;
  76678. /* get distance extra bits, if any */
  76679. state->extra = (unsigned)(thisx.op) & 15;
  76680. if (state->extra != 0) {
  76681. NEEDBITS(state->extra);
  76682. state->offset += BITS(state->extra);
  76683. DROPBITS(state->extra);
  76684. }
  76685. if (state->offset > state->wsize - (state->whave < state->wsize ?
  76686. left : 0)) {
  76687. strm->msg = (char *)"invalid distance too far back";
  76688. state->mode = BAD;
  76689. break;
  76690. }
  76691. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  76692. /* copy match from window to output */
  76693. do {
  76694. ROOM();
  76695. copy = state->wsize - state->offset;
  76696. if (copy < left) {
  76697. from = put + copy;
  76698. copy = left - copy;
  76699. }
  76700. else {
  76701. from = put - state->offset;
  76702. copy = left;
  76703. }
  76704. if (copy > state->length) copy = state->length;
  76705. state->length -= copy;
  76706. left -= copy;
  76707. do {
  76708. *put++ = *from++;
  76709. } while (--copy);
  76710. } while (state->length != 0);
  76711. break;
  76712. case DONE:
  76713. /* inflate stream terminated properly -- write leftover output */
  76714. ret = Z_STREAM_END;
  76715. if (left < state->wsize) {
  76716. if (out(out_desc, state->window, state->wsize - left))
  76717. ret = Z_BUF_ERROR;
  76718. }
  76719. goto inf_leave;
  76720. case BAD:
  76721. ret = Z_DATA_ERROR;
  76722. goto inf_leave;
  76723. default: /* can't happen, but makes compilers happy */
  76724. ret = Z_STREAM_ERROR;
  76725. goto inf_leave;
  76726. }
  76727. /* Return unused input */
  76728. inf_leave:
  76729. strm->next_in = next;
  76730. strm->avail_in = have;
  76731. return ret;
  76732. }
  76733. int ZEXPORT inflateBackEnd (z_streamp strm)
  76734. {
  76735. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  76736. return Z_STREAM_ERROR;
  76737. ZFREE(strm, strm->state);
  76738. strm->state = Z_NULL;
  76739. Tracev((stderr, "inflate: end\n"));
  76740. return Z_OK;
  76741. }
  76742. /********* End of inlined file: infback.c *********/
  76743. /********* Start of inlined file: inffast.c *********/
  76744. /********* Start of inlined file: inffast.h *********/
  76745. /* WARNING: this file should *not* be used by applications. It is
  76746. part of the implementation of the compression library and is
  76747. subject to change. Applications should only use zlib.h.
  76748. */
  76749. void inflate_fast OF((z_streamp strm, unsigned start));
  76750. /********* End of inlined file: inffast.h *********/
  76751. #ifndef ASMINF
  76752. /* Allow machine dependent optimization for post-increment or pre-increment.
  76753. Based on testing to date,
  76754. Pre-increment preferred for:
  76755. - PowerPC G3 (Adler)
  76756. - MIPS R5000 (Randers-Pehrson)
  76757. Post-increment preferred for:
  76758. - none
  76759. No measurable difference:
  76760. - Pentium III (Anderson)
  76761. - M68060 (Nikl)
  76762. */
  76763. #ifdef POSTINC
  76764. # define OFF 0
  76765. # define PUP(a) *(a)++
  76766. #else
  76767. # define OFF 1
  76768. # define PUP(a) *++(a)
  76769. #endif
  76770. /*
  76771. Decode literal, length, and distance codes and write out the resulting
  76772. literal and match bytes until either not enough input or output is
  76773. available, an end-of-block is encountered, or a data error is encountered.
  76774. When large enough input and output buffers are supplied to inflate(), for
  76775. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  76776. inflate execution time is spent in this routine.
  76777. Entry assumptions:
  76778. state->mode == LEN
  76779. strm->avail_in >= 6
  76780. strm->avail_out >= 258
  76781. start >= strm->avail_out
  76782. state->bits < 8
  76783. On return, state->mode is one of:
  76784. LEN -- ran out of enough output space or enough available input
  76785. TYPE -- reached end of block code, inflate() to interpret next block
  76786. BAD -- error in block data
  76787. Notes:
  76788. - The maximum input bits used by a length/distance pair is 15 bits for the
  76789. length code, 5 bits for the length extra, 15 bits for the distance code,
  76790. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  76791. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  76792. checking for available input while decoding.
  76793. - The maximum bytes that a single length/distance pair can output is 258
  76794. bytes, which is the maximum length that can be coded. inflate_fast()
  76795. requires strm->avail_out >= 258 for each loop to avoid checking for
  76796. output space.
  76797. */
  76798. void inflate_fast (z_streamp strm, unsigned start)
  76799. {
  76800. struct inflate_state FAR *state;
  76801. unsigned char FAR *in; /* local strm->next_in */
  76802. unsigned char FAR *last; /* while in < last, enough input available */
  76803. unsigned char FAR *out; /* local strm->next_out */
  76804. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  76805. unsigned char FAR *end; /* while out < end, enough space available */
  76806. #ifdef INFLATE_STRICT
  76807. unsigned dmax; /* maximum distance from zlib header */
  76808. #endif
  76809. unsigned wsize; /* window size or zero if not using window */
  76810. unsigned whave; /* valid bytes in the window */
  76811. unsigned write; /* window write index */
  76812. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  76813. unsigned long hold; /* local strm->hold */
  76814. unsigned bits; /* local strm->bits */
  76815. code const FAR *lcode; /* local strm->lencode */
  76816. code const FAR *dcode; /* local strm->distcode */
  76817. unsigned lmask; /* mask for first level of length codes */
  76818. unsigned dmask; /* mask for first level of distance codes */
  76819. code thisx; /* retrieved table entry */
  76820. unsigned op; /* code bits, operation, extra bits, or */
  76821. /* window position, window bytes to copy */
  76822. unsigned len; /* match length, unused bytes */
  76823. unsigned dist; /* match distance */
  76824. unsigned char FAR *from; /* where to copy match from */
  76825. /* copy state to local variables */
  76826. state = (struct inflate_state FAR *)strm->state;
  76827. in = strm->next_in - OFF;
  76828. last = in + (strm->avail_in - 5);
  76829. out = strm->next_out - OFF;
  76830. beg = out - (start - strm->avail_out);
  76831. end = out + (strm->avail_out - 257);
  76832. #ifdef INFLATE_STRICT
  76833. dmax = state->dmax;
  76834. #endif
  76835. wsize = state->wsize;
  76836. whave = state->whave;
  76837. write = state->write;
  76838. window = state->window;
  76839. hold = state->hold;
  76840. bits = state->bits;
  76841. lcode = state->lencode;
  76842. dcode = state->distcode;
  76843. lmask = (1U << state->lenbits) - 1;
  76844. dmask = (1U << state->distbits) - 1;
  76845. /* decode literals and length/distances until end-of-block or not enough
  76846. input data or output space */
  76847. do {
  76848. if (bits < 15) {
  76849. hold += (unsigned long)(PUP(in)) << bits;
  76850. bits += 8;
  76851. hold += (unsigned long)(PUP(in)) << bits;
  76852. bits += 8;
  76853. }
  76854. thisx = lcode[hold & lmask];
  76855. dolen:
  76856. op = (unsigned)(thisx.bits);
  76857. hold >>= op;
  76858. bits -= op;
  76859. op = (unsigned)(thisx.op);
  76860. if (op == 0) { /* literal */
  76861. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  76862. "inflate: literal '%c'\n" :
  76863. "inflate: literal 0x%02x\n", thisx.val));
  76864. PUP(out) = (unsigned char)(thisx.val);
  76865. }
  76866. else if (op & 16) { /* length base */
  76867. len = (unsigned)(thisx.val);
  76868. op &= 15; /* number of extra bits */
  76869. if (op) {
  76870. if (bits < op) {
  76871. hold += (unsigned long)(PUP(in)) << bits;
  76872. bits += 8;
  76873. }
  76874. len += (unsigned)hold & ((1U << op) - 1);
  76875. hold >>= op;
  76876. bits -= op;
  76877. }
  76878. Tracevv((stderr, "inflate: length %u\n", len));
  76879. if (bits < 15) {
  76880. hold += (unsigned long)(PUP(in)) << bits;
  76881. bits += 8;
  76882. hold += (unsigned long)(PUP(in)) << bits;
  76883. bits += 8;
  76884. }
  76885. thisx = dcode[hold & dmask];
  76886. dodist:
  76887. op = (unsigned)(thisx.bits);
  76888. hold >>= op;
  76889. bits -= op;
  76890. op = (unsigned)(thisx.op);
  76891. if (op & 16) { /* distance base */
  76892. dist = (unsigned)(thisx.val);
  76893. op &= 15; /* number of extra bits */
  76894. if (bits < op) {
  76895. hold += (unsigned long)(PUP(in)) << bits;
  76896. bits += 8;
  76897. if (bits < op) {
  76898. hold += (unsigned long)(PUP(in)) << bits;
  76899. bits += 8;
  76900. }
  76901. }
  76902. dist += (unsigned)hold & ((1U << op) - 1);
  76903. #ifdef INFLATE_STRICT
  76904. if (dist > dmax) {
  76905. strm->msg = (char *)"invalid distance too far back";
  76906. state->mode = BAD;
  76907. break;
  76908. }
  76909. #endif
  76910. hold >>= op;
  76911. bits -= op;
  76912. Tracevv((stderr, "inflate: distance %u\n", dist));
  76913. op = (unsigned)(out - beg); /* max distance in output */
  76914. if (dist > op) { /* see if copy from window */
  76915. op = dist - op; /* distance back in window */
  76916. if (op > whave) {
  76917. strm->msg = (char *)"invalid distance too far back";
  76918. state->mode = BAD;
  76919. break;
  76920. }
  76921. from = window - OFF;
  76922. if (write == 0) { /* very common case */
  76923. from += wsize - op;
  76924. if (op < len) { /* some from window */
  76925. len -= op;
  76926. do {
  76927. PUP(out) = PUP(from);
  76928. } while (--op);
  76929. from = out - dist; /* rest from output */
  76930. }
  76931. }
  76932. else if (write < op) { /* wrap around window */
  76933. from += wsize + write - op;
  76934. op -= write;
  76935. if (op < len) { /* some from end of window */
  76936. len -= op;
  76937. do {
  76938. PUP(out) = PUP(from);
  76939. } while (--op);
  76940. from = window - OFF;
  76941. if (write < len) { /* some from start of window */
  76942. op = write;
  76943. len -= op;
  76944. do {
  76945. PUP(out) = PUP(from);
  76946. } while (--op);
  76947. from = out - dist; /* rest from output */
  76948. }
  76949. }
  76950. }
  76951. else { /* contiguous in window */
  76952. from += write - op;
  76953. if (op < len) { /* some from window */
  76954. len -= op;
  76955. do {
  76956. PUP(out) = PUP(from);
  76957. } while (--op);
  76958. from = out - dist; /* rest from output */
  76959. }
  76960. }
  76961. while (len > 2) {
  76962. PUP(out) = PUP(from);
  76963. PUP(out) = PUP(from);
  76964. PUP(out) = PUP(from);
  76965. len -= 3;
  76966. }
  76967. if (len) {
  76968. PUP(out) = PUP(from);
  76969. if (len > 1)
  76970. PUP(out) = PUP(from);
  76971. }
  76972. }
  76973. else {
  76974. from = out - dist; /* copy direct from output */
  76975. do { /* minimum length is three */
  76976. PUP(out) = PUP(from);
  76977. PUP(out) = PUP(from);
  76978. PUP(out) = PUP(from);
  76979. len -= 3;
  76980. } while (len > 2);
  76981. if (len) {
  76982. PUP(out) = PUP(from);
  76983. if (len > 1)
  76984. PUP(out) = PUP(from);
  76985. }
  76986. }
  76987. }
  76988. else if ((op & 64) == 0) { /* 2nd level distance code */
  76989. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  76990. goto dodist;
  76991. }
  76992. else {
  76993. strm->msg = (char *)"invalid distance code";
  76994. state->mode = BAD;
  76995. break;
  76996. }
  76997. }
  76998. else if ((op & 64) == 0) { /* 2nd level length code */
  76999. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  77000. goto dolen;
  77001. }
  77002. else if (op & 32) { /* end-of-block */
  77003. Tracevv((stderr, "inflate: end of block\n"));
  77004. state->mode = TYPE;
  77005. break;
  77006. }
  77007. else {
  77008. strm->msg = (char *)"invalid literal/length code";
  77009. state->mode = BAD;
  77010. break;
  77011. }
  77012. } while (in < last && out < end);
  77013. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  77014. len = bits >> 3;
  77015. in -= len;
  77016. bits -= len << 3;
  77017. hold &= (1U << bits) - 1;
  77018. /* update state and return */
  77019. strm->next_in = in + OFF;
  77020. strm->next_out = out + OFF;
  77021. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  77022. strm->avail_out = (unsigned)(out < end ?
  77023. 257 + (end - out) : 257 - (out - end));
  77024. state->hold = hold;
  77025. state->bits = bits;
  77026. return;
  77027. }
  77028. /*
  77029. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  77030. - Using bit fields for code structure
  77031. - Different op definition to avoid & for extra bits (do & for table bits)
  77032. - Three separate decoding do-loops for direct, window, and write == 0
  77033. - Special case for distance > 1 copies to do overlapped load and store copy
  77034. - Explicit branch predictions (based on measured branch probabilities)
  77035. - Deferring match copy and interspersed it with decoding subsequent codes
  77036. - Swapping literal/length else
  77037. - Swapping window/direct else
  77038. - Larger unrolled copy loops (three is about right)
  77039. - Moving len -= 3 statement into middle of loop
  77040. */
  77041. #endif /* !ASMINF */
  77042. /********* End of inlined file: inffast.c *********/
  77043. #undef PULLBYTE
  77044. #undef LOAD
  77045. #undef RESTORE
  77046. #undef INITBITS
  77047. #undef NEEDBITS
  77048. #undef DROPBITS
  77049. #undef BYTEBITS
  77050. /********* Start of inlined file: inflate.c *********/
  77051. /*
  77052. * Change history:
  77053. *
  77054. * 1.2.beta0 24 Nov 2002
  77055. * - First version -- complete rewrite of inflate to simplify code, avoid
  77056. * creation of window when not needed, minimize use of window when it is
  77057. * needed, make inffast.c even faster, implement gzip decoding, and to
  77058. * improve code readability and style over the previous zlib inflate code
  77059. *
  77060. * 1.2.beta1 25 Nov 2002
  77061. * - Use pointers for available input and output checking in inffast.c
  77062. * - Remove input and output counters in inffast.c
  77063. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  77064. * - Remove unnecessary second byte pull from length extra in inffast.c
  77065. * - Unroll direct copy to three copies per loop in inffast.c
  77066. *
  77067. * 1.2.beta2 4 Dec 2002
  77068. * - Change external routine names to reduce potential conflicts
  77069. * - Correct filename to inffixed.h for fixed tables in inflate.c
  77070. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  77071. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  77072. * to avoid negation problem on Alphas (64 bit) in inflate.c
  77073. *
  77074. * 1.2.beta3 22 Dec 2002
  77075. * - Add comments on state->bits assertion in inffast.c
  77076. * - Add comments on op field in inftrees.h
  77077. * - Fix bug in reuse of allocated window after inflateReset()
  77078. * - Remove bit fields--back to byte structure for speed
  77079. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  77080. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  77081. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  77082. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  77083. * - Use local copies of stream next and avail values, as well as local bit
  77084. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  77085. *
  77086. * 1.2.beta4 1 Jan 2003
  77087. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  77088. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  77089. * - Add comments in inffast.c to introduce the inflate_fast() routine
  77090. * - Rearrange window copies in inflate_fast() for speed and simplification
  77091. * - Unroll last copy for window match in inflate_fast()
  77092. * - Use local copies of window variables in inflate_fast() for speed
  77093. * - Pull out common write == 0 case for speed in inflate_fast()
  77094. * - Make op and len in inflate_fast() unsigned for consistency
  77095. * - Add FAR to lcode and dcode declarations in inflate_fast()
  77096. * - Simplified bad distance check in inflate_fast()
  77097. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  77098. * source file infback.c to provide a call-back interface to inflate for
  77099. * programs like gzip and unzip -- uses window as output buffer to avoid
  77100. * window copying
  77101. *
  77102. * 1.2.beta5 1 Jan 2003
  77103. * - Improved inflateBack() interface to allow the caller to provide initial
  77104. * input in strm.
  77105. * - Fixed stored blocks bug in inflateBack()
  77106. *
  77107. * 1.2.beta6 4 Jan 2003
  77108. * - Added comments in inffast.c on effectiveness of POSTINC
  77109. * - Typecasting all around to reduce compiler warnings
  77110. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  77111. * make compilers happy
  77112. * - Changed type of window in inflateBackInit() to unsigned char *
  77113. *
  77114. * 1.2.beta7 27 Jan 2003
  77115. * - Changed many types to unsigned or unsigned short to avoid warnings
  77116. * - Added inflateCopy() function
  77117. *
  77118. * 1.2.0 9 Mar 2003
  77119. * - Changed inflateBack() interface to provide separate opaque descriptors
  77120. * for the in() and out() functions
  77121. * - Changed inflateBack() argument and in_func typedef to swap the length
  77122. * and buffer address return values for the input function
  77123. * - Check next_in and next_out for Z_NULL on entry to inflate()
  77124. *
  77125. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  77126. */
  77127. /********* Start of inlined file: inffast.h *********/
  77128. /* WARNING: this file should *not* be used by applications. It is
  77129. part of the implementation of the compression library and is
  77130. subject to change. Applications should only use zlib.h.
  77131. */
  77132. void inflate_fast OF((z_streamp strm, unsigned start));
  77133. /********* End of inlined file: inffast.h *********/
  77134. #ifdef MAKEFIXED
  77135. # ifndef BUILDFIXED
  77136. # define BUILDFIXED
  77137. # endif
  77138. #endif
  77139. /* function prototypes */
  77140. local void fixedtables OF((struct inflate_state FAR *state));
  77141. local int updatewindow OF((z_streamp strm, unsigned out));
  77142. #ifdef BUILDFIXED
  77143. void makefixed OF((void));
  77144. #endif
  77145. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  77146. unsigned len));
  77147. int ZEXPORT inflateReset (z_streamp strm)
  77148. {
  77149. struct inflate_state FAR *state;
  77150. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77151. state = (struct inflate_state FAR *)strm->state;
  77152. strm->total_in = strm->total_out = state->total = 0;
  77153. strm->msg = Z_NULL;
  77154. strm->adler = 1; /* to support ill-conceived Java test suite */
  77155. state->mode = HEAD;
  77156. state->last = 0;
  77157. state->havedict = 0;
  77158. state->dmax = 32768U;
  77159. state->head = Z_NULL;
  77160. state->wsize = 0;
  77161. state->whave = 0;
  77162. state->write = 0;
  77163. state->hold = 0;
  77164. state->bits = 0;
  77165. state->lencode = state->distcode = state->next = state->codes;
  77166. Tracev((stderr, "inflate: reset\n"));
  77167. return Z_OK;
  77168. }
  77169. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  77170. {
  77171. struct inflate_state FAR *state;
  77172. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77173. state = (struct inflate_state FAR *)strm->state;
  77174. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  77175. value &= (1L << bits) - 1;
  77176. state->hold += value << state->bits;
  77177. state->bits += bits;
  77178. return Z_OK;
  77179. }
  77180. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  77181. {
  77182. struct inflate_state FAR *state;
  77183. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  77184. stream_size != (int)(sizeof(z_stream)))
  77185. return Z_VERSION_ERROR;
  77186. if (strm == Z_NULL) return Z_STREAM_ERROR;
  77187. strm->msg = Z_NULL; /* in case we return an error */
  77188. if (strm->zalloc == (alloc_func)0) {
  77189. strm->zalloc = zcalloc;
  77190. strm->opaque = (voidpf)0;
  77191. }
  77192. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  77193. state = (struct inflate_state FAR *)
  77194. ZALLOC(strm, 1, sizeof(struct inflate_state));
  77195. if (state == Z_NULL) return Z_MEM_ERROR;
  77196. Tracev((stderr, "inflate: allocated\n"));
  77197. strm->state = (struct internal_state FAR *)state;
  77198. if (windowBits < 0) {
  77199. state->wrap = 0;
  77200. windowBits = -windowBits;
  77201. }
  77202. else {
  77203. state->wrap = (windowBits >> 4) + 1;
  77204. #ifdef GUNZIP
  77205. if (windowBits < 48) windowBits &= 15;
  77206. #endif
  77207. }
  77208. if (windowBits < 8 || windowBits > 15) {
  77209. ZFREE(strm, state);
  77210. strm->state = Z_NULL;
  77211. return Z_STREAM_ERROR;
  77212. }
  77213. state->wbits = (unsigned)windowBits;
  77214. state->window = Z_NULL;
  77215. return inflateReset(strm);
  77216. }
  77217. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  77218. {
  77219. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  77220. }
  77221. /*
  77222. Return state with length and distance decoding tables and index sizes set to
  77223. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  77224. If BUILDFIXED is defined, then instead this routine builds the tables the
  77225. first time it's called, and returns those tables the first time and
  77226. thereafter. This reduces the size of the code by about 2K bytes, in
  77227. exchange for a little execution time. However, BUILDFIXED should not be
  77228. used for threaded applications, since the rewriting of the tables and virgin
  77229. may not be thread-safe.
  77230. */
  77231. local void fixedtables (struct inflate_state FAR *state)
  77232. {
  77233. #ifdef BUILDFIXED
  77234. static int virgin = 1;
  77235. static code *lenfix, *distfix;
  77236. static code fixed[544];
  77237. /* build fixed huffman tables if first call (may not be thread safe) */
  77238. if (virgin) {
  77239. unsigned sym, bits;
  77240. static code *next;
  77241. /* literal/length table */
  77242. sym = 0;
  77243. while (sym < 144) state->lens[sym++] = 8;
  77244. while (sym < 256) state->lens[sym++] = 9;
  77245. while (sym < 280) state->lens[sym++] = 7;
  77246. while (sym < 288) state->lens[sym++] = 8;
  77247. next = fixed;
  77248. lenfix = next;
  77249. bits = 9;
  77250. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  77251. /* distance table */
  77252. sym = 0;
  77253. while (sym < 32) state->lens[sym++] = 5;
  77254. distfix = next;
  77255. bits = 5;
  77256. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  77257. /* do this just once */
  77258. virgin = 0;
  77259. }
  77260. #else /* !BUILDFIXED */
  77261. /********* Start of inlined file: inffixed.h *********/
  77262. /* inffixed.h -- table for decoding fixed codes
  77263. * Generated automatically by makefixed().
  77264. */
  77265. /* WARNING: this file should *not* be used by applications. It
  77266. is part of the implementation of the compression library and
  77267. is subject to change. Applications should only use zlib.h.
  77268. */
  77269. static const code lenfix[512] = {
  77270. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  77271. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  77272. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  77273. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  77274. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  77275. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  77276. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  77277. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  77278. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  77279. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  77280. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  77281. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  77282. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  77283. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  77284. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  77285. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  77286. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  77287. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  77288. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  77289. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  77290. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  77291. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  77292. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  77293. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  77294. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  77295. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  77296. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  77297. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  77298. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  77299. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  77300. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  77301. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  77302. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  77303. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  77304. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  77305. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  77306. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  77307. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  77308. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  77309. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  77310. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  77311. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  77312. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  77313. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  77314. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  77315. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  77316. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  77317. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  77318. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  77319. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  77320. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  77321. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  77322. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  77323. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  77324. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  77325. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  77326. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  77327. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  77328. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  77329. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  77330. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  77331. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  77332. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  77333. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  77334. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  77335. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  77336. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  77337. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  77338. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  77339. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  77340. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  77341. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  77342. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  77343. {0,9,255}
  77344. };
  77345. static const code distfix[32] = {
  77346. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  77347. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  77348. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  77349. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  77350. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  77351. {22,5,193},{64,5,0}
  77352. };
  77353. /********* End of inlined file: inffixed.h *********/
  77354. #endif /* BUILDFIXED */
  77355. state->lencode = lenfix;
  77356. state->lenbits = 9;
  77357. state->distcode = distfix;
  77358. state->distbits = 5;
  77359. }
  77360. #ifdef MAKEFIXED
  77361. #include <stdio.h>
  77362. /*
  77363. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  77364. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  77365. those tables to stdout, which would be piped to inffixed.h. A small program
  77366. can simply call makefixed to do this:
  77367. void makefixed(void);
  77368. int main(void)
  77369. {
  77370. makefixed();
  77371. return 0;
  77372. }
  77373. Then that can be linked with zlib built with MAKEFIXED defined and run:
  77374. a.out > inffixed.h
  77375. */
  77376. void makefixed()
  77377. {
  77378. unsigned low, size;
  77379. struct inflate_state state;
  77380. fixedtables(&state);
  77381. puts(" /* inffixed.h -- table for decoding fixed codes");
  77382. puts(" * Generated automatically by makefixed().");
  77383. puts(" */");
  77384. puts("");
  77385. puts(" /* WARNING: this file should *not* be used by applications.");
  77386. puts(" It is part of the implementation of this library and is");
  77387. puts(" subject to change. Applications should only use zlib.h.");
  77388. puts(" */");
  77389. puts("");
  77390. size = 1U << 9;
  77391. printf(" static const code lenfix[%u] = {", size);
  77392. low = 0;
  77393. for (;;) {
  77394. if ((low % 7) == 0) printf("\n ");
  77395. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  77396. state.lencode[low].val);
  77397. if (++low == size) break;
  77398. putchar(',');
  77399. }
  77400. puts("\n };");
  77401. size = 1U << 5;
  77402. printf("\n static const code distfix[%u] = {", size);
  77403. low = 0;
  77404. for (;;) {
  77405. if ((low % 6) == 0) printf("\n ");
  77406. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  77407. state.distcode[low].val);
  77408. if (++low == size) break;
  77409. putchar(',');
  77410. }
  77411. puts("\n };");
  77412. }
  77413. #endif /* MAKEFIXED */
  77414. /*
  77415. Update the window with the last wsize (normally 32K) bytes written before
  77416. returning. If window does not exist yet, create it. This is only called
  77417. when a window is already in use, or when output has been written during this
  77418. inflate call, but the end of the deflate stream has not been reached yet.
  77419. It is also called to create a window for dictionary data when a dictionary
  77420. is loaded.
  77421. Providing output buffers larger than 32K to inflate() should provide a speed
  77422. advantage, since only the last 32K of output is copied to the sliding window
  77423. upon return from inflate(), and since all distances after the first 32K of
  77424. output will fall in the output data, making match copies simpler and faster.
  77425. The advantage may be dependent on the size of the processor's data caches.
  77426. */
  77427. local int updatewindow (z_streamp strm, unsigned out)
  77428. {
  77429. struct inflate_state FAR *state;
  77430. unsigned copy, dist;
  77431. state = (struct inflate_state FAR *)strm->state;
  77432. /* if it hasn't been done already, allocate space for the window */
  77433. if (state->window == Z_NULL) {
  77434. state->window = (unsigned char FAR *)
  77435. ZALLOC(strm, 1U << state->wbits,
  77436. sizeof(unsigned char));
  77437. if (state->window == Z_NULL) return 1;
  77438. }
  77439. /* if window not in use yet, initialize */
  77440. if (state->wsize == 0) {
  77441. state->wsize = 1U << state->wbits;
  77442. state->write = 0;
  77443. state->whave = 0;
  77444. }
  77445. /* copy state->wsize or less output bytes into the circular window */
  77446. copy = out - strm->avail_out;
  77447. if (copy >= state->wsize) {
  77448. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  77449. state->write = 0;
  77450. state->whave = state->wsize;
  77451. }
  77452. else {
  77453. dist = state->wsize - state->write;
  77454. if (dist > copy) dist = copy;
  77455. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  77456. copy -= dist;
  77457. if (copy) {
  77458. zmemcpy(state->window, strm->next_out - copy, copy);
  77459. state->write = copy;
  77460. state->whave = state->wsize;
  77461. }
  77462. else {
  77463. state->write += dist;
  77464. if (state->write == state->wsize) state->write = 0;
  77465. if (state->whave < state->wsize) state->whave += dist;
  77466. }
  77467. }
  77468. return 0;
  77469. }
  77470. /* Macros for inflate(): */
  77471. /* check function to use adler32() for zlib or crc32() for gzip */
  77472. #ifdef GUNZIP
  77473. # define UPDATE(check, buf, len) \
  77474. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  77475. #else
  77476. # define UPDATE(check, buf, len) adler32(check, buf, len)
  77477. #endif
  77478. /* check macros for header crc */
  77479. #ifdef GUNZIP
  77480. # define CRC2(check, word) \
  77481. do { \
  77482. hbuf[0] = (unsigned char)(word); \
  77483. hbuf[1] = (unsigned char)((word) >> 8); \
  77484. check = crc32(check, hbuf, 2); \
  77485. } while (0)
  77486. # define CRC4(check, word) \
  77487. do { \
  77488. hbuf[0] = (unsigned char)(word); \
  77489. hbuf[1] = (unsigned char)((word) >> 8); \
  77490. hbuf[2] = (unsigned char)((word) >> 16); \
  77491. hbuf[3] = (unsigned char)((word) >> 24); \
  77492. check = crc32(check, hbuf, 4); \
  77493. } while (0)
  77494. #endif
  77495. /* Load registers with state in inflate() for speed */
  77496. #define LOAD() \
  77497. do { \
  77498. put = strm->next_out; \
  77499. left = strm->avail_out; \
  77500. next = strm->next_in; \
  77501. have = strm->avail_in; \
  77502. hold = state->hold; \
  77503. bits = state->bits; \
  77504. } while (0)
  77505. /* Restore state from registers in inflate() */
  77506. #define RESTORE() \
  77507. do { \
  77508. strm->next_out = put; \
  77509. strm->avail_out = left; \
  77510. strm->next_in = next; \
  77511. strm->avail_in = have; \
  77512. state->hold = hold; \
  77513. state->bits = bits; \
  77514. } while (0)
  77515. /* Clear the input bit accumulator */
  77516. #define INITBITS() \
  77517. do { \
  77518. hold = 0; \
  77519. bits = 0; \
  77520. } while (0)
  77521. /* Get a byte of input into the bit accumulator, or return from inflate()
  77522. if there is no input available. */
  77523. #define PULLBYTE() \
  77524. do { \
  77525. if (have == 0) goto inf_leave; \
  77526. have--; \
  77527. hold += (unsigned long)(*next++) << bits; \
  77528. bits += 8; \
  77529. } while (0)
  77530. /* Assure that there are at least n bits in the bit accumulator. If there is
  77531. not enough available input to do that, then return from inflate(). */
  77532. #define NEEDBITS(n) \
  77533. do { \
  77534. while (bits < (unsigned)(n)) \
  77535. PULLBYTE(); \
  77536. } while (0)
  77537. /* Return the low n bits of the bit accumulator (n < 16) */
  77538. #define BITS(n) \
  77539. ((unsigned)hold & ((1U << (n)) - 1))
  77540. /* Remove n bits from the bit accumulator */
  77541. #define DROPBITS(n) \
  77542. do { \
  77543. hold >>= (n); \
  77544. bits -= (unsigned)(n); \
  77545. } while (0)
  77546. /* Remove zero to seven bits as needed to go to a byte boundary */
  77547. #define BYTEBITS() \
  77548. do { \
  77549. hold >>= bits & 7; \
  77550. bits -= bits & 7; \
  77551. } while (0)
  77552. /* Reverse the bytes in a 32-bit value */
  77553. #define REVERSE(q) \
  77554. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  77555. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  77556. /*
  77557. inflate() uses a state machine to process as much input data and generate as
  77558. much output data as possible before returning. The state machine is
  77559. structured roughly as follows:
  77560. for (;;) switch (state) {
  77561. ...
  77562. case STATEn:
  77563. if (not enough input data or output space to make progress)
  77564. return;
  77565. ... make progress ...
  77566. state = STATEm;
  77567. break;
  77568. ...
  77569. }
  77570. so when inflate() is called again, the same case is attempted again, and
  77571. if the appropriate resources are provided, the machine proceeds to the
  77572. next state. The NEEDBITS() macro is usually the way the state evaluates
  77573. whether it can proceed or should return. NEEDBITS() does the return if
  77574. the requested bits are not available. The typical use of the BITS macros
  77575. is:
  77576. NEEDBITS(n);
  77577. ... do something with BITS(n) ...
  77578. DROPBITS(n);
  77579. where NEEDBITS(n) either returns from inflate() if there isn't enough
  77580. input left to load n bits into the accumulator, or it continues. BITS(n)
  77581. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  77582. the low n bits off the accumulator. INITBITS() clears the accumulator
  77583. and sets the number of available bits to zero. BYTEBITS() discards just
  77584. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  77585. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  77586. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  77587. if there is no input available. The decoding of variable length codes uses
  77588. PULLBYTE() directly in order to pull just enough bytes to decode the next
  77589. code, and no more.
  77590. Some states loop until they get enough input, making sure that enough
  77591. state information is maintained to continue the loop where it left off
  77592. if NEEDBITS() returns in the loop. For example, want, need, and keep
  77593. would all have to actually be part of the saved state in case NEEDBITS()
  77594. returns:
  77595. case STATEw:
  77596. while (want < need) {
  77597. NEEDBITS(n);
  77598. keep[want++] = BITS(n);
  77599. DROPBITS(n);
  77600. }
  77601. state = STATEx;
  77602. case STATEx:
  77603. As shown above, if the next state is also the next case, then the break
  77604. is omitted.
  77605. A state may also return if there is not enough output space available to
  77606. complete that state. Those states are copying stored data, writing a
  77607. literal byte, and copying a matching string.
  77608. When returning, a "goto inf_leave" is used to update the total counters,
  77609. update the check value, and determine whether any progress has been made
  77610. during that inflate() call in order to return the proper return code.
  77611. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  77612. When there is a window, goto inf_leave will update the window with the last
  77613. output written. If a goto inf_leave occurs in the middle of decompression
  77614. and there is no window currently, goto inf_leave will create one and copy
  77615. output to the window for the next call of inflate().
  77616. In this implementation, the flush parameter of inflate() only affects the
  77617. return code (per zlib.h). inflate() always writes as much as possible to
  77618. strm->next_out, given the space available and the provided input--the effect
  77619. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  77620. the allocation of and copying into a sliding window until necessary, which
  77621. provides the effect documented in zlib.h for Z_FINISH when the entire input
  77622. stream available. So the only thing the flush parameter actually does is:
  77623. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  77624. will return Z_BUF_ERROR if it has not reached the end of the stream.
  77625. */
  77626. int ZEXPORT inflate (z_streamp strm, int flush)
  77627. {
  77628. struct inflate_state FAR *state;
  77629. unsigned char FAR *next; /* next input */
  77630. unsigned char FAR *put; /* next output */
  77631. unsigned have, left; /* available input and output */
  77632. unsigned long hold; /* bit buffer */
  77633. unsigned bits; /* bits in bit buffer */
  77634. unsigned in, out; /* save starting available input and output */
  77635. unsigned copy; /* number of stored or match bytes to copy */
  77636. unsigned char FAR *from; /* where to copy match bytes from */
  77637. code thisx; /* current decoding table entry */
  77638. code last; /* parent table entry */
  77639. unsigned len; /* length to copy for repeats, bits to drop */
  77640. int ret; /* return code */
  77641. #ifdef GUNZIP
  77642. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  77643. #endif
  77644. static const unsigned short order[19] = /* permutation of code lengths */
  77645. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  77646. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  77647. (strm->next_in == Z_NULL && strm->avail_in != 0))
  77648. return Z_STREAM_ERROR;
  77649. state = (struct inflate_state FAR *)strm->state;
  77650. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  77651. LOAD();
  77652. in = have;
  77653. out = left;
  77654. ret = Z_OK;
  77655. for (;;)
  77656. switch (state->mode) {
  77657. case HEAD:
  77658. if (state->wrap == 0) {
  77659. state->mode = TYPEDO;
  77660. break;
  77661. }
  77662. NEEDBITS(16);
  77663. #ifdef GUNZIP
  77664. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  77665. state->check = crc32(0L, Z_NULL, 0);
  77666. CRC2(state->check, hold);
  77667. INITBITS();
  77668. state->mode = FLAGS;
  77669. break;
  77670. }
  77671. state->flags = 0; /* expect zlib header */
  77672. if (state->head != Z_NULL)
  77673. state->head->done = -1;
  77674. if (!(state->wrap & 1) || /* check if zlib header allowed */
  77675. #else
  77676. if (
  77677. #endif
  77678. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  77679. strm->msg = (char *)"incorrect header check";
  77680. state->mode = BAD;
  77681. break;
  77682. }
  77683. if (BITS(4) != Z_DEFLATED) {
  77684. strm->msg = (char *)"unknown compression method";
  77685. state->mode = BAD;
  77686. break;
  77687. }
  77688. DROPBITS(4);
  77689. len = BITS(4) + 8;
  77690. if (len > state->wbits) {
  77691. strm->msg = (char *)"invalid window size";
  77692. state->mode = BAD;
  77693. break;
  77694. }
  77695. state->dmax = 1U << len;
  77696. Tracev((stderr, "inflate: zlib header ok\n"));
  77697. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  77698. state->mode = hold & 0x200 ? DICTID : TYPE;
  77699. INITBITS();
  77700. break;
  77701. #ifdef GUNZIP
  77702. case FLAGS:
  77703. NEEDBITS(16);
  77704. state->flags = (int)(hold);
  77705. if ((state->flags & 0xff) != Z_DEFLATED) {
  77706. strm->msg = (char *)"unknown compression method";
  77707. state->mode = BAD;
  77708. break;
  77709. }
  77710. if (state->flags & 0xe000) {
  77711. strm->msg = (char *)"unknown header flags set";
  77712. state->mode = BAD;
  77713. break;
  77714. }
  77715. if (state->head != Z_NULL)
  77716. state->head->text = (int)((hold >> 8) & 1);
  77717. if (state->flags & 0x0200) CRC2(state->check, hold);
  77718. INITBITS();
  77719. state->mode = TIME;
  77720. case TIME:
  77721. NEEDBITS(32);
  77722. if (state->head != Z_NULL)
  77723. state->head->time = hold;
  77724. if (state->flags & 0x0200) CRC4(state->check, hold);
  77725. INITBITS();
  77726. state->mode = OS;
  77727. case OS:
  77728. NEEDBITS(16);
  77729. if (state->head != Z_NULL) {
  77730. state->head->xflags = (int)(hold & 0xff);
  77731. state->head->os = (int)(hold >> 8);
  77732. }
  77733. if (state->flags & 0x0200) CRC2(state->check, hold);
  77734. INITBITS();
  77735. state->mode = EXLEN;
  77736. case EXLEN:
  77737. if (state->flags & 0x0400) {
  77738. NEEDBITS(16);
  77739. state->length = (unsigned)(hold);
  77740. if (state->head != Z_NULL)
  77741. state->head->extra_len = (unsigned)hold;
  77742. if (state->flags & 0x0200) CRC2(state->check, hold);
  77743. INITBITS();
  77744. }
  77745. else if (state->head != Z_NULL)
  77746. state->head->extra = Z_NULL;
  77747. state->mode = EXTRA;
  77748. case EXTRA:
  77749. if (state->flags & 0x0400) {
  77750. copy = state->length;
  77751. if (copy > have) copy = have;
  77752. if (copy) {
  77753. if (state->head != Z_NULL &&
  77754. state->head->extra != Z_NULL) {
  77755. len = state->head->extra_len - state->length;
  77756. zmemcpy(state->head->extra + len, next,
  77757. len + copy > state->head->extra_max ?
  77758. state->head->extra_max - len : copy);
  77759. }
  77760. if (state->flags & 0x0200)
  77761. state->check = crc32(state->check, next, copy);
  77762. have -= copy;
  77763. next += copy;
  77764. state->length -= copy;
  77765. }
  77766. if (state->length) goto inf_leave;
  77767. }
  77768. state->length = 0;
  77769. state->mode = NAME;
  77770. case NAME:
  77771. if (state->flags & 0x0800) {
  77772. if (have == 0) goto inf_leave;
  77773. copy = 0;
  77774. do {
  77775. len = (unsigned)(next[copy++]);
  77776. if (state->head != Z_NULL &&
  77777. state->head->name != Z_NULL &&
  77778. state->length < state->head->name_max)
  77779. state->head->name[state->length++] = len;
  77780. } while (len && copy < have);
  77781. if (state->flags & 0x0200)
  77782. state->check = crc32(state->check, next, copy);
  77783. have -= copy;
  77784. next += copy;
  77785. if (len) goto inf_leave;
  77786. }
  77787. else if (state->head != Z_NULL)
  77788. state->head->name = Z_NULL;
  77789. state->length = 0;
  77790. state->mode = COMMENT;
  77791. case COMMENT:
  77792. if (state->flags & 0x1000) {
  77793. if (have == 0) goto inf_leave;
  77794. copy = 0;
  77795. do {
  77796. len = (unsigned)(next[copy++]);
  77797. if (state->head != Z_NULL &&
  77798. state->head->comment != Z_NULL &&
  77799. state->length < state->head->comm_max)
  77800. state->head->comment[state->length++] = len;
  77801. } while (len && copy < have);
  77802. if (state->flags & 0x0200)
  77803. state->check = crc32(state->check, next, copy);
  77804. have -= copy;
  77805. next += copy;
  77806. if (len) goto inf_leave;
  77807. }
  77808. else if (state->head != Z_NULL)
  77809. state->head->comment = Z_NULL;
  77810. state->mode = HCRC;
  77811. case HCRC:
  77812. if (state->flags & 0x0200) {
  77813. NEEDBITS(16);
  77814. if (hold != (state->check & 0xffff)) {
  77815. strm->msg = (char *)"header crc mismatch";
  77816. state->mode = BAD;
  77817. break;
  77818. }
  77819. INITBITS();
  77820. }
  77821. if (state->head != Z_NULL) {
  77822. state->head->hcrc = (int)((state->flags >> 9) & 1);
  77823. state->head->done = 1;
  77824. }
  77825. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  77826. state->mode = TYPE;
  77827. break;
  77828. #endif
  77829. case DICTID:
  77830. NEEDBITS(32);
  77831. strm->adler = state->check = REVERSE(hold);
  77832. INITBITS();
  77833. state->mode = DICT;
  77834. case DICT:
  77835. if (state->havedict == 0) {
  77836. RESTORE();
  77837. return Z_NEED_DICT;
  77838. }
  77839. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  77840. state->mode = TYPE;
  77841. case TYPE:
  77842. if (flush == Z_BLOCK) goto inf_leave;
  77843. case TYPEDO:
  77844. if (state->last) {
  77845. BYTEBITS();
  77846. state->mode = CHECK;
  77847. break;
  77848. }
  77849. NEEDBITS(3);
  77850. state->last = BITS(1);
  77851. DROPBITS(1);
  77852. switch (BITS(2)) {
  77853. case 0: /* stored block */
  77854. Tracev((stderr, "inflate: stored block%s\n",
  77855. state->last ? " (last)" : ""));
  77856. state->mode = STORED;
  77857. break;
  77858. case 1: /* fixed block */
  77859. fixedtables(state);
  77860. Tracev((stderr, "inflate: fixed codes block%s\n",
  77861. state->last ? " (last)" : ""));
  77862. state->mode = LEN; /* decode codes */
  77863. break;
  77864. case 2: /* dynamic block */
  77865. Tracev((stderr, "inflate: dynamic codes block%s\n",
  77866. state->last ? " (last)" : ""));
  77867. state->mode = TABLE;
  77868. break;
  77869. case 3:
  77870. strm->msg = (char *)"invalid block type";
  77871. state->mode = BAD;
  77872. }
  77873. DROPBITS(2);
  77874. break;
  77875. case STORED:
  77876. BYTEBITS(); /* go to byte boundary */
  77877. NEEDBITS(32);
  77878. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  77879. strm->msg = (char *)"invalid stored block lengths";
  77880. state->mode = BAD;
  77881. break;
  77882. }
  77883. state->length = (unsigned)hold & 0xffff;
  77884. Tracev((stderr, "inflate: stored length %u\n",
  77885. state->length));
  77886. INITBITS();
  77887. state->mode = COPY;
  77888. case COPY:
  77889. copy = state->length;
  77890. if (copy) {
  77891. if (copy > have) copy = have;
  77892. if (copy > left) copy = left;
  77893. if (copy == 0) goto inf_leave;
  77894. zmemcpy(put, next, copy);
  77895. have -= copy;
  77896. next += copy;
  77897. left -= copy;
  77898. put += copy;
  77899. state->length -= copy;
  77900. break;
  77901. }
  77902. Tracev((stderr, "inflate: stored end\n"));
  77903. state->mode = TYPE;
  77904. break;
  77905. case TABLE:
  77906. NEEDBITS(14);
  77907. state->nlen = BITS(5) + 257;
  77908. DROPBITS(5);
  77909. state->ndist = BITS(5) + 1;
  77910. DROPBITS(5);
  77911. state->ncode = BITS(4) + 4;
  77912. DROPBITS(4);
  77913. #ifndef PKZIP_BUG_WORKAROUND
  77914. if (state->nlen > 286 || state->ndist > 30) {
  77915. strm->msg = (char *)"too many length or distance symbols";
  77916. state->mode = BAD;
  77917. break;
  77918. }
  77919. #endif
  77920. Tracev((stderr, "inflate: table sizes ok\n"));
  77921. state->have = 0;
  77922. state->mode = LENLENS;
  77923. case LENLENS:
  77924. while (state->have < state->ncode) {
  77925. NEEDBITS(3);
  77926. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  77927. DROPBITS(3);
  77928. }
  77929. while (state->have < 19)
  77930. state->lens[order[state->have++]] = 0;
  77931. state->next = state->codes;
  77932. state->lencode = (code const FAR *)(state->next);
  77933. state->lenbits = 7;
  77934. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  77935. &(state->lenbits), state->work);
  77936. if (ret) {
  77937. strm->msg = (char *)"invalid code lengths set";
  77938. state->mode = BAD;
  77939. break;
  77940. }
  77941. Tracev((stderr, "inflate: code lengths ok\n"));
  77942. state->have = 0;
  77943. state->mode = CODELENS;
  77944. case CODELENS:
  77945. while (state->have < state->nlen + state->ndist) {
  77946. for (;;) {
  77947. thisx = state->lencode[BITS(state->lenbits)];
  77948. if ((unsigned)(thisx.bits) <= bits) break;
  77949. PULLBYTE();
  77950. }
  77951. if (thisx.val < 16) {
  77952. NEEDBITS(thisx.bits);
  77953. DROPBITS(thisx.bits);
  77954. state->lens[state->have++] = thisx.val;
  77955. }
  77956. else {
  77957. if (thisx.val == 16) {
  77958. NEEDBITS(thisx.bits + 2);
  77959. DROPBITS(thisx.bits);
  77960. if (state->have == 0) {
  77961. strm->msg = (char *)"invalid bit length repeat";
  77962. state->mode = BAD;
  77963. break;
  77964. }
  77965. len = state->lens[state->have - 1];
  77966. copy = 3 + BITS(2);
  77967. DROPBITS(2);
  77968. }
  77969. else if (thisx.val == 17) {
  77970. NEEDBITS(thisx.bits + 3);
  77971. DROPBITS(thisx.bits);
  77972. len = 0;
  77973. copy = 3 + BITS(3);
  77974. DROPBITS(3);
  77975. }
  77976. else {
  77977. NEEDBITS(thisx.bits + 7);
  77978. DROPBITS(thisx.bits);
  77979. len = 0;
  77980. copy = 11 + BITS(7);
  77981. DROPBITS(7);
  77982. }
  77983. if (state->have + copy > state->nlen + state->ndist) {
  77984. strm->msg = (char *)"invalid bit length repeat";
  77985. state->mode = BAD;
  77986. break;
  77987. }
  77988. while (copy--)
  77989. state->lens[state->have++] = (unsigned short)len;
  77990. }
  77991. }
  77992. /* handle error breaks in while */
  77993. if (state->mode == BAD) break;
  77994. /* build code tables */
  77995. state->next = state->codes;
  77996. state->lencode = (code const FAR *)(state->next);
  77997. state->lenbits = 9;
  77998. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  77999. &(state->lenbits), state->work);
  78000. if (ret) {
  78001. strm->msg = (char *)"invalid literal/lengths set";
  78002. state->mode = BAD;
  78003. break;
  78004. }
  78005. state->distcode = (code const FAR *)(state->next);
  78006. state->distbits = 6;
  78007. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  78008. &(state->next), &(state->distbits), state->work);
  78009. if (ret) {
  78010. strm->msg = (char *)"invalid distances set";
  78011. state->mode = BAD;
  78012. break;
  78013. }
  78014. Tracev((stderr, "inflate: codes ok\n"));
  78015. state->mode = LEN;
  78016. case LEN:
  78017. if (have >= 6 && left >= 258) {
  78018. RESTORE();
  78019. inflate_fast(strm, out);
  78020. LOAD();
  78021. break;
  78022. }
  78023. for (;;) {
  78024. thisx = state->lencode[BITS(state->lenbits)];
  78025. if ((unsigned)(thisx.bits) <= bits) break;
  78026. PULLBYTE();
  78027. }
  78028. if (thisx.op && (thisx.op & 0xf0) == 0) {
  78029. last = thisx;
  78030. for (;;) {
  78031. thisx = state->lencode[last.val +
  78032. (BITS(last.bits + last.op) >> last.bits)];
  78033. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  78034. PULLBYTE();
  78035. }
  78036. DROPBITS(last.bits);
  78037. }
  78038. DROPBITS(thisx.bits);
  78039. state->length = (unsigned)thisx.val;
  78040. if ((int)(thisx.op) == 0) {
  78041. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  78042. "inflate: literal '%c'\n" :
  78043. "inflate: literal 0x%02x\n", thisx.val));
  78044. state->mode = LIT;
  78045. break;
  78046. }
  78047. if (thisx.op & 32) {
  78048. Tracevv((stderr, "inflate: end of block\n"));
  78049. state->mode = TYPE;
  78050. break;
  78051. }
  78052. if (thisx.op & 64) {
  78053. strm->msg = (char *)"invalid literal/length code";
  78054. state->mode = BAD;
  78055. break;
  78056. }
  78057. state->extra = (unsigned)(thisx.op) & 15;
  78058. state->mode = LENEXT;
  78059. case LENEXT:
  78060. if (state->extra) {
  78061. NEEDBITS(state->extra);
  78062. state->length += BITS(state->extra);
  78063. DROPBITS(state->extra);
  78064. }
  78065. Tracevv((stderr, "inflate: length %u\n", state->length));
  78066. state->mode = DIST;
  78067. case DIST:
  78068. for (;;) {
  78069. thisx = state->distcode[BITS(state->distbits)];
  78070. if ((unsigned)(thisx.bits) <= bits) break;
  78071. PULLBYTE();
  78072. }
  78073. if ((thisx.op & 0xf0) == 0) {
  78074. last = thisx;
  78075. for (;;) {
  78076. thisx = state->distcode[last.val +
  78077. (BITS(last.bits + last.op) >> last.bits)];
  78078. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  78079. PULLBYTE();
  78080. }
  78081. DROPBITS(last.bits);
  78082. }
  78083. DROPBITS(thisx.bits);
  78084. if (thisx.op & 64) {
  78085. strm->msg = (char *)"invalid distance code";
  78086. state->mode = BAD;
  78087. break;
  78088. }
  78089. state->offset = (unsigned)thisx.val;
  78090. state->extra = (unsigned)(thisx.op) & 15;
  78091. state->mode = DISTEXT;
  78092. case DISTEXT:
  78093. if (state->extra) {
  78094. NEEDBITS(state->extra);
  78095. state->offset += BITS(state->extra);
  78096. DROPBITS(state->extra);
  78097. }
  78098. #ifdef INFLATE_STRICT
  78099. if (state->offset > state->dmax) {
  78100. strm->msg = (char *)"invalid distance too far back";
  78101. state->mode = BAD;
  78102. break;
  78103. }
  78104. #endif
  78105. if (state->offset > state->whave + out - left) {
  78106. strm->msg = (char *)"invalid distance too far back";
  78107. state->mode = BAD;
  78108. break;
  78109. }
  78110. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  78111. state->mode = MATCH;
  78112. case MATCH:
  78113. if (left == 0) goto inf_leave;
  78114. copy = out - left;
  78115. if (state->offset > copy) { /* copy from window */
  78116. copy = state->offset - copy;
  78117. if (copy > state->write) {
  78118. copy -= state->write;
  78119. from = state->window + (state->wsize - copy);
  78120. }
  78121. else
  78122. from = state->window + (state->write - copy);
  78123. if (copy > state->length) copy = state->length;
  78124. }
  78125. else { /* copy from output */
  78126. from = put - state->offset;
  78127. copy = state->length;
  78128. }
  78129. if (copy > left) copy = left;
  78130. left -= copy;
  78131. state->length -= copy;
  78132. do {
  78133. *put++ = *from++;
  78134. } while (--copy);
  78135. if (state->length == 0) state->mode = LEN;
  78136. break;
  78137. case LIT:
  78138. if (left == 0) goto inf_leave;
  78139. *put++ = (unsigned char)(state->length);
  78140. left--;
  78141. state->mode = LEN;
  78142. break;
  78143. case CHECK:
  78144. if (state->wrap) {
  78145. NEEDBITS(32);
  78146. out -= left;
  78147. strm->total_out += out;
  78148. state->total += out;
  78149. if (out)
  78150. strm->adler = state->check =
  78151. UPDATE(state->check, put - out, out);
  78152. out = left;
  78153. if ((
  78154. #ifdef GUNZIP
  78155. state->flags ? hold :
  78156. #endif
  78157. REVERSE(hold)) != state->check) {
  78158. strm->msg = (char *)"incorrect data check";
  78159. state->mode = BAD;
  78160. break;
  78161. }
  78162. INITBITS();
  78163. Tracev((stderr, "inflate: check matches trailer\n"));
  78164. }
  78165. #ifdef GUNZIP
  78166. state->mode = LENGTH;
  78167. case LENGTH:
  78168. if (state->wrap && state->flags) {
  78169. NEEDBITS(32);
  78170. if (hold != (state->total & 0xffffffffUL)) {
  78171. strm->msg = (char *)"incorrect length check";
  78172. state->mode = BAD;
  78173. break;
  78174. }
  78175. INITBITS();
  78176. Tracev((stderr, "inflate: length matches trailer\n"));
  78177. }
  78178. #endif
  78179. state->mode = DONE;
  78180. case DONE:
  78181. ret = Z_STREAM_END;
  78182. goto inf_leave;
  78183. case BAD:
  78184. ret = Z_DATA_ERROR;
  78185. goto inf_leave;
  78186. case MEM:
  78187. return Z_MEM_ERROR;
  78188. case SYNC:
  78189. default:
  78190. return Z_STREAM_ERROR;
  78191. }
  78192. /*
  78193. Return from inflate(), updating the total counts and the check value.
  78194. If there was no progress during the inflate() call, return a buffer
  78195. error. Call updatewindow() to create and/or update the window state.
  78196. Note: a memory error from inflate() is non-recoverable.
  78197. */
  78198. inf_leave:
  78199. RESTORE();
  78200. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  78201. if (updatewindow(strm, out)) {
  78202. state->mode = MEM;
  78203. return Z_MEM_ERROR;
  78204. }
  78205. in -= strm->avail_in;
  78206. out -= strm->avail_out;
  78207. strm->total_in += in;
  78208. strm->total_out += out;
  78209. state->total += out;
  78210. if (state->wrap && out)
  78211. strm->adler = state->check =
  78212. UPDATE(state->check, strm->next_out - out, out);
  78213. strm->data_type = state->bits + (state->last ? 64 : 0) +
  78214. (state->mode == TYPE ? 128 : 0);
  78215. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  78216. ret = Z_BUF_ERROR;
  78217. return ret;
  78218. }
  78219. int ZEXPORT inflateEnd (z_streamp strm)
  78220. {
  78221. struct inflate_state FAR *state;
  78222. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  78223. return Z_STREAM_ERROR;
  78224. state = (struct inflate_state FAR *)strm->state;
  78225. if (state->window != Z_NULL) ZFREE(strm, state->window);
  78226. ZFREE(strm, strm->state);
  78227. strm->state = Z_NULL;
  78228. Tracev((stderr, "inflate: end\n"));
  78229. return Z_OK;
  78230. }
  78231. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  78232. {
  78233. struct inflate_state FAR *state;
  78234. unsigned long id_;
  78235. /* check state */
  78236. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78237. state = (struct inflate_state FAR *)strm->state;
  78238. if (state->wrap != 0 && state->mode != DICT)
  78239. return Z_STREAM_ERROR;
  78240. /* check for correct dictionary id */
  78241. if (state->mode == DICT) {
  78242. id_ = adler32(0L, Z_NULL, 0);
  78243. id_ = adler32(id_, dictionary, dictLength);
  78244. if (id_ != state->check)
  78245. return Z_DATA_ERROR;
  78246. }
  78247. /* copy dictionary to window */
  78248. if (updatewindow(strm, strm->avail_out)) {
  78249. state->mode = MEM;
  78250. return Z_MEM_ERROR;
  78251. }
  78252. if (dictLength > state->wsize) {
  78253. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  78254. state->wsize);
  78255. state->whave = state->wsize;
  78256. }
  78257. else {
  78258. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  78259. dictLength);
  78260. state->whave = dictLength;
  78261. }
  78262. state->havedict = 1;
  78263. Tracev((stderr, "inflate: dictionary set\n"));
  78264. return Z_OK;
  78265. }
  78266. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  78267. {
  78268. struct inflate_state FAR *state;
  78269. /* check state */
  78270. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78271. state = (struct inflate_state FAR *)strm->state;
  78272. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  78273. /* save header structure */
  78274. state->head = head;
  78275. head->done = 0;
  78276. return Z_OK;
  78277. }
  78278. /*
  78279. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  78280. or when out of input. When called, *have is the number of pattern bytes
  78281. found in order so far, in 0..3. On return *have is updated to the new
  78282. state. If on return *have equals four, then the pattern was found and the
  78283. return value is how many bytes were read including the last byte of the
  78284. pattern. If *have is less than four, then the pattern has not been found
  78285. yet and the return value is len. In the latter case, syncsearch() can be
  78286. called again with more data and the *have state. *have is initialized to
  78287. zero for the first call.
  78288. */
  78289. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  78290. {
  78291. unsigned got;
  78292. unsigned next;
  78293. got = *have;
  78294. next = 0;
  78295. while (next < len && got < 4) {
  78296. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  78297. got++;
  78298. else if (buf[next])
  78299. got = 0;
  78300. else
  78301. got = 4 - got;
  78302. next++;
  78303. }
  78304. *have = got;
  78305. return next;
  78306. }
  78307. int ZEXPORT inflateSync (z_streamp strm)
  78308. {
  78309. unsigned len; /* number of bytes to look at or looked at */
  78310. unsigned long in, out; /* temporary to save total_in and total_out */
  78311. unsigned char buf[4]; /* to restore bit buffer to byte string */
  78312. struct inflate_state FAR *state;
  78313. /* check parameters */
  78314. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78315. state = (struct inflate_state FAR *)strm->state;
  78316. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  78317. /* if first time, start search in bit buffer */
  78318. if (state->mode != SYNC) {
  78319. state->mode = SYNC;
  78320. state->hold <<= state->bits & 7;
  78321. state->bits -= state->bits & 7;
  78322. len = 0;
  78323. while (state->bits >= 8) {
  78324. buf[len++] = (unsigned char)(state->hold);
  78325. state->hold >>= 8;
  78326. state->bits -= 8;
  78327. }
  78328. state->have = 0;
  78329. syncsearch(&(state->have), buf, len);
  78330. }
  78331. /* search available input */
  78332. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  78333. strm->avail_in -= len;
  78334. strm->next_in += len;
  78335. strm->total_in += len;
  78336. /* return no joy or set up to restart inflate() on a new block */
  78337. if (state->have != 4) return Z_DATA_ERROR;
  78338. in = strm->total_in; out = strm->total_out;
  78339. inflateReset(strm);
  78340. strm->total_in = in; strm->total_out = out;
  78341. state->mode = TYPE;
  78342. return Z_OK;
  78343. }
  78344. /*
  78345. Returns true if inflate is currently at the end of a block generated by
  78346. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  78347. implementation to provide an additional safety check. PPP uses
  78348. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  78349. block. When decompressing, PPP checks that at the end of input packet,
  78350. inflate is waiting for these length bytes.
  78351. */
  78352. int ZEXPORT inflateSyncPoint (z_streamp strm)
  78353. {
  78354. struct inflate_state FAR *state;
  78355. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78356. state = (struct inflate_state FAR *)strm->state;
  78357. return state->mode == STORED && state->bits == 0;
  78358. }
  78359. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  78360. {
  78361. struct inflate_state FAR *state;
  78362. struct inflate_state FAR *copy;
  78363. unsigned char FAR *window;
  78364. unsigned wsize;
  78365. /* check input */
  78366. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  78367. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  78368. return Z_STREAM_ERROR;
  78369. state = (struct inflate_state FAR *)source->state;
  78370. /* allocate space */
  78371. copy = (struct inflate_state FAR *)
  78372. ZALLOC(source, 1, sizeof(struct inflate_state));
  78373. if (copy == Z_NULL) return Z_MEM_ERROR;
  78374. window = Z_NULL;
  78375. if (state->window != Z_NULL) {
  78376. window = (unsigned char FAR *)
  78377. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  78378. if (window == Z_NULL) {
  78379. ZFREE(source, copy);
  78380. return Z_MEM_ERROR;
  78381. }
  78382. }
  78383. /* copy state */
  78384. zmemcpy(dest, source, sizeof(z_stream));
  78385. zmemcpy(copy, state, sizeof(struct inflate_state));
  78386. if (state->lencode >= state->codes &&
  78387. state->lencode <= state->codes + ENOUGH - 1) {
  78388. copy->lencode = copy->codes + (state->lencode - state->codes);
  78389. copy->distcode = copy->codes + (state->distcode - state->codes);
  78390. }
  78391. copy->next = copy->codes + (state->next - state->codes);
  78392. if (window != Z_NULL) {
  78393. wsize = 1U << state->wbits;
  78394. zmemcpy(window, state->window, wsize);
  78395. }
  78396. copy->window = window;
  78397. dest->state = (struct internal_state FAR *)copy;
  78398. return Z_OK;
  78399. }
  78400. /********* End of inlined file: inflate.c *********/
  78401. /********* Start of inlined file: inftrees.c *********/
  78402. #define MAXBITS 15
  78403. const char inflate_copyright[] =
  78404. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  78405. /*
  78406. If you use the zlib library in a product, an acknowledgment is welcome
  78407. in the documentation of your product. If for some reason you cannot
  78408. include such an acknowledgment, I would appreciate that you keep this
  78409. copyright string in the executable of your product.
  78410. */
  78411. /*
  78412. Build a set of tables to decode the provided canonical Huffman code.
  78413. The code lengths are lens[0..codes-1]. The result starts at *table,
  78414. whose indices are 0..2^bits-1. work is a writable array of at least
  78415. lens shorts, which is used as a work area. type is the type of code
  78416. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  78417. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  78418. on return points to the next available entry's address. bits is the
  78419. requested root table index bits, and on return it is the actual root
  78420. table index bits. It will differ if the request is greater than the
  78421. longest code or if it is less than the shortest code.
  78422. */
  78423. int inflate_table (codetype type,
  78424. unsigned short FAR *lens,
  78425. unsigned codes,
  78426. code FAR * FAR *table,
  78427. unsigned FAR *bits,
  78428. unsigned short FAR *work)
  78429. {
  78430. unsigned len; /* a code's length in bits */
  78431. unsigned sym; /* index of code symbols */
  78432. unsigned min, max; /* minimum and maximum code lengths */
  78433. unsigned root; /* number of index bits for root table */
  78434. unsigned curr; /* number of index bits for current table */
  78435. unsigned drop; /* code bits to drop for sub-table */
  78436. int left; /* number of prefix codes available */
  78437. unsigned used; /* code entries in table used */
  78438. unsigned huff; /* Huffman code */
  78439. unsigned incr; /* for incrementing code, index */
  78440. unsigned fill; /* index for replicating entries */
  78441. unsigned low; /* low bits for current root entry */
  78442. unsigned mask; /* mask for low root bits */
  78443. code thisx; /* table entry for duplication */
  78444. code FAR *next; /* next available space in table */
  78445. const unsigned short FAR *base; /* base value table to use */
  78446. const unsigned short FAR *extra; /* extra bits table to use */
  78447. int end; /* use base and extra for symbol > end */
  78448. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  78449. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  78450. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  78451. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  78452. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  78453. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  78454. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  78455. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  78456. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  78457. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  78458. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  78459. 8193, 12289, 16385, 24577, 0, 0};
  78460. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  78461. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  78462. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  78463. 28, 28, 29, 29, 64, 64};
  78464. /*
  78465. Process a set of code lengths to create a canonical Huffman code. The
  78466. code lengths are lens[0..codes-1]. Each length corresponds to the
  78467. symbols 0..codes-1. The Huffman code is generated by first sorting the
  78468. symbols by length from short to long, and retaining the symbol order
  78469. for codes with equal lengths. Then the code starts with all zero bits
  78470. for the first code of the shortest length, and the codes are integer
  78471. increments for the same length, and zeros are appended as the length
  78472. increases. For the deflate format, these bits are stored backwards
  78473. from their more natural integer increment ordering, and so when the
  78474. decoding tables are built in the large loop below, the integer codes
  78475. are incremented backwards.
  78476. This routine assumes, but does not check, that all of the entries in
  78477. lens[] are in the range 0..MAXBITS. The caller must assure this.
  78478. 1..MAXBITS is interpreted as that code length. zero means that that
  78479. symbol does not occur in this code.
  78480. The codes are sorted by computing a count of codes for each length,
  78481. creating from that a table of starting indices for each length in the
  78482. sorted table, and then entering the symbols in order in the sorted
  78483. table. The sorted table is work[], with that space being provided by
  78484. the caller.
  78485. The length counts are used for other purposes as well, i.e. finding
  78486. the minimum and maximum length codes, determining if there are any
  78487. codes at all, checking for a valid set of lengths, and looking ahead
  78488. at length counts to determine sub-table sizes when building the
  78489. decoding tables.
  78490. */
  78491. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  78492. for (len = 0; len <= MAXBITS; len++)
  78493. count[len] = 0;
  78494. for (sym = 0; sym < codes; sym++)
  78495. count[lens[sym]]++;
  78496. /* bound code lengths, force root to be within code lengths */
  78497. root = *bits;
  78498. for (max = MAXBITS; max >= 1; max--)
  78499. if (count[max] != 0) break;
  78500. if (root > max) root = max;
  78501. if (max == 0) { /* no symbols to code at all */
  78502. thisx.op = (unsigned char)64; /* invalid code marker */
  78503. thisx.bits = (unsigned char)1;
  78504. thisx.val = (unsigned short)0;
  78505. *(*table)++ = thisx; /* make a table to force an error */
  78506. *(*table)++ = thisx;
  78507. *bits = 1;
  78508. return 0; /* no symbols, but wait for decoding to report error */
  78509. }
  78510. for (min = 1; min <= MAXBITS; min++)
  78511. if (count[min] != 0) break;
  78512. if (root < min) root = min;
  78513. /* check for an over-subscribed or incomplete set of lengths */
  78514. left = 1;
  78515. for (len = 1; len <= MAXBITS; len++) {
  78516. left <<= 1;
  78517. left -= count[len];
  78518. if (left < 0) return -1; /* over-subscribed */
  78519. }
  78520. if (left > 0 && (type == CODES || max != 1))
  78521. return -1; /* incomplete set */
  78522. /* generate offsets into symbol table for each length for sorting */
  78523. offs[1] = 0;
  78524. for (len = 1; len < MAXBITS; len++)
  78525. offs[len + 1] = offs[len] + count[len];
  78526. /* sort symbols by length, by symbol order within each length */
  78527. for (sym = 0; sym < codes; sym++)
  78528. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  78529. /*
  78530. Create and fill in decoding tables. In this loop, the table being
  78531. filled is at next and has curr index bits. The code being used is huff
  78532. with length len. That code is converted to an index by dropping drop
  78533. bits off of the bottom. For codes where len is less than drop + curr,
  78534. those top drop + curr - len bits are incremented through all values to
  78535. fill the table with replicated entries.
  78536. root is the number of index bits for the root table. When len exceeds
  78537. root, sub-tables are created pointed to by the root entry with an index
  78538. of the low root bits of huff. This is saved in low to check for when a
  78539. new sub-table should be started. drop is zero when the root table is
  78540. being filled, and drop is root when sub-tables are being filled.
  78541. When a new sub-table is needed, it is necessary to look ahead in the
  78542. code lengths to determine what size sub-table is needed. The length
  78543. counts are used for this, and so count[] is decremented as codes are
  78544. entered in the tables.
  78545. used keeps track of how many table entries have been allocated from the
  78546. provided *table space. It is checked when a LENS table is being made
  78547. against the space in *table, ENOUGH, minus the maximum space needed by
  78548. the worst case distance code, MAXD. This should never happen, but the
  78549. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  78550. This assumes that when type == LENS, bits == 9.
  78551. sym increments through all symbols, and the loop terminates when
  78552. all codes of length max, i.e. all codes, have been processed. This
  78553. routine permits incomplete codes, so another loop after this one fills
  78554. in the rest of the decoding tables with invalid code markers.
  78555. */
  78556. /* set up for code type */
  78557. switch (type) {
  78558. case CODES:
  78559. base = extra = work; /* dummy value--not used */
  78560. end = 19;
  78561. break;
  78562. case LENS:
  78563. base = lbase;
  78564. base -= 257;
  78565. extra = lext;
  78566. extra -= 257;
  78567. end = 256;
  78568. break;
  78569. default: /* DISTS */
  78570. base = dbase;
  78571. extra = dext;
  78572. end = -1;
  78573. }
  78574. /* initialize state for loop */
  78575. huff = 0; /* starting code */
  78576. sym = 0; /* starting code symbol */
  78577. len = min; /* starting code length */
  78578. next = *table; /* current table to fill in */
  78579. curr = root; /* current table index bits */
  78580. drop = 0; /* current bits to drop from code for index */
  78581. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  78582. used = 1U << root; /* use root table entries */
  78583. mask = used - 1; /* mask for comparing low */
  78584. /* check available table space */
  78585. if (type == LENS && used >= ENOUGH - MAXD)
  78586. return 1;
  78587. /* process all codes and make table entries */
  78588. for (;;) {
  78589. /* create table entry */
  78590. thisx.bits = (unsigned char)(len - drop);
  78591. if ((int)(work[sym]) < end) {
  78592. thisx.op = (unsigned char)0;
  78593. thisx.val = work[sym];
  78594. }
  78595. else if ((int)(work[sym]) > end) {
  78596. thisx.op = (unsigned char)(extra[work[sym]]);
  78597. thisx.val = base[work[sym]];
  78598. }
  78599. else {
  78600. thisx.op = (unsigned char)(32 + 64); /* end of block */
  78601. thisx.val = 0;
  78602. }
  78603. /* replicate for those indices with low len bits equal to huff */
  78604. incr = 1U << (len - drop);
  78605. fill = 1U << curr;
  78606. min = fill; /* save offset to next table */
  78607. do {
  78608. fill -= incr;
  78609. next[(huff >> drop) + fill] = thisx;
  78610. } while (fill != 0);
  78611. /* backwards increment the len-bit code huff */
  78612. incr = 1U << (len - 1);
  78613. while (huff & incr)
  78614. incr >>= 1;
  78615. if (incr != 0) {
  78616. huff &= incr - 1;
  78617. huff += incr;
  78618. }
  78619. else
  78620. huff = 0;
  78621. /* go to next symbol, update count, len */
  78622. sym++;
  78623. if (--(count[len]) == 0) {
  78624. if (len == max) break;
  78625. len = lens[work[sym]];
  78626. }
  78627. /* create new sub-table if needed */
  78628. if (len > root && (huff & mask) != low) {
  78629. /* if first time, transition to sub-tables */
  78630. if (drop == 0)
  78631. drop = root;
  78632. /* increment past last table */
  78633. next += min; /* here min is 1 << curr */
  78634. /* determine length of next table */
  78635. curr = len - drop;
  78636. left = (int)(1 << curr);
  78637. while (curr + drop < max) {
  78638. left -= count[curr + drop];
  78639. if (left <= 0) break;
  78640. curr++;
  78641. left <<= 1;
  78642. }
  78643. /* check for enough space */
  78644. used += 1U << curr;
  78645. if (type == LENS && used >= ENOUGH - MAXD)
  78646. return 1;
  78647. /* point entry in root table to sub-table */
  78648. low = huff & mask;
  78649. (*table)[low].op = (unsigned char)curr;
  78650. (*table)[low].bits = (unsigned char)root;
  78651. (*table)[low].val = (unsigned short)(next - *table);
  78652. }
  78653. }
  78654. /*
  78655. Fill in rest of table for incomplete codes. This loop is similar to the
  78656. loop above in incrementing huff for table indices. It is assumed that
  78657. len is equal to curr + drop, so there is no loop needed to increment
  78658. through high index bits. When the current sub-table is filled, the loop
  78659. drops back to the root table to fill in any remaining entries there.
  78660. */
  78661. thisx.op = (unsigned char)64; /* invalid code marker */
  78662. thisx.bits = (unsigned char)(len - drop);
  78663. thisx.val = (unsigned short)0;
  78664. while (huff != 0) {
  78665. /* when done with sub-table, drop back to root table */
  78666. if (drop != 0 && (huff & mask) != low) {
  78667. drop = 0;
  78668. len = root;
  78669. next = *table;
  78670. thisx.bits = (unsigned char)len;
  78671. }
  78672. /* put invalid code marker in table */
  78673. next[huff >> drop] = thisx;
  78674. /* backwards increment the len-bit code huff */
  78675. incr = 1U << (len - 1);
  78676. while (huff & incr)
  78677. incr >>= 1;
  78678. if (incr != 0) {
  78679. huff &= incr - 1;
  78680. huff += incr;
  78681. }
  78682. else
  78683. huff = 0;
  78684. }
  78685. /* set return parameters */
  78686. *table += used;
  78687. *bits = root;
  78688. return 0;
  78689. }
  78690. /********* End of inlined file: inftrees.c *********/
  78691. /********* Start of inlined file: trees.c *********/
  78692. /*
  78693. * ALGORITHM
  78694. *
  78695. * The "deflation" process uses several Huffman trees. The more
  78696. * common source values are represented by shorter bit sequences.
  78697. *
  78698. * Each code tree is stored in a compressed form which is itself
  78699. * a Huffman encoding of the lengths of all the code strings (in
  78700. * ascending order by source values). The actual code strings are
  78701. * reconstructed from the lengths in the inflate process, as described
  78702. * in the deflate specification.
  78703. *
  78704. * REFERENCES
  78705. *
  78706. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  78707. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  78708. *
  78709. * Storer, James A.
  78710. * Data Compression: Methods and Theory, pp. 49-50.
  78711. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  78712. *
  78713. * Sedgewick, R.
  78714. * Algorithms, p290.
  78715. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  78716. */
  78717. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78718. /* #define GEN_TREES_H */
  78719. #ifdef DEBUG
  78720. # include <ctype.h>
  78721. #endif
  78722. /* ===========================================================================
  78723. * Constants
  78724. */
  78725. #define MAX_BL_BITS 7
  78726. /* Bit length codes must not exceed MAX_BL_BITS bits */
  78727. #define END_BLOCK 256
  78728. /* end of block literal code */
  78729. #define REP_3_6 16
  78730. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  78731. #define REPZ_3_10 17
  78732. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  78733. #define REPZ_11_138 18
  78734. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  78735. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  78736. = {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};
  78737. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  78738. = {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};
  78739. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  78740. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  78741. local const uch bl_order[BL_CODES]
  78742. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  78743. /* The lengths of the bit length codes are sent in order of decreasing
  78744. * probability, to avoid transmitting the lengths for unused bit length codes.
  78745. */
  78746. #define Buf_size (8 * 2*sizeof(char))
  78747. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  78748. * more than 16 bits on some systems.)
  78749. */
  78750. /* ===========================================================================
  78751. * Local data. These are initialized only once.
  78752. */
  78753. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  78754. #if defined(GEN_TREES_H) || !defined(STDC)
  78755. /* non ANSI compilers may not accept trees.h */
  78756. local ct_data static_ltree[L_CODES+2];
  78757. /* The static literal tree. Since the bit lengths are imposed, there is no
  78758. * need for the L_CODES extra codes used during heap construction. However
  78759. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  78760. * below).
  78761. */
  78762. local ct_data static_dtree[D_CODES];
  78763. /* The static distance tree. (Actually a trivial tree since all codes use
  78764. * 5 bits.)
  78765. */
  78766. uch _dist_code[DIST_CODE_LEN];
  78767. /* Distance codes. The first 256 values correspond to the distances
  78768. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  78769. * the 15 bit distances.
  78770. */
  78771. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  78772. /* length code for each normalized match length (0 == MIN_MATCH) */
  78773. local int base_length[LENGTH_CODES];
  78774. /* First normalized length for each code (0 = MIN_MATCH) */
  78775. local int base_dist[D_CODES];
  78776. /* First normalized distance for each code (0 = distance of 1) */
  78777. #else
  78778. /********* Start of inlined file: trees.h *********/
  78779. local const ct_data static_ltree[L_CODES+2] = {
  78780. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  78781. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  78782. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  78783. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  78784. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  78785. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  78786. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  78787. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  78788. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  78789. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  78790. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  78791. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  78792. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  78793. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  78794. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  78795. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  78796. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  78797. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  78798. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  78799. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  78800. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  78801. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  78802. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  78803. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  78804. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  78805. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  78806. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  78807. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  78808. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  78809. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  78810. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  78811. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  78812. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  78813. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  78814. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  78815. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  78816. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  78817. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  78818. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  78819. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  78820. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  78821. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  78822. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  78823. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  78824. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  78825. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  78826. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  78827. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  78828. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  78829. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  78830. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  78831. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  78832. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  78833. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  78834. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  78835. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  78836. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  78837. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  78838. };
  78839. local const ct_data static_dtree[D_CODES] = {
  78840. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  78841. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  78842. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  78843. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  78844. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  78845. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  78846. };
  78847. const uch _dist_code[DIST_CODE_LEN] = {
  78848. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  78849. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  78850. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  78851. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  78852. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  78853. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  78854. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  78855. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  78856. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  78857. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  78858. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  78859. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  78860. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  78861. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  78862. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  78863. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  78864. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  78865. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  78866. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  78867. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  78868. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  78869. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  78870. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  78871. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  78872. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  78873. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  78874. };
  78875. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  78876. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  78877. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  78878. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  78879. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  78880. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  78881. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  78882. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  78883. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  78884. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  78885. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  78886. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  78887. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  78888. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  78889. };
  78890. local const int base_length[LENGTH_CODES] = {
  78891. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  78892. 64, 80, 96, 112, 128, 160, 192, 224, 0
  78893. };
  78894. local const int base_dist[D_CODES] = {
  78895. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  78896. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  78897. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  78898. };
  78899. /********* End of inlined file: trees.h *********/
  78900. #endif /* GEN_TREES_H */
  78901. struct static_tree_desc_s {
  78902. const ct_data *static_tree; /* static tree or NULL */
  78903. const intf *extra_bits; /* extra bits for each code or NULL */
  78904. int extra_base; /* base index for extra_bits */
  78905. int elems; /* max number of elements in the tree */
  78906. int max_length; /* max bit length for the codes */
  78907. };
  78908. local static_tree_desc static_l_desc =
  78909. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  78910. local static_tree_desc static_d_desc =
  78911. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  78912. local static_tree_desc static_bl_desc =
  78913. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  78914. /* ===========================================================================
  78915. * Local (static) routines in this file.
  78916. */
  78917. local void tr_static_init OF((void));
  78918. local void init_block OF((deflate_state *s));
  78919. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  78920. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  78921. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  78922. local void build_tree OF((deflate_state *s, tree_desc *desc));
  78923. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  78924. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  78925. local int build_bl_tree OF((deflate_state *s));
  78926. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  78927. int blcodes));
  78928. local void compress_block OF((deflate_state *s, ct_data *ltree,
  78929. ct_data *dtree));
  78930. local void set_data_type OF((deflate_state *s));
  78931. local unsigned bi_reverse OF((unsigned value, int length));
  78932. local void bi_windup OF((deflate_state *s));
  78933. local void bi_flush OF((deflate_state *s));
  78934. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  78935. int header));
  78936. #ifdef GEN_TREES_H
  78937. local void gen_trees_header OF((void));
  78938. #endif
  78939. #ifndef DEBUG
  78940. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  78941. /* Send a code of the given tree. c and tree must not have side effects */
  78942. #else /* DEBUG */
  78943. # define send_code(s, c, tree) \
  78944. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  78945. send_bits(s, tree[c].Code, tree[c].Len); }
  78946. #endif
  78947. /* ===========================================================================
  78948. * Output a short LSB first on the stream.
  78949. * IN assertion: there is enough room in pendingBuf.
  78950. */
  78951. #define put_short(s, w) { \
  78952. put_byte(s, (uch)((w) & 0xff)); \
  78953. put_byte(s, (uch)((ush)(w) >> 8)); \
  78954. }
  78955. /* ===========================================================================
  78956. * Send a value on a given number of bits.
  78957. * IN assertion: length <= 16 and value fits in length bits.
  78958. */
  78959. #ifdef DEBUG
  78960. local void send_bits OF((deflate_state *s, int value, int length));
  78961. local void send_bits (deflate_state *s, int value, int length)
  78962. {
  78963. Tracevv((stderr," l %2d v %4x ", length, value));
  78964. Assert(length > 0 && length <= 15, "invalid length");
  78965. s->bits_sent += (ulg)length;
  78966. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  78967. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  78968. * unused bits in value.
  78969. */
  78970. if (s->bi_valid > (int)Buf_size - length) {
  78971. s->bi_buf |= (value << s->bi_valid);
  78972. put_short(s, s->bi_buf);
  78973. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  78974. s->bi_valid += length - Buf_size;
  78975. } else {
  78976. s->bi_buf |= value << s->bi_valid;
  78977. s->bi_valid += length;
  78978. }
  78979. }
  78980. #else /* !DEBUG */
  78981. #define send_bits(s, value, length) \
  78982. { int len = length;\
  78983. if (s->bi_valid > (int)Buf_size - len) {\
  78984. int val = value;\
  78985. s->bi_buf |= (val << s->bi_valid);\
  78986. put_short(s, s->bi_buf);\
  78987. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  78988. s->bi_valid += len - Buf_size;\
  78989. } else {\
  78990. s->bi_buf |= (value) << s->bi_valid;\
  78991. s->bi_valid += len;\
  78992. }\
  78993. }
  78994. #endif /* DEBUG */
  78995. /* the arguments must not have side effects */
  78996. /* ===========================================================================
  78997. * Initialize the various 'constant' tables.
  78998. */
  78999. local void tr_static_init()
  79000. {
  79001. #if defined(GEN_TREES_H) || !defined(STDC)
  79002. static int static_init_done = 0;
  79003. int n; /* iterates over tree elements */
  79004. int bits; /* bit counter */
  79005. int length; /* length value */
  79006. int code; /* code value */
  79007. int dist; /* distance index */
  79008. ush bl_count[MAX_BITS+1];
  79009. /* number of codes at each bit length for an optimal tree */
  79010. if (static_init_done) return;
  79011. /* For some embedded targets, global variables are not initialized: */
  79012. static_l_desc.static_tree = static_ltree;
  79013. static_l_desc.extra_bits = extra_lbits;
  79014. static_d_desc.static_tree = static_dtree;
  79015. static_d_desc.extra_bits = extra_dbits;
  79016. static_bl_desc.extra_bits = extra_blbits;
  79017. /* Initialize the mapping length (0..255) -> length code (0..28) */
  79018. length = 0;
  79019. for (code = 0; code < LENGTH_CODES-1; code++) {
  79020. base_length[code] = length;
  79021. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  79022. _length_code[length++] = (uch)code;
  79023. }
  79024. }
  79025. Assert (length == 256, "tr_static_init: length != 256");
  79026. /* Note that the length 255 (match length 258) can be represented
  79027. * in two different ways: code 284 + 5 bits or code 285, so we
  79028. * overwrite length_code[255] to use the best encoding:
  79029. */
  79030. _length_code[length-1] = (uch)code;
  79031. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  79032. dist = 0;
  79033. for (code = 0 ; code < 16; code++) {
  79034. base_dist[code] = dist;
  79035. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  79036. _dist_code[dist++] = (uch)code;
  79037. }
  79038. }
  79039. Assert (dist == 256, "tr_static_init: dist != 256");
  79040. dist >>= 7; /* from now on, all distances are divided by 128 */
  79041. for ( ; code < D_CODES; code++) {
  79042. base_dist[code] = dist << 7;
  79043. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  79044. _dist_code[256 + dist++] = (uch)code;
  79045. }
  79046. }
  79047. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  79048. /* Construct the codes of the static literal tree */
  79049. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  79050. n = 0;
  79051. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  79052. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  79053. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  79054. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  79055. /* Codes 286 and 287 do not exist, but we must include them in the
  79056. * tree construction to get a canonical Huffman tree (longest code
  79057. * all ones)
  79058. */
  79059. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  79060. /* The static distance tree is trivial: */
  79061. for (n = 0; n < D_CODES; n++) {
  79062. static_dtree[n].Len = 5;
  79063. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  79064. }
  79065. static_init_done = 1;
  79066. # ifdef GEN_TREES_H
  79067. gen_trees_header();
  79068. # endif
  79069. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  79070. }
  79071. /* ===========================================================================
  79072. * Genererate the file trees.h describing the static trees.
  79073. */
  79074. #ifdef GEN_TREES_H
  79075. # ifndef DEBUG
  79076. # include <stdio.h>
  79077. # endif
  79078. # define SEPARATOR(i, last, width) \
  79079. ((i) == (last)? "\n};\n\n" : \
  79080. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  79081. void gen_trees_header()
  79082. {
  79083. FILE *header = fopen("trees.h", "w");
  79084. int i;
  79085. Assert (header != NULL, "Can't open trees.h");
  79086. fprintf(header,
  79087. "/* header created automatically with -DGEN_TREES_H */\n\n");
  79088. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  79089. for (i = 0; i < L_CODES+2; i++) {
  79090. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  79091. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  79092. }
  79093. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  79094. for (i = 0; i < D_CODES; i++) {
  79095. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  79096. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  79097. }
  79098. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  79099. for (i = 0; i < DIST_CODE_LEN; i++) {
  79100. fprintf(header, "%2u%s", _dist_code[i],
  79101. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  79102. }
  79103. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  79104. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  79105. fprintf(header, "%2u%s", _length_code[i],
  79106. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  79107. }
  79108. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  79109. for (i = 0; i < LENGTH_CODES; i++) {
  79110. fprintf(header, "%1u%s", base_length[i],
  79111. SEPARATOR(i, LENGTH_CODES-1, 20));
  79112. }
  79113. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  79114. for (i = 0; i < D_CODES; i++) {
  79115. fprintf(header, "%5u%s", base_dist[i],
  79116. SEPARATOR(i, D_CODES-1, 10));
  79117. }
  79118. fclose(header);
  79119. }
  79120. #endif /* GEN_TREES_H */
  79121. /* ===========================================================================
  79122. * Initialize the tree data structures for a new zlib stream.
  79123. */
  79124. void _tr_init(deflate_state *s)
  79125. {
  79126. tr_static_init();
  79127. s->l_desc.dyn_tree = s->dyn_ltree;
  79128. s->l_desc.stat_desc = &static_l_desc;
  79129. s->d_desc.dyn_tree = s->dyn_dtree;
  79130. s->d_desc.stat_desc = &static_d_desc;
  79131. s->bl_desc.dyn_tree = s->bl_tree;
  79132. s->bl_desc.stat_desc = &static_bl_desc;
  79133. s->bi_buf = 0;
  79134. s->bi_valid = 0;
  79135. s->last_eob_len = 8; /* enough lookahead for inflate */
  79136. #ifdef DEBUG
  79137. s->compressed_len = 0L;
  79138. s->bits_sent = 0L;
  79139. #endif
  79140. /* Initialize the first block of the first file: */
  79141. init_block(s);
  79142. }
  79143. /* ===========================================================================
  79144. * Initialize a new block.
  79145. */
  79146. local void init_block (deflate_state *s)
  79147. {
  79148. int n; /* iterates over tree elements */
  79149. /* Initialize the trees. */
  79150. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  79151. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  79152. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  79153. s->dyn_ltree[END_BLOCK].Freq = 1;
  79154. s->opt_len = s->static_len = 0L;
  79155. s->last_lit = s->matches = 0;
  79156. }
  79157. #define SMALLEST 1
  79158. /* Index within the heap array of least frequent node in the Huffman tree */
  79159. /* ===========================================================================
  79160. * Remove the smallest element from the heap and recreate the heap with
  79161. * one less element. Updates heap and heap_len.
  79162. */
  79163. #define pqremove(s, tree, top) \
  79164. {\
  79165. top = s->heap[SMALLEST]; \
  79166. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  79167. pqdownheap(s, tree, SMALLEST); \
  79168. }
  79169. /* ===========================================================================
  79170. * Compares to subtrees, using the tree depth as tie breaker when
  79171. * the subtrees have equal frequency. This minimizes the worst case length.
  79172. */
  79173. #define smaller(tree, n, m, depth) \
  79174. (tree[n].Freq < tree[m].Freq || \
  79175. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  79176. /* ===========================================================================
  79177. * Restore the heap property by moving down the tree starting at node k,
  79178. * exchanging a node with the smallest of its two sons if necessary, stopping
  79179. * when the heap property is re-established (each father smaller than its
  79180. * two sons).
  79181. */
  79182. local void pqdownheap (deflate_state *s,
  79183. ct_data *tree, /* the tree to restore */
  79184. int k) /* node to move down */
  79185. {
  79186. int v = s->heap[k];
  79187. int j = k << 1; /* left son of k */
  79188. while (j <= s->heap_len) {
  79189. /* Set j to the smallest of the two sons: */
  79190. if (j < s->heap_len &&
  79191. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  79192. j++;
  79193. }
  79194. /* Exit if v is smaller than both sons */
  79195. if (smaller(tree, v, s->heap[j], s->depth)) break;
  79196. /* Exchange v with the smallest son */
  79197. s->heap[k] = s->heap[j]; k = j;
  79198. /* And continue down the tree, setting j to the left son of k */
  79199. j <<= 1;
  79200. }
  79201. s->heap[k] = v;
  79202. }
  79203. /* ===========================================================================
  79204. * Compute the optimal bit lengths for a tree and update the total bit length
  79205. * for the current block.
  79206. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  79207. * above are the tree nodes sorted by increasing frequency.
  79208. * OUT assertions: the field len is set to the optimal bit length, the
  79209. * array bl_count contains the frequencies for each bit length.
  79210. * The length opt_len is updated; static_len is also updated if stree is
  79211. * not null.
  79212. */
  79213. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  79214. {
  79215. ct_data *tree = desc->dyn_tree;
  79216. int max_code = desc->max_code;
  79217. const ct_data *stree = desc->stat_desc->static_tree;
  79218. const intf *extra = desc->stat_desc->extra_bits;
  79219. int base = desc->stat_desc->extra_base;
  79220. int max_length = desc->stat_desc->max_length;
  79221. int h; /* heap index */
  79222. int n, m; /* iterate over the tree elements */
  79223. int bits; /* bit length */
  79224. int xbits; /* extra bits */
  79225. ush f; /* frequency */
  79226. int overflow = 0; /* number of elements with bit length too large */
  79227. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  79228. /* In a first pass, compute the optimal bit lengths (which may
  79229. * overflow in the case of the bit length tree).
  79230. */
  79231. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  79232. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  79233. n = s->heap[h];
  79234. bits = tree[tree[n].Dad].Len + 1;
  79235. if (bits > max_length) bits = max_length, overflow++;
  79236. tree[n].Len = (ush)bits;
  79237. /* We overwrite tree[n].Dad which is no longer needed */
  79238. if (n > max_code) continue; /* not a leaf node */
  79239. s->bl_count[bits]++;
  79240. xbits = 0;
  79241. if (n >= base) xbits = extra[n-base];
  79242. f = tree[n].Freq;
  79243. s->opt_len += (ulg)f * (bits + xbits);
  79244. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  79245. }
  79246. if (overflow == 0) return;
  79247. Trace((stderr,"\nbit length overflow\n"));
  79248. /* This happens for example on obj2 and pic of the Calgary corpus */
  79249. /* Find the first bit length which could increase: */
  79250. do {
  79251. bits = max_length-1;
  79252. while (s->bl_count[bits] == 0) bits--;
  79253. s->bl_count[bits]--; /* move one leaf down the tree */
  79254. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  79255. s->bl_count[max_length]--;
  79256. /* The brother of the overflow item also moves one step up,
  79257. * but this does not affect bl_count[max_length]
  79258. */
  79259. overflow -= 2;
  79260. } while (overflow > 0);
  79261. /* Now recompute all bit lengths, scanning in increasing frequency.
  79262. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  79263. * lengths instead of fixing only the wrong ones. This idea is taken
  79264. * from 'ar' written by Haruhiko Okumura.)
  79265. */
  79266. for (bits = max_length; bits != 0; bits--) {
  79267. n = s->bl_count[bits];
  79268. while (n != 0) {
  79269. m = s->heap[--h];
  79270. if (m > max_code) continue;
  79271. if ((unsigned) tree[m].Len != (unsigned) bits) {
  79272. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  79273. s->opt_len += ((long)bits - (long)tree[m].Len)
  79274. *(long)tree[m].Freq;
  79275. tree[m].Len = (ush)bits;
  79276. }
  79277. n--;
  79278. }
  79279. }
  79280. }
  79281. /* ===========================================================================
  79282. * Generate the codes for a given tree and bit counts (which need not be
  79283. * optimal).
  79284. * IN assertion: the array bl_count contains the bit length statistics for
  79285. * the given tree and the field len is set for all tree elements.
  79286. * OUT assertion: the field code is set for all tree elements of non
  79287. * zero code length.
  79288. */
  79289. local void gen_codes (ct_data *tree, /* the tree to decorate */
  79290. int max_code, /* largest code with non zero frequency */
  79291. ushf *bl_count) /* number of codes at each bit length */
  79292. {
  79293. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  79294. ush code = 0; /* running code value */
  79295. int bits; /* bit index */
  79296. int n; /* code index */
  79297. /* The distribution counts are first used to generate the code values
  79298. * without bit reversal.
  79299. */
  79300. for (bits = 1; bits <= MAX_BITS; bits++) {
  79301. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  79302. }
  79303. /* Check that the bit counts in bl_count are consistent. The last code
  79304. * must be all ones.
  79305. */
  79306. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  79307. "inconsistent bit counts");
  79308. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  79309. for (n = 0; n <= max_code; n++) {
  79310. int len = tree[n].Len;
  79311. if (len == 0) continue;
  79312. /* Now reverse the bits */
  79313. tree[n].Code = bi_reverse(next_code[len]++, len);
  79314. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  79315. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  79316. }
  79317. }
  79318. /* ===========================================================================
  79319. * Construct one Huffman tree and assigns the code bit strings and lengths.
  79320. * Update the total bit length for the current block.
  79321. * IN assertion: the field freq is set for all tree elements.
  79322. * OUT assertions: the fields len and code are set to the optimal bit length
  79323. * and corresponding code. The length opt_len is updated; static_len is
  79324. * also updated if stree is not null. The field max_code is set.
  79325. */
  79326. local void build_tree (deflate_state *s,
  79327. tree_desc *desc) /* the tree descriptor */
  79328. {
  79329. ct_data *tree = desc->dyn_tree;
  79330. const ct_data *stree = desc->stat_desc->static_tree;
  79331. int elems = desc->stat_desc->elems;
  79332. int n, m; /* iterate over heap elements */
  79333. int max_code = -1; /* largest code with non zero frequency */
  79334. int node; /* new node being created */
  79335. /* Construct the initial heap, with least frequent element in
  79336. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  79337. * heap[0] is not used.
  79338. */
  79339. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  79340. for (n = 0; n < elems; n++) {
  79341. if (tree[n].Freq != 0) {
  79342. s->heap[++(s->heap_len)] = max_code = n;
  79343. s->depth[n] = 0;
  79344. } else {
  79345. tree[n].Len = 0;
  79346. }
  79347. }
  79348. /* The pkzip format requires that at least one distance code exists,
  79349. * and that at least one bit should be sent even if there is only one
  79350. * possible code. So to avoid special checks later on we force at least
  79351. * two codes of non zero frequency.
  79352. */
  79353. while (s->heap_len < 2) {
  79354. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  79355. tree[node].Freq = 1;
  79356. s->depth[node] = 0;
  79357. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  79358. /* node is 0 or 1 so it does not have extra bits */
  79359. }
  79360. desc->max_code = max_code;
  79361. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  79362. * establish sub-heaps of increasing lengths:
  79363. */
  79364. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  79365. /* Construct the Huffman tree by repeatedly combining the least two
  79366. * frequent nodes.
  79367. */
  79368. node = elems; /* next internal node of the tree */
  79369. do {
  79370. pqremove(s, tree, n); /* n = node of least frequency */
  79371. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  79372. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  79373. s->heap[--(s->heap_max)] = m;
  79374. /* Create a new node father of n and m */
  79375. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  79376. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  79377. s->depth[n] : s->depth[m]) + 1);
  79378. tree[n].Dad = tree[m].Dad = (ush)node;
  79379. #ifdef DUMP_BL_TREE
  79380. if (tree == s->bl_tree) {
  79381. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  79382. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  79383. }
  79384. #endif
  79385. /* and insert the new node in the heap */
  79386. s->heap[SMALLEST] = node++;
  79387. pqdownheap(s, tree, SMALLEST);
  79388. } while (s->heap_len >= 2);
  79389. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  79390. /* At this point, the fields freq and dad are set. We can now
  79391. * generate the bit lengths.
  79392. */
  79393. gen_bitlen(s, (tree_desc *)desc);
  79394. /* The field len is now set, we can generate the bit codes */
  79395. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  79396. }
  79397. /* ===========================================================================
  79398. * Scan a literal or distance tree to determine the frequencies of the codes
  79399. * in the bit length tree.
  79400. */
  79401. local void scan_tree (deflate_state *s,
  79402. ct_data *tree, /* the tree to be scanned */
  79403. int max_code) /* and its largest code of non zero frequency */
  79404. {
  79405. int n; /* iterates over all tree elements */
  79406. int prevlen = -1; /* last emitted length */
  79407. int curlen; /* length of current code */
  79408. int nextlen = tree[0].Len; /* length of next code */
  79409. int count = 0; /* repeat count of the current code */
  79410. int max_count = 7; /* max repeat count */
  79411. int min_count = 4; /* min repeat count */
  79412. if (nextlen == 0) max_count = 138, min_count = 3;
  79413. tree[max_code+1].Len = (ush)0xffff; /* guard */
  79414. for (n = 0; n <= max_code; n++) {
  79415. curlen = nextlen; nextlen = tree[n+1].Len;
  79416. if (++count < max_count && curlen == nextlen) {
  79417. continue;
  79418. } else if (count < min_count) {
  79419. s->bl_tree[curlen].Freq += count;
  79420. } else if (curlen != 0) {
  79421. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  79422. s->bl_tree[REP_3_6].Freq++;
  79423. } else if (count <= 10) {
  79424. s->bl_tree[REPZ_3_10].Freq++;
  79425. } else {
  79426. s->bl_tree[REPZ_11_138].Freq++;
  79427. }
  79428. count = 0; prevlen = curlen;
  79429. if (nextlen == 0) {
  79430. max_count = 138, min_count = 3;
  79431. } else if (curlen == nextlen) {
  79432. max_count = 6, min_count = 3;
  79433. } else {
  79434. max_count = 7, min_count = 4;
  79435. }
  79436. }
  79437. }
  79438. /* ===========================================================================
  79439. * Send a literal or distance tree in compressed form, using the codes in
  79440. * bl_tree.
  79441. */
  79442. local void send_tree (deflate_state *s,
  79443. ct_data *tree, /* the tree to be scanned */
  79444. int max_code) /* and its largest code of non zero frequency */
  79445. {
  79446. int n; /* iterates over all tree elements */
  79447. int prevlen = -1; /* last emitted length */
  79448. int curlen; /* length of current code */
  79449. int nextlen = tree[0].Len; /* length of next code */
  79450. int count = 0; /* repeat count of the current code */
  79451. int max_count = 7; /* max repeat count */
  79452. int min_count = 4; /* min repeat count */
  79453. /* tree[max_code+1].Len = -1; */ /* guard already set */
  79454. if (nextlen == 0) max_count = 138, min_count = 3;
  79455. for (n = 0; n <= max_code; n++) {
  79456. curlen = nextlen; nextlen = tree[n+1].Len;
  79457. if (++count < max_count && curlen == nextlen) {
  79458. continue;
  79459. } else if (count < min_count) {
  79460. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  79461. } else if (curlen != 0) {
  79462. if (curlen != prevlen) {
  79463. send_code(s, curlen, s->bl_tree); count--;
  79464. }
  79465. Assert(count >= 3 && count <= 6, " 3_6?");
  79466. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  79467. } else if (count <= 10) {
  79468. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  79469. } else {
  79470. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  79471. }
  79472. count = 0; prevlen = curlen;
  79473. if (nextlen == 0) {
  79474. max_count = 138, min_count = 3;
  79475. } else if (curlen == nextlen) {
  79476. max_count = 6, min_count = 3;
  79477. } else {
  79478. max_count = 7, min_count = 4;
  79479. }
  79480. }
  79481. }
  79482. /* ===========================================================================
  79483. * Construct the Huffman tree for the bit lengths and return the index in
  79484. * bl_order of the last bit length code to send.
  79485. */
  79486. local int build_bl_tree (deflate_state *s)
  79487. {
  79488. int max_blindex; /* index of last bit length code of non zero freq */
  79489. /* Determine the bit length frequencies for literal and distance trees */
  79490. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  79491. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  79492. /* Build the bit length tree: */
  79493. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  79494. /* opt_len now includes the length of the tree representations, except
  79495. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  79496. */
  79497. /* Determine the number of bit length codes to send. The pkzip format
  79498. * requires that at least 4 bit length codes be sent. (appnote.txt says
  79499. * 3 but the actual value used is 4.)
  79500. */
  79501. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  79502. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  79503. }
  79504. /* Update opt_len to include the bit length tree and counts */
  79505. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  79506. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  79507. s->opt_len, s->static_len));
  79508. return max_blindex;
  79509. }
  79510. /* ===========================================================================
  79511. * Send the header for a block using dynamic Huffman trees: the counts, the
  79512. * lengths of the bit length codes, the literal tree and the distance tree.
  79513. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  79514. */
  79515. local void send_all_trees (deflate_state *s,
  79516. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  79517. {
  79518. int rank; /* index in bl_order */
  79519. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  79520. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  79521. "too many codes");
  79522. Tracev((stderr, "\nbl counts: "));
  79523. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  79524. send_bits(s, dcodes-1, 5);
  79525. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  79526. for (rank = 0; rank < blcodes; rank++) {
  79527. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  79528. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  79529. }
  79530. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  79531. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  79532. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  79533. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  79534. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  79535. }
  79536. /* ===========================================================================
  79537. * Send a stored block
  79538. */
  79539. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  79540. {
  79541. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  79542. #ifdef DEBUG
  79543. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  79544. s->compressed_len += (stored_len + 4) << 3;
  79545. #endif
  79546. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  79547. }
  79548. /* ===========================================================================
  79549. * Send one empty static block to give enough lookahead for inflate.
  79550. * This takes 10 bits, of which 7 may remain in the bit buffer.
  79551. * The current inflate code requires 9 bits of lookahead. If the
  79552. * last two codes for the previous block (real code plus EOB) were coded
  79553. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  79554. * the last real code. In this case we send two empty static blocks instead
  79555. * of one. (There are no problems if the previous block is stored or fixed.)
  79556. * To simplify the code, we assume the worst case of last real code encoded
  79557. * on one bit only.
  79558. */
  79559. void _tr_align (deflate_state *s)
  79560. {
  79561. send_bits(s, STATIC_TREES<<1, 3);
  79562. send_code(s, END_BLOCK, static_ltree);
  79563. #ifdef DEBUG
  79564. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  79565. #endif
  79566. bi_flush(s);
  79567. /* Of the 10 bits for the empty block, we have already sent
  79568. * (10 - bi_valid) bits. The lookahead for the last real code (before
  79569. * the EOB of the previous block) was thus at least one plus the length
  79570. * of the EOB plus what we have just sent of the empty static block.
  79571. */
  79572. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  79573. send_bits(s, STATIC_TREES<<1, 3);
  79574. send_code(s, END_BLOCK, static_ltree);
  79575. #ifdef DEBUG
  79576. s->compressed_len += 10L;
  79577. #endif
  79578. bi_flush(s);
  79579. }
  79580. s->last_eob_len = 7;
  79581. }
  79582. /* ===========================================================================
  79583. * Determine the best encoding for the current block: dynamic trees, static
  79584. * trees or store, and output the encoded block to the zip file.
  79585. */
  79586. void _tr_flush_block (deflate_state *s,
  79587. charf *buf, /* input block, or NULL if too old */
  79588. ulg stored_len, /* length of input block */
  79589. int eof) /* true if this is the last block for a file */
  79590. {
  79591. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  79592. int max_blindex = 0; /* index of last bit length code of non zero freq */
  79593. /* Build the Huffman trees unless a stored block is forced */
  79594. if (s->level > 0) {
  79595. /* Check if the file is binary or text */
  79596. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  79597. set_data_type(s);
  79598. /* Construct the literal and distance trees */
  79599. build_tree(s, (tree_desc *)(&(s->l_desc)));
  79600. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  79601. s->static_len));
  79602. build_tree(s, (tree_desc *)(&(s->d_desc)));
  79603. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  79604. s->static_len));
  79605. /* At this point, opt_len and static_len are the total bit lengths of
  79606. * the compressed block data, excluding the tree representations.
  79607. */
  79608. /* Build the bit length tree for the above two trees, and get the index
  79609. * in bl_order of the last bit length code to send.
  79610. */
  79611. max_blindex = build_bl_tree(s);
  79612. /* Determine the best encoding. Compute the block lengths in bytes. */
  79613. opt_lenb = (s->opt_len+3+7)>>3;
  79614. static_lenb = (s->static_len+3+7)>>3;
  79615. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  79616. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  79617. s->last_lit));
  79618. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  79619. } else {
  79620. Assert(buf != (char*)0, "lost buf");
  79621. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  79622. }
  79623. #ifdef FORCE_STORED
  79624. if (buf != (char*)0) { /* force stored block */
  79625. #else
  79626. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  79627. /* 4: two words for the lengths */
  79628. #endif
  79629. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  79630. * Otherwise we can't have processed more than WSIZE input bytes since
  79631. * the last block flush, because compression would have been
  79632. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  79633. * transform a block into a stored block.
  79634. */
  79635. _tr_stored_block(s, buf, stored_len, eof);
  79636. #ifdef FORCE_STATIC
  79637. } else if (static_lenb >= 0) { /* force static trees */
  79638. #else
  79639. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  79640. #endif
  79641. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  79642. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  79643. #ifdef DEBUG
  79644. s->compressed_len += 3 + s->static_len;
  79645. #endif
  79646. } else {
  79647. send_bits(s, (DYN_TREES<<1)+eof, 3);
  79648. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  79649. max_blindex+1);
  79650. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  79651. #ifdef DEBUG
  79652. s->compressed_len += 3 + s->opt_len;
  79653. #endif
  79654. }
  79655. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  79656. /* The above check is made mod 2^32, for files larger than 512 MB
  79657. * and uLong implemented on 32 bits.
  79658. */
  79659. init_block(s);
  79660. if (eof) {
  79661. bi_windup(s);
  79662. #ifdef DEBUG
  79663. s->compressed_len += 7; /* align on byte boundary */
  79664. #endif
  79665. }
  79666. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  79667. s->compressed_len-7*eof));
  79668. }
  79669. /* ===========================================================================
  79670. * Save the match info and tally the frequency counts. Return true if
  79671. * the current block must be flushed.
  79672. */
  79673. int _tr_tally (deflate_state *s,
  79674. unsigned dist, /* distance of matched string */
  79675. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  79676. {
  79677. s->d_buf[s->last_lit] = (ush)dist;
  79678. s->l_buf[s->last_lit++] = (uch)lc;
  79679. if (dist == 0) {
  79680. /* lc is the unmatched char */
  79681. s->dyn_ltree[lc].Freq++;
  79682. } else {
  79683. s->matches++;
  79684. /* Here, lc is the match length - MIN_MATCH */
  79685. dist--; /* dist = match distance - 1 */
  79686. Assert((ush)dist < (ush)MAX_DIST(s) &&
  79687. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  79688. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  79689. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  79690. s->dyn_dtree[d_code(dist)].Freq++;
  79691. }
  79692. #ifdef TRUNCATE_BLOCK
  79693. /* Try to guess if it is profitable to stop the current block here */
  79694. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  79695. /* Compute an upper bound for the compressed length */
  79696. ulg out_length = (ulg)s->last_lit*8L;
  79697. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  79698. int dcode;
  79699. for (dcode = 0; dcode < D_CODES; dcode++) {
  79700. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  79701. (5L+extra_dbits[dcode]);
  79702. }
  79703. out_length >>= 3;
  79704. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  79705. s->last_lit, in_length, out_length,
  79706. 100L - out_length*100L/in_length));
  79707. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  79708. }
  79709. #endif
  79710. return (s->last_lit == s->lit_bufsize-1);
  79711. /* We avoid equality with lit_bufsize because of wraparound at 64K
  79712. * on 16 bit machines and because stored blocks are restricted to
  79713. * 64K-1 bytes.
  79714. */
  79715. }
  79716. /* ===========================================================================
  79717. * Send the block data compressed using the given Huffman trees
  79718. */
  79719. local void compress_block (deflate_state *s,
  79720. ct_data *ltree, /* literal tree */
  79721. ct_data *dtree) /* distance tree */
  79722. {
  79723. unsigned dist; /* distance of matched string */
  79724. int lc; /* match length or unmatched char (if dist == 0) */
  79725. unsigned lx = 0; /* running index in l_buf */
  79726. unsigned code; /* the code to send */
  79727. int extra; /* number of extra bits to send */
  79728. if (s->last_lit != 0) do {
  79729. dist = s->d_buf[lx];
  79730. lc = s->l_buf[lx++];
  79731. if (dist == 0) {
  79732. send_code(s, lc, ltree); /* send a literal byte */
  79733. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  79734. } else {
  79735. /* Here, lc is the match length - MIN_MATCH */
  79736. code = _length_code[lc];
  79737. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  79738. extra = extra_lbits[code];
  79739. if (extra != 0) {
  79740. lc -= base_length[code];
  79741. send_bits(s, lc, extra); /* send the extra length bits */
  79742. }
  79743. dist--; /* dist is now the match distance - 1 */
  79744. code = d_code(dist);
  79745. Assert (code < D_CODES, "bad d_code");
  79746. send_code(s, code, dtree); /* send the distance code */
  79747. extra = extra_dbits[code];
  79748. if (extra != 0) {
  79749. dist -= base_dist[code];
  79750. send_bits(s, dist, extra); /* send the extra distance bits */
  79751. }
  79752. } /* literal or match pair ? */
  79753. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  79754. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  79755. "pendingBuf overflow");
  79756. } while (lx < s->last_lit);
  79757. send_code(s, END_BLOCK, ltree);
  79758. s->last_eob_len = ltree[END_BLOCK].Len;
  79759. }
  79760. /* ===========================================================================
  79761. * Set the data type to BINARY or TEXT, using a crude approximation:
  79762. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  79763. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  79764. * IN assertion: the fields Freq of dyn_ltree are set.
  79765. */
  79766. local void set_data_type (deflate_state *s)
  79767. {
  79768. int n;
  79769. for (n = 0; n < 9; n++)
  79770. if (s->dyn_ltree[n].Freq != 0)
  79771. break;
  79772. if (n == 9)
  79773. for (n = 14; n < 32; n++)
  79774. if (s->dyn_ltree[n].Freq != 0)
  79775. break;
  79776. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  79777. }
  79778. /* ===========================================================================
  79779. * Reverse the first len bits of a code, using straightforward code (a faster
  79780. * method would use a table)
  79781. * IN assertion: 1 <= len <= 15
  79782. */
  79783. local unsigned bi_reverse (unsigned code, int len)
  79784. {
  79785. register unsigned res = 0;
  79786. do {
  79787. res |= code & 1;
  79788. code >>= 1, res <<= 1;
  79789. } while (--len > 0);
  79790. return res >> 1;
  79791. }
  79792. /* ===========================================================================
  79793. * Flush the bit buffer, keeping at most 7 bits in it.
  79794. */
  79795. local void bi_flush (deflate_state *s)
  79796. {
  79797. if (s->bi_valid == 16) {
  79798. put_short(s, s->bi_buf);
  79799. s->bi_buf = 0;
  79800. s->bi_valid = 0;
  79801. } else if (s->bi_valid >= 8) {
  79802. put_byte(s, (Byte)s->bi_buf);
  79803. s->bi_buf >>= 8;
  79804. s->bi_valid -= 8;
  79805. }
  79806. }
  79807. /* ===========================================================================
  79808. * Flush the bit buffer and align the output on a byte boundary
  79809. */
  79810. local void bi_windup (deflate_state *s)
  79811. {
  79812. if (s->bi_valid > 8) {
  79813. put_short(s, s->bi_buf);
  79814. } else if (s->bi_valid > 0) {
  79815. put_byte(s, (Byte)s->bi_buf);
  79816. }
  79817. s->bi_buf = 0;
  79818. s->bi_valid = 0;
  79819. #ifdef DEBUG
  79820. s->bits_sent = (s->bits_sent+7) & ~7;
  79821. #endif
  79822. }
  79823. /* ===========================================================================
  79824. * Copy a stored block, storing first the length and its
  79825. * one's complement if requested.
  79826. */
  79827. local void copy_block(deflate_state *s,
  79828. charf *buf, /* the input data */
  79829. unsigned len, /* its length */
  79830. int header) /* true if block header must be written */
  79831. {
  79832. bi_windup(s); /* align on byte boundary */
  79833. s->last_eob_len = 8; /* enough lookahead for inflate */
  79834. if (header) {
  79835. put_short(s, (ush)len);
  79836. put_short(s, (ush)~len);
  79837. #ifdef DEBUG
  79838. s->bits_sent += 2*16;
  79839. #endif
  79840. }
  79841. #ifdef DEBUG
  79842. s->bits_sent += (ulg)len<<3;
  79843. #endif
  79844. while (len--) {
  79845. put_byte(s, *buf++);
  79846. }
  79847. }
  79848. /********* End of inlined file: trees.c *********/
  79849. /********* Start of inlined file: uncompr.c *********/
  79850. /* @(#) $Id: uncompr.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79851. #define ZLIB_INTERNAL
  79852. /* ===========================================================================
  79853. Decompresses the source buffer into the destination buffer. sourceLen is
  79854. the byte length of the source buffer. Upon entry, destLen is the total
  79855. size of the destination buffer, which must be large enough to hold the
  79856. entire uncompressed data. (The size of the uncompressed data must have
  79857. been saved previously by the compressor and transmitted to the decompressor
  79858. by some mechanism outside the scope of this compression library.)
  79859. Upon exit, destLen is the actual size of the compressed buffer.
  79860. This function can be used to decompress a whole file at once if the
  79861. input file is mmap'ed.
  79862. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79863. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79864. buffer, or Z_DATA_ERROR if the input data was corrupted.
  79865. */
  79866. int ZEXPORT uncompress (Bytef *dest,
  79867. uLongf *destLen,
  79868. const Bytef *source,
  79869. uLong sourceLen)
  79870. {
  79871. z_stream stream;
  79872. int err;
  79873. stream.next_in = (Bytef*)source;
  79874. stream.avail_in = (uInt)sourceLen;
  79875. /* Check for source > 64K on 16-bit machine: */
  79876. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79877. stream.next_out = dest;
  79878. stream.avail_out = (uInt)*destLen;
  79879. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79880. stream.zalloc = (alloc_func)0;
  79881. stream.zfree = (free_func)0;
  79882. err = inflateInit(&stream);
  79883. if (err != Z_OK) return err;
  79884. err = inflate(&stream, Z_FINISH);
  79885. if (err != Z_STREAM_END) {
  79886. inflateEnd(&stream);
  79887. if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0))
  79888. return Z_DATA_ERROR;
  79889. return err;
  79890. }
  79891. *destLen = stream.total_out;
  79892. err = inflateEnd(&stream);
  79893. return err;
  79894. }
  79895. /********* End of inlined file: uncompr.c *********/
  79896. /********* Start of inlined file: zutil.c *********/
  79897. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79898. #ifndef NO_DUMMY_DECL
  79899. struct internal_state {int dummy;}; /* for buggy compilers */
  79900. #endif
  79901. const char * const z_errmsg[10] = {
  79902. "need dictionary", /* Z_NEED_DICT 2 */
  79903. "stream end", /* Z_STREAM_END 1 */
  79904. "", /* Z_OK 0 */
  79905. "file error", /* Z_ERRNO (-1) */
  79906. "stream error", /* Z_STREAM_ERROR (-2) */
  79907. "data error", /* Z_DATA_ERROR (-3) */
  79908. "insufficient memory", /* Z_MEM_ERROR (-4) */
  79909. "buffer error", /* Z_BUF_ERROR (-5) */
  79910. "incompatible version",/* Z_VERSION_ERROR (-6) */
  79911. ""};
  79912. /*const char * ZEXPORT zlibVersion()
  79913. {
  79914. return ZLIB_VERSION;
  79915. }
  79916. uLong ZEXPORT zlibCompileFlags()
  79917. {
  79918. uLong flags;
  79919. flags = 0;
  79920. switch (sizeof(uInt)) {
  79921. case 2: break;
  79922. case 4: flags += 1; break;
  79923. case 8: flags += 2; break;
  79924. default: flags += 3;
  79925. }
  79926. switch (sizeof(uLong)) {
  79927. case 2: break;
  79928. case 4: flags += 1 << 2; break;
  79929. case 8: flags += 2 << 2; break;
  79930. default: flags += 3 << 2;
  79931. }
  79932. switch (sizeof(voidpf)) {
  79933. case 2: break;
  79934. case 4: flags += 1 << 4; break;
  79935. case 8: flags += 2 << 4; break;
  79936. default: flags += 3 << 4;
  79937. }
  79938. switch (sizeof(z_off_t)) {
  79939. case 2: break;
  79940. case 4: flags += 1 << 6; break;
  79941. case 8: flags += 2 << 6; break;
  79942. default: flags += 3 << 6;
  79943. }
  79944. #ifdef DEBUG
  79945. flags += 1 << 8;
  79946. #endif
  79947. #if defined(ASMV) || defined(ASMINF)
  79948. flags += 1 << 9;
  79949. #endif
  79950. #ifdef ZLIB_WINAPI
  79951. flags += 1 << 10;
  79952. #endif
  79953. #ifdef BUILDFIXED
  79954. flags += 1 << 12;
  79955. #endif
  79956. #ifdef DYNAMIC_CRC_TABLE
  79957. flags += 1 << 13;
  79958. #endif
  79959. #ifdef NO_GZCOMPRESS
  79960. flags += 1L << 16;
  79961. #endif
  79962. #ifdef NO_GZIP
  79963. flags += 1L << 17;
  79964. #endif
  79965. #ifdef PKZIP_BUG_WORKAROUND
  79966. flags += 1L << 20;
  79967. #endif
  79968. #ifdef FASTEST
  79969. flags += 1L << 21;
  79970. #endif
  79971. #ifdef STDC
  79972. # ifdef NO_vsnprintf
  79973. flags += 1L << 25;
  79974. # ifdef HAS_vsprintf_void
  79975. flags += 1L << 26;
  79976. # endif
  79977. # else
  79978. # ifdef HAS_vsnprintf_void
  79979. flags += 1L << 26;
  79980. # endif
  79981. # endif
  79982. #else
  79983. flags += 1L << 24;
  79984. # ifdef NO_snprintf
  79985. flags += 1L << 25;
  79986. # ifdef HAS_sprintf_void
  79987. flags += 1L << 26;
  79988. # endif
  79989. # else
  79990. # ifdef HAS_snprintf_void
  79991. flags += 1L << 26;
  79992. # endif
  79993. # endif
  79994. #endif
  79995. return flags;
  79996. }*/
  79997. #ifdef DEBUG
  79998. # ifndef verbose
  79999. # define verbose 0
  80000. # endif
  80001. int z_verbose = verbose;
  80002. void z_error (char *m)
  80003. {
  80004. fprintf(stderr, "%s\n", m);
  80005. exit(1);
  80006. }
  80007. #endif
  80008. /* exported to allow conversion of error code to string for compress() and
  80009. * uncompress()
  80010. */
  80011. const char * ZEXPORT zError(int err)
  80012. {
  80013. return ERR_MSG(err);
  80014. }
  80015. #if defined(_WIN32_WCE)
  80016. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  80017. * errno. We define it as a global variable to simplify porting.
  80018. * Its value is always 0 and should not be used.
  80019. */
  80020. int errno = 0;
  80021. #endif
  80022. #ifndef HAVE_MEMCPY
  80023. void zmemcpy(dest, source, len)
  80024. Bytef* dest;
  80025. const Bytef* source;
  80026. uInt len;
  80027. {
  80028. if (len == 0) return;
  80029. do {
  80030. *dest++ = *source++; /* ??? to be unrolled */
  80031. } while (--len != 0);
  80032. }
  80033. int zmemcmp(s1, s2, len)
  80034. const Bytef* s1;
  80035. const Bytef* s2;
  80036. uInt len;
  80037. {
  80038. uInt j;
  80039. for (j = 0; j < len; j++) {
  80040. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  80041. }
  80042. return 0;
  80043. }
  80044. void zmemzero(dest, len)
  80045. Bytef* dest;
  80046. uInt len;
  80047. {
  80048. if (len == 0) return;
  80049. do {
  80050. *dest++ = 0; /* ??? to be unrolled */
  80051. } while (--len != 0);
  80052. }
  80053. #endif
  80054. #ifdef SYS16BIT
  80055. #ifdef __TURBOC__
  80056. /* Turbo C in 16-bit mode */
  80057. # define MY_ZCALLOC
  80058. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  80059. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  80060. * must fix the pointer. Warning: the pointer must be put back to its
  80061. * original form in order to free it, use zcfree().
  80062. */
  80063. #define MAX_PTR 10
  80064. /* 10*64K = 640K */
  80065. local int next_ptr = 0;
  80066. typedef struct ptr_table_s {
  80067. voidpf org_ptr;
  80068. voidpf new_ptr;
  80069. } ptr_table;
  80070. local ptr_table table[MAX_PTR];
  80071. /* This table is used to remember the original form of pointers
  80072. * to large buffers (64K). Such pointers are normalized with a zero offset.
  80073. * Since MSDOS is not a preemptive multitasking OS, this table is not
  80074. * protected from concurrent access. This hack doesn't work anyway on
  80075. * a protected system like OS/2. Use Microsoft C instead.
  80076. */
  80077. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  80078. {
  80079. voidpf buf = opaque; /* just to make some compilers happy */
  80080. ulg bsize = (ulg)items*size;
  80081. /* If we allocate less than 65520 bytes, we assume that farmalloc
  80082. * will return a usable pointer which doesn't have to be normalized.
  80083. */
  80084. if (bsize < 65520L) {
  80085. buf = farmalloc(bsize);
  80086. if (*(ush*)&buf != 0) return buf;
  80087. } else {
  80088. buf = farmalloc(bsize + 16L);
  80089. }
  80090. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  80091. table[next_ptr].org_ptr = buf;
  80092. /* Normalize the pointer to seg:0 */
  80093. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  80094. *(ush*)&buf = 0;
  80095. table[next_ptr++].new_ptr = buf;
  80096. return buf;
  80097. }
  80098. void zcfree (voidpf opaque, voidpf ptr)
  80099. {
  80100. int n;
  80101. if (*(ush*)&ptr != 0) { /* object < 64K */
  80102. farfree(ptr);
  80103. return;
  80104. }
  80105. /* Find the original pointer */
  80106. for (n = 0; n < next_ptr; n++) {
  80107. if (ptr != table[n].new_ptr) continue;
  80108. farfree(table[n].org_ptr);
  80109. while (++n < next_ptr) {
  80110. table[n-1] = table[n];
  80111. }
  80112. next_ptr--;
  80113. return;
  80114. }
  80115. ptr = opaque; /* just to make some compilers happy */
  80116. Assert(0, "zcfree: ptr not found");
  80117. }
  80118. #endif /* __TURBOC__ */
  80119. #ifdef M_I86
  80120. /* Microsoft C in 16-bit mode */
  80121. # define MY_ZCALLOC
  80122. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  80123. # define _halloc halloc
  80124. # define _hfree hfree
  80125. #endif
  80126. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  80127. {
  80128. if (opaque) opaque = 0; /* to make compiler happy */
  80129. return _halloc((long)items, size);
  80130. }
  80131. void zcfree (voidpf opaque, voidpf ptr)
  80132. {
  80133. if (opaque) opaque = 0; /* to make compiler happy */
  80134. _hfree(ptr);
  80135. }
  80136. #endif /* M_I86 */
  80137. #endif /* SYS16BIT */
  80138. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  80139. #ifndef STDC
  80140. extern voidp malloc OF((uInt size));
  80141. extern voidp calloc OF((uInt items, uInt size));
  80142. extern void free OF((voidpf ptr));
  80143. #endif
  80144. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  80145. {
  80146. if (opaque) items += size - size; /* make compiler happy */
  80147. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  80148. (voidpf)calloc(items, size);
  80149. }
  80150. void zcfree (voidpf opaque, voidpf ptr)
  80151. {
  80152. free(ptr);
  80153. if (opaque) return; /* make compiler happy */
  80154. }
  80155. #endif /* MY_ZCALLOC */
  80156. /********* End of inlined file: zutil.c *********/
  80157. #undef Byte
  80158. }
  80159. }
  80160. #if JUCE_MSVC
  80161. #pragma warning (pop)
  80162. #endif
  80163. BEGIN_JUCE_NAMESPACE
  80164. using namespace zlibNamespace;
  80165. // internal helper object that holds the zlib structures so they don't have to be
  80166. // included publicly.
  80167. class GZIPDecompressHelper
  80168. {
  80169. private:
  80170. z_stream* stream;
  80171. uint8* data;
  80172. int dataSize;
  80173. public:
  80174. bool finished, needsDictionary, error;
  80175. GZIPDecompressHelper (const bool noWrap) throw()
  80176. : data (0),
  80177. dataSize (0),
  80178. finished (false),
  80179. needsDictionary (false),
  80180. error (false)
  80181. {
  80182. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  80183. if (inflateInit2 (stream, (noWrap) ? -MAX_WBITS
  80184. : MAX_WBITS) != Z_OK)
  80185. {
  80186. juce_free (stream);
  80187. stream = 0;
  80188. error = true;
  80189. finished = true;
  80190. }
  80191. }
  80192. ~GZIPDecompressHelper() throw()
  80193. {
  80194. if (stream != 0)
  80195. {
  80196. inflateEnd (stream);
  80197. juce_free (stream);
  80198. }
  80199. }
  80200. bool needsInput() const throw() { return dataSize <= 0; }
  80201. void setInput (uint8* const data_, const int size) throw()
  80202. {
  80203. data = data_;
  80204. dataSize = size;
  80205. }
  80206. int doNextBlock (uint8* const dest, const int destSize) throw()
  80207. {
  80208. if (stream != 0 && data != 0 && ! finished)
  80209. {
  80210. stream->next_in = data;
  80211. stream->next_out = dest;
  80212. stream->avail_in = dataSize;
  80213. stream->avail_out = destSize;
  80214. switch (inflate (stream, Z_PARTIAL_FLUSH))
  80215. {
  80216. case Z_STREAM_END:
  80217. finished = true;
  80218. // deliberate fall-through
  80219. case Z_OK:
  80220. data += dataSize - stream->avail_in;
  80221. dataSize = stream->avail_in;
  80222. return destSize - stream->avail_out;
  80223. case Z_NEED_DICT:
  80224. needsDictionary = true;
  80225. data += dataSize - stream->avail_in;
  80226. dataSize = stream->avail_in;
  80227. break;
  80228. case Z_DATA_ERROR:
  80229. case Z_MEM_ERROR:
  80230. error = true;
  80231. default:
  80232. break;
  80233. }
  80234. }
  80235. return 0;
  80236. }
  80237. };
  80238. const int gzipDecompBufferSize = 32768;
  80239. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  80240. const bool deleteSourceWhenDestroyed_,
  80241. const bool noWrap_,
  80242. const int64 uncompressedStreamLength_)
  80243. : sourceStream (sourceStream_),
  80244. uncompressedStreamLength (uncompressedStreamLength_),
  80245. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  80246. noWrap (noWrap_),
  80247. isEof (false),
  80248. activeBufferSize (0),
  80249. originalSourcePos (sourceStream_->getPosition()),
  80250. currentPos (0)
  80251. {
  80252. buffer = (uint8*) juce_malloc (gzipDecompBufferSize);
  80253. helper = new GZIPDecompressHelper (noWrap_);
  80254. }
  80255. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  80256. {
  80257. juce_free (buffer);
  80258. if (deleteSourceWhenDestroyed)
  80259. delete sourceStream;
  80260. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  80261. delete h;
  80262. }
  80263. int64 GZIPDecompressorInputStream::getTotalLength()
  80264. {
  80265. return uncompressedStreamLength;
  80266. }
  80267. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  80268. {
  80269. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  80270. if ((howMany > 0) && ! isEof)
  80271. {
  80272. jassert (destBuffer != 0);
  80273. if (destBuffer != 0)
  80274. {
  80275. int numRead = 0;
  80276. uint8* d = (uint8*) destBuffer;
  80277. while (! h->error)
  80278. {
  80279. const int n = h->doNextBlock (d, howMany);
  80280. currentPos += n;
  80281. if (n == 0)
  80282. {
  80283. if (h->finished || h->needsDictionary)
  80284. {
  80285. isEof = true;
  80286. return numRead;
  80287. }
  80288. if (h->needsInput())
  80289. {
  80290. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  80291. if (activeBufferSize > 0)
  80292. {
  80293. h->setInput ((uint8*) buffer, activeBufferSize);
  80294. }
  80295. else
  80296. {
  80297. isEof = true;
  80298. return numRead;
  80299. }
  80300. }
  80301. }
  80302. else
  80303. {
  80304. numRead += n;
  80305. howMany -= n;
  80306. d += n;
  80307. if (howMany <= 0)
  80308. return numRead;
  80309. }
  80310. }
  80311. }
  80312. }
  80313. return 0;
  80314. }
  80315. bool GZIPDecompressorInputStream::isExhausted()
  80316. {
  80317. const GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  80318. return h->error || isEof;
  80319. }
  80320. int64 GZIPDecompressorInputStream::getPosition()
  80321. {
  80322. return currentPos;
  80323. }
  80324. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  80325. {
  80326. if (newPos != currentPos)
  80327. {
  80328. if (newPos > currentPos)
  80329. {
  80330. skipNextBytes (newPos - currentPos);
  80331. }
  80332. else
  80333. {
  80334. // reset the stream and start again..
  80335. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  80336. delete h;
  80337. isEof = false;
  80338. activeBufferSize = 0;
  80339. currentPos = 0;
  80340. helper = new GZIPDecompressHelper (noWrap);
  80341. sourceStream->setPosition (originalSourcePos);
  80342. skipNextBytes (newPos);
  80343. }
  80344. }
  80345. return true;
  80346. }
  80347. END_JUCE_NAMESPACE
  80348. /********* End of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  80349. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  80350. /********* Start of inlined file: juce_FlacAudioFormat.cpp *********/
  80351. #ifdef _MSC_VER
  80352. #include <windows.h>
  80353. #endif
  80354. #if JUCE_USE_FLAC
  80355. #ifdef _MSC_VER
  80356. #pragma warning (disable : 4505)
  80357. #pragma warning (push)
  80358. #endif
  80359. namespace FlacNamespace
  80360. {
  80361. #define FLAC__NO_DLL 1
  80362. #if ! defined (SIZE_MAX)
  80363. #define SIZE_MAX 0xffffffff
  80364. #endif
  80365. #define __STDC_LIMIT_MACROS 1
  80366. /********* Start of inlined file: all.h *********/
  80367. #ifndef FLAC__ALL_H
  80368. #define FLAC__ALL_H
  80369. /********* Start of inlined file: export.h *********/
  80370. #ifndef FLAC__EXPORT_H
  80371. #define FLAC__EXPORT_H
  80372. /** \file include/FLAC/export.h
  80373. *
  80374. * \brief
  80375. * This module contains #defines and symbols for exporting function
  80376. * calls, and providing version information and compiled-in features.
  80377. *
  80378. * See the \link flac_export export \endlink module.
  80379. */
  80380. /** \defgroup flac_export FLAC/export.h: export symbols
  80381. * \ingroup flac
  80382. *
  80383. * \brief
  80384. * This module contains #defines and symbols for exporting function
  80385. * calls, and providing version information and compiled-in features.
  80386. *
  80387. * If you are compiling with MSVC and will link to the static library
  80388. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  80389. * make sure the symbols are exported properly.
  80390. *
  80391. * \{
  80392. */
  80393. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  80394. #define FLAC_API
  80395. #else
  80396. #ifdef FLAC_API_EXPORTS
  80397. #define FLAC_API _declspec(dllexport)
  80398. #else
  80399. #define FLAC_API _declspec(dllimport)
  80400. #endif
  80401. #endif
  80402. /** These #defines will mirror the libtool-based library version number, see
  80403. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  80404. */
  80405. #define FLAC_API_VERSION_CURRENT 10
  80406. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  80407. #define FLAC_API_VERSION_AGE 2 /**< see above */
  80408. #ifdef __cplusplus
  80409. extern "C" {
  80410. #endif
  80411. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  80412. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  80413. #ifdef __cplusplus
  80414. }
  80415. #endif
  80416. /* \} */
  80417. #endif
  80418. /********* End of inlined file: export.h *********/
  80419. /********* Start of inlined file: assert.h *********/
  80420. #ifndef FLAC__ASSERT_H
  80421. #define FLAC__ASSERT_H
  80422. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  80423. #ifdef DEBUG
  80424. #include <assert.h>
  80425. #define FLAC__ASSERT(x) assert(x)
  80426. #define FLAC__ASSERT_DECLARATION(x) x
  80427. #else
  80428. #define FLAC__ASSERT(x)
  80429. #define FLAC__ASSERT_DECLARATION(x)
  80430. #endif
  80431. #endif
  80432. /********* End of inlined file: assert.h *********/
  80433. /********* Start of inlined file: callback.h *********/
  80434. #ifndef FLAC__CALLBACK_H
  80435. #define FLAC__CALLBACK_H
  80436. /********* Start of inlined file: ordinals.h *********/
  80437. #ifndef FLAC__ORDINALS_H
  80438. #define FLAC__ORDINALS_H
  80439. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  80440. #include <inttypes.h>
  80441. #endif
  80442. typedef signed char FLAC__int8;
  80443. typedef unsigned char FLAC__uint8;
  80444. #if defined(_MSC_VER) || defined(__BORLANDC__)
  80445. typedef __int16 FLAC__int16;
  80446. typedef __int32 FLAC__int32;
  80447. typedef __int64 FLAC__int64;
  80448. typedef unsigned __int16 FLAC__uint16;
  80449. typedef unsigned __int32 FLAC__uint32;
  80450. typedef unsigned __int64 FLAC__uint64;
  80451. #elif defined(__EMX__)
  80452. typedef short FLAC__int16;
  80453. typedef long FLAC__int32;
  80454. typedef long long FLAC__int64;
  80455. typedef unsigned short FLAC__uint16;
  80456. typedef unsigned long FLAC__uint32;
  80457. typedef unsigned long long FLAC__uint64;
  80458. #else
  80459. typedef int16_t FLAC__int16;
  80460. typedef int32_t FLAC__int32;
  80461. typedef int64_t FLAC__int64;
  80462. typedef uint16_t FLAC__uint16;
  80463. typedef uint32_t FLAC__uint32;
  80464. typedef uint64_t FLAC__uint64;
  80465. #endif
  80466. typedef int FLAC__bool;
  80467. typedef FLAC__uint8 FLAC__byte;
  80468. #ifdef true
  80469. #undef true
  80470. #endif
  80471. #ifdef false
  80472. #undef false
  80473. #endif
  80474. #ifndef __cplusplus
  80475. #define true 1
  80476. #define false 0
  80477. #endif
  80478. #endif
  80479. /********* End of inlined file: ordinals.h *********/
  80480. #include <stdlib.h> /* for size_t */
  80481. /** \file include/FLAC/callback.h
  80482. *
  80483. * \brief
  80484. * This module defines the structures for describing I/O callbacks
  80485. * to the other FLAC interfaces.
  80486. *
  80487. * See the detailed documentation for callbacks in the
  80488. * \link flac_callbacks callbacks \endlink module.
  80489. */
  80490. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  80491. * \ingroup flac
  80492. *
  80493. * \brief
  80494. * This module defines the structures for describing I/O callbacks
  80495. * to the other FLAC interfaces.
  80496. *
  80497. * The purpose of the I/O callback functions is to create a common way
  80498. * for the metadata interfaces to handle I/O.
  80499. *
  80500. * Originally the metadata interfaces required filenames as the way of
  80501. * specifying FLAC files to operate on. This is problematic in some
  80502. * environments so there is an additional option to specify a set of
  80503. * callbacks for doing I/O on the FLAC file, instead of the filename.
  80504. *
  80505. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  80506. * opaque structure for a data source.
  80507. *
  80508. * The callback function prototypes are similar (but not identical) to the
  80509. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  80510. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  80511. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  80512. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  80513. * is required. \warning You generally CANNOT directly use fseek or ftell
  80514. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  80515. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  80516. * large files. You will have to find an equivalent function (e.g. ftello),
  80517. * or write a wrapper. The same is true for feof() since this is usually
  80518. * implemented as a macro, not as a function whose address can be taken.
  80519. *
  80520. * \{
  80521. */
  80522. #ifdef __cplusplus
  80523. extern "C" {
  80524. #endif
  80525. /** This is the opaque handle type used by the callbacks. Typically
  80526. * this is a \c FILE* or address of a file descriptor.
  80527. */
  80528. typedef void* FLAC__IOHandle;
  80529. /** Signature for the read callback.
  80530. * The signature and semantics match POSIX fread() implementations
  80531. * and can generally be used interchangeably.
  80532. *
  80533. * \param ptr The address of the read buffer.
  80534. * \param size The size of the records to be read.
  80535. * \param nmemb The number of records to be read.
  80536. * \param handle The handle to the data source.
  80537. * \retval size_t
  80538. * The number of records read.
  80539. */
  80540. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  80541. /** Signature for the write callback.
  80542. * The signature and semantics match POSIX fwrite() implementations
  80543. * and can generally be used interchangeably.
  80544. *
  80545. * \param ptr The address of the write buffer.
  80546. * \param size The size of the records to be written.
  80547. * \param nmemb The number of records to be written.
  80548. * \param handle The handle to the data source.
  80549. * \retval size_t
  80550. * The number of records written.
  80551. */
  80552. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  80553. /** Signature for the seek callback.
  80554. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  80555. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  80556. * and 32-bits wide.
  80557. *
  80558. * \param handle The handle to the data source.
  80559. * \param offset The new position, relative to \a whence
  80560. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  80561. * \retval int
  80562. * \c 0 on success, \c -1 on error.
  80563. */
  80564. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  80565. /** Signature for the tell callback.
  80566. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  80567. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  80568. * and 32-bits wide.
  80569. *
  80570. * \param handle The handle to the data source.
  80571. * \retval FLAC__int64
  80572. * The current position on success, \c -1 on error.
  80573. */
  80574. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  80575. /** Signature for the EOF callback.
  80576. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  80577. * on many systems, feof() is a macro, so in this case a wrapper function
  80578. * must be provided instead.
  80579. *
  80580. * \param handle The handle to the data source.
  80581. * \retval int
  80582. * \c 0 if not at end of file, nonzero if at end of file.
  80583. */
  80584. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  80585. /** Signature for the close callback.
  80586. * The signature and semantics match POSIX fclose() implementations
  80587. * and can generally be used interchangeably.
  80588. *
  80589. * \param handle The handle to the data source.
  80590. * \retval int
  80591. * \c 0 on success, \c EOF on error.
  80592. */
  80593. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  80594. /** A structure for holding a set of callbacks.
  80595. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  80596. * describe which of the callbacks are required. The ones that are not
  80597. * required may be set to NULL.
  80598. *
  80599. * If the seek requirement for an interface is optional, you can signify that
  80600. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  80601. */
  80602. typedef struct {
  80603. FLAC__IOCallback_Read read;
  80604. FLAC__IOCallback_Write write;
  80605. FLAC__IOCallback_Seek seek;
  80606. FLAC__IOCallback_Tell tell;
  80607. FLAC__IOCallback_Eof eof;
  80608. FLAC__IOCallback_Close close;
  80609. } FLAC__IOCallbacks;
  80610. /* \} */
  80611. #ifdef __cplusplus
  80612. }
  80613. #endif
  80614. #endif
  80615. /********* End of inlined file: callback.h *********/
  80616. /********* Start of inlined file: format.h *********/
  80617. #ifndef FLAC__FORMAT_H
  80618. #define FLAC__FORMAT_H
  80619. #ifdef __cplusplus
  80620. extern "C" {
  80621. #endif
  80622. /** \file include/FLAC/format.h
  80623. *
  80624. * \brief
  80625. * This module contains structure definitions for the representation
  80626. * of FLAC format components in memory. These are the basic
  80627. * structures used by the rest of the interfaces.
  80628. *
  80629. * See the detailed documentation in the
  80630. * \link flac_format format \endlink module.
  80631. */
  80632. /** \defgroup flac_format FLAC/format.h: format components
  80633. * \ingroup flac
  80634. *
  80635. * \brief
  80636. * This module contains structure definitions for the representation
  80637. * of FLAC format components in memory. These are the basic
  80638. * structures used by the rest of the interfaces.
  80639. *
  80640. * First, you should be familiar with the
  80641. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  80642. * follow directly from the specification. As a user of libFLAC, the
  80643. * interesting parts really are the structures that describe the frame
  80644. * header and metadata blocks.
  80645. *
  80646. * The format structures here are very primitive, designed to store
  80647. * information in an efficient way. Reading information from the
  80648. * structures is easy but creating or modifying them directly is
  80649. * more complex. For the most part, as a user of a library, editing
  80650. * is not necessary; however, for metadata blocks it is, so there are
  80651. * convenience functions provided in the \link flac_metadata metadata
  80652. * module \endlink to simplify the manipulation of metadata blocks.
  80653. *
  80654. * \note
  80655. * It's not the best convention, but symbols ending in _LEN are in bits
  80656. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  80657. * global variables because they are usually used when declaring byte
  80658. * arrays and some compilers require compile-time knowledge of array
  80659. * sizes when declared on the stack.
  80660. *
  80661. * \{
  80662. */
  80663. /*
  80664. Most of the values described in this file are defined by the FLAC
  80665. format specification. There is nothing to tune here.
  80666. */
  80667. /** The largest legal metadata type code. */
  80668. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  80669. /** The minimum block size, in samples, permitted by the format. */
  80670. #define FLAC__MIN_BLOCK_SIZE (16u)
  80671. /** The maximum block size, in samples, permitted by the format. */
  80672. #define FLAC__MAX_BLOCK_SIZE (65535u)
  80673. /** The maximum block size, in samples, permitted by the FLAC subset for
  80674. * sample rates up to 48kHz. */
  80675. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  80676. /** The maximum number of channels permitted by the format. */
  80677. #define FLAC__MAX_CHANNELS (8u)
  80678. /** The minimum sample resolution permitted by the format. */
  80679. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  80680. /** The maximum sample resolution permitted by the format. */
  80681. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  80682. /** The maximum sample resolution permitted by libFLAC.
  80683. *
  80684. * \warning
  80685. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  80686. * the reference encoder/decoder is currently limited to 24 bits because
  80687. * of prevalent 32-bit math, so make sure and use this value when
  80688. * appropriate.
  80689. */
  80690. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  80691. /** The maximum sample rate permitted by the format. The value is
  80692. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  80693. * as to why.
  80694. */
  80695. #define FLAC__MAX_SAMPLE_RATE (655350u)
  80696. /** The maximum LPC order permitted by the format. */
  80697. #define FLAC__MAX_LPC_ORDER (32u)
  80698. /** The maximum LPC order permitted by the FLAC subset for sample rates
  80699. * up to 48kHz. */
  80700. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  80701. /** The minimum quantized linear predictor coefficient precision
  80702. * permitted by the format.
  80703. */
  80704. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  80705. /** The maximum quantized linear predictor coefficient precision
  80706. * permitted by the format.
  80707. */
  80708. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  80709. /** The maximum order of the fixed predictors permitted by the format. */
  80710. #define FLAC__MAX_FIXED_ORDER (4u)
  80711. /** The maximum Rice partition order permitted by the format. */
  80712. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  80713. /** The maximum Rice partition order permitted by the FLAC Subset. */
  80714. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  80715. /** The version string of the release, stamped onto the libraries and binaries.
  80716. *
  80717. * \note
  80718. * This does not correspond to the shared library version number, which
  80719. * is used to determine binary compatibility.
  80720. */
  80721. extern FLAC_API const char *FLAC__VERSION_STRING;
  80722. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  80723. * This is a NUL-terminated ASCII string; when inserted into the
  80724. * VORBIS_COMMENT the trailing null is stripped.
  80725. */
  80726. extern FLAC_API const char *FLAC__VENDOR_STRING;
  80727. /** The byte string representation of the beginning of a FLAC stream. */
  80728. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  80729. /** The 32-bit integer big-endian representation of the beginning of
  80730. * a FLAC stream.
  80731. */
  80732. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  80733. /** The length of the FLAC signature in bits. */
  80734. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  80735. /** The length of the FLAC signature in bytes. */
  80736. #define FLAC__STREAM_SYNC_LENGTH (4u)
  80737. /*****************************************************************************
  80738. *
  80739. * Subframe structures
  80740. *
  80741. *****************************************************************************/
  80742. /*****************************************************************************/
  80743. /** An enumeration of the available entropy coding methods. */
  80744. typedef enum {
  80745. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  80746. /**< Residual is coded by partitioning into contexts, each with it's own
  80747. * 4-bit Rice parameter. */
  80748. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  80749. /**< Residual is coded by partitioning into contexts, each with it's own
  80750. * 5-bit Rice parameter. */
  80751. } FLAC__EntropyCodingMethodType;
  80752. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  80753. *
  80754. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  80755. * give the string equivalent. The contents should not be modified.
  80756. */
  80757. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  80758. /** Contents of a Rice partitioned residual
  80759. */
  80760. typedef struct {
  80761. unsigned *parameters;
  80762. /**< The Rice parameters for each context. */
  80763. unsigned *raw_bits;
  80764. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  80765. * partitions and zero for unescaped partitions.
  80766. */
  80767. unsigned capacity_by_order;
  80768. /**< The capacity of the \a parameters and \a raw_bits arrays
  80769. * specified as an order, i.e. the number of array elements
  80770. * allocated is 2 ^ \a capacity_by_order.
  80771. */
  80772. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  80773. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  80774. */
  80775. typedef struct {
  80776. unsigned order;
  80777. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  80778. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  80779. /**< The context's Rice parameters and/or raw bits. */
  80780. } FLAC__EntropyCodingMethod_PartitionedRice;
  80781. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  80782. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  80783. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  80784. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  80785. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  80786. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  80787. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  80788. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  80789. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  80790. */
  80791. typedef struct {
  80792. FLAC__EntropyCodingMethodType type;
  80793. union {
  80794. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  80795. } data;
  80796. } FLAC__EntropyCodingMethod;
  80797. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  80798. /*****************************************************************************/
  80799. /** An enumeration of the available subframe types. */
  80800. typedef enum {
  80801. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  80802. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  80803. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  80804. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  80805. } FLAC__SubframeType;
  80806. /** Maps a FLAC__SubframeType to a C string.
  80807. *
  80808. * Using a FLAC__SubframeType as the index to this array will
  80809. * give the string equivalent. The contents should not be modified.
  80810. */
  80811. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  80812. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  80813. */
  80814. typedef struct {
  80815. FLAC__int32 value; /**< The constant signal value. */
  80816. } FLAC__Subframe_Constant;
  80817. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  80818. */
  80819. typedef struct {
  80820. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  80821. } FLAC__Subframe_Verbatim;
  80822. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  80823. */
  80824. typedef struct {
  80825. FLAC__EntropyCodingMethod entropy_coding_method;
  80826. /**< The residual coding method. */
  80827. unsigned order;
  80828. /**< The polynomial order. */
  80829. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  80830. /**< Warmup samples to prime the predictor, length == order. */
  80831. const FLAC__int32 *residual;
  80832. /**< The residual signal, length == (blocksize minus order) samples. */
  80833. } FLAC__Subframe_Fixed;
  80834. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  80835. */
  80836. typedef struct {
  80837. FLAC__EntropyCodingMethod entropy_coding_method;
  80838. /**< The residual coding method. */
  80839. unsigned order;
  80840. /**< The FIR order. */
  80841. unsigned qlp_coeff_precision;
  80842. /**< Quantized FIR filter coefficient precision in bits. */
  80843. int quantization_level;
  80844. /**< The qlp coeff shift needed. */
  80845. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  80846. /**< FIR filter coefficients. */
  80847. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  80848. /**< Warmup samples to prime the predictor, length == order. */
  80849. const FLAC__int32 *residual;
  80850. /**< The residual signal, length == (blocksize minus order) samples. */
  80851. } FLAC__Subframe_LPC;
  80852. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  80853. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  80854. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  80855. */
  80856. typedef struct {
  80857. FLAC__SubframeType type;
  80858. union {
  80859. FLAC__Subframe_Constant constant;
  80860. FLAC__Subframe_Fixed fixed;
  80861. FLAC__Subframe_LPC lpc;
  80862. FLAC__Subframe_Verbatim verbatim;
  80863. } data;
  80864. unsigned wasted_bits;
  80865. } FLAC__Subframe;
  80866. /** == 1 (bit)
  80867. *
  80868. * This used to be a zero-padding bit (hence the name
  80869. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  80870. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  80871. * to mean something else.
  80872. */
  80873. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  80874. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  80875. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  80876. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  80877. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  80878. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  80879. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  80880. /*****************************************************************************/
  80881. /*****************************************************************************
  80882. *
  80883. * Frame structures
  80884. *
  80885. *****************************************************************************/
  80886. /** An enumeration of the available channel assignments. */
  80887. typedef enum {
  80888. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  80889. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  80890. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  80891. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  80892. } FLAC__ChannelAssignment;
  80893. /** Maps a FLAC__ChannelAssignment to a C string.
  80894. *
  80895. * Using a FLAC__ChannelAssignment as the index to this array will
  80896. * give the string equivalent. The contents should not be modified.
  80897. */
  80898. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  80899. /** An enumeration of the possible frame numbering methods. */
  80900. typedef enum {
  80901. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  80902. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  80903. } FLAC__FrameNumberType;
  80904. /** Maps a FLAC__FrameNumberType to a C string.
  80905. *
  80906. * Using a FLAC__FrameNumberType as the index to this array will
  80907. * give the string equivalent. The contents should not be modified.
  80908. */
  80909. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  80910. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  80911. */
  80912. typedef struct {
  80913. unsigned blocksize;
  80914. /**< The number of samples per subframe. */
  80915. unsigned sample_rate;
  80916. /**< The sample rate in Hz. */
  80917. unsigned channels;
  80918. /**< The number of channels (== number of subframes). */
  80919. FLAC__ChannelAssignment channel_assignment;
  80920. /**< The channel assignment for the frame. */
  80921. unsigned bits_per_sample;
  80922. /**< The sample resolution. */
  80923. FLAC__FrameNumberType number_type;
  80924. /**< The numbering scheme used for the frame. As a convenience, the
  80925. * decoder will always convert a frame number to a sample number because
  80926. * the rules are complex. */
  80927. union {
  80928. FLAC__uint32 frame_number;
  80929. FLAC__uint64 sample_number;
  80930. } number;
  80931. /**< The frame number or sample number of first sample in frame;
  80932. * use the \a number_type value to determine which to use. */
  80933. FLAC__uint8 crc;
  80934. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  80935. * of the raw frame header bytes, meaning everything before the CRC byte
  80936. * including the sync code.
  80937. */
  80938. } FLAC__FrameHeader;
  80939. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  80940. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  80941. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  80942. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  80943. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  80944. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  80945. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  80946. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  80947. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  80948. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  80949. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  80950. */
  80951. typedef struct {
  80952. FLAC__uint16 crc;
  80953. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  80954. * 0) of the bytes before the crc, back to and including the frame header
  80955. * sync code.
  80956. */
  80957. } FLAC__FrameFooter;
  80958. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  80959. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  80960. */
  80961. typedef struct {
  80962. FLAC__FrameHeader header;
  80963. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  80964. FLAC__FrameFooter footer;
  80965. } FLAC__Frame;
  80966. /*****************************************************************************/
  80967. /*****************************************************************************
  80968. *
  80969. * Meta-data structures
  80970. *
  80971. *****************************************************************************/
  80972. /** An enumeration of the available metadata block types. */
  80973. typedef enum {
  80974. FLAC__METADATA_TYPE_STREAMINFO = 0,
  80975. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  80976. FLAC__METADATA_TYPE_PADDING = 1,
  80977. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  80978. FLAC__METADATA_TYPE_APPLICATION = 2,
  80979. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  80980. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  80981. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  80982. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  80983. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  80984. FLAC__METADATA_TYPE_CUESHEET = 5,
  80985. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  80986. FLAC__METADATA_TYPE_PICTURE = 6,
  80987. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  80988. FLAC__METADATA_TYPE_UNDEFINED = 7
  80989. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  80990. } FLAC__MetadataType;
  80991. /** Maps a FLAC__MetadataType to a C string.
  80992. *
  80993. * Using a FLAC__MetadataType as the index to this array will
  80994. * give the string equivalent. The contents should not be modified.
  80995. */
  80996. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  80997. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  80998. */
  80999. typedef struct {
  81000. unsigned min_blocksize, max_blocksize;
  81001. unsigned min_framesize, max_framesize;
  81002. unsigned sample_rate;
  81003. unsigned channels;
  81004. unsigned bits_per_sample;
  81005. FLAC__uint64 total_samples;
  81006. FLAC__byte md5sum[16];
  81007. } FLAC__StreamMetadata_StreamInfo;
  81008. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  81009. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  81010. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  81011. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  81012. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  81013. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  81014. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  81015. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  81016. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  81017. /** The total stream length of the STREAMINFO block in bytes. */
  81018. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  81019. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  81020. */
  81021. typedef struct {
  81022. int dummy;
  81023. /**< Conceptually this is an empty struct since we don't store the
  81024. * padding bytes. Empty structs are not allowed by some C compilers,
  81025. * hence the dummy.
  81026. */
  81027. } FLAC__StreamMetadata_Padding;
  81028. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  81029. */
  81030. typedef struct {
  81031. FLAC__byte id[4];
  81032. FLAC__byte *data;
  81033. } FLAC__StreamMetadata_Application;
  81034. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  81035. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  81036. */
  81037. typedef struct {
  81038. FLAC__uint64 sample_number;
  81039. /**< The sample number of the target frame. */
  81040. FLAC__uint64 stream_offset;
  81041. /**< The offset, in bytes, of the target frame with respect to
  81042. * beginning of the first frame. */
  81043. unsigned frame_samples;
  81044. /**< The number of samples in the target frame. */
  81045. } FLAC__StreamMetadata_SeekPoint;
  81046. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  81047. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  81048. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  81049. /** The total stream length of a seek point in bytes. */
  81050. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  81051. /** The value used in the \a sample_number field of
  81052. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  81053. * point (== 0xffffffffffffffff).
  81054. */
  81055. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  81056. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  81057. *
  81058. * \note From the format specification:
  81059. * - The seek points must be sorted by ascending sample number.
  81060. * - Each seek point's sample number must be the first sample of the
  81061. * target frame.
  81062. * - Each seek point's sample number must be unique within the table.
  81063. * - Existence of a SEEKTABLE block implies a correct setting of
  81064. * total_samples in the stream_info block.
  81065. * - Behavior is undefined when more than one SEEKTABLE block is
  81066. * present in a stream.
  81067. */
  81068. typedef struct {
  81069. unsigned num_points;
  81070. FLAC__StreamMetadata_SeekPoint *points;
  81071. } FLAC__StreamMetadata_SeekTable;
  81072. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  81073. *
  81074. * For convenience, the APIs maintain a trailing NUL character at the end of
  81075. * \a entry which is not counted toward \a length, i.e.
  81076. * \code strlen(entry) == length \endcode
  81077. */
  81078. typedef struct {
  81079. FLAC__uint32 length;
  81080. FLAC__byte *entry;
  81081. } FLAC__StreamMetadata_VorbisComment_Entry;
  81082. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  81083. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  81084. */
  81085. typedef struct {
  81086. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  81087. FLAC__uint32 num_comments;
  81088. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  81089. } FLAC__StreamMetadata_VorbisComment;
  81090. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  81091. /** FLAC CUESHEET track index structure. (See the
  81092. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  81093. * the full description of each field.)
  81094. */
  81095. typedef struct {
  81096. FLAC__uint64 offset;
  81097. /**< Offset in samples, relative to the track offset, of the index
  81098. * point.
  81099. */
  81100. FLAC__byte number;
  81101. /**< The index point number. */
  81102. } FLAC__StreamMetadata_CueSheet_Index;
  81103. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  81104. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  81105. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  81106. /** FLAC CUESHEET track structure. (See the
  81107. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  81108. * the full description of each field.)
  81109. */
  81110. typedef struct {
  81111. FLAC__uint64 offset;
  81112. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  81113. FLAC__byte number;
  81114. /**< The track number. */
  81115. char isrc[13];
  81116. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  81117. unsigned type:1;
  81118. /**< The track type: 0 for audio, 1 for non-audio. */
  81119. unsigned pre_emphasis:1;
  81120. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  81121. FLAC__byte num_indices;
  81122. /**< The number of track index points. */
  81123. FLAC__StreamMetadata_CueSheet_Index *indices;
  81124. /**< NULL if num_indices == 0, else pointer to array of index points. */
  81125. } FLAC__StreamMetadata_CueSheet_Track;
  81126. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  81127. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  81128. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  81129. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  81130. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  81131. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  81132. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  81133. /** FLAC CUESHEET structure. (See the
  81134. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  81135. * for the full description of each field.)
  81136. */
  81137. typedef struct {
  81138. char media_catalog_number[129];
  81139. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  81140. * general, the media catalog number may be 0 to 128 bytes long; any
  81141. * unused characters should be right-padded with NUL characters.
  81142. */
  81143. FLAC__uint64 lead_in;
  81144. /**< The number of lead-in samples. */
  81145. FLAC__bool is_cd;
  81146. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  81147. unsigned num_tracks;
  81148. /**< The number of tracks. */
  81149. FLAC__StreamMetadata_CueSheet_Track *tracks;
  81150. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  81151. } FLAC__StreamMetadata_CueSheet;
  81152. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  81153. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  81154. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  81155. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  81156. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  81157. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  81158. typedef enum {
  81159. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  81160. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  81161. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  81162. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  81163. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  81164. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  81165. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  81166. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  81167. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  81168. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  81169. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  81170. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  81171. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  81172. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  81173. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  81174. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  81175. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  81176. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  81177. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  81178. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  81179. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  81180. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  81181. } FLAC__StreamMetadata_Picture_Type;
  81182. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  81183. *
  81184. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  81185. * will give the string equivalent. The contents should not be
  81186. * modified.
  81187. */
  81188. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  81189. /** FLAC PICTURE structure. (See the
  81190. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  81191. * for the full description of each field.)
  81192. */
  81193. typedef struct {
  81194. FLAC__StreamMetadata_Picture_Type type;
  81195. /**< The kind of picture stored. */
  81196. char *mime_type;
  81197. /**< Picture data's MIME type, in ASCII printable characters
  81198. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  81199. * use picture data of MIME type \c image/jpeg or \c image/png. A
  81200. * MIME type of '-->' is also allowed, in which case the picture
  81201. * data should be a complete URL. In file storage, the MIME type is
  81202. * stored as a 32-bit length followed by the ASCII string with no NUL
  81203. * terminator, but is converted to a plain C string in this structure
  81204. * for convenience.
  81205. */
  81206. FLAC__byte *description;
  81207. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  81208. * the description is stored as a 32-bit length followed by the UTF-8
  81209. * string with no NUL terminator, but is converted to a plain C string
  81210. * in this structure for convenience.
  81211. */
  81212. FLAC__uint32 width;
  81213. /**< Picture's width in pixels. */
  81214. FLAC__uint32 height;
  81215. /**< Picture's height in pixels. */
  81216. FLAC__uint32 depth;
  81217. /**< Picture's color depth in bits-per-pixel. */
  81218. FLAC__uint32 colors;
  81219. /**< For indexed palettes (like GIF), picture's number of colors (the
  81220. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  81221. */
  81222. FLAC__uint32 data_length;
  81223. /**< Length of binary picture data in bytes. */
  81224. FLAC__byte *data;
  81225. /**< Binary picture data. */
  81226. } FLAC__StreamMetadata_Picture;
  81227. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  81228. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  81229. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  81230. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  81231. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  81232. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  81233. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  81234. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  81235. /** Structure that is used when a metadata block of unknown type is loaded.
  81236. * The contents are opaque. The structure is used only internally to
  81237. * correctly handle unknown metadata.
  81238. */
  81239. typedef struct {
  81240. FLAC__byte *data;
  81241. } FLAC__StreamMetadata_Unknown;
  81242. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  81243. */
  81244. typedef struct {
  81245. FLAC__MetadataType type;
  81246. /**< The type of the metadata block; used determine which member of the
  81247. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  81248. * then \a data.unknown must be used. */
  81249. FLAC__bool is_last;
  81250. /**< \c true if this metadata block is the last, else \a false */
  81251. unsigned length;
  81252. /**< Length, in bytes, of the block data as it appears in the stream. */
  81253. union {
  81254. FLAC__StreamMetadata_StreamInfo stream_info;
  81255. FLAC__StreamMetadata_Padding padding;
  81256. FLAC__StreamMetadata_Application application;
  81257. FLAC__StreamMetadata_SeekTable seek_table;
  81258. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  81259. FLAC__StreamMetadata_CueSheet cue_sheet;
  81260. FLAC__StreamMetadata_Picture picture;
  81261. FLAC__StreamMetadata_Unknown unknown;
  81262. } data;
  81263. /**< Polymorphic block data; use the \a type value to determine which
  81264. * to use. */
  81265. } FLAC__StreamMetadata;
  81266. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  81267. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  81268. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  81269. /** The total stream length of a metadata block header in bytes. */
  81270. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  81271. /*****************************************************************************/
  81272. /*****************************************************************************
  81273. *
  81274. * Utility functions
  81275. *
  81276. *****************************************************************************/
  81277. /** Tests that a sample rate is valid for FLAC.
  81278. *
  81279. * \param sample_rate The sample rate to test for compliance.
  81280. * \retval FLAC__bool
  81281. * \c true if the given sample rate conforms to the specification, else
  81282. * \c false.
  81283. */
  81284. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  81285. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  81286. * for valid sample rates are slightly more complex since the rate has to
  81287. * be expressible completely in the frame header.
  81288. *
  81289. * \param sample_rate The sample rate to test for compliance.
  81290. * \retval FLAC__bool
  81291. * \c true if the given sample rate conforms to the specification for the
  81292. * subset, else \c false.
  81293. */
  81294. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  81295. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  81296. * comment specification.
  81297. *
  81298. * Vorbis comment names must be composed only of characters from
  81299. * [0x20-0x3C,0x3E-0x7D].
  81300. *
  81301. * \param name A NUL-terminated string to be checked.
  81302. * \assert
  81303. * \code name != NULL \endcode
  81304. * \retval FLAC__bool
  81305. * \c false if entry name is illegal, else \c true.
  81306. */
  81307. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  81308. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  81309. * comment specification.
  81310. *
  81311. * Vorbis comment values must be valid UTF-8 sequences.
  81312. *
  81313. * \param value A string to be checked.
  81314. * \param length A the length of \a value in bytes. May be
  81315. * \c (unsigned)(-1) to indicate that \a value is a plain
  81316. * UTF-8 NUL-terminated string.
  81317. * \assert
  81318. * \code value != NULL \endcode
  81319. * \retval FLAC__bool
  81320. * \c false if entry name is illegal, else \c true.
  81321. */
  81322. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  81323. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  81324. * comment specification.
  81325. *
  81326. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  81327. * 'value' must be legal according to
  81328. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  81329. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  81330. *
  81331. * \param entry An entry to be checked.
  81332. * \param length The length of \a entry in bytes.
  81333. * \assert
  81334. * \code value != NULL \endcode
  81335. * \retval FLAC__bool
  81336. * \c false if entry name is illegal, else \c true.
  81337. */
  81338. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  81339. /** Check a seek table to see if it conforms to the FLAC specification.
  81340. * See the format specification for limits on the contents of the
  81341. * seek table.
  81342. *
  81343. * \param seek_table A pointer to a seek table to be checked.
  81344. * \assert
  81345. * \code seek_table != NULL \endcode
  81346. * \retval FLAC__bool
  81347. * \c false if seek table is illegal, else \c true.
  81348. */
  81349. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  81350. /** Sort a seek table's seek points according to the format specification.
  81351. * This includes a "unique-ification" step to remove duplicates, i.e.
  81352. * seek points with identical \a sample_number values. Duplicate seek
  81353. * points are converted into placeholder points and sorted to the end of
  81354. * the table.
  81355. *
  81356. * \param seek_table A pointer to a seek table to be sorted.
  81357. * \assert
  81358. * \code seek_table != NULL \endcode
  81359. * \retval unsigned
  81360. * The number of duplicate seek points converted into placeholders.
  81361. */
  81362. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  81363. /** Check a cue sheet to see if it conforms to the FLAC specification.
  81364. * See the format specification for limits on the contents of the
  81365. * cue sheet.
  81366. *
  81367. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  81368. * \param check_cd_da_subset If \c true, check CUESHEET against more
  81369. * stringent requirements for a CD-DA (audio) disc.
  81370. * \param violation Address of a pointer to a string. If there is a
  81371. * violation, a pointer to a string explanation of the
  81372. * violation will be returned here. \a violation may be
  81373. * \c NULL if you don't need the returned string. Do not
  81374. * free the returned string; it will always point to static
  81375. * data.
  81376. * \assert
  81377. * \code cue_sheet != NULL \endcode
  81378. * \retval FLAC__bool
  81379. * \c false if cue sheet is illegal, else \c true.
  81380. */
  81381. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  81382. /** Check picture data to see if it conforms to the FLAC specification.
  81383. * See the format specification for limits on the contents of the
  81384. * PICTURE block.
  81385. *
  81386. * \param picture A pointer to existing picture data to be checked.
  81387. * \param violation Address of a pointer to a string. If there is a
  81388. * violation, a pointer to a string explanation of the
  81389. * violation will be returned here. \a violation may be
  81390. * \c NULL if you don't need the returned string. Do not
  81391. * free the returned string; it will always point to static
  81392. * data.
  81393. * \assert
  81394. * \code picture != NULL \endcode
  81395. * \retval FLAC__bool
  81396. * \c false if picture data is illegal, else \c true.
  81397. */
  81398. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  81399. /* \} */
  81400. #ifdef __cplusplus
  81401. }
  81402. #endif
  81403. #endif
  81404. /********* End of inlined file: format.h *********/
  81405. /********* Start of inlined file: metadata.h *********/
  81406. #ifndef FLAC__METADATA_H
  81407. #define FLAC__METADATA_H
  81408. #include <sys/types.h> /* for off_t */
  81409. /* --------------------------------------------------------------------
  81410. (For an example of how all these routines are used, see the source
  81411. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  81412. metaflac in src/metaflac/)
  81413. ------------------------------------------------------------------*/
  81414. /** \file include/FLAC/metadata.h
  81415. *
  81416. * \brief
  81417. * This module provides functions for creating and manipulating FLAC
  81418. * metadata blocks in memory, and three progressively more powerful
  81419. * interfaces for traversing and editing metadata in FLAC files.
  81420. *
  81421. * See the detailed documentation for each interface in the
  81422. * \link flac_metadata metadata \endlink module.
  81423. */
  81424. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  81425. * \ingroup flac
  81426. *
  81427. * \brief
  81428. * This module provides functions for creating and manipulating FLAC
  81429. * metadata blocks in memory, and three progressively more powerful
  81430. * interfaces for traversing and editing metadata in native FLAC files.
  81431. * Note that currently only the Chain interface (level 2) supports Ogg
  81432. * FLAC files, and it is read-only i.e. no writing back changed
  81433. * metadata to file.
  81434. *
  81435. * There are three metadata interfaces of increasing complexity:
  81436. *
  81437. * Level 0:
  81438. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  81439. * PICTURE blocks.
  81440. *
  81441. * Level 1:
  81442. * Read-write access to all metadata blocks. This level is write-
  81443. * efficient in most cases (more on this below), and uses less memory
  81444. * than level 2.
  81445. *
  81446. * Level 2:
  81447. * Read-write access to all metadata blocks. This level is write-
  81448. * efficient in all cases, but uses more memory since all metadata for
  81449. * the whole file is read into memory and manipulated before writing
  81450. * out again.
  81451. *
  81452. * What do we mean by efficient? Since FLAC metadata appears at the
  81453. * beginning of the file, when writing metadata back to a FLAC file
  81454. * it is possible to grow or shrink the metadata such that the entire
  81455. * file must be rewritten. However, if the size remains the same during
  81456. * changes or PADDING blocks are utilized, only the metadata needs to be
  81457. * overwritten, which is much faster.
  81458. *
  81459. * Efficient means the whole file is rewritten at most one time, and only
  81460. * when necessary. Level 1 is not efficient only in the case that you
  81461. * cause more than one metadata block to grow or shrink beyond what can
  81462. * be accomodated by padding. In this case you should probably use level
  81463. * 2, which allows you to edit all the metadata for a file in memory and
  81464. * write it out all at once.
  81465. *
  81466. * All levels know how to skip over and not disturb an ID3v2 tag at the
  81467. * front of the file.
  81468. *
  81469. * All levels access files via their filenames. In addition, level 2
  81470. * has additional alternative read and write functions that take an I/O
  81471. * handle and callbacks, for situations where access by filename is not
  81472. * possible.
  81473. *
  81474. * In addition to the three interfaces, this module defines functions for
  81475. * creating and manipulating various metadata objects in memory. As we see
  81476. * from the Format module, FLAC metadata blocks in memory are very primitive
  81477. * structures for storing information in an efficient way. Reading
  81478. * information from the structures is easy but creating or modifying them
  81479. * directly is more complex. The metadata object routines here facilitate
  81480. * this by taking care of the consistency and memory management drudgery.
  81481. *
  81482. * Unless you will be using the level 1 or 2 interfaces to modify existing
  81483. * metadata however, you will not probably not need these.
  81484. *
  81485. * From a dependency standpoint, none of the encoders or decoders require
  81486. * the metadata module. This is so that embedded users can strip out the
  81487. * metadata module from libFLAC to reduce the size and complexity.
  81488. */
  81489. #ifdef __cplusplus
  81490. extern "C" {
  81491. #endif
  81492. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  81493. * \ingroup flac_metadata
  81494. *
  81495. * \brief
  81496. * The level 0 interface consists of individual routines to read the
  81497. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  81498. * only a filename.
  81499. *
  81500. * They try to skip any ID3v2 tag at the head of the file.
  81501. *
  81502. * \{
  81503. */
  81504. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  81505. * will try to skip any ID3v2 tag at the head of the file.
  81506. *
  81507. * \param filename The path to the FLAC file to read.
  81508. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  81509. * FLAC__StreamMetadata is a simple structure with no
  81510. * memory allocation involved, you pass the address of
  81511. * an existing structure. It need not be initialized.
  81512. * \assert
  81513. * \code filename != NULL \endcode
  81514. * \code streaminfo != NULL \endcode
  81515. * \retval FLAC__bool
  81516. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  81517. * \c false if there was a memory allocation error, a file decoder error,
  81518. * or the file contained no STREAMINFO block. (A memory allocation error
  81519. * is possible because this function must set up a file decoder.)
  81520. */
  81521. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  81522. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  81523. * function will try to skip any ID3v2 tag at the head of the file.
  81524. *
  81525. * \param filename The path to the FLAC file to read.
  81526. * \param tags The address where the returned pointer will be
  81527. * stored. The \a tags object must be deleted by
  81528. * the caller using FLAC__metadata_object_delete().
  81529. * \assert
  81530. * \code filename != NULL \endcode
  81531. * \code tags != NULL \endcode
  81532. * \retval FLAC__bool
  81533. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  81534. * and \a *tags will be set to the address of the metadata structure.
  81535. * Returns \c false if there was a memory allocation error, a file
  81536. * decoder error, or the file contained no VORBIS_COMMENT block, and
  81537. * \a *tags will be set to \c NULL.
  81538. */
  81539. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  81540. /** Read the CUESHEET metadata block of the given FLAC file. This
  81541. * function will try to skip any ID3v2 tag at the head of the file.
  81542. *
  81543. * \param filename The path to the FLAC file to read.
  81544. * \param cuesheet The address where the returned pointer will be
  81545. * stored. The \a cuesheet object must be deleted by
  81546. * the caller using FLAC__metadata_object_delete().
  81547. * \assert
  81548. * \code filename != NULL \endcode
  81549. * \code cuesheet != NULL \endcode
  81550. * \retval FLAC__bool
  81551. * \c true if a valid CUESHEET block was read from \a filename,
  81552. * and \a *cuesheet will be set to the address of the metadata
  81553. * structure. Returns \c false if there was a memory allocation
  81554. * error, a file decoder error, or the file contained no CUESHEET
  81555. * block, and \a *cuesheet will be set to \c NULL.
  81556. */
  81557. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  81558. /** Read a PICTURE metadata block of the given FLAC file. This
  81559. * function will try to skip any ID3v2 tag at the head of the file.
  81560. * Since there can be more than one PICTURE block in a file, this
  81561. * function takes a number of parameters that act as constraints to
  81562. * the search. The PICTURE block with the largest area matching all
  81563. * the constraints will be returned, or \a *picture will be set to
  81564. * \c NULL if there was no such block.
  81565. *
  81566. * \param filename The path to the FLAC file to read.
  81567. * \param picture The address where the returned pointer will be
  81568. * stored. The \a picture object must be deleted by
  81569. * the caller using FLAC__metadata_object_delete().
  81570. * \param type The desired picture type. Use \c -1 to mean
  81571. * "any type".
  81572. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  81573. * string will be matched exactly. Use \c NULL to
  81574. * mean "any MIME type".
  81575. * \param description The desired description. The string will be
  81576. * matched exactly. Use \c NULL to mean "any
  81577. * description".
  81578. * \param max_width The maximum width in pixels desired. Use
  81579. * \c (unsigned)(-1) to mean "any width".
  81580. * \param max_height The maximum height in pixels desired. Use
  81581. * \c (unsigned)(-1) to mean "any height".
  81582. * \param max_depth The maximum color depth in bits-per-pixel desired.
  81583. * Use \c (unsigned)(-1) to mean "any depth".
  81584. * \param max_colors The maximum number of colors desired. Use
  81585. * \c (unsigned)(-1) to mean "any number of colors".
  81586. * \assert
  81587. * \code filename != NULL \endcode
  81588. * \code picture != NULL \endcode
  81589. * \retval FLAC__bool
  81590. * \c true if a valid PICTURE block was read from \a filename,
  81591. * and \a *picture will be set to the address of the metadata
  81592. * structure. Returns \c false if there was a memory allocation
  81593. * error, a file decoder error, or the file contained no PICTURE
  81594. * block, and \a *picture will be set to \c NULL.
  81595. */
  81596. 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);
  81597. /* \} */
  81598. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  81599. * \ingroup flac_metadata
  81600. *
  81601. * \brief
  81602. * The level 1 interface provides read-write access to FLAC file metadata and
  81603. * operates directly on the FLAC file.
  81604. *
  81605. * The general usage of this interface is:
  81606. *
  81607. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  81608. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  81609. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  81610. * see if the file is writable, or only read access is allowed.
  81611. * - Use FLAC__metadata_simple_iterator_next() and
  81612. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  81613. * This is does not read the actual blocks themselves.
  81614. * FLAC__metadata_simple_iterator_next() is relatively fast.
  81615. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  81616. * forward from the front of the file.
  81617. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  81618. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  81619. * the current iterator position. The returned object is yours to modify
  81620. * and free.
  81621. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  81622. * back. You must have write permission to the original file. Make sure to
  81623. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  81624. * below.
  81625. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  81626. * Use the object creation functions from
  81627. * \link flac_metadata_object here \endlink to generate new objects.
  81628. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  81629. * currently referred to by the iterator, or replace it with padding.
  81630. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  81631. * finished.
  81632. *
  81633. * \note
  81634. * The FLAC file remains open the whole time between
  81635. * FLAC__metadata_simple_iterator_init() and
  81636. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  81637. * the file during this time.
  81638. *
  81639. * \note
  81640. * Do not modify the \a is_last, \a length, or \a type fields of returned
  81641. * FLAC__StreamMetadata objects. These are managed automatically.
  81642. *
  81643. * \note
  81644. * If any of the modification functions
  81645. * (FLAC__metadata_simple_iterator_set_block(),
  81646. * FLAC__metadata_simple_iterator_delete_block(),
  81647. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  81648. * you should delete the iterator as it may no longer be valid.
  81649. *
  81650. * \{
  81651. */
  81652. struct FLAC__Metadata_SimpleIterator;
  81653. /** The opaque structure definition for the level 1 iterator type.
  81654. * See the
  81655. * \link flac_metadata_level1 metadata level 1 module \endlink
  81656. * for a detailed description.
  81657. */
  81658. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  81659. /** Status type for FLAC__Metadata_SimpleIterator.
  81660. *
  81661. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  81662. */
  81663. typedef enum {
  81664. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  81665. /**< The iterator is in the normal OK state */
  81666. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  81667. /**< The data passed into a function violated the function's usage criteria */
  81668. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  81669. /**< The iterator could not open the target file */
  81670. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  81671. /**< The iterator could not find the FLAC signature at the start of the file */
  81672. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  81673. /**< The iterator tried to write to a file that was not writable */
  81674. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  81675. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  81676. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  81677. /**< The iterator encountered an error while reading the FLAC file */
  81678. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  81679. /**< The iterator encountered an error while seeking in the FLAC file */
  81680. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  81681. /**< The iterator encountered an error while writing the FLAC file */
  81682. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  81683. /**< The iterator encountered an error renaming the FLAC file */
  81684. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  81685. /**< The iterator encountered an error removing the temporary file */
  81686. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  81687. /**< Memory allocation failed */
  81688. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  81689. /**< The caller violated an assertion or an unexpected error occurred */
  81690. } FLAC__Metadata_SimpleIteratorStatus;
  81691. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  81692. *
  81693. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  81694. * will give the string equivalent. The contents should not be modified.
  81695. */
  81696. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  81697. /** Create a new iterator instance.
  81698. *
  81699. * \retval FLAC__Metadata_SimpleIterator*
  81700. * \c NULL if there was an error allocating memory, else the new instance.
  81701. */
  81702. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  81703. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  81704. *
  81705. * \param iterator A pointer to an existing iterator.
  81706. * \assert
  81707. * \code iterator != NULL \endcode
  81708. */
  81709. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  81710. /** Get the current status of the iterator. Call this after a function
  81711. * returns \c false to get the reason for the error. Also resets the status
  81712. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  81713. *
  81714. * \param iterator A pointer to an existing iterator.
  81715. * \assert
  81716. * \code iterator != NULL \endcode
  81717. * \retval FLAC__Metadata_SimpleIteratorStatus
  81718. * The current status of the iterator.
  81719. */
  81720. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  81721. /** Initialize the iterator to point to the first metadata block in the
  81722. * given FLAC file.
  81723. *
  81724. * \param iterator A pointer to an existing iterator.
  81725. * \param filename The path to the FLAC file.
  81726. * \param read_only If \c true, the FLAC file will be opened
  81727. * in read-only mode; if \c false, the FLAC
  81728. * file will be opened for edit even if no
  81729. * edits are performed.
  81730. * \param preserve_file_stats If \c true, the owner and modification
  81731. * time will be preserved even if the FLAC
  81732. * file is written to.
  81733. * \assert
  81734. * \code iterator != NULL \endcode
  81735. * \code filename != NULL \endcode
  81736. * \retval FLAC__bool
  81737. * \c false if a memory allocation error occurs, the file can't be
  81738. * opened, or another error occurs, else \c true.
  81739. */
  81740. 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);
  81741. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  81742. * FLAC__metadata_simple_iterator_set_block() and
  81743. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  81744. *
  81745. * \param iterator A pointer to an existing iterator.
  81746. * \assert
  81747. * \code iterator != NULL \endcode
  81748. * \retval FLAC__bool
  81749. * See above.
  81750. */
  81751. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  81752. /** Moves the iterator forward one metadata block, returning \c false if
  81753. * already at the end.
  81754. *
  81755. * \param iterator A pointer to an existing initialized iterator.
  81756. * \assert
  81757. * \code iterator != NULL \endcode
  81758. * \a iterator has been successfully initialized with
  81759. * FLAC__metadata_simple_iterator_init()
  81760. * \retval FLAC__bool
  81761. * \c false if already at the last metadata block of the chain, else
  81762. * \c true.
  81763. */
  81764. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  81765. /** Moves the iterator backward one metadata block, returning \c false if
  81766. * already at the beginning.
  81767. *
  81768. * \param iterator A pointer to an existing initialized iterator.
  81769. * \assert
  81770. * \code iterator != NULL \endcode
  81771. * \a iterator has been successfully initialized with
  81772. * FLAC__metadata_simple_iterator_init()
  81773. * \retval FLAC__bool
  81774. * \c false if already at the first metadata block of the chain, else
  81775. * \c true.
  81776. */
  81777. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  81778. /** Returns a flag telling if the current metadata block is the last.
  81779. *
  81780. * \param iterator A pointer to an existing initialized iterator.
  81781. * \assert
  81782. * \code iterator != NULL \endcode
  81783. * \a iterator has been successfully initialized with
  81784. * FLAC__metadata_simple_iterator_init()
  81785. * \retval FLAC__bool
  81786. * \c true if the current metadata block is the last in the file,
  81787. * else \c false.
  81788. */
  81789. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  81790. /** Get the offset of the metadata block at the current position. This
  81791. * avoids reading the actual block data which can save time for large
  81792. * blocks.
  81793. *
  81794. * \param iterator A pointer to an existing initialized iterator.
  81795. * \assert
  81796. * \code iterator != NULL \endcode
  81797. * \a iterator has been successfully initialized with
  81798. * FLAC__metadata_simple_iterator_init()
  81799. * \retval off_t
  81800. * The offset of the metadata block at the current iterator position.
  81801. * This is the byte offset relative to the beginning of the file of
  81802. * the current metadata block's header.
  81803. */
  81804. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  81805. /** Get the type of the metadata block at the current position. This
  81806. * avoids reading the actual block data which can save time for large
  81807. * blocks.
  81808. *
  81809. * \param iterator A pointer to an existing initialized iterator.
  81810. * \assert
  81811. * \code iterator != NULL \endcode
  81812. * \a iterator has been successfully initialized with
  81813. * FLAC__metadata_simple_iterator_init()
  81814. * \retval FLAC__MetadataType
  81815. * The type of the metadata block at the current iterator position.
  81816. */
  81817. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  81818. /** Get the length of the metadata block at the current position. This
  81819. * avoids reading the actual block data which can save time for large
  81820. * blocks.
  81821. *
  81822. * \param iterator A pointer to an existing initialized iterator.
  81823. * \assert
  81824. * \code iterator != NULL \endcode
  81825. * \a iterator has been successfully initialized with
  81826. * FLAC__metadata_simple_iterator_init()
  81827. * \retval unsigned
  81828. * The length of the metadata block at the current iterator position.
  81829. * The is same length as that in the
  81830. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  81831. * i.e. the length of the metadata body that follows the header.
  81832. */
  81833. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  81834. /** Get the application ID of the \c APPLICATION block at the current
  81835. * position. This avoids reading the actual block data which can save
  81836. * time for large blocks.
  81837. *
  81838. * \param iterator A pointer to an existing initialized iterator.
  81839. * \param id A pointer to a buffer of at least \c 4 bytes where
  81840. * the ID will be stored.
  81841. * \assert
  81842. * \code iterator != NULL \endcode
  81843. * \code id != NULL \endcode
  81844. * \a iterator has been successfully initialized with
  81845. * FLAC__metadata_simple_iterator_init()
  81846. * \retval FLAC__bool
  81847. * \c true if the ID was successfully read, else \c false, in which
  81848. * case you should check FLAC__metadata_simple_iterator_status() to
  81849. * find out why. If the status is
  81850. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  81851. * current metadata block is not an \c APPLICATION block. Otherwise
  81852. * if the status is
  81853. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  81854. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  81855. * occurred and the iterator can no longer be used.
  81856. */
  81857. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  81858. /** Get the metadata block at the current position. You can modify the
  81859. * block but must use FLAC__metadata_simple_iterator_set_block() to
  81860. * write it back to the FLAC file.
  81861. *
  81862. * You must call FLAC__metadata_object_delete() on the returned object
  81863. * when you are finished with it.
  81864. *
  81865. * \param iterator A pointer to an existing initialized iterator.
  81866. * \assert
  81867. * \code iterator != NULL \endcode
  81868. * \a iterator has been successfully initialized with
  81869. * FLAC__metadata_simple_iterator_init()
  81870. * \retval FLAC__StreamMetadata*
  81871. * The current metadata block, or \c NULL if there was a memory
  81872. * allocation error.
  81873. */
  81874. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  81875. /** Write a block back to the FLAC file. This function tries to be
  81876. * as efficient as possible; how the block is actually written is
  81877. * shown by the following:
  81878. *
  81879. * Existing block is a STREAMINFO block and the new block is a
  81880. * STREAMINFO block: the new block is written in place. Make sure
  81881. * you know what you're doing when changing the values of a
  81882. * STREAMINFO block.
  81883. *
  81884. * Existing block is a STREAMINFO block and the new block is a
  81885. * not a STREAMINFO block: this is an error since the first block
  81886. * must be a STREAMINFO block. Returns \c false without altering the
  81887. * file.
  81888. *
  81889. * Existing block is not a STREAMINFO block and the new block is a
  81890. * STREAMINFO block: this is an error since there may be only one
  81891. * STREAMINFO block. Returns \c false without altering the file.
  81892. *
  81893. * Existing block and new block are the same length: the existing
  81894. * block will be replaced by the new block, written in place.
  81895. *
  81896. * Existing block is longer than new block: if use_padding is \c true,
  81897. * the existing block will be overwritten in place with the new
  81898. * block followed by a PADDING block, if possible, to make the total
  81899. * size the same as the existing block. Remember that a padding
  81900. * block requires at least four bytes so if the difference in size
  81901. * between the new block and existing block is less than that, the
  81902. * entire file will have to be rewritten, using the new block's
  81903. * exact size. If use_padding is \c false, the entire file will be
  81904. * rewritten, replacing the existing block by the new block.
  81905. *
  81906. * Existing block is shorter than new block: if use_padding is \c true,
  81907. * the function will try and expand the new block into the following
  81908. * PADDING block, if it exists and doing so won't shrink the PADDING
  81909. * block to less than 4 bytes. If there is no following PADDING
  81910. * block, or it will shrink to less than 4 bytes, or use_padding is
  81911. * \c false, the entire file is rewritten, replacing the existing block
  81912. * with the new block. Note that in this case any following PADDING
  81913. * block is preserved as is.
  81914. *
  81915. * After writing the block, the iterator will remain in the same
  81916. * place, i.e. pointing to the new block.
  81917. *
  81918. * \param iterator A pointer to an existing initialized iterator.
  81919. * \param block The block to set.
  81920. * \param use_padding See above.
  81921. * \assert
  81922. * \code iterator != NULL \endcode
  81923. * \a iterator has been successfully initialized with
  81924. * FLAC__metadata_simple_iterator_init()
  81925. * \code block != NULL \endcode
  81926. * \retval FLAC__bool
  81927. * \c true if successful, else \c false.
  81928. */
  81929. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  81930. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  81931. * except that instead of writing over an existing block, it appends
  81932. * a block after the existing block. \a use_padding is again used to
  81933. * tell the function to try an expand into following padding in an
  81934. * attempt to avoid rewriting the entire file.
  81935. *
  81936. * This function will fail and return \c false if given a STREAMINFO
  81937. * block.
  81938. *
  81939. * After writing the block, the iterator will be pointing to the
  81940. * new block.
  81941. *
  81942. * \param iterator A pointer to an existing initialized iterator.
  81943. * \param block The block to set.
  81944. * \param use_padding See above.
  81945. * \assert
  81946. * \code iterator != NULL \endcode
  81947. * \a iterator has been successfully initialized with
  81948. * FLAC__metadata_simple_iterator_init()
  81949. * \code block != NULL \endcode
  81950. * \retval FLAC__bool
  81951. * \c true if successful, else \c false.
  81952. */
  81953. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  81954. /** Deletes the block at the current position. This will cause the
  81955. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  81956. * in which case the block will be replaced by an equal-sized PADDING
  81957. * block. The iterator will be left pointing to the block before the
  81958. * one just deleted.
  81959. *
  81960. * You may not delete the STREAMINFO block.
  81961. *
  81962. * \param iterator A pointer to an existing initialized iterator.
  81963. * \param use_padding See above.
  81964. * \assert
  81965. * \code iterator != NULL \endcode
  81966. * \a iterator has been successfully initialized with
  81967. * FLAC__metadata_simple_iterator_init()
  81968. * \retval FLAC__bool
  81969. * \c true if successful, else \c false.
  81970. */
  81971. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  81972. /* \} */
  81973. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  81974. * \ingroup flac_metadata
  81975. *
  81976. * \brief
  81977. * The level 2 interface provides read-write access to FLAC file metadata;
  81978. * all metadata is read into memory, operated on in memory, and then written
  81979. * to file, which is more efficient than level 1 when editing multiple blocks.
  81980. *
  81981. * Currently Ogg FLAC is supported for read only, via
  81982. * FLAC__metadata_chain_read_ogg() but a subsequent
  81983. * FLAC__metadata_chain_write() will fail.
  81984. *
  81985. * The general usage of this interface is:
  81986. *
  81987. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  81988. * linked list of FLAC metadata blocks.
  81989. * - Read all metadata into the the chain from a FLAC file using
  81990. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  81991. * check the status.
  81992. * - Optionally, consolidate the padding using
  81993. * FLAC__metadata_chain_merge_padding() or
  81994. * FLAC__metadata_chain_sort_padding().
  81995. * - Create a new iterator using FLAC__metadata_iterator_new()
  81996. * - Initialize the iterator to point to the first element in the chain
  81997. * using FLAC__metadata_iterator_init()
  81998. * - Traverse the chain using FLAC__metadata_iterator_next and
  81999. * FLAC__metadata_iterator_prev().
  82000. * - Get a block for reading or modification using
  82001. * FLAC__metadata_iterator_get_block(). The pointer to the object
  82002. * inside the chain is returned, so the block is yours to modify.
  82003. * Changes will be reflected in the FLAC file when you write the
  82004. * chain. You can also add and delete blocks (see functions below).
  82005. * - When done, write out the chain using FLAC__metadata_chain_write().
  82006. * Make sure to read the whole comment to the function below.
  82007. * - Delete the chain using FLAC__metadata_chain_delete().
  82008. *
  82009. * \note
  82010. * Even though the FLAC file is not open while the chain is being
  82011. * manipulated, you must not alter the file externally during
  82012. * this time. The chain assumes the FLAC file will not change
  82013. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  82014. * and FLAC__metadata_chain_write().
  82015. *
  82016. * \note
  82017. * Do not modify the is_last, length, or type fields of returned
  82018. * FLAC__StreamMetadata objects. These are managed automatically.
  82019. *
  82020. * \note
  82021. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  82022. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  82023. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  82024. * become owned by the chain and they will be deleted when the chain is
  82025. * deleted.
  82026. *
  82027. * \{
  82028. */
  82029. struct FLAC__Metadata_Chain;
  82030. /** The opaque structure definition for the level 2 chain type.
  82031. */
  82032. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  82033. struct FLAC__Metadata_Iterator;
  82034. /** The opaque structure definition for the level 2 iterator type.
  82035. */
  82036. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  82037. typedef enum {
  82038. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  82039. /**< The chain is in the normal OK state */
  82040. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  82041. /**< The data passed into a function violated the function's usage criteria */
  82042. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  82043. /**< The chain could not open the target file */
  82044. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  82045. /**< The chain could not find the FLAC signature at the start of the file */
  82046. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  82047. /**< The chain tried to write to a file that was not writable */
  82048. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  82049. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  82050. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  82051. /**< The chain encountered an error while reading the FLAC file */
  82052. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  82053. /**< The chain encountered an error while seeking in the FLAC file */
  82054. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  82055. /**< The chain encountered an error while writing the FLAC file */
  82056. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  82057. /**< The chain encountered an error renaming the FLAC file */
  82058. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  82059. /**< The chain encountered an error removing the temporary file */
  82060. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  82061. /**< Memory allocation failed */
  82062. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  82063. /**< The caller violated an assertion or an unexpected error occurred */
  82064. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  82065. /**< One or more of the required callbacks was NULL */
  82066. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  82067. /**< FLAC__metadata_chain_write() was called on a chain read by
  82068. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  82069. * or
  82070. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  82071. * was called on a chain read by
  82072. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  82073. * Matching read/write methods must always be used. */
  82074. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  82075. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  82076. * chain write requires a tempfile; use
  82077. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  82078. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  82079. * called when the chain write does not require a tempfile; use
  82080. * FLAC__metadata_chain_write_with_callbacks() instead.
  82081. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  82082. * before writing via callbacks. */
  82083. } FLAC__Metadata_ChainStatus;
  82084. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  82085. *
  82086. * Using a FLAC__Metadata_ChainStatus as the index to this array
  82087. * will give the string equivalent. The contents should not be modified.
  82088. */
  82089. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  82090. /*********** FLAC__Metadata_Chain ***********/
  82091. /** Create a new chain instance.
  82092. *
  82093. * \retval FLAC__Metadata_Chain*
  82094. * \c NULL if there was an error allocating memory, else the new instance.
  82095. */
  82096. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  82097. /** Free a chain instance. Deletes the object pointed to by \a chain.
  82098. *
  82099. * \param chain A pointer to an existing chain.
  82100. * \assert
  82101. * \code chain != NULL \endcode
  82102. */
  82103. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  82104. /** Get the current status of the chain. Call this after a function
  82105. * returns \c false to get the reason for the error. Also resets the
  82106. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  82107. *
  82108. * \param chain A pointer to an existing chain.
  82109. * \assert
  82110. * \code chain != NULL \endcode
  82111. * \retval FLAC__Metadata_ChainStatus
  82112. * The current status of the chain.
  82113. */
  82114. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  82115. /** Read all metadata from a FLAC file into the chain.
  82116. *
  82117. * \param chain A pointer to an existing chain.
  82118. * \param filename The path to the FLAC file to read.
  82119. * \assert
  82120. * \code chain != NULL \endcode
  82121. * \code filename != NULL \endcode
  82122. * \retval FLAC__bool
  82123. * \c true if a valid list of metadata blocks was read from
  82124. * \a filename, else \c false. On failure, check the status with
  82125. * FLAC__metadata_chain_status().
  82126. */
  82127. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  82128. /** Read all metadata from an Ogg FLAC file into the chain.
  82129. *
  82130. * \note Ogg FLAC metadata data writing is not supported yet and
  82131. * FLAC__metadata_chain_write() will fail.
  82132. *
  82133. * \param chain A pointer to an existing chain.
  82134. * \param filename The path to the Ogg FLAC file to read.
  82135. * \assert
  82136. * \code chain != NULL \endcode
  82137. * \code filename != NULL \endcode
  82138. * \retval FLAC__bool
  82139. * \c true if a valid list of metadata blocks was read from
  82140. * \a filename, else \c false. On failure, check the status with
  82141. * FLAC__metadata_chain_status().
  82142. */
  82143. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  82144. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  82145. *
  82146. * The \a handle need only be open for reading, but must be seekable.
  82147. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  82148. * for Windows).
  82149. *
  82150. * \param chain A pointer to an existing chain.
  82151. * \param handle The I/O handle of the FLAC stream to read. The
  82152. * handle will NOT be closed after the metadata is read;
  82153. * that is the duty of the caller.
  82154. * \param callbacks
  82155. * A set of callbacks to use for I/O. The mandatory
  82156. * callbacks are \a read, \a seek, and \a tell.
  82157. * \assert
  82158. * \code chain != NULL \endcode
  82159. * \retval FLAC__bool
  82160. * \c true if a valid list of metadata blocks was read from
  82161. * \a handle, else \c false. On failure, check the status with
  82162. * FLAC__metadata_chain_status().
  82163. */
  82164. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  82165. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  82166. *
  82167. * The \a handle need only be open for reading, but must be seekable.
  82168. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  82169. * for Windows).
  82170. *
  82171. * \note Ogg FLAC metadata data writing is not supported yet and
  82172. * FLAC__metadata_chain_write() will fail.
  82173. *
  82174. * \param chain A pointer to an existing chain.
  82175. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  82176. * handle will NOT be closed after the metadata is read;
  82177. * that is the duty of the caller.
  82178. * \param callbacks
  82179. * A set of callbacks to use for I/O. The mandatory
  82180. * callbacks are \a read, \a seek, and \a tell.
  82181. * \assert
  82182. * \code chain != NULL \endcode
  82183. * \retval FLAC__bool
  82184. * \c true if a valid list of metadata blocks was read from
  82185. * \a handle, else \c false. On failure, check the status with
  82186. * FLAC__metadata_chain_status().
  82187. */
  82188. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  82189. /** Checks if writing the given chain would require the use of a
  82190. * temporary file, or if it could be written in place.
  82191. *
  82192. * Under certain conditions, padding can be utilized so that writing
  82193. * edited metadata back to the FLAC file does not require rewriting the
  82194. * entire file. If rewriting is required, then a temporary workfile is
  82195. * required. When writing metadata using callbacks, you must check
  82196. * this function to know whether to call
  82197. * FLAC__metadata_chain_write_with_callbacks() or
  82198. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  82199. * writing with FLAC__metadata_chain_write(), the temporary file is
  82200. * handled internally.
  82201. *
  82202. * \param chain A pointer to an existing chain.
  82203. * \param use_padding
  82204. * Whether or not padding will be allowed to be used
  82205. * during the write. The value of \a use_padding given
  82206. * here must match the value later passed to
  82207. * FLAC__metadata_chain_write_with_callbacks() or
  82208. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  82209. * \assert
  82210. * \code chain != NULL \endcode
  82211. * \retval FLAC__bool
  82212. * \c true if writing the current chain would require a tempfile, or
  82213. * \c false if metadata can be written in place.
  82214. */
  82215. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  82216. /** Write all metadata out to the FLAC file. This function tries to be as
  82217. * efficient as possible; how the metadata is actually written is shown by
  82218. * the following:
  82219. *
  82220. * If the current chain is the same size as the existing metadata, the new
  82221. * data is written in place.
  82222. *
  82223. * If the current chain is longer than the existing metadata, and
  82224. * \a use_padding is \c true, and the last block is a PADDING block of
  82225. * sufficient length, the function will truncate the final padding block
  82226. * so that the overall size of the metadata is the same as the existing
  82227. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  82228. * the above conditions are met, the entire FLAC file must be rewritten.
  82229. * If you want to use padding this way it is a good idea to call
  82230. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  82231. * amount of padding to work with, unless you need to preserve ordering
  82232. * of the PADDING blocks for some reason.
  82233. *
  82234. * If the current chain is shorter than the existing metadata, and
  82235. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  82236. * is extended to make the overall size the same as the existing data. If
  82237. * \a use_padding is \c true and the last block is not a PADDING block, a new
  82238. * PADDING block is added to the end of the new data to make it the same
  82239. * size as the existing data (if possible, see the note to
  82240. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  82241. * and the new data is written in place. If none of the above apply or
  82242. * \a use_padding is \c false, the entire FLAC file is rewritten.
  82243. *
  82244. * If \a preserve_file_stats is \c true, the owner and modification time will
  82245. * be preserved even if the FLAC file is written.
  82246. *
  82247. * For this write function to be used, the chain must have been read with
  82248. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  82249. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  82250. *
  82251. * \param chain A pointer to an existing chain.
  82252. * \param use_padding See above.
  82253. * \param preserve_file_stats See above.
  82254. * \assert
  82255. * \code chain != NULL \endcode
  82256. * \retval FLAC__bool
  82257. * \c true if the write succeeded, else \c false. On failure,
  82258. * check the status with FLAC__metadata_chain_status().
  82259. */
  82260. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  82261. /** Write all metadata out to a FLAC stream via callbacks.
  82262. *
  82263. * (See FLAC__metadata_chain_write() for the details on how padding is
  82264. * used to write metadata in place if possible.)
  82265. *
  82266. * The \a handle must be open for updating and be seekable. The
  82267. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  82268. * for Windows).
  82269. *
  82270. * For this write function to be used, the chain must have been read with
  82271. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  82272. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  82273. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  82274. * \c false.
  82275. *
  82276. * \param chain A pointer to an existing chain.
  82277. * \param use_padding See FLAC__metadata_chain_write()
  82278. * \param handle The I/O handle of the FLAC stream to write. The
  82279. * handle will NOT be closed after the metadata is
  82280. * written; that is the duty of the caller.
  82281. * \param callbacks A set of callbacks to use for I/O. The mandatory
  82282. * callbacks are \a write and \a seek.
  82283. * \assert
  82284. * \code chain != NULL \endcode
  82285. * \retval FLAC__bool
  82286. * \c true if the write succeeded, else \c false. On failure,
  82287. * check the status with FLAC__metadata_chain_status().
  82288. */
  82289. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  82290. /** Write all metadata out to a FLAC stream via callbacks.
  82291. *
  82292. * (See FLAC__metadata_chain_write() for the details on how padding is
  82293. * used to write metadata in place if possible.)
  82294. *
  82295. * This version of the write-with-callbacks function must be used when
  82296. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  82297. * this function, you must supply an I/O handle corresponding to the
  82298. * FLAC file to edit, and a temporary handle to which the new FLAC
  82299. * file will be written. It is the caller's job to move this temporary
  82300. * FLAC file on top of the original FLAC file to complete the metadata
  82301. * edit.
  82302. *
  82303. * The \a handle must be open for reading and be seekable. The
  82304. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  82305. * for Windows).
  82306. *
  82307. * The \a temp_handle must be open for writing. The
  82308. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  82309. * for Windows). It should be an empty stream, or at least positioned
  82310. * at the start-of-file (in which case it is the caller's duty to
  82311. * truncate it on return).
  82312. *
  82313. * For this write function to be used, the chain must have been read with
  82314. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  82315. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  82316. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  82317. * \c true.
  82318. *
  82319. * \param chain A pointer to an existing chain.
  82320. * \param use_padding See FLAC__metadata_chain_write()
  82321. * \param handle The I/O handle of the original FLAC stream to read.
  82322. * The handle will NOT be closed after the metadata is
  82323. * written; that is the duty of the caller.
  82324. * \param callbacks A set of callbacks to use for I/O on \a handle.
  82325. * The mandatory callbacks are \a read, \a seek, and
  82326. * \a eof.
  82327. * \param temp_handle The I/O handle of the FLAC stream to write. The
  82328. * handle will NOT be closed after the metadata is
  82329. * written; that is the duty of the caller.
  82330. * \param temp_callbacks
  82331. * A set of callbacks to use for I/O on temp_handle.
  82332. * The only mandatory callback is \a write.
  82333. * \assert
  82334. * \code chain != NULL \endcode
  82335. * \retval FLAC__bool
  82336. * \c true if the write succeeded, else \c false. On failure,
  82337. * check the status with FLAC__metadata_chain_status().
  82338. */
  82339. 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);
  82340. /** Merge adjacent PADDING blocks into a single block.
  82341. *
  82342. * \note This function does not write to the FLAC file, it only
  82343. * modifies the chain.
  82344. *
  82345. * \warning Any iterator on the current chain will become invalid after this
  82346. * call. You should delete the iterator and get a new one.
  82347. *
  82348. * \param chain A pointer to an existing chain.
  82349. * \assert
  82350. * \code chain != NULL \endcode
  82351. */
  82352. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  82353. /** This function will move all PADDING blocks to the end on the metadata,
  82354. * then merge them into a single block.
  82355. *
  82356. * \note This function does not write to the FLAC file, it only
  82357. * modifies the chain.
  82358. *
  82359. * \warning Any iterator on the current chain will become invalid after this
  82360. * call. You should delete the iterator and get a new one.
  82361. *
  82362. * \param chain A pointer to an existing chain.
  82363. * \assert
  82364. * \code chain != NULL \endcode
  82365. */
  82366. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  82367. /*********** FLAC__Metadata_Iterator ***********/
  82368. /** Create a new iterator instance.
  82369. *
  82370. * \retval FLAC__Metadata_Iterator*
  82371. * \c NULL if there was an error allocating memory, else the new instance.
  82372. */
  82373. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  82374. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  82375. *
  82376. * \param iterator A pointer to an existing iterator.
  82377. * \assert
  82378. * \code iterator != NULL \endcode
  82379. */
  82380. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  82381. /** Initialize the iterator to point to the first metadata block in the
  82382. * given chain.
  82383. *
  82384. * \param iterator A pointer to an existing iterator.
  82385. * \param chain A pointer to an existing and initialized (read) chain.
  82386. * \assert
  82387. * \code iterator != NULL \endcode
  82388. * \code chain != NULL \endcode
  82389. */
  82390. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  82391. /** Moves the iterator forward one metadata block, returning \c false if
  82392. * already at the end.
  82393. *
  82394. * \param iterator A pointer to an existing initialized iterator.
  82395. * \assert
  82396. * \code iterator != NULL \endcode
  82397. * \a iterator has been successfully initialized with
  82398. * FLAC__metadata_iterator_init()
  82399. * \retval FLAC__bool
  82400. * \c false if already at the last metadata block of the chain, else
  82401. * \c true.
  82402. */
  82403. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  82404. /** Moves the iterator backward one metadata block, returning \c false if
  82405. * already at the beginning.
  82406. *
  82407. * \param iterator A pointer to an existing initialized iterator.
  82408. * \assert
  82409. * \code iterator != NULL \endcode
  82410. * \a iterator has been successfully initialized with
  82411. * FLAC__metadata_iterator_init()
  82412. * \retval FLAC__bool
  82413. * \c false if already at the first metadata block of the chain, else
  82414. * \c true.
  82415. */
  82416. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  82417. /** Get the type of the metadata block at the current position.
  82418. *
  82419. * \param iterator A pointer to an existing initialized iterator.
  82420. * \assert
  82421. * \code iterator != NULL \endcode
  82422. * \a iterator has been successfully initialized with
  82423. * FLAC__metadata_iterator_init()
  82424. * \retval FLAC__MetadataType
  82425. * The type of the metadata block at the current iterator position.
  82426. */
  82427. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  82428. /** Get the metadata block at the current position. You can modify
  82429. * the block in place but must write the chain before the changes
  82430. * are reflected to the FLAC file. You do not need to call
  82431. * FLAC__metadata_iterator_set_block() to reflect the changes;
  82432. * the pointer returned by FLAC__metadata_iterator_get_block()
  82433. * points directly into the chain.
  82434. *
  82435. * \warning
  82436. * Do not call FLAC__metadata_object_delete() on the returned object;
  82437. * to delete a block use FLAC__metadata_iterator_delete_block().
  82438. *
  82439. * \param iterator A pointer to an existing initialized iterator.
  82440. * \assert
  82441. * \code iterator != NULL \endcode
  82442. * \a iterator has been successfully initialized with
  82443. * FLAC__metadata_iterator_init()
  82444. * \retval FLAC__StreamMetadata*
  82445. * The current metadata block.
  82446. */
  82447. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  82448. /** Set the metadata block at the current position, replacing the existing
  82449. * block. The new block passed in becomes owned by the chain and it will be
  82450. * deleted when the chain is deleted.
  82451. *
  82452. * \param iterator A pointer to an existing initialized iterator.
  82453. * \param block A pointer to a metadata block.
  82454. * \assert
  82455. * \code iterator != NULL \endcode
  82456. * \a iterator has been successfully initialized with
  82457. * FLAC__metadata_iterator_init()
  82458. * \code block != NULL \endcode
  82459. * \retval FLAC__bool
  82460. * \c false if the conditions in the above description are not met, or
  82461. * a memory allocation error occurs, otherwise \c true.
  82462. */
  82463. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  82464. /** Removes the current block from the chain. If \a replace_with_padding is
  82465. * \c true, the block will instead be replaced with a padding block of equal
  82466. * size. You can not delete the STREAMINFO block. The iterator will be
  82467. * left pointing to the block before the one just "deleted", even if
  82468. * \a replace_with_padding is \c true.
  82469. *
  82470. * \param iterator A pointer to an existing initialized iterator.
  82471. * \param replace_with_padding See above.
  82472. * \assert
  82473. * \code iterator != NULL \endcode
  82474. * \a iterator has been successfully initialized with
  82475. * FLAC__metadata_iterator_init()
  82476. * \retval FLAC__bool
  82477. * \c false if the conditions in the above description are not met,
  82478. * otherwise \c true.
  82479. */
  82480. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  82481. /** Insert a new block before the current block. You cannot insert a block
  82482. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  82483. * as there can be only one, the one that already exists at the head when you
  82484. * read in a chain. The chain takes ownership of the new block and it will be
  82485. * deleted when the chain is deleted. The iterator will be left pointing to
  82486. * the new block.
  82487. *
  82488. * \param iterator A pointer to an existing initialized iterator.
  82489. * \param block A pointer to a metadata block to insert.
  82490. * \assert
  82491. * \code iterator != NULL \endcode
  82492. * \a iterator has been successfully initialized with
  82493. * FLAC__metadata_iterator_init()
  82494. * \retval FLAC__bool
  82495. * \c false if the conditions in the above description are not met, or
  82496. * a memory allocation error occurs, otherwise \c true.
  82497. */
  82498. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  82499. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  82500. * block as there can be only one, the one that already exists at the head when
  82501. * you read in a chain. The chain takes ownership of the new block and it will
  82502. * be deleted when the chain is deleted. The iterator will be left pointing to
  82503. * the new block.
  82504. *
  82505. * \param iterator A pointer to an existing initialized iterator.
  82506. * \param block A pointer to a metadata block to insert.
  82507. * \assert
  82508. * \code iterator != NULL \endcode
  82509. * \a iterator has been successfully initialized with
  82510. * FLAC__metadata_iterator_init()
  82511. * \retval FLAC__bool
  82512. * \c false if the conditions in the above description are not met, or
  82513. * a memory allocation error occurs, otherwise \c true.
  82514. */
  82515. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  82516. /* \} */
  82517. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  82518. * \ingroup flac_metadata
  82519. *
  82520. * \brief
  82521. * This module contains methods for manipulating FLAC metadata objects.
  82522. *
  82523. * Since many are variable length we have to be careful about the memory
  82524. * management. We decree that all pointers to data in the object are
  82525. * owned by the object and memory-managed by the object.
  82526. *
  82527. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  82528. * functions to create all instances. When using the
  82529. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  82530. * \a copy to \c true to have the function make it's own copy of the data, or
  82531. * to \c false to give the object ownership of your data. In the latter case
  82532. * your pointer must be freeable by free() and will be free()d when the object
  82533. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  82534. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  82535. * the length argument is 0 and the \a copy argument is \c false.
  82536. *
  82537. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  82538. * will return \c NULL in the case of a memory allocation error, otherwise a new
  82539. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  82540. * case of a memory allocation error.
  82541. *
  82542. * We don't have the convenience of C++ here, so note that the library relies
  82543. * on you to keep the types straight. In other words, if you pass, for
  82544. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  82545. * FLAC__metadata_object_application_set_data(), you will get an assertion
  82546. * failure.
  82547. *
  82548. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  82549. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  82550. * toward the length or stored in the stream, but it can make working with plain
  82551. * comments (those that don't contain embedded-NULs in the value) easier.
  82552. * Entries passed into these functions have trailing NULs added if missing, and
  82553. * returned entries are guaranteed to have a trailing NUL.
  82554. *
  82555. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  82556. * comment entry/name/value will first validate that it complies with the Vorbis
  82557. * comment specification and return false if it does not.
  82558. *
  82559. * There is no need to recalculate the length field on metadata blocks you
  82560. * have modified. They will be calculated automatically before they are
  82561. * written back to a file.
  82562. *
  82563. * \{
  82564. */
  82565. /** Create a new metadata object instance of the given type.
  82566. *
  82567. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  82568. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  82569. * the vendor string set (but zero comments).
  82570. *
  82571. * Do not pass in a value greater than or equal to
  82572. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  82573. * doing.
  82574. *
  82575. * \param type Type of object to create
  82576. * \retval FLAC__StreamMetadata*
  82577. * \c NULL if there was an error allocating memory or the type code is
  82578. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  82579. */
  82580. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  82581. /** Create a copy of an existing metadata object.
  82582. *
  82583. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  82584. * object is also copied. The caller takes ownership of the new block and
  82585. * is responsible for freeing it with FLAC__metadata_object_delete().
  82586. *
  82587. * \param object Pointer to object to copy.
  82588. * \assert
  82589. * \code object != NULL \endcode
  82590. * \retval FLAC__StreamMetadata*
  82591. * \c NULL if there was an error allocating memory, else the new instance.
  82592. */
  82593. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  82594. /** Free a metadata object. Deletes the object pointed to by \a object.
  82595. *
  82596. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  82597. * object is also deleted.
  82598. *
  82599. * \param object A pointer to an existing object.
  82600. * \assert
  82601. * \code object != NULL \endcode
  82602. */
  82603. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  82604. /** Compares two metadata objects.
  82605. *
  82606. * The compare is "deep", i.e. dynamically allocated data within the
  82607. * object is also compared.
  82608. *
  82609. * \param block1 A pointer to an existing object.
  82610. * \param block2 A pointer to an existing object.
  82611. * \assert
  82612. * \code block1 != NULL \endcode
  82613. * \code block2 != NULL \endcode
  82614. * \retval FLAC__bool
  82615. * \c true if objects are identical, else \c false.
  82616. */
  82617. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  82618. /** Sets the application data of an APPLICATION block.
  82619. *
  82620. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  82621. * takes ownership of the pointer. The existing data will be freed if this
  82622. * function is successful, otherwise the original data will remain if \a copy
  82623. * is \c true and malloc() fails.
  82624. *
  82625. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  82626. *
  82627. * \param object A pointer to an existing APPLICATION object.
  82628. * \param data A pointer to the data to set.
  82629. * \param length The length of \a data in bytes.
  82630. * \param copy See above.
  82631. * \assert
  82632. * \code object != NULL \endcode
  82633. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  82634. * \code (data != NULL && length > 0) ||
  82635. * (data == NULL && length == 0 && copy == false) \endcode
  82636. * \retval FLAC__bool
  82637. * \c false if \a copy is \c true and malloc() fails, else \c true.
  82638. */
  82639. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  82640. /** Resize the seekpoint array.
  82641. *
  82642. * If the size shrinks, elements will truncated; if it grows, new placeholder
  82643. * points will be added to the end.
  82644. *
  82645. * \param object A pointer to an existing SEEKTABLE object.
  82646. * \param new_num_points The desired length of the array; may be \c 0.
  82647. * \assert
  82648. * \code object != NULL \endcode
  82649. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82650. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  82651. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  82652. * \retval FLAC__bool
  82653. * \c false if memory allocation error, else \c true.
  82654. */
  82655. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  82656. /** Set a seekpoint in a seektable.
  82657. *
  82658. * \param object A pointer to an existing SEEKTABLE object.
  82659. * \param point_num Index into seekpoint array to set.
  82660. * \param point The point to set.
  82661. * \assert
  82662. * \code object != NULL \endcode
  82663. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82664. * \code object->data.seek_table.num_points > point_num \endcode
  82665. */
  82666. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  82667. /** Insert a seekpoint into a seektable.
  82668. *
  82669. * \param object A pointer to an existing SEEKTABLE object.
  82670. * \param point_num Index into seekpoint array to set.
  82671. * \param point The point to set.
  82672. * \assert
  82673. * \code object != NULL \endcode
  82674. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82675. * \code object->data.seek_table.num_points >= point_num \endcode
  82676. * \retval FLAC__bool
  82677. * \c false if memory allocation error, else \c true.
  82678. */
  82679. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  82680. /** Delete a seekpoint from a seektable.
  82681. *
  82682. * \param object A pointer to an existing SEEKTABLE object.
  82683. * \param point_num Index into seekpoint array to set.
  82684. * \assert
  82685. * \code object != NULL \endcode
  82686. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82687. * \code object->data.seek_table.num_points > point_num \endcode
  82688. * \retval FLAC__bool
  82689. * \c false if memory allocation error, else \c true.
  82690. */
  82691. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  82692. /** Check a seektable to see if it conforms to the FLAC specification.
  82693. * See the format specification for limits on the contents of the
  82694. * seektable.
  82695. *
  82696. * \param object A pointer to an existing SEEKTABLE object.
  82697. * \assert
  82698. * \code object != NULL \endcode
  82699. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82700. * \retval FLAC__bool
  82701. * \c false if seek table is illegal, else \c true.
  82702. */
  82703. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  82704. /** Append a number of placeholder points to the end of a seek table.
  82705. *
  82706. * \note
  82707. * As with the other ..._seektable_template_... functions, you should
  82708. * call FLAC__metadata_object_seektable_template_sort() when finished
  82709. * to make the seek table legal.
  82710. *
  82711. * \param object A pointer to an existing SEEKTABLE object.
  82712. * \param num The number of placeholder points to append.
  82713. * \assert
  82714. * \code object != NULL \endcode
  82715. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82716. * \retval FLAC__bool
  82717. * \c false if memory allocation fails, else \c true.
  82718. */
  82719. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  82720. /** Append a specific seek point template to the end of a seek table.
  82721. *
  82722. * \note
  82723. * As with the other ..._seektable_template_... functions, you should
  82724. * call FLAC__metadata_object_seektable_template_sort() when finished
  82725. * to make the seek table legal.
  82726. *
  82727. * \param object A pointer to an existing SEEKTABLE object.
  82728. * \param sample_number The sample number of the seek point template.
  82729. * \assert
  82730. * \code object != NULL \endcode
  82731. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82732. * \retval FLAC__bool
  82733. * \c false if memory allocation fails, else \c true.
  82734. */
  82735. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  82736. /** Append specific seek point templates to the end of a seek table.
  82737. *
  82738. * \note
  82739. * As with the other ..._seektable_template_... functions, you should
  82740. * call FLAC__metadata_object_seektable_template_sort() when finished
  82741. * to make the seek table legal.
  82742. *
  82743. * \param object A pointer to an existing SEEKTABLE object.
  82744. * \param sample_numbers An array of sample numbers for the seek points.
  82745. * \param num The number of seek point templates to append.
  82746. * \assert
  82747. * \code object != NULL \endcode
  82748. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82749. * \retval FLAC__bool
  82750. * \c false if memory allocation fails, else \c true.
  82751. */
  82752. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  82753. /** Append a set of evenly-spaced seek point templates to the end of a
  82754. * seek table.
  82755. *
  82756. * \note
  82757. * As with the other ..._seektable_template_... functions, you should
  82758. * call FLAC__metadata_object_seektable_template_sort() when finished
  82759. * to make the seek table legal.
  82760. *
  82761. * \param object A pointer to an existing SEEKTABLE object.
  82762. * \param num The number of placeholder points to append.
  82763. * \param total_samples The total number of samples to be encoded;
  82764. * the seekpoints will be spaced approximately
  82765. * \a total_samples / \a num samples apart.
  82766. * \assert
  82767. * \code object != NULL \endcode
  82768. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82769. * \code total_samples > 0 \endcode
  82770. * \retval FLAC__bool
  82771. * \c false if memory allocation fails, else \c true.
  82772. */
  82773. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  82774. /** Append a set of evenly-spaced seek point templates to the end of a
  82775. * seek table.
  82776. *
  82777. * \note
  82778. * As with the other ..._seektable_template_... functions, you should
  82779. * call FLAC__metadata_object_seektable_template_sort() when finished
  82780. * to make the seek table legal.
  82781. *
  82782. * \param object A pointer to an existing SEEKTABLE object.
  82783. * \param samples The number of samples apart to space the placeholder
  82784. * points. The first point will be at sample \c 0, the
  82785. * second at sample \a samples, then 2*\a samples, and
  82786. * so on. As long as \a samples and \a total_samples
  82787. * are greater than \c 0, there will always be at least
  82788. * one seekpoint at sample \c 0.
  82789. * \param total_samples The total number of samples to be encoded;
  82790. * the seekpoints will be spaced
  82791. * \a samples samples apart.
  82792. * \assert
  82793. * \code object != NULL \endcode
  82794. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82795. * \code samples > 0 \endcode
  82796. * \code total_samples > 0 \endcode
  82797. * \retval FLAC__bool
  82798. * \c false if memory allocation fails, else \c true.
  82799. */
  82800. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  82801. /** Sort a seek table's seek points according to the format specification,
  82802. * removing duplicates.
  82803. *
  82804. * \param object A pointer to a seek table to be sorted.
  82805. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  82806. * If \c true, duplicates are deleted and the seek table is
  82807. * shrunk appropriately; the number of placeholder points
  82808. * present in the seek table will be the same after the call
  82809. * as before.
  82810. * \assert
  82811. * \code object != NULL \endcode
  82812. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82813. * \retval FLAC__bool
  82814. * \c false if realloc() fails, else \c true.
  82815. */
  82816. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  82817. /** Sets the vendor string in a VORBIS_COMMENT block.
  82818. *
  82819. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82820. * one already.
  82821. *
  82822. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82823. * takes ownership of the \c entry.entry pointer.
  82824. *
  82825. * \note If this function returns \c false, the caller still owns the
  82826. * pointer.
  82827. *
  82828. * \param object A pointer to an existing VORBIS_COMMENT object.
  82829. * \param entry The entry to set the vendor string to.
  82830. * \param copy See above.
  82831. * \assert
  82832. * \code object != NULL \endcode
  82833. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82834. * \code (entry.entry != NULL && entry.length > 0) ||
  82835. * (entry.entry == NULL && entry.length == 0) \endcode
  82836. * \retval FLAC__bool
  82837. * \c false if memory allocation fails or \a entry does not comply with the
  82838. * Vorbis comment specification, else \c true.
  82839. */
  82840. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  82841. /** Resize the comment array.
  82842. *
  82843. * If the size shrinks, elements will truncated; if it grows, new empty
  82844. * fields will be added to the end.
  82845. *
  82846. * \param object A pointer to an existing VORBIS_COMMENT object.
  82847. * \param new_num_comments The desired length of the array; may be \c 0.
  82848. * \assert
  82849. * \code object != NULL \endcode
  82850. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82851. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  82852. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  82853. * \retval FLAC__bool
  82854. * \c false if memory allocation fails, else \c true.
  82855. */
  82856. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  82857. /** Sets a comment in a VORBIS_COMMENT block.
  82858. *
  82859. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82860. * one already.
  82861. *
  82862. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82863. * takes ownership of the \c entry.entry pointer.
  82864. *
  82865. * \note If this function returns \c false, the caller still owns the
  82866. * pointer.
  82867. *
  82868. * \param object A pointer to an existing VORBIS_COMMENT object.
  82869. * \param comment_num Index into comment array to set.
  82870. * \param entry The entry to set the comment to.
  82871. * \param copy See above.
  82872. * \assert
  82873. * \code object != NULL \endcode
  82874. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82875. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  82876. * \code (entry.entry != NULL && entry.length > 0) ||
  82877. * (entry.entry == NULL && entry.length == 0) \endcode
  82878. * \retval FLAC__bool
  82879. * \c false if memory allocation fails or \a entry does not comply with the
  82880. * Vorbis comment specification, else \c true.
  82881. */
  82882. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  82883. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  82884. *
  82885. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82886. * one already.
  82887. *
  82888. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82889. * takes ownership of the \c entry.entry pointer.
  82890. *
  82891. * \note If this function returns \c false, the caller still owns the
  82892. * pointer.
  82893. *
  82894. * \param object A pointer to an existing VORBIS_COMMENT object.
  82895. * \param comment_num The index at which to insert the comment. The comments
  82896. * at and after \a comment_num move right one position.
  82897. * To append a comment to the end, set \a comment_num to
  82898. * \c object->data.vorbis_comment.num_comments .
  82899. * \param entry The comment to insert.
  82900. * \param copy See above.
  82901. * \assert
  82902. * \code object != NULL \endcode
  82903. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82904. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  82905. * \code (entry.entry != NULL && entry.length > 0) ||
  82906. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  82907. * \retval FLAC__bool
  82908. * \c false if memory allocation fails or \a entry does not comply with the
  82909. * Vorbis comment specification, else \c true.
  82910. */
  82911. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  82912. /** Appends a comment to a VORBIS_COMMENT block.
  82913. *
  82914. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82915. * one already.
  82916. *
  82917. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82918. * takes ownership of the \c entry.entry pointer.
  82919. *
  82920. * \note If this function returns \c false, the caller still owns the
  82921. * pointer.
  82922. *
  82923. * \param object A pointer to an existing VORBIS_COMMENT object.
  82924. * \param entry The comment to insert.
  82925. * \param copy See above.
  82926. * \assert
  82927. * \code object != NULL \endcode
  82928. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82929. * \code (entry.entry != NULL && entry.length > 0) ||
  82930. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  82931. * \retval FLAC__bool
  82932. * \c false if memory allocation fails or \a entry does not comply with the
  82933. * Vorbis comment specification, else \c true.
  82934. */
  82935. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  82936. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  82937. *
  82938. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82939. * one already.
  82940. *
  82941. * Depending on the the value of \a all, either all or just the first comment
  82942. * whose field name(s) match the given entry's name will be replaced by the
  82943. * given entry. If no comments match, \a entry will simply be appended.
  82944. *
  82945. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82946. * takes ownership of the \c entry.entry pointer.
  82947. *
  82948. * \note If this function returns \c false, the caller still owns the
  82949. * pointer.
  82950. *
  82951. * \param object A pointer to an existing VORBIS_COMMENT object.
  82952. * \param entry The comment to insert.
  82953. * \param all If \c true, all comments whose field name matches
  82954. * \a entry's field name will be removed, and \a entry will
  82955. * be inserted at the position of the first matching
  82956. * comment. If \c false, only the first comment whose
  82957. * field name matches \a entry's field name will be
  82958. * replaced with \a entry.
  82959. * \param copy See above.
  82960. * \assert
  82961. * \code object != NULL \endcode
  82962. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82963. * \code (entry.entry != NULL && entry.length > 0) ||
  82964. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  82965. * \retval FLAC__bool
  82966. * \c false if memory allocation fails or \a entry does not comply with the
  82967. * Vorbis comment specification, else \c true.
  82968. */
  82969. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  82970. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  82971. *
  82972. * \param object A pointer to an existing VORBIS_COMMENT object.
  82973. * \param comment_num The index of the comment to delete.
  82974. * \assert
  82975. * \code object != NULL \endcode
  82976. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82977. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  82978. * \retval FLAC__bool
  82979. * \c false if realloc() fails, else \c true.
  82980. */
  82981. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  82982. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  82983. *
  82984. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  82985. * memory and shall be owned by the caller. For convenience the entry will
  82986. * have a terminating NUL.
  82987. *
  82988. * \param entry A pointer to a Vorbis comment entry. The entry's
  82989. * \c entry pointer should not point to allocated
  82990. * memory as it will be overwritten.
  82991. * \param field_name The field name in ASCII, \c NUL terminated.
  82992. * \param field_value The field value in UTF-8, \c NUL terminated.
  82993. * \assert
  82994. * \code entry != NULL \endcode
  82995. * \code field_name != NULL \endcode
  82996. * \code field_value != NULL \endcode
  82997. * \retval FLAC__bool
  82998. * \c false if malloc() fails, or if \a field_name or \a field_value does
  82999. * not comply with the Vorbis comment specification, else \c true.
  83000. */
  83001. 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);
  83002. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  83003. *
  83004. * The returned pointers to name and value will be allocated by malloc()
  83005. * and shall be owned by the caller.
  83006. *
  83007. * \param entry An existing Vorbis comment entry.
  83008. * \param field_name The address of where the returned pointer to the
  83009. * field name will be stored.
  83010. * \param field_value The address of where the returned pointer to the
  83011. * field value will be stored.
  83012. * \assert
  83013. * \code (entry.entry != NULL && entry.length > 0) \endcode
  83014. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  83015. * \code field_name != NULL \endcode
  83016. * \code field_value != NULL \endcode
  83017. * \retval FLAC__bool
  83018. * \c false if memory allocation fails or \a entry does not comply with the
  83019. * Vorbis comment specification, else \c true.
  83020. */
  83021. 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);
  83022. /** Check if the given Vorbis comment entry's field name matches the given
  83023. * field name.
  83024. *
  83025. * \param entry An existing Vorbis comment entry.
  83026. * \param field_name The field name to check.
  83027. * \param field_name_length The length of \a field_name, not including the
  83028. * terminating \c NUL.
  83029. * \assert
  83030. * \code (entry.entry != NULL && entry.length > 0) \endcode
  83031. * \retval FLAC__bool
  83032. * \c true if the field names match, else \c false
  83033. */
  83034. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  83035. /** Find a Vorbis comment with the given field name.
  83036. *
  83037. * The search begins at entry number \a offset; use an offset of 0 to
  83038. * search from the beginning of the comment array.
  83039. *
  83040. * \param object A pointer to an existing VORBIS_COMMENT object.
  83041. * \param offset The offset into the comment array from where to start
  83042. * the search.
  83043. * \param field_name The field name of the comment to find.
  83044. * \assert
  83045. * \code object != NULL \endcode
  83046. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83047. * \code field_name != NULL \endcode
  83048. * \retval int
  83049. * The offset in the comment array of the first comment whose field
  83050. * name matches \a field_name, or \c -1 if no match was found.
  83051. */
  83052. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  83053. /** Remove first Vorbis comment matching the given field name.
  83054. *
  83055. * \param object A pointer to an existing VORBIS_COMMENT object.
  83056. * \param field_name The field name of comment to delete.
  83057. * \assert
  83058. * \code object != NULL \endcode
  83059. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83060. * \retval int
  83061. * \c -1 for memory allocation error, \c 0 for no matching entries,
  83062. * \c 1 for one matching entry deleted.
  83063. */
  83064. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  83065. /** Remove all Vorbis comments matching the given field name.
  83066. *
  83067. * \param object A pointer to an existing VORBIS_COMMENT object.
  83068. * \param field_name The field name of comments to delete.
  83069. * \assert
  83070. * \code object != NULL \endcode
  83071. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83072. * \retval int
  83073. * \c -1 for memory allocation error, \c 0 for no matching entries,
  83074. * else the number of matching entries deleted.
  83075. */
  83076. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  83077. /** Create a new CUESHEET track instance.
  83078. *
  83079. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  83080. *
  83081. * \retval FLAC__StreamMetadata_CueSheet_Track*
  83082. * \c NULL if there was an error allocating memory, else the new instance.
  83083. */
  83084. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  83085. /** Create a copy of an existing CUESHEET track object.
  83086. *
  83087. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  83088. * object is also copied. The caller takes ownership of the new object and
  83089. * is responsible for freeing it with
  83090. * FLAC__metadata_object_cuesheet_track_delete().
  83091. *
  83092. * \param object Pointer to object to copy.
  83093. * \assert
  83094. * \code object != NULL \endcode
  83095. * \retval FLAC__StreamMetadata_CueSheet_Track*
  83096. * \c NULL if there was an error allocating memory, else the new instance.
  83097. */
  83098. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  83099. /** Delete a CUESHEET track object
  83100. *
  83101. * \param object A pointer to an existing CUESHEET track object.
  83102. * \assert
  83103. * \code object != NULL \endcode
  83104. */
  83105. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  83106. /** Resize a track's index point array.
  83107. *
  83108. * If the size shrinks, elements will truncated; if it grows, new blank
  83109. * indices will be added to the end.
  83110. *
  83111. * \param object A pointer to an existing CUESHEET object.
  83112. * \param track_num The index of the track to modify. NOTE: this is not
  83113. * necessarily the same as the track's \a number field.
  83114. * \param new_num_indices The desired length of the array; may be \c 0.
  83115. * \assert
  83116. * \code object != NULL \endcode
  83117. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83118. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83119. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  83120. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  83121. * \retval FLAC__bool
  83122. * \c false if memory allocation error, else \c true.
  83123. */
  83124. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  83125. /** Insert an index point in a CUESHEET track at the given index.
  83126. *
  83127. * \param object A pointer to an existing CUESHEET object.
  83128. * \param track_num The index of the track to modify. NOTE: this is not
  83129. * necessarily the same as the track's \a number field.
  83130. * \param index_num The index into the track's index array at which to
  83131. * insert the index point. NOTE: this is not necessarily
  83132. * the same as the index point's \a number field. The
  83133. * indices at and after \a index_num move right one
  83134. * position. To append an index point to the end, set
  83135. * \a index_num to
  83136. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  83137. * \param index The index point to insert.
  83138. * \assert
  83139. * \code object != NULL \endcode
  83140. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83141. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83142. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  83143. * \retval FLAC__bool
  83144. * \c false if realloc() fails, else \c true.
  83145. */
  83146. 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);
  83147. /** Insert a blank index point in a CUESHEET track at the given index.
  83148. *
  83149. * A blank index point is one in which all field values are zero.
  83150. *
  83151. * \param object A pointer to an existing CUESHEET object.
  83152. * \param track_num The index of the track to modify. NOTE: this is not
  83153. * necessarily the same as the track's \a number field.
  83154. * \param index_num The index into the track's index array at which to
  83155. * insert the index point. NOTE: this is not necessarily
  83156. * the same as the index point's \a number field. The
  83157. * indices at and after \a index_num move right one
  83158. * position. To append an index point to the end, set
  83159. * \a index_num to
  83160. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  83161. * \assert
  83162. * \code object != NULL \endcode
  83163. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83164. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83165. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  83166. * \retval FLAC__bool
  83167. * \c false if realloc() fails, else \c true.
  83168. */
  83169. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  83170. /** Delete an index point in a CUESHEET track at the given index.
  83171. *
  83172. * \param object A pointer to an existing CUESHEET object.
  83173. * \param track_num The index into the track array of the track to
  83174. * modify. NOTE: this is not necessarily the same
  83175. * as the track's \a number field.
  83176. * \param index_num The index into the track's index array of the index
  83177. * to delete. NOTE: this is not necessarily the same
  83178. * as the index's \a number field.
  83179. * \assert
  83180. * \code object != NULL \endcode
  83181. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83182. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83183. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  83184. * \retval FLAC__bool
  83185. * \c false if realloc() fails, else \c true.
  83186. */
  83187. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  83188. /** Resize the track array.
  83189. *
  83190. * If the size shrinks, elements will truncated; if it grows, new blank
  83191. * tracks will be added to the end.
  83192. *
  83193. * \param object A pointer to an existing CUESHEET object.
  83194. * \param new_num_tracks The desired length of the array; may be \c 0.
  83195. * \assert
  83196. * \code object != NULL \endcode
  83197. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83198. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  83199. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  83200. * \retval FLAC__bool
  83201. * \c false if memory allocation error, else \c true.
  83202. */
  83203. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  83204. /** Sets a track in a CUESHEET block.
  83205. *
  83206. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  83207. * takes ownership of the \a track pointer.
  83208. *
  83209. * \param object A pointer to an existing CUESHEET object.
  83210. * \param track_num Index into track array to set. NOTE: this is not
  83211. * necessarily the same as the track's \a number field.
  83212. * \param track The track to set the track to. You may safely pass in
  83213. * a const pointer if \a copy is \c true.
  83214. * \param copy See above.
  83215. * \assert
  83216. * \code object != NULL \endcode
  83217. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83218. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  83219. * \code (track->indices != NULL && track->num_indices > 0) ||
  83220. * (track->indices == NULL && track->num_indices == 0)
  83221. * \retval FLAC__bool
  83222. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83223. */
  83224. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  83225. /** Insert a track in a CUESHEET block at the given index.
  83226. *
  83227. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  83228. * takes ownership of the \a track pointer.
  83229. *
  83230. * \param object A pointer to an existing CUESHEET object.
  83231. * \param track_num The index at which to insert the track. NOTE: this
  83232. * is not necessarily the same as the track's \a number
  83233. * field. The tracks at and after \a track_num move right
  83234. * one position. To append a track to the end, set
  83235. * \a track_num to \c object->data.cue_sheet.num_tracks .
  83236. * \param track The track to insert. You may safely pass in a const
  83237. * pointer if \a copy is \c true.
  83238. * \param copy See above.
  83239. * \assert
  83240. * \code object != NULL \endcode
  83241. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83242. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  83243. * \retval FLAC__bool
  83244. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83245. */
  83246. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  83247. /** Insert a blank track in a CUESHEET block at the given index.
  83248. *
  83249. * A blank track is one in which all field values are zero.
  83250. *
  83251. * \param object A pointer to an existing CUESHEET object.
  83252. * \param track_num The index at which to insert the track. NOTE: this
  83253. * is not necessarily the same as the track's \a number
  83254. * field. The tracks at and after \a track_num move right
  83255. * one position. To append a track to the end, set
  83256. * \a track_num to \c object->data.cue_sheet.num_tracks .
  83257. * \assert
  83258. * \code object != NULL \endcode
  83259. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83260. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  83261. * \retval FLAC__bool
  83262. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83263. */
  83264. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  83265. /** Delete a track in a CUESHEET block at the given index.
  83266. *
  83267. * \param object A pointer to an existing CUESHEET object.
  83268. * \param track_num The index into the track array of the track to
  83269. * delete. NOTE: this is not necessarily the same
  83270. * as the track's \a number field.
  83271. * \assert
  83272. * \code object != NULL \endcode
  83273. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83274. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83275. * \retval FLAC__bool
  83276. * \c false if realloc() fails, else \c true.
  83277. */
  83278. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  83279. /** Check a cue sheet to see if it conforms to the FLAC specification.
  83280. * See the format specification for limits on the contents of the
  83281. * cue sheet.
  83282. *
  83283. * \param object A pointer to an existing CUESHEET object.
  83284. * \param check_cd_da_subset If \c true, check CUESHEET against more
  83285. * stringent requirements for a CD-DA (audio) disc.
  83286. * \param violation Address of a pointer to a string. If there is a
  83287. * violation, a pointer to a string explanation of the
  83288. * violation will be returned here. \a violation may be
  83289. * \c NULL if you don't need the returned string. Do not
  83290. * free the returned string; it will always point to static
  83291. * data.
  83292. * \assert
  83293. * \code object != NULL \endcode
  83294. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83295. * \retval FLAC__bool
  83296. * \c false if cue sheet is illegal, else \c true.
  83297. */
  83298. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  83299. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  83300. * assumes the cue sheet corresponds to a CD; the result is undefined
  83301. * if the cuesheet's is_cd bit is not set.
  83302. *
  83303. * \param object A pointer to an existing CUESHEET object.
  83304. * \assert
  83305. * \code object != NULL \endcode
  83306. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83307. * \retval FLAC__uint32
  83308. * The unsigned integer representation of the CDDB/freedb ID
  83309. */
  83310. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  83311. /** Sets the MIME type of a PICTURE block.
  83312. *
  83313. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  83314. * takes ownership of the pointer. The existing string will be freed if this
  83315. * function is successful, otherwise the original string will remain if \a copy
  83316. * is \c true and malloc() fails.
  83317. *
  83318. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  83319. *
  83320. * \param object A pointer to an existing PICTURE object.
  83321. * \param mime_type A pointer to the MIME type string. The string must be
  83322. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  83323. * is done.
  83324. * \param copy See above.
  83325. * \assert
  83326. * \code object != NULL \endcode
  83327. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  83328. * \code (mime_type != NULL) \endcode
  83329. * \retval FLAC__bool
  83330. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83331. */
  83332. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  83333. /** Sets the description of a PICTURE block.
  83334. *
  83335. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  83336. * takes ownership of the pointer. The existing string will be freed if this
  83337. * function is successful, otherwise the original string will remain if \a copy
  83338. * is \c true and malloc() fails.
  83339. *
  83340. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  83341. *
  83342. * \param object A pointer to an existing PICTURE object.
  83343. * \param description A pointer to the description string. The string must be
  83344. * valid UTF-8, NUL-terminated. No validation is done.
  83345. * \param copy See above.
  83346. * \assert
  83347. * \code object != NULL \endcode
  83348. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  83349. * \code (description != NULL) \endcode
  83350. * \retval FLAC__bool
  83351. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83352. */
  83353. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  83354. /** Sets the picture data of a PICTURE block.
  83355. *
  83356. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  83357. * takes ownership of the pointer. Also sets the \a data_length field of the
  83358. * metadata object to what is passed in as the \a length parameter. The
  83359. * existing data will be freed if this function is successful, otherwise the
  83360. * original data and data_length will remain if \a copy is \c true and
  83361. * malloc() fails.
  83362. *
  83363. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  83364. *
  83365. * \param object A pointer to an existing PICTURE object.
  83366. * \param data A pointer to the data to set.
  83367. * \param length The length of \a data in bytes.
  83368. * \param copy See above.
  83369. * \assert
  83370. * \code object != NULL \endcode
  83371. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  83372. * \code (data != NULL && length > 0) ||
  83373. * (data == NULL && length == 0 && copy == false) \endcode
  83374. * \retval FLAC__bool
  83375. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83376. */
  83377. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  83378. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  83379. * See the format specification for limits on the contents of the
  83380. * PICTURE block.
  83381. *
  83382. * \param object A pointer to existing PICTURE block to be checked.
  83383. * \param violation Address of a pointer to a string. If there is a
  83384. * violation, a pointer to a string explanation of the
  83385. * violation will be returned here. \a violation may be
  83386. * \c NULL if you don't need the returned string. Do not
  83387. * free the returned string; it will always point to static
  83388. * data.
  83389. * \assert
  83390. * \code object != NULL \endcode
  83391. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  83392. * \retval FLAC__bool
  83393. * \c false if PICTURE block is illegal, else \c true.
  83394. */
  83395. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  83396. /* \} */
  83397. #ifdef __cplusplus
  83398. }
  83399. #endif
  83400. #endif
  83401. /********* End of inlined file: metadata.h *********/
  83402. /********* Start of inlined file: stream_decoder.h *********/
  83403. #ifndef FLAC__STREAM_DECODER_H
  83404. #define FLAC__STREAM_DECODER_H
  83405. #include <stdio.h> /* for FILE */
  83406. #ifdef __cplusplus
  83407. extern "C" {
  83408. #endif
  83409. /** \file include/FLAC/stream_decoder.h
  83410. *
  83411. * \brief
  83412. * This module contains the functions which implement the stream
  83413. * decoder.
  83414. *
  83415. * See the detailed documentation in the
  83416. * \link flac_stream_decoder stream decoder \endlink module.
  83417. */
  83418. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  83419. * \ingroup flac
  83420. *
  83421. * \brief
  83422. * This module describes the decoder layers provided by libFLAC.
  83423. *
  83424. * The stream decoder can be used to decode complete streams either from
  83425. * the client via callbacks, or directly from a file, depending on how
  83426. * it is initialized. When decoding via callbacks, the client provides
  83427. * callbacks for reading FLAC data and writing decoded samples, and
  83428. * handling metadata and errors. If the client also supplies seek-related
  83429. * callback, the decoder function for sample-accurate seeking within the
  83430. * FLAC input is also available. When decoding from a file, the client
  83431. * needs only supply a filename or open \c FILE* and write/metadata/error
  83432. * callbacks; the rest of the callbacks are supplied internally. For more
  83433. * info see the \link flac_stream_decoder stream decoder \endlink module.
  83434. */
  83435. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  83436. * \ingroup flac_decoder
  83437. *
  83438. * \brief
  83439. * This module contains the functions which implement the stream
  83440. * decoder.
  83441. *
  83442. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  83443. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  83444. *
  83445. * The basic usage of this decoder is as follows:
  83446. * - The program creates an instance of a decoder using
  83447. * FLAC__stream_decoder_new().
  83448. * - The program overrides the default settings using
  83449. * FLAC__stream_decoder_set_*() functions.
  83450. * - The program initializes the instance to validate the settings and
  83451. * prepare for decoding using
  83452. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  83453. * or FLAC__stream_decoder_init_file() for native FLAC,
  83454. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  83455. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  83456. * - The program calls the FLAC__stream_decoder_process_*() functions
  83457. * to decode data, which subsequently calls the callbacks.
  83458. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  83459. * which flushes the input and output and resets the decoder to the
  83460. * uninitialized state.
  83461. * - The instance may be used again or deleted with
  83462. * FLAC__stream_decoder_delete().
  83463. *
  83464. * In more detail, the program will create a new instance by calling
  83465. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  83466. * functions to override the default decoder options, and call
  83467. * one of the FLAC__stream_decoder_init_*() functions.
  83468. *
  83469. * There are three initialization functions for native FLAC, one for
  83470. * setting up the decoder to decode FLAC data from the client via
  83471. * callbacks, and two for decoding directly from a FLAC file.
  83472. *
  83473. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  83474. * You must also supply several callbacks for handling I/O. Some (like
  83475. * seeking) are optional, depending on the capabilities of the input.
  83476. *
  83477. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  83478. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  83479. * \c FILE* or filename and fewer callbacks; the decoder will handle
  83480. * the other callbacks internally.
  83481. *
  83482. * There are three similarly-named init functions for decoding from Ogg
  83483. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  83484. * library has been built with Ogg support.
  83485. *
  83486. * Once the decoder is initialized, your program will call one of several
  83487. * functions to start the decoding process:
  83488. *
  83489. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  83490. * most one metadata block or audio frame and return, calling either the
  83491. * metadata callback or write callback, respectively, once. If the decoder
  83492. * loses sync it will return with only the error callback being called.
  83493. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  83494. * to process the stream from the current location and stop upon reaching
  83495. * the first audio frame. The client will get one metadata, write, or error
  83496. * callback per metadata block, audio frame, or sync error, respectively.
  83497. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  83498. * to process the stream from the current location until the read callback
  83499. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  83500. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  83501. * write, or error callback per metadata block, audio frame, or sync error,
  83502. * respectively.
  83503. *
  83504. * When the decoder has finished decoding (normally or through an abort),
  83505. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  83506. * ensures the decoder is in the correct state and frees memory. Then the
  83507. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  83508. * again to decode another stream.
  83509. *
  83510. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  83511. * At any point after the stream decoder has been initialized, the client can
  83512. * call this function to seek to an exact sample within the stream.
  83513. * Subsequently, the first time the write callback is called it will be
  83514. * passed a (possibly partial) block starting at that sample.
  83515. *
  83516. * If the client cannot seek via the callback interface provided, but still
  83517. * has another way of seeking, it can flush the decoder using
  83518. * FLAC__stream_decoder_flush() and start feeding data from the new position
  83519. * through the read callback.
  83520. *
  83521. * The stream decoder also provides MD5 signature checking. If this is
  83522. * turned on before initialization, FLAC__stream_decoder_finish() will
  83523. * report when the decoded MD5 signature does not match the one stored
  83524. * in the STREAMINFO block. MD5 checking is automatically turned off
  83525. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  83526. * in the STREAMINFO block or when a seek is attempted.
  83527. *
  83528. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  83529. * attention. By default, the decoder only calls the metadata_callback for
  83530. * the STREAMINFO block. These functions allow you to tell the decoder
  83531. * explicitly which blocks to parse and return via the metadata_callback
  83532. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  83533. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  83534. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  83535. * which blocks to return. Remember that metadata blocks can potentially
  83536. * be big (for example, cover art) so filtering out the ones you don't
  83537. * use can reduce the memory requirements of the decoder. Also note the
  83538. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  83539. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  83540. * filtering APPLICATION blocks based on the application ID.
  83541. *
  83542. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  83543. * they still can legally be filtered from the metadata_callback.
  83544. *
  83545. * \note
  83546. * The "set" functions may only be called when the decoder is in the
  83547. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  83548. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  83549. * before FLAC__stream_decoder_init_*(). If this is the case they will
  83550. * return \c true, otherwise \c false.
  83551. *
  83552. * \note
  83553. * FLAC__stream_decoder_finish() resets all settings to the constructor
  83554. * defaults, including the callbacks.
  83555. *
  83556. * \{
  83557. */
  83558. /** State values for a FLAC__StreamDecoder
  83559. *
  83560. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  83561. */
  83562. typedef enum {
  83563. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  83564. /**< The decoder is ready to search for metadata. */
  83565. FLAC__STREAM_DECODER_READ_METADATA,
  83566. /**< The decoder is ready to or is in the process of reading metadata. */
  83567. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  83568. /**< The decoder is ready to or is in the process of searching for the
  83569. * frame sync code.
  83570. */
  83571. FLAC__STREAM_DECODER_READ_FRAME,
  83572. /**< The decoder is ready to or is in the process of reading a frame. */
  83573. FLAC__STREAM_DECODER_END_OF_STREAM,
  83574. /**< The decoder has reached the end of the stream. */
  83575. FLAC__STREAM_DECODER_OGG_ERROR,
  83576. /**< An error occurred in the underlying Ogg layer. */
  83577. FLAC__STREAM_DECODER_SEEK_ERROR,
  83578. /**< An error occurred while seeking. The decoder must be flushed
  83579. * with FLAC__stream_decoder_flush() or reset with
  83580. * FLAC__stream_decoder_reset() before decoding can continue.
  83581. */
  83582. FLAC__STREAM_DECODER_ABORTED,
  83583. /**< The decoder was aborted by the read callback. */
  83584. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  83585. /**< An error occurred allocating memory. The decoder is in an invalid
  83586. * state and can no longer be used.
  83587. */
  83588. FLAC__STREAM_DECODER_UNINITIALIZED
  83589. /**< The decoder is in the uninitialized state; one of the
  83590. * FLAC__stream_decoder_init_*() functions must be called before samples
  83591. * can be processed.
  83592. */
  83593. } FLAC__StreamDecoderState;
  83594. /** Maps a FLAC__StreamDecoderState to a C string.
  83595. *
  83596. * Using a FLAC__StreamDecoderState as the index to this array
  83597. * will give the string equivalent. The contents should not be modified.
  83598. */
  83599. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  83600. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  83601. */
  83602. typedef enum {
  83603. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  83604. /**< Initialization was successful. */
  83605. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  83606. /**< The library was not compiled with support for the given container
  83607. * format.
  83608. */
  83609. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  83610. /**< A required callback was not supplied. */
  83611. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  83612. /**< An error occurred allocating memory. */
  83613. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  83614. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  83615. * FLAC__stream_decoder_init_ogg_file(). */
  83616. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  83617. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  83618. * already initialized, usually because
  83619. * FLAC__stream_decoder_finish() was not called.
  83620. */
  83621. } FLAC__StreamDecoderInitStatus;
  83622. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  83623. *
  83624. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  83625. * will give the string equivalent. The contents should not be modified.
  83626. */
  83627. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  83628. /** Return values for the FLAC__StreamDecoder read callback.
  83629. */
  83630. typedef enum {
  83631. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  83632. /**< The read was OK and decoding can continue. */
  83633. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  83634. /**< The read was attempted while at the end of the stream. Note that
  83635. * the client must only return this value when the read callback was
  83636. * called when already at the end of the stream. Otherwise, if the read
  83637. * itself moves to the end of the stream, the client should still return
  83638. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  83639. * the next read callback it should return
  83640. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  83641. * of \c 0.
  83642. */
  83643. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  83644. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  83645. } FLAC__StreamDecoderReadStatus;
  83646. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  83647. *
  83648. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  83649. * will give the string equivalent. The contents should not be modified.
  83650. */
  83651. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  83652. /** Return values for the FLAC__StreamDecoder seek callback.
  83653. */
  83654. typedef enum {
  83655. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  83656. /**< The seek was OK and decoding can continue. */
  83657. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  83658. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  83659. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  83660. /**< Client does not support seeking. */
  83661. } FLAC__StreamDecoderSeekStatus;
  83662. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  83663. *
  83664. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  83665. * will give the string equivalent. The contents should not be modified.
  83666. */
  83667. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  83668. /** Return values for the FLAC__StreamDecoder tell callback.
  83669. */
  83670. typedef enum {
  83671. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  83672. /**< The tell was OK and decoding can continue. */
  83673. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  83674. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  83675. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  83676. /**< Client does not support telling the position. */
  83677. } FLAC__StreamDecoderTellStatus;
  83678. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  83679. *
  83680. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  83681. * will give the string equivalent. The contents should not be modified.
  83682. */
  83683. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  83684. /** Return values for the FLAC__StreamDecoder length callback.
  83685. */
  83686. typedef enum {
  83687. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  83688. /**< The length call was OK and decoding can continue. */
  83689. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  83690. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  83691. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  83692. /**< Client does not support reporting the length. */
  83693. } FLAC__StreamDecoderLengthStatus;
  83694. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  83695. *
  83696. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  83697. * will give the string equivalent. The contents should not be modified.
  83698. */
  83699. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  83700. /** Return values for the FLAC__StreamDecoder write callback.
  83701. */
  83702. typedef enum {
  83703. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  83704. /**< The write was OK and decoding can continue. */
  83705. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  83706. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  83707. } FLAC__StreamDecoderWriteStatus;
  83708. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  83709. *
  83710. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  83711. * will give the string equivalent. The contents should not be modified.
  83712. */
  83713. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  83714. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  83715. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  83716. * all. The rest could be caused by bad sync (false synchronization on
  83717. * data that is not the start of a frame) or corrupted data. The error
  83718. * itself is the decoder's best guess at what happened assuming a correct
  83719. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  83720. * could be caused by a correct sync on the start of a frame, but some
  83721. * data in the frame header was corrupted. Or it could be the result of
  83722. * syncing on a point the stream that looked like the starting of a frame
  83723. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  83724. * could be because the decoder encountered a valid frame made by a future
  83725. * version of the encoder which it cannot parse, or because of a false
  83726. * sync making it appear as though an encountered frame was generated by
  83727. * a future encoder.
  83728. */
  83729. typedef enum {
  83730. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  83731. /**< An error in the stream caused the decoder to lose synchronization. */
  83732. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  83733. /**< The decoder encountered a corrupted frame header. */
  83734. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  83735. /**< The frame's data did not match the CRC in the footer. */
  83736. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  83737. /**< The decoder encountered reserved fields in use in the stream. */
  83738. } FLAC__StreamDecoderErrorStatus;
  83739. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  83740. *
  83741. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  83742. * will give the string equivalent. The contents should not be modified.
  83743. */
  83744. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  83745. /***********************************************************************
  83746. *
  83747. * class FLAC__StreamDecoder
  83748. *
  83749. ***********************************************************************/
  83750. struct FLAC__StreamDecoderProtected;
  83751. struct FLAC__StreamDecoderPrivate;
  83752. /** The opaque structure definition for the stream decoder type.
  83753. * See the \link flac_stream_decoder stream decoder module \endlink
  83754. * for a detailed description.
  83755. */
  83756. typedef struct {
  83757. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  83758. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  83759. } FLAC__StreamDecoder;
  83760. /** Signature for the read callback.
  83761. *
  83762. * A function pointer matching this signature must be passed to
  83763. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83764. * called when the decoder needs more input data. The address of the
  83765. * buffer to be filled is supplied, along with the number of bytes the
  83766. * buffer can hold. The callback may choose to supply less data and
  83767. * modify the byte count but must be careful not to overflow the buffer.
  83768. * The callback then returns a status code chosen from
  83769. * FLAC__StreamDecoderReadStatus.
  83770. *
  83771. * Here is an example of a read callback for stdio streams:
  83772. * \code
  83773. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  83774. * {
  83775. * FILE *file = ((MyClientData*)client_data)->file;
  83776. * if(*bytes > 0) {
  83777. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  83778. * if(ferror(file))
  83779. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  83780. * else if(*bytes == 0)
  83781. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  83782. * else
  83783. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  83784. * }
  83785. * else
  83786. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  83787. * }
  83788. * \endcode
  83789. *
  83790. * \note In general, FLAC__StreamDecoder functions which change the
  83791. * state should not be called on the \a decoder while in the callback.
  83792. *
  83793. * \param decoder The decoder instance calling the callback.
  83794. * \param buffer A pointer to a location for the callee to store
  83795. * data to be decoded.
  83796. * \param bytes A pointer to the size of the buffer. On entry
  83797. * to the callback, it contains the maximum number
  83798. * of bytes that may be stored in \a buffer. The
  83799. * callee must set it to the actual number of bytes
  83800. * stored (0 in case of error or end-of-stream) before
  83801. * returning.
  83802. * \param client_data The callee's client data set through
  83803. * FLAC__stream_decoder_init_*().
  83804. * \retval FLAC__StreamDecoderReadStatus
  83805. * The callee's return status. Note that the callback should return
  83806. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  83807. * zero bytes were read and there is no more data to be read.
  83808. */
  83809. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  83810. /** Signature for the seek callback.
  83811. *
  83812. * A function pointer matching this signature may be passed to
  83813. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83814. * called when the decoder needs to seek the input stream. The decoder
  83815. * will pass the absolute byte offset to seek to, 0 meaning the
  83816. * beginning of the stream.
  83817. *
  83818. * Here is an example of a seek callback for stdio streams:
  83819. * \code
  83820. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  83821. * {
  83822. * FILE *file = ((MyClientData*)client_data)->file;
  83823. * if(file == stdin)
  83824. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  83825. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  83826. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  83827. * else
  83828. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  83829. * }
  83830. * \endcode
  83831. *
  83832. * \note In general, FLAC__StreamDecoder functions which change the
  83833. * state should not be called on the \a decoder while in the callback.
  83834. *
  83835. * \param decoder The decoder instance calling the callback.
  83836. * \param absolute_byte_offset The offset from the beginning of the stream
  83837. * to seek to.
  83838. * \param client_data The callee's client data set through
  83839. * FLAC__stream_decoder_init_*().
  83840. * \retval FLAC__StreamDecoderSeekStatus
  83841. * The callee's return status.
  83842. */
  83843. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  83844. /** Signature for the tell callback.
  83845. *
  83846. * A function pointer matching this signature may be passed to
  83847. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83848. * called when the decoder wants to know the current position of the
  83849. * stream. The callback should return the byte offset from the
  83850. * beginning of the stream.
  83851. *
  83852. * Here is an example of a tell callback for stdio streams:
  83853. * \code
  83854. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  83855. * {
  83856. * FILE *file = ((MyClientData*)client_data)->file;
  83857. * off_t pos;
  83858. * if(file == stdin)
  83859. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  83860. * else if((pos = ftello(file)) < 0)
  83861. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  83862. * else {
  83863. * *absolute_byte_offset = (FLAC__uint64)pos;
  83864. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  83865. * }
  83866. * }
  83867. * \endcode
  83868. *
  83869. * \note In general, FLAC__StreamDecoder functions which change the
  83870. * state should not be called on the \a decoder while in the callback.
  83871. *
  83872. * \param decoder The decoder instance calling the callback.
  83873. * \param absolute_byte_offset A pointer to storage for the current offset
  83874. * from the beginning of the stream.
  83875. * \param client_data The callee's client data set through
  83876. * FLAC__stream_decoder_init_*().
  83877. * \retval FLAC__StreamDecoderTellStatus
  83878. * The callee's return status.
  83879. */
  83880. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  83881. /** Signature for the length callback.
  83882. *
  83883. * A function pointer matching this signature may be passed to
  83884. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83885. * called when the decoder wants to know the total length of the stream
  83886. * in bytes.
  83887. *
  83888. * Here is an example of a length callback for stdio streams:
  83889. * \code
  83890. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  83891. * {
  83892. * FILE *file = ((MyClientData*)client_data)->file;
  83893. * struct stat filestats;
  83894. *
  83895. * if(file == stdin)
  83896. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  83897. * else if(fstat(fileno(file), &filestats) != 0)
  83898. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  83899. * else {
  83900. * *stream_length = (FLAC__uint64)filestats.st_size;
  83901. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  83902. * }
  83903. * }
  83904. * \endcode
  83905. *
  83906. * \note In general, FLAC__StreamDecoder functions which change the
  83907. * state should not be called on the \a decoder while in the callback.
  83908. *
  83909. * \param decoder The decoder instance calling the callback.
  83910. * \param stream_length A pointer to storage for the length of the stream
  83911. * in bytes.
  83912. * \param client_data The callee's client data set through
  83913. * FLAC__stream_decoder_init_*().
  83914. * \retval FLAC__StreamDecoderLengthStatus
  83915. * The callee's return status.
  83916. */
  83917. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  83918. /** Signature for the EOF callback.
  83919. *
  83920. * A function pointer matching this signature may be passed to
  83921. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83922. * called when the decoder needs to know if the end of the stream has
  83923. * been reached.
  83924. *
  83925. * Here is an example of a EOF callback for stdio streams:
  83926. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  83927. * \code
  83928. * {
  83929. * FILE *file = ((MyClientData*)client_data)->file;
  83930. * return feof(file)? true : false;
  83931. * }
  83932. * \endcode
  83933. *
  83934. * \note In general, FLAC__StreamDecoder functions which change the
  83935. * state should not be called on the \a decoder while in the callback.
  83936. *
  83937. * \param decoder The decoder instance calling the callback.
  83938. * \param client_data The callee's client data set through
  83939. * FLAC__stream_decoder_init_*().
  83940. * \retval FLAC__bool
  83941. * \c true if the currently at the end of the stream, else \c false.
  83942. */
  83943. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  83944. /** Signature for the write callback.
  83945. *
  83946. * A function pointer matching this signature must be passed to one of
  83947. * the FLAC__stream_decoder_init_*() functions.
  83948. * The supplied function will be called when the decoder has decoded a
  83949. * single audio frame. The decoder will pass the frame metadata as well
  83950. * as an array of pointers (one for each channel) pointing to the
  83951. * decoded audio.
  83952. *
  83953. * \note In general, FLAC__StreamDecoder functions which change the
  83954. * state should not be called on the \a decoder while in the callback.
  83955. *
  83956. * \param decoder The decoder instance calling the callback.
  83957. * \param frame The description of the decoded frame. See
  83958. * FLAC__Frame.
  83959. * \param buffer An array of pointers to decoded channels of data.
  83960. * Each pointer will point to an array of signed
  83961. * samples of length \a frame->header.blocksize.
  83962. * Channels will be ordered according to the FLAC
  83963. * specification; see the documentation for the
  83964. * <A HREF="../format.html#frame_header">frame header</A>.
  83965. * \param client_data The callee's client data set through
  83966. * FLAC__stream_decoder_init_*().
  83967. * \retval FLAC__StreamDecoderWriteStatus
  83968. * The callee's return status.
  83969. */
  83970. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  83971. /** Signature for the metadata callback.
  83972. *
  83973. * A function pointer matching this signature must be passed to one of
  83974. * the FLAC__stream_decoder_init_*() functions.
  83975. * The supplied function will be called when the decoder has decoded a
  83976. * metadata block. In a valid FLAC file there will always be one
  83977. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  83978. * These will be supplied by the decoder in the same order as they
  83979. * appear in the stream and always before the first audio frame (i.e.
  83980. * write callback). The metadata block that is passed in must not be
  83981. * modified, and it doesn't live beyond the callback, so you should make
  83982. * a copy of it with FLAC__metadata_object_clone() if you will need it
  83983. * elsewhere. Since metadata blocks can potentially be large, by
  83984. * default the decoder only calls the metadata callback for the
  83985. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  83986. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  83987. *
  83988. * \note In general, FLAC__StreamDecoder functions which change the
  83989. * state should not be called on the \a decoder while in the callback.
  83990. *
  83991. * \param decoder The decoder instance calling the callback.
  83992. * \param metadata The decoded metadata block.
  83993. * \param client_data The callee's client data set through
  83994. * FLAC__stream_decoder_init_*().
  83995. */
  83996. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  83997. /** Signature for the error callback.
  83998. *
  83999. * A function pointer matching this signature must be passed to one of
  84000. * the FLAC__stream_decoder_init_*() functions.
  84001. * The supplied function will be called whenever an error occurs during
  84002. * decoding.
  84003. *
  84004. * \note In general, FLAC__StreamDecoder functions which change the
  84005. * state should not be called on the \a decoder while in the callback.
  84006. *
  84007. * \param decoder The decoder instance calling the callback.
  84008. * \param status The error encountered by the decoder.
  84009. * \param client_data The callee's client data set through
  84010. * FLAC__stream_decoder_init_*().
  84011. */
  84012. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  84013. /***********************************************************************
  84014. *
  84015. * Class constructor/destructor
  84016. *
  84017. ***********************************************************************/
  84018. /** Create a new stream decoder instance. The instance is created with
  84019. * default settings; see the individual FLAC__stream_decoder_set_*()
  84020. * functions for each setting's default.
  84021. *
  84022. * \retval FLAC__StreamDecoder*
  84023. * \c NULL if there was an error allocating memory, else the new instance.
  84024. */
  84025. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  84026. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  84027. *
  84028. * \param decoder A pointer to an existing decoder.
  84029. * \assert
  84030. * \code decoder != NULL \endcode
  84031. */
  84032. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  84033. /***********************************************************************
  84034. *
  84035. * Public class method prototypes
  84036. *
  84037. ***********************************************************************/
  84038. /** Set the serial number for the FLAC stream within the Ogg container.
  84039. * The default behavior is to use the serial number of the first Ogg
  84040. * page. Setting a serial number here will explicitly specify which
  84041. * stream is to be decoded.
  84042. *
  84043. * \note
  84044. * This does not need to be set for native FLAC decoding.
  84045. *
  84046. * \default \c use serial number of first page
  84047. * \param decoder A decoder instance to set.
  84048. * \param serial_number See above.
  84049. * \assert
  84050. * \code decoder != NULL \endcode
  84051. * \retval FLAC__bool
  84052. * \c false if the decoder is already initialized, else \c true.
  84053. */
  84054. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  84055. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  84056. * compute the MD5 signature of the unencoded audio data while decoding
  84057. * and compare it to the signature from the STREAMINFO block, if it
  84058. * exists, during FLAC__stream_decoder_finish().
  84059. *
  84060. * MD5 signature checking will be turned off (until the next
  84061. * FLAC__stream_decoder_reset()) if there is no signature in the
  84062. * STREAMINFO block or when a seek is attempted.
  84063. *
  84064. * Clients that do not use the MD5 check should leave this off to speed
  84065. * up decoding.
  84066. *
  84067. * \default \c false
  84068. * \param decoder A decoder instance to set.
  84069. * \param value Flag value (see above).
  84070. * \assert
  84071. * \code decoder != NULL \endcode
  84072. * \retval FLAC__bool
  84073. * \c false if the decoder is already initialized, else \c true.
  84074. */
  84075. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  84076. /** Direct the decoder to pass on all metadata blocks of type \a type.
  84077. *
  84078. * \default By default, only the \c STREAMINFO block is returned via the
  84079. * metadata callback.
  84080. * \param decoder A decoder instance to set.
  84081. * \param type See above.
  84082. * \assert
  84083. * \code decoder != NULL \endcode
  84084. * \a type is valid
  84085. * \retval FLAC__bool
  84086. * \c false if the decoder is already initialized, else \c true.
  84087. */
  84088. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  84089. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  84090. * given \a id.
  84091. *
  84092. * \default By default, only the \c STREAMINFO block is returned via the
  84093. * metadata callback.
  84094. * \param decoder A decoder instance to set.
  84095. * \param id See above.
  84096. * \assert
  84097. * \code decoder != NULL \endcode
  84098. * \code id != NULL \endcode
  84099. * \retval FLAC__bool
  84100. * \c false if the decoder is already initialized, else \c true.
  84101. */
  84102. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  84103. /** Direct the decoder to pass on all metadata blocks of any type.
  84104. *
  84105. * \default By default, only the \c STREAMINFO block is returned via the
  84106. * metadata callback.
  84107. * \param decoder A decoder instance to set.
  84108. * \assert
  84109. * \code decoder != NULL \endcode
  84110. * \retval FLAC__bool
  84111. * \c false if the decoder is already initialized, else \c true.
  84112. */
  84113. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  84114. /** Direct the decoder to filter out all metadata blocks of type \a type.
  84115. *
  84116. * \default By default, only the \c STREAMINFO block is returned via the
  84117. * metadata callback.
  84118. * \param decoder A decoder instance to set.
  84119. * \param type See above.
  84120. * \assert
  84121. * \code decoder != NULL \endcode
  84122. * \a type is valid
  84123. * \retval FLAC__bool
  84124. * \c false if the decoder is already initialized, else \c true.
  84125. */
  84126. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  84127. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  84128. * the given \a id.
  84129. *
  84130. * \default By default, only the \c STREAMINFO block is returned via the
  84131. * metadata callback.
  84132. * \param decoder A decoder instance to set.
  84133. * \param id See above.
  84134. * \assert
  84135. * \code decoder != NULL \endcode
  84136. * \code id != NULL \endcode
  84137. * \retval FLAC__bool
  84138. * \c false if the decoder is already initialized, else \c true.
  84139. */
  84140. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  84141. /** Direct the decoder to filter out all metadata blocks of any type.
  84142. *
  84143. * \default By default, only the \c STREAMINFO block is returned via the
  84144. * metadata callback.
  84145. * \param decoder A decoder instance to set.
  84146. * \assert
  84147. * \code decoder != NULL \endcode
  84148. * \retval FLAC__bool
  84149. * \c false if the decoder is already initialized, else \c true.
  84150. */
  84151. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  84152. /** Get the current decoder state.
  84153. *
  84154. * \param decoder A decoder instance to query.
  84155. * \assert
  84156. * \code decoder != NULL \endcode
  84157. * \retval FLAC__StreamDecoderState
  84158. * The current decoder state.
  84159. */
  84160. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  84161. /** Get the current decoder state as a C string.
  84162. *
  84163. * \param decoder A decoder instance to query.
  84164. * \assert
  84165. * \code decoder != NULL \endcode
  84166. * \retval const char *
  84167. * The decoder state as a C string. Do not modify the contents.
  84168. */
  84169. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  84170. /** Get the "MD5 signature checking" flag.
  84171. * This is the value of the setting, not whether or not the decoder is
  84172. * currently checking the MD5 (remember, it can be turned off automatically
  84173. * by a seek). When the decoder is reset the flag will be restored to the
  84174. * value returned by this function.
  84175. *
  84176. * \param decoder A decoder instance to query.
  84177. * \assert
  84178. * \code decoder != NULL \endcode
  84179. * \retval FLAC__bool
  84180. * See above.
  84181. */
  84182. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  84183. /** Get the total number of samples in the stream being decoded.
  84184. * Will only be valid after decoding has started and will contain the
  84185. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  84186. *
  84187. * \param decoder A decoder instance to query.
  84188. * \assert
  84189. * \code decoder != NULL \endcode
  84190. * \retval unsigned
  84191. * See above.
  84192. */
  84193. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  84194. /** Get the current number of channels in the stream being decoded.
  84195. * Will only be valid after decoding has started and will contain the
  84196. * value from the most recently decoded frame header.
  84197. *
  84198. * \param decoder A decoder instance to query.
  84199. * \assert
  84200. * \code decoder != NULL \endcode
  84201. * \retval unsigned
  84202. * See above.
  84203. */
  84204. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  84205. /** Get the current channel assignment in the stream being decoded.
  84206. * Will only be valid after decoding has started and will contain the
  84207. * value from the most recently decoded frame header.
  84208. *
  84209. * \param decoder A decoder instance to query.
  84210. * \assert
  84211. * \code decoder != NULL \endcode
  84212. * \retval FLAC__ChannelAssignment
  84213. * See above.
  84214. */
  84215. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  84216. /** Get the current sample resolution in the stream being decoded.
  84217. * Will only be valid after decoding has started and will contain the
  84218. * value from the most recently decoded frame header.
  84219. *
  84220. * \param decoder A decoder instance to query.
  84221. * \assert
  84222. * \code decoder != NULL \endcode
  84223. * \retval unsigned
  84224. * See above.
  84225. */
  84226. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  84227. /** Get the current sample rate in Hz of the stream being decoded.
  84228. * Will only be valid after decoding has started and will contain the
  84229. * value from the most recently decoded frame header.
  84230. *
  84231. * \param decoder A decoder instance to query.
  84232. * \assert
  84233. * \code decoder != NULL \endcode
  84234. * \retval unsigned
  84235. * See above.
  84236. */
  84237. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  84238. /** Get the current blocksize of the stream being decoded.
  84239. * Will only be valid after decoding has started and will contain the
  84240. * value from the most recently decoded frame header.
  84241. *
  84242. * \param decoder A decoder instance to query.
  84243. * \assert
  84244. * \code decoder != NULL \endcode
  84245. * \retval unsigned
  84246. * See above.
  84247. */
  84248. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  84249. /** Returns the decoder's current read position within the stream.
  84250. * The position is the byte offset from the start of the stream.
  84251. * Bytes before this position have been fully decoded. Note that
  84252. * there may still be undecoded bytes in the decoder's read FIFO.
  84253. * The returned position is correct even after a seek.
  84254. *
  84255. * \warning This function currently only works for native FLAC,
  84256. * not Ogg FLAC streams.
  84257. *
  84258. * \param decoder A decoder instance to query.
  84259. * \param position Address at which to return the desired position.
  84260. * \assert
  84261. * \code decoder != NULL \endcode
  84262. * \code position != NULL \endcode
  84263. * \retval FLAC__bool
  84264. * \c true if successful, \c false if the stream is not native FLAC,
  84265. * or there was an error from the 'tell' callback or it returned
  84266. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  84267. */
  84268. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  84269. /** Initialize the decoder instance to decode native FLAC streams.
  84270. *
  84271. * This flavor of initialization sets up the decoder to decode from a
  84272. * native FLAC stream. I/O is performed via callbacks to the client.
  84273. * For decoding from a plain file via filename or open FILE*,
  84274. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  84275. * provide a simpler interface.
  84276. *
  84277. * This function should be called after FLAC__stream_decoder_new() and
  84278. * FLAC__stream_decoder_set_*() but before any of the
  84279. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84280. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84281. * if initialization succeeded.
  84282. *
  84283. * \param decoder An uninitialized decoder instance.
  84284. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  84285. * pointer must not be \c NULL.
  84286. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  84287. * pointer may be \c NULL if seeking is not
  84288. * supported. If \a seek_callback is not \c NULL then a
  84289. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  84290. * Alternatively, a dummy seek callback that just
  84291. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  84292. * may also be supplied, all though this is slightly
  84293. * less efficient for the decoder.
  84294. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  84295. * pointer may be \c NULL if not supported by the client. If
  84296. * \a seek_callback is not \c NULL then a
  84297. * \a tell_callback must also be supplied.
  84298. * Alternatively, a dummy tell callback that just
  84299. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  84300. * may also be supplied, all though this is slightly
  84301. * less efficient for the decoder.
  84302. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  84303. * pointer may be \c NULL if not supported by the client. If
  84304. * \a seek_callback is not \c NULL then a
  84305. * \a length_callback must also be supplied.
  84306. * Alternatively, a dummy length callback that just
  84307. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  84308. * may also be supplied, all though this is slightly
  84309. * less efficient for the decoder.
  84310. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  84311. * pointer may be \c NULL if not supported by the client. If
  84312. * \a seek_callback is not \c NULL then a
  84313. * \a eof_callback must also be supplied.
  84314. * Alternatively, a dummy length callback that just
  84315. * returns \c false
  84316. * may also be supplied, all though this is slightly
  84317. * less efficient for the decoder.
  84318. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84319. * pointer must not be \c NULL.
  84320. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84321. * pointer may be \c NULL if the callback is not
  84322. * desired.
  84323. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84324. * pointer must not be \c NULL.
  84325. * \param client_data This value will be supplied to callbacks in their
  84326. * \a client_data argument.
  84327. * \assert
  84328. * \code decoder != NULL \endcode
  84329. * \retval FLAC__StreamDecoderInitStatus
  84330. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84331. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84332. */
  84333. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  84334. FLAC__StreamDecoder *decoder,
  84335. FLAC__StreamDecoderReadCallback read_callback,
  84336. FLAC__StreamDecoderSeekCallback seek_callback,
  84337. FLAC__StreamDecoderTellCallback tell_callback,
  84338. FLAC__StreamDecoderLengthCallback length_callback,
  84339. FLAC__StreamDecoderEofCallback eof_callback,
  84340. FLAC__StreamDecoderWriteCallback write_callback,
  84341. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84342. FLAC__StreamDecoderErrorCallback error_callback,
  84343. void *client_data
  84344. );
  84345. /** Initialize the decoder instance to decode Ogg FLAC streams.
  84346. *
  84347. * This flavor of initialization sets up the decoder to decode from a
  84348. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  84349. * client. For decoding from a plain file via filename or open FILE*,
  84350. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  84351. * provide a simpler interface.
  84352. *
  84353. * This function should be called after FLAC__stream_decoder_new() and
  84354. * FLAC__stream_decoder_set_*() but before any of the
  84355. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84356. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84357. * if initialization succeeded.
  84358. *
  84359. * \note Support for Ogg FLAC in the library is optional. If this
  84360. * library has been built without support for Ogg FLAC, this function
  84361. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  84362. *
  84363. * \param decoder An uninitialized decoder instance.
  84364. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  84365. * pointer must not be \c NULL.
  84366. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  84367. * pointer may be \c NULL if seeking is not
  84368. * supported. If \a seek_callback is not \c NULL then a
  84369. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  84370. * Alternatively, a dummy seek callback that just
  84371. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  84372. * may also be supplied, all though this is slightly
  84373. * less efficient for the decoder.
  84374. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  84375. * pointer may be \c NULL if not supported by the client. If
  84376. * \a seek_callback is not \c NULL then a
  84377. * \a tell_callback must also be supplied.
  84378. * Alternatively, a dummy tell callback that just
  84379. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  84380. * may also be supplied, all though this is slightly
  84381. * less efficient for the decoder.
  84382. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  84383. * pointer may be \c NULL if not supported by the client. If
  84384. * \a seek_callback is not \c NULL then a
  84385. * \a length_callback must also be supplied.
  84386. * Alternatively, a dummy length callback that just
  84387. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  84388. * may also be supplied, all though this is slightly
  84389. * less efficient for the decoder.
  84390. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  84391. * pointer may be \c NULL if not supported by the client. If
  84392. * \a seek_callback is not \c NULL then a
  84393. * \a eof_callback must also be supplied.
  84394. * Alternatively, a dummy length callback that just
  84395. * returns \c false
  84396. * may also be supplied, all though this is slightly
  84397. * less efficient for the decoder.
  84398. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84399. * pointer must not be \c NULL.
  84400. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84401. * pointer may be \c NULL if the callback is not
  84402. * desired.
  84403. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84404. * pointer must not be \c NULL.
  84405. * \param client_data This value will be supplied to callbacks in their
  84406. * \a client_data argument.
  84407. * \assert
  84408. * \code decoder != NULL \endcode
  84409. * \retval FLAC__StreamDecoderInitStatus
  84410. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84411. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84412. */
  84413. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  84414. FLAC__StreamDecoder *decoder,
  84415. FLAC__StreamDecoderReadCallback read_callback,
  84416. FLAC__StreamDecoderSeekCallback seek_callback,
  84417. FLAC__StreamDecoderTellCallback tell_callback,
  84418. FLAC__StreamDecoderLengthCallback length_callback,
  84419. FLAC__StreamDecoderEofCallback eof_callback,
  84420. FLAC__StreamDecoderWriteCallback write_callback,
  84421. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84422. FLAC__StreamDecoderErrorCallback error_callback,
  84423. void *client_data
  84424. );
  84425. /** Initialize the decoder instance to decode native FLAC files.
  84426. *
  84427. * This flavor of initialization sets up the decoder to decode from a
  84428. * plain native FLAC file. For non-stdio streams, you must use
  84429. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  84430. *
  84431. * This function should be called after FLAC__stream_decoder_new() and
  84432. * FLAC__stream_decoder_set_*() but before any of the
  84433. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84434. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84435. * if initialization succeeded.
  84436. *
  84437. * \param decoder An uninitialized decoder instance.
  84438. * \param file An open FLAC file. The file should have been
  84439. * opened with mode \c "rb" and rewound. The file
  84440. * becomes owned by the decoder and should not be
  84441. * manipulated by the client while decoding.
  84442. * Unless \a file is \c stdin, it will be closed
  84443. * when FLAC__stream_decoder_finish() is called.
  84444. * Note however that seeking will not work when
  84445. * decoding from \c stdout since it is not seekable.
  84446. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84447. * pointer must not be \c NULL.
  84448. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84449. * pointer may be \c NULL if the callback is not
  84450. * desired.
  84451. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84452. * pointer must not be \c NULL.
  84453. * \param client_data This value will be supplied to callbacks in their
  84454. * \a client_data argument.
  84455. * \assert
  84456. * \code decoder != NULL \endcode
  84457. * \code file != NULL \endcode
  84458. * \retval FLAC__StreamDecoderInitStatus
  84459. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84460. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84461. */
  84462. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  84463. FLAC__StreamDecoder *decoder,
  84464. FILE *file,
  84465. FLAC__StreamDecoderWriteCallback write_callback,
  84466. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84467. FLAC__StreamDecoderErrorCallback error_callback,
  84468. void *client_data
  84469. );
  84470. /** Initialize the decoder instance to decode Ogg FLAC files.
  84471. *
  84472. * This flavor of initialization sets up the decoder to decode from a
  84473. * plain Ogg FLAC file. For non-stdio streams, you must use
  84474. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  84475. *
  84476. * This function should be called after FLAC__stream_decoder_new() and
  84477. * FLAC__stream_decoder_set_*() but before any of the
  84478. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84479. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84480. * if initialization succeeded.
  84481. *
  84482. * \note Support for Ogg FLAC in the library is optional. If this
  84483. * library has been built without support for Ogg FLAC, this function
  84484. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  84485. *
  84486. * \param decoder An uninitialized decoder instance.
  84487. * \param file An open FLAC file. The file should have been
  84488. * opened with mode \c "rb" and rewound. The file
  84489. * becomes owned by the decoder and should not be
  84490. * manipulated by the client while decoding.
  84491. * Unless \a file is \c stdin, it will be closed
  84492. * when FLAC__stream_decoder_finish() is called.
  84493. * Note however that seeking will not work when
  84494. * decoding from \c stdout since it is not seekable.
  84495. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84496. * pointer must not be \c NULL.
  84497. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84498. * pointer may be \c NULL if the callback is not
  84499. * desired.
  84500. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84501. * pointer must not be \c NULL.
  84502. * \param client_data This value will be supplied to callbacks in their
  84503. * \a client_data argument.
  84504. * \assert
  84505. * \code decoder != NULL \endcode
  84506. * \code file != NULL \endcode
  84507. * \retval FLAC__StreamDecoderInitStatus
  84508. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84509. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84510. */
  84511. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  84512. FLAC__StreamDecoder *decoder,
  84513. FILE *file,
  84514. FLAC__StreamDecoderWriteCallback write_callback,
  84515. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84516. FLAC__StreamDecoderErrorCallback error_callback,
  84517. void *client_data
  84518. );
  84519. /** Initialize the decoder instance to decode native FLAC files.
  84520. *
  84521. * This flavor of initialization sets up the decoder to decode from a plain
  84522. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  84523. * example, with Unicode filenames on Windows), you must use
  84524. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  84525. * and provide callbacks for the I/O.
  84526. *
  84527. * This function should be called after FLAC__stream_decoder_new() and
  84528. * FLAC__stream_decoder_set_*() but before any of the
  84529. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84530. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84531. * if initialization succeeded.
  84532. *
  84533. * \param decoder An uninitialized decoder instance.
  84534. * \param filename The name of the file to decode from. The file will
  84535. * be opened with fopen(). Use \c NULL to decode from
  84536. * \c stdin. Note that \c stdin is not seekable.
  84537. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84538. * pointer must not be \c NULL.
  84539. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84540. * pointer may be \c NULL if the callback is not
  84541. * desired.
  84542. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84543. * pointer must not be \c NULL.
  84544. * \param client_data This value will be supplied to callbacks in their
  84545. * \a client_data argument.
  84546. * \assert
  84547. * \code decoder != NULL \endcode
  84548. * \retval FLAC__StreamDecoderInitStatus
  84549. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84550. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84551. */
  84552. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  84553. FLAC__StreamDecoder *decoder,
  84554. const char *filename,
  84555. FLAC__StreamDecoderWriteCallback write_callback,
  84556. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84557. FLAC__StreamDecoderErrorCallback error_callback,
  84558. void *client_data
  84559. );
  84560. /** Initialize the decoder instance to decode Ogg FLAC files.
  84561. *
  84562. * This flavor of initialization sets up the decoder to decode from a plain
  84563. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  84564. * example, with Unicode filenames on Windows), you must use
  84565. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  84566. * and provide callbacks for the I/O.
  84567. *
  84568. * This function should be called after FLAC__stream_decoder_new() and
  84569. * FLAC__stream_decoder_set_*() but before any of the
  84570. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84571. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84572. * if initialization succeeded.
  84573. *
  84574. * \note Support for Ogg FLAC in the library is optional. If this
  84575. * library has been built without support for Ogg FLAC, this function
  84576. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  84577. *
  84578. * \param decoder An uninitialized decoder instance.
  84579. * \param filename The name of the file to decode from. The file will
  84580. * be opened with fopen(). Use \c NULL to decode from
  84581. * \c stdin. Note that \c stdin is not seekable.
  84582. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84583. * pointer must not be \c NULL.
  84584. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84585. * pointer may be \c NULL if the callback is not
  84586. * desired.
  84587. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84588. * pointer must not be \c NULL.
  84589. * \param client_data This value will be supplied to callbacks in their
  84590. * \a client_data argument.
  84591. * \assert
  84592. * \code decoder != NULL \endcode
  84593. * \retval FLAC__StreamDecoderInitStatus
  84594. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84595. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84596. */
  84597. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  84598. FLAC__StreamDecoder *decoder,
  84599. const char *filename,
  84600. FLAC__StreamDecoderWriteCallback write_callback,
  84601. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84602. FLAC__StreamDecoderErrorCallback error_callback,
  84603. void *client_data
  84604. );
  84605. /** Finish the decoding process.
  84606. * Flushes the decoding buffer, releases resources, resets the decoder
  84607. * settings to their defaults, and returns the decoder state to
  84608. * FLAC__STREAM_DECODER_UNINITIALIZED.
  84609. *
  84610. * In the event of a prematurely-terminated decode, it is not strictly
  84611. * necessary to call this immediately before FLAC__stream_decoder_delete()
  84612. * but it is good practice to match every FLAC__stream_decoder_init_*()
  84613. * with a FLAC__stream_decoder_finish().
  84614. *
  84615. * \param decoder An uninitialized decoder instance.
  84616. * \assert
  84617. * \code decoder != NULL \endcode
  84618. * \retval FLAC__bool
  84619. * \c false if MD5 checking is on AND a STREAMINFO block was available
  84620. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  84621. * signature does not match the one computed by the decoder; else
  84622. * \c true.
  84623. */
  84624. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  84625. /** Flush the stream input.
  84626. * The decoder's input buffer will be cleared and the state set to
  84627. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  84628. * off MD5 checking.
  84629. *
  84630. * \param decoder A decoder instance.
  84631. * \assert
  84632. * \code decoder != NULL \endcode
  84633. * \retval FLAC__bool
  84634. * \c true if successful, else \c false if a memory allocation
  84635. * error occurs (in which case the state will be set to
  84636. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  84637. */
  84638. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  84639. /** Reset the decoding process.
  84640. * The decoder's input buffer will be cleared and the state set to
  84641. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  84642. * FLAC__stream_decoder_finish() except that the settings are
  84643. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  84644. * before decoding again. MD5 checking will be restored to its original
  84645. * setting.
  84646. *
  84647. * If the decoder is seekable, or was initialized with
  84648. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  84649. * the decoder will also attempt to seek to the beginning of the file.
  84650. * If this rewind fails, this function will return \c false. It follows
  84651. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  84652. * \c stdin.
  84653. *
  84654. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  84655. * and is not seekable (i.e. no seek callback was provided or the seek
  84656. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  84657. * is the duty of the client to start feeding data from the beginning of
  84658. * the stream on the next FLAC__stream_decoder_process() or
  84659. * FLAC__stream_decoder_process_interleaved() call.
  84660. *
  84661. * \param decoder A decoder instance.
  84662. * \assert
  84663. * \code decoder != NULL \endcode
  84664. * \retval FLAC__bool
  84665. * \c true if successful, else \c false if a memory allocation occurs
  84666. * (in which case the state will be set to
  84667. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  84668. * occurs (the state will be unchanged).
  84669. */
  84670. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  84671. /** Decode one metadata block or audio frame.
  84672. * This version instructs the decoder to decode a either a single metadata
  84673. * block or a single frame and stop, unless the callbacks return a fatal
  84674. * error or the read callback returns
  84675. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  84676. *
  84677. * As the decoder needs more input it will call the read callback.
  84678. * Depending on what was decoded, the metadata or write callback will be
  84679. * called with the decoded metadata block or audio frame.
  84680. *
  84681. * Unless there is a fatal read error or end of stream, this function
  84682. * will return once one whole frame is decoded. In other words, if the
  84683. * stream is not synchronized or points to a corrupt frame header, the
  84684. * decoder will continue to try and resync until it gets to a valid
  84685. * frame, then decode one frame, then return. If the decoder points to
  84686. * a frame whose frame CRC in the frame footer does not match the
  84687. * computed frame CRC, this function will issue a
  84688. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  84689. * error callback, and return, having decoded one complete, although
  84690. * corrupt, frame. (Such corrupted frames are sent as silence of the
  84691. * correct length to the write callback.)
  84692. *
  84693. * \param decoder An initialized decoder instance.
  84694. * \assert
  84695. * \code decoder != NULL \endcode
  84696. * \retval FLAC__bool
  84697. * \c false if any fatal read, write, or memory allocation error
  84698. * occurred (meaning decoding must stop), else \c true; for more
  84699. * information about the decoder, check the decoder state with
  84700. * FLAC__stream_decoder_get_state().
  84701. */
  84702. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  84703. /** Decode until the end of the metadata.
  84704. * This version instructs the decoder to decode from the current position
  84705. * and continue until all the metadata has been read, or until the
  84706. * callbacks return a fatal error or the read callback returns
  84707. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  84708. *
  84709. * As the decoder needs more input it will call the read callback.
  84710. * As each metadata block is decoded, the metadata callback will be called
  84711. * with the decoded metadata.
  84712. *
  84713. * \param decoder An initialized decoder instance.
  84714. * \assert
  84715. * \code decoder != NULL \endcode
  84716. * \retval FLAC__bool
  84717. * \c false if any fatal read, write, or memory allocation error
  84718. * occurred (meaning decoding must stop), else \c true; for more
  84719. * information about the decoder, check the decoder state with
  84720. * FLAC__stream_decoder_get_state().
  84721. */
  84722. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  84723. /** Decode until the end of the stream.
  84724. * This version instructs the decoder to decode from the current position
  84725. * and continue until the end of stream (the read callback returns
  84726. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  84727. * callbacks return a fatal error.
  84728. *
  84729. * As the decoder needs more input it will call the read callback.
  84730. * As each metadata block and frame is decoded, the metadata or write
  84731. * callback will be called with the decoded metadata or frame.
  84732. *
  84733. * \param decoder An initialized decoder instance.
  84734. * \assert
  84735. * \code decoder != NULL \endcode
  84736. * \retval FLAC__bool
  84737. * \c false if any fatal read, write, or memory allocation error
  84738. * occurred (meaning decoding must stop), else \c true; for more
  84739. * information about the decoder, check the decoder state with
  84740. * FLAC__stream_decoder_get_state().
  84741. */
  84742. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  84743. /** Skip one audio frame.
  84744. * This version instructs the decoder to 'skip' a single frame and stop,
  84745. * unless the callbacks return a fatal error or the read callback returns
  84746. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  84747. *
  84748. * The decoding flow is the same as what occurs when
  84749. * FLAC__stream_decoder_process_single() is called to process an audio
  84750. * frame, except that this function does not decode the parsed data into
  84751. * PCM or call the write callback. The integrity of the frame is still
  84752. * checked the same way as in the other process functions.
  84753. *
  84754. * This function will return once one whole frame is skipped, in the
  84755. * same way that FLAC__stream_decoder_process_single() will return once
  84756. * one whole frame is decoded.
  84757. *
  84758. * This function can be used in more quickly determining FLAC frame
  84759. * boundaries when decoding of the actual data is not needed, for
  84760. * example when an application is separating a FLAC stream into frames
  84761. * for editing or storing in a container. To do this, the application
  84762. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  84763. * to the next frame, then use
  84764. * FLAC__stream_decoder_get_decode_position() to find the new frame
  84765. * boundary.
  84766. *
  84767. * This function should only be called when the stream has advanced
  84768. * past all the metadata, otherwise it will return \c false.
  84769. *
  84770. * \param decoder An initialized decoder instance not in a metadata
  84771. * state.
  84772. * \assert
  84773. * \code decoder != NULL \endcode
  84774. * \retval FLAC__bool
  84775. * \c false if any fatal read, write, or memory allocation error
  84776. * occurred (meaning decoding must stop), or if the decoder
  84777. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  84778. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  84779. * information about the decoder, check the decoder state with
  84780. * FLAC__stream_decoder_get_state().
  84781. */
  84782. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  84783. /** Flush the input and seek to an absolute sample.
  84784. * Decoding will resume at the given sample. Note that because of
  84785. * this, the next write callback may contain a partial block. The
  84786. * client must support seeking the input or this function will fail
  84787. * and return \c false. Furthermore, if the decoder state is
  84788. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  84789. * with FLAC__stream_decoder_flush() or reset with
  84790. * FLAC__stream_decoder_reset() before decoding can continue.
  84791. *
  84792. * \param decoder A decoder instance.
  84793. * \param sample The target sample number to seek to.
  84794. * \assert
  84795. * \code decoder != NULL \endcode
  84796. * \retval FLAC__bool
  84797. * \c true if successful, else \c false.
  84798. */
  84799. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  84800. /* \} */
  84801. #ifdef __cplusplus
  84802. }
  84803. #endif
  84804. #endif
  84805. /********* End of inlined file: stream_decoder.h *********/
  84806. /********* Start of inlined file: stream_encoder.h *********/
  84807. #ifndef FLAC__STREAM_ENCODER_H
  84808. #define FLAC__STREAM_ENCODER_H
  84809. #include <stdio.h> /* for FILE */
  84810. #ifdef __cplusplus
  84811. extern "C" {
  84812. #endif
  84813. /** \file include/FLAC/stream_encoder.h
  84814. *
  84815. * \brief
  84816. * This module contains the functions which implement the stream
  84817. * encoder.
  84818. *
  84819. * See the detailed documentation in the
  84820. * \link flac_stream_encoder stream encoder \endlink module.
  84821. */
  84822. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  84823. * \ingroup flac
  84824. *
  84825. * \brief
  84826. * This module describes the encoder layers provided by libFLAC.
  84827. *
  84828. * The stream encoder can be used to encode complete streams either to the
  84829. * client via callbacks, or directly to a file, depending on how it is
  84830. * initialized. When encoding via callbacks, the client provides a write
  84831. * callback which will be called whenever FLAC data is ready to be written.
  84832. * If the client also supplies a seek callback, the encoder will also
  84833. * automatically handle the writing back of metadata discovered while
  84834. * encoding, like stream info, seek points offsets, etc. When encoding to
  84835. * a file, the client needs only supply a filename or open \c FILE* and an
  84836. * optional progress callback for periodic notification of progress; the
  84837. * write and seek callbacks are supplied internally. For more info see the
  84838. * \link flac_stream_encoder stream encoder \endlink module.
  84839. */
  84840. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  84841. * \ingroup flac_encoder
  84842. *
  84843. * \brief
  84844. * This module contains the functions which implement the stream
  84845. * encoder.
  84846. *
  84847. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  84848. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  84849. *
  84850. * The basic usage of this encoder is as follows:
  84851. * - The program creates an instance of an encoder using
  84852. * FLAC__stream_encoder_new().
  84853. * - The program overrides the default settings using
  84854. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  84855. * functions should be called:
  84856. * - FLAC__stream_encoder_set_channels()
  84857. * - FLAC__stream_encoder_set_bits_per_sample()
  84858. * - FLAC__stream_encoder_set_sample_rate()
  84859. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  84860. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  84861. * - If the application wants to control the compression level or set its own
  84862. * metadata, then the following should also be called:
  84863. * - FLAC__stream_encoder_set_compression_level()
  84864. * - FLAC__stream_encoder_set_verify()
  84865. * - FLAC__stream_encoder_set_metadata()
  84866. * - The rest of the set functions should only be called if the client needs
  84867. * exact control over how the audio is compressed; thorough understanding
  84868. * of the FLAC format is necessary to achieve good results.
  84869. * - The program initializes the instance to validate the settings and
  84870. * prepare for encoding using
  84871. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  84872. * or FLAC__stream_encoder_init_file() for native FLAC
  84873. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  84874. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  84875. * - The program calls FLAC__stream_encoder_process() or
  84876. * FLAC__stream_encoder_process_interleaved() to encode data, which
  84877. * subsequently calls the callbacks when there is encoder data ready
  84878. * to be written.
  84879. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  84880. * which causes the encoder to encode any data still in its input pipe,
  84881. * update the metadata with the final encoding statistics if output
  84882. * seeking is possible, and finally reset the encoder to the
  84883. * uninitialized state.
  84884. * - The instance may be used again or deleted with
  84885. * FLAC__stream_encoder_delete().
  84886. *
  84887. * In more detail, the stream encoder functions similarly to the
  84888. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  84889. * callbacks and more options. Typically the client will create a new
  84890. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  84891. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  84892. * calling one of the FLAC__stream_encoder_init_*() functions.
  84893. *
  84894. * Unlike the decoders, the stream encoder has many options that can
  84895. * affect the speed and compression ratio. When setting these parameters
  84896. * you should have some basic knowledge of the format (see the
  84897. * <A HREF="../documentation.html#format">user-level documentation</A>
  84898. * or the <A HREF="../format.html">formal description</A>). The
  84899. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  84900. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  84901. * functions will do this, so make sure to pay attention to the state
  84902. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  84903. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  84904. * before FLAC__stream_encoder_init_*() will take on the defaults from
  84905. * the constructor.
  84906. *
  84907. * There are three initialization functions for native FLAC, one for
  84908. * setting up the encoder to encode FLAC data to the client via
  84909. * callbacks, and two for encoding directly to a file.
  84910. *
  84911. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  84912. * You must also supply a write callback which will be called anytime
  84913. * there is raw encoded data to write. If the client can seek the output
  84914. * it is best to also supply seek and tell callbacks, as this allows the
  84915. * encoder to go back after encoding is finished to write back
  84916. * information that was collected while encoding, like seek point offsets,
  84917. * frame sizes, etc.
  84918. *
  84919. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  84920. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  84921. * filename or open \c FILE*; the encoder will handle all the callbacks
  84922. * internally. You may also supply a progress callback for periodic
  84923. * notification of the encoding progress.
  84924. *
  84925. * There are three similarly-named init functions for encoding to Ogg
  84926. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  84927. * library has been built with Ogg support.
  84928. *
  84929. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  84930. * call the write callback several times, once with the \c fLaC signature,
  84931. * and once for each encoded metadata block. Note that for Ogg FLAC
  84932. * encoding you will usually get at least twice the number of callbacks than
  84933. * with native FLAC, one for the Ogg page header and one for the page body.
  84934. *
  84935. * After initializing the instance, the client may feed audio data to the
  84936. * encoder in one of two ways:
  84937. *
  84938. * - Channel separate, through FLAC__stream_encoder_process() - The client
  84939. * will pass an array of pointers to buffers, one for each channel, to
  84940. * the encoder, each of the same length. The samples need not be
  84941. * block-aligned, but each channel should have the same number of samples.
  84942. * - Channel interleaved, through
  84943. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  84944. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  84945. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  84946. * Again, the samples need not be block-aligned but they must be
  84947. * sample-aligned, i.e. the first value should be channel0_sample0 and
  84948. * the last value channelN_sampleM.
  84949. *
  84950. * Note that for either process call, each sample in the buffers should be a
  84951. * signed integer, right-justified to the resolution set by
  84952. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  84953. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  84954. *
  84955. * When the client is finished encoding data, it calls
  84956. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  84957. * data still in its input pipe, and call the metadata callback with the
  84958. * final encoding statistics. Then the instance may be deleted with
  84959. * FLAC__stream_encoder_delete() or initialized again to encode another
  84960. * stream.
  84961. *
  84962. * For programs that write their own metadata, but that do not know the
  84963. * actual metadata until after encoding, it is advantageous to instruct
  84964. * the encoder to write a PADDING block of the correct size, so that
  84965. * instead of rewriting the whole stream after encoding, the program can
  84966. * just overwrite the PADDING block. If only the maximum size of the
  84967. * metadata is known, the program can write a slightly larger padding
  84968. * block, then split it after encoding.
  84969. *
  84970. * Make sure you understand how lengths are calculated. All FLAC metadata
  84971. * blocks have a 4 byte header which contains the type and length. This
  84972. * length does not include the 4 bytes of the header. See the format page
  84973. * for the specification of metadata blocks and their lengths.
  84974. *
  84975. * \note
  84976. * If you are writing the FLAC data to a file via callbacks, make sure it
  84977. * is open for update (e.g. mode "w+" for stdio streams). This is because
  84978. * after the first encoding pass, the encoder will try to seek back to the
  84979. * beginning of the stream, to the STREAMINFO block, to write some data
  84980. * there. (If using FLAC__stream_encoder_init*_file() or
  84981. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  84982. *
  84983. * \note
  84984. * The "set" functions may only be called when the encoder is in the
  84985. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  84986. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  84987. * before FLAC__stream_encoder_init_*(). If this is the case they will
  84988. * return \c true, otherwise \c false.
  84989. *
  84990. * \note
  84991. * FLAC__stream_encoder_finish() resets all settings to the constructor
  84992. * defaults.
  84993. *
  84994. * \{
  84995. */
  84996. /** State values for a FLAC__StreamEncoder.
  84997. *
  84998. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  84999. *
  85000. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  85001. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  85002. * must be deleted with FLAC__stream_encoder_delete().
  85003. */
  85004. typedef enum {
  85005. FLAC__STREAM_ENCODER_OK = 0,
  85006. /**< The encoder is in the normal OK state and samples can be processed. */
  85007. FLAC__STREAM_ENCODER_UNINITIALIZED,
  85008. /**< The encoder is in the uninitialized state; one of the
  85009. * FLAC__stream_encoder_init_*() functions must be called before samples
  85010. * can be processed.
  85011. */
  85012. FLAC__STREAM_ENCODER_OGG_ERROR,
  85013. /**< An error occurred in the underlying Ogg layer. */
  85014. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  85015. /**< An error occurred in the underlying verify stream decoder;
  85016. * check FLAC__stream_encoder_get_verify_decoder_state().
  85017. */
  85018. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  85019. /**< The verify decoder detected a mismatch between the original
  85020. * audio signal and the decoded audio signal.
  85021. */
  85022. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  85023. /**< One of the callbacks returned a fatal error. */
  85024. FLAC__STREAM_ENCODER_IO_ERROR,
  85025. /**< An I/O error occurred while opening/reading/writing a file.
  85026. * Check \c errno.
  85027. */
  85028. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  85029. /**< An error occurred while writing the stream; usually, the
  85030. * write_callback returned an error.
  85031. */
  85032. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  85033. /**< Memory allocation failed. */
  85034. } FLAC__StreamEncoderState;
  85035. /** Maps a FLAC__StreamEncoderState to a C string.
  85036. *
  85037. * Using a FLAC__StreamEncoderState as the index to this array
  85038. * will give the string equivalent. The contents should not be modified.
  85039. */
  85040. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  85041. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  85042. */
  85043. typedef enum {
  85044. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  85045. /**< Initialization was successful. */
  85046. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  85047. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  85048. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  85049. /**< The library was not compiled with support for the given container
  85050. * format.
  85051. */
  85052. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  85053. /**< A required callback was not supplied. */
  85054. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  85055. /**< The encoder has an invalid setting for number of channels. */
  85056. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  85057. /**< The encoder has an invalid setting for bits-per-sample.
  85058. * FLAC supports 4-32 bps but the reference encoder currently supports
  85059. * only up to 24 bps.
  85060. */
  85061. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  85062. /**< The encoder has an invalid setting for the input sample rate. */
  85063. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  85064. /**< The encoder has an invalid setting for the block size. */
  85065. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  85066. /**< The encoder has an invalid setting for the maximum LPC order. */
  85067. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  85068. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  85069. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  85070. /**< The specified block size is less than the maximum LPC order. */
  85071. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  85072. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  85073. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  85074. /**< The metadata input to the encoder is invalid, in one of the following ways:
  85075. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  85076. * - One of the metadata blocks contains an undefined type
  85077. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  85078. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  85079. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  85080. */
  85081. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  85082. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  85083. * already initialized, usually because
  85084. * FLAC__stream_encoder_finish() was not called.
  85085. */
  85086. } FLAC__StreamEncoderInitStatus;
  85087. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  85088. *
  85089. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  85090. * will give the string equivalent. The contents should not be modified.
  85091. */
  85092. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  85093. /** Return values for the FLAC__StreamEncoder read callback.
  85094. */
  85095. typedef enum {
  85096. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  85097. /**< The read was OK and decoding can continue. */
  85098. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  85099. /**< The read was attempted at the end of the stream. */
  85100. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  85101. /**< An unrecoverable error occurred. */
  85102. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  85103. /**< Client does not support reading back from the output. */
  85104. } FLAC__StreamEncoderReadStatus;
  85105. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  85106. *
  85107. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  85108. * will give the string equivalent. The contents should not be modified.
  85109. */
  85110. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  85111. /** Return values for the FLAC__StreamEncoder write callback.
  85112. */
  85113. typedef enum {
  85114. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  85115. /**< The write was OK and encoding can continue. */
  85116. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  85117. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  85118. } FLAC__StreamEncoderWriteStatus;
  85119. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  85120. *
  85121. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  85122. * will give the string equivalent. The contents should not be modified.
  85123. */
  85124. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  85125. /** Return values for the FLAC__StreamEncoder seek callback.
  85126. */
  85127. typedef enum {
  85128. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  85129. /**< The seek was OK and encoding can continue. */
  85130. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  85131. /**< An unrecoverable error occurred. */
  85132. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  85133. /**< Client does not support seeking. */
  85134. } FLAC__StreamEncoderSeekStatus;
  85135. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  85136. *
  85137. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  85138. * will give the string equivalent. The contents should not be modified.
  85139. */
  85140. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  85141. /** Return values for the FLAC__StreamEncoder tell callback.
  85142. */
  85143. typedef enum {
  85144. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  85145. /**< The tell was OK and encoding can continue. */
  85146. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  85147. /**< An unrecoverable error occurred. */
  85148. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  85149. /**< Client does not support seeking. */
  85150. } FLAC__StreamEncoderTellStatus;
  85151. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  85152. *
  85153. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  85154. * will give the string equivalent. The contents should not be modified.
  85155. */
  85156. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  85157. /***********************************************************************
  85158. *
  85159. * class FLAC__StreamEncoder
  85160. *
  85161. ***********************************************************************/
  85162. struct FLAC__StreamEncoderProtected;
  85163. struct FLAC__StreamEncoderPrivate;
  85164. /** The opaque structure definition for the stream encoder type.
  85165. * See the \link flac_stream_encoder stream encoder module \endlink
  85166. * for a detailed description.
  85167. */
  85168. typedef struct {
  85169. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  85170. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  85171. } FLAC__StreamEncoder;
  85172. /** Signature for the read callback.
  85173. *
  85174. * A function pointer matching this signature must be passed to
  85175. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  85176. * The supplied function will be called when the encoder needs to read back
  85177. * encoded data. This happens during the metadata callback, when the encoder
  85178. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  85179. * while encoding. The address of the buffer to be filled is supplied, along
  85180. * with the number of bytes the buffer can hold. The callback may choose to
  85181. * supply less data and modify the byte count but must be careful not to
  85182. * overflow the buffer. The callback then returns a status code chosen from
  85183. * FLAC__StreamEncoderReadStatus.
  85184. *
  85185. * Here is an example of a read callback for stdio streams:
  85186. * \code
  85187. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  85188. * {
  85189. * FILE *file = ((MyClientData*)client_data)->file;
  85190. * if(*bytes > 0) {
  85191. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  85192. * if(ferror(file))
  85193. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  85194. * else if(*bytes == 0)
  85195. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  85196. * else
  85197. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  85198. * }
  85199. * else
  85200. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  85201. * }
  85202. * \endcode
  85203. *
  85204. * \note In general, FLAC__StreamEncoder functions which change the
  85205. * state should not be called on the \a encoder while in the callback.
  85206. *
  85207. * \param encoder The encoder instance calling the callback.
  85208. * \param buffer A pointer to a location for the callee to store
  85209. * data to be encoded.
  85210. * \param bytes A pointer to the size of the buffer. On entry
  85211. * to the callback, it contains the maximum number
  85212. * of bytes that may be stored in \a buffer. The
  85213. * callee must set it to the actual number of bytes
  85214. * stored (0 in case of error or end-of-stream) before
  85215. * returning.
  85216. * \param client_data The callee's client data set through
  85217. * FLAC__stream_encoder_set_client_data().
  85218. * \retval FLAC__StreamEncoderReadStatus
  85219. * The callee's return status.
  85220. */
  85221. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  85222. /** Signature for the write callback.
  85223. *
  85224. * A function pointer matching this signature must be passed to
  85225. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  85226. * by the encoder anytime there is raw encoded data ready to write. It may
  85227. * include metadata mixed with encoded audio frames and the data is not
  85228. * guaranteed to be aligned on frame or metadata block boundaries.
  85229. *
  85230. * The only duty of the callback is to write out the \a bytes worth of data
  85231. * in \a buffer to the current position in the output stream. The arguments
  85232. * \a samples and \a current_frame are purely informational. If \a samples
  85233. * is greater than \c 0, then \a current_frame will hold the current frame
  85234. * number that is being written; otherwise it indicates that the write
  85235. * callback is being called to write metadata.
  85236. *
  85237. * \note
  85238. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  85239. * write callback will be called twice when writing each audio
  85240. * frame; once for the page header, and once for the page body.
  85241. * When writing the page header, the \a samples argument to the
  85242. * write callback will be \c 0.
  85243. *
  85244. * \note In general, FLAC__StreamEncoder functions which change the
  85245. * state should not be called on the \a encoder while in the callback.
  85246. *
  85247. * \param encoder The encoder instance calling the callback.
  85248. * \param buffer An array of encoded data of length \a bytes.
  85249. * \param bytes The byte length of \a buffer.
  85250. * \param samples The number of samples encoded by \a buffer.
  85251. * \c 0 has a special meaning; see above.
  85252. * \param current_frame The number of the current frame being encoded.
  85253. * \param client_data The callee's client data set through
  85254. * FLAC__stream_encoder_init_*().
  85255. * \retval FLAC__StreamEncoderWriteStatus
  85256. * The callee's return status.
  85257. */
  85258. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  85259. /** Signature for the seek callback.
  85260. *
  85261. * A function pointer matching this signature may be passed to
  85262. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  85263. * when the encoder needs to seek the output stream. The encoder will pass
  85264. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  85265. *
  85266. * Here is an example of a seek callback for stdio streams:
  85267. * \code
  85268. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  85269. * {
  85270. * FILE *file = ((MyClientData*)client_data)->file;
  85271. * if(file == stdin)
  85272. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  85273. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  85274. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  85275. * else
  85276. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  85277. * }
  85278. * \endcode
  85279. *
  85280. * \note In general, FLAC__StreamEncoder functions which change the
  85281. * state should not be called on the \a encoder while in the callback.
  85282. *
  85283. * \param encoder The encoder instance calling the callback.
  85284. * \param absolute_byte_offset The offset from the beginning of the stream
  85285. * to seek to.
  85286. * \param client_data The callee's client data set through
  85287. * FLAC__stream_encoder_init_*().
  85288. * \retval FLAC__StreamEncoderSeekStatus
  85289. * The callee's return status.
  85290. */
  85291. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  85292. /** Signature for the tell callback.
  85293. *
  85294. * A function pointer matching this signature may be passed to
  85295. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  85296. * when the encoder needs to know the current position of the output stream.
  85297. *
  85298. * \warning
  85299. * The callback must return the true current byte offset of the output to
  85300. * which the encoder is writing. If you are buffering the output, make
  85301. * sure and take this into account. If you are writing directly to a
  85302. * FILE* from your write callback, ftell() is sufficient. If you are
  85303. * writing directly to a file descriptor from your write callback, you
  85304. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  85305. * these points to rewrite metadata after encoding.
  85306. *
  85307. * Here is an example of a tell callback for stdio streams:
  85308. * \code
  85309. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  85310. * {
  85311. * FILE *file = ((MyClientData*)client_data)->file;
  85312. * off_t pos;
  85313. * if(file == stdin)
  85314. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  85315. * else if((pos = ftello(file)) < 0)
  85316. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  85317. * else {
  85318. * *absolute_byte_offset = (FLAC__uint64)pos;
  85319. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  85320. * }
  85321. * }
  85322. * \endcode
  85323. *
  85324. * \note In general, FLAC__StreamEncoder functions which change the
  85325. * state should not be called on the \a encoder while in the callback.
  85326. *
  85327. * \param encoder The encoder instance calling the callback.
  85328. * \param absolute_byte_offset The address at which to store the current
  85329. * position of the output.
  85330. * \param client_data The callee's client data set through
  85331. * FLAC__stream_encoder_init_*().
  85332. * \retval FLAC__StreamEncoderTellStatus
  85333. * The callee's return status.
  85334. */
  85335. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  85336. /** Signature for the metadata callback.
  85337. *
  85338. * A function pointer matching this signature may be passed to
  85339. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  85340. * once at the end of encoding with the populated STREAMINFO structure. This
  85341. * is so the client can seek back to the beginning of the file and write the
  85342. * STREAMINFO block with the correct statistics after encoding (like
  85343. * minimum/maximum frame size and total samples).
  85344. *
  85345. * \note In general, FLAC__StreamEncoder functions which change the
  85346. * state should not be called on the \a encoder while in the callback.
  85347. *
  85348. * \param encoder The encoder instance calling the callback.
  85349. * \param metadata The final populated STREAMINFO block.
  85350. * \param client_data The callee's client data set through
  85351. * FLAC__stream_encoder_init_*().
  85352. */
  85353. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  85354. /** Signature for the progress callback.
  85355. *
  85356. * A function pointer matching this signature may be passed to
  85357. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  85358. * The supplied function will be called when the encoder has finished
  85359. * writing a frame. The \c total_frames_estimate argument to the
  85360. * callback will be based on the value from
  85361. * FLAC__stream_encoder_set_total_samples_estimate().
  85362. *
  85363. * \note In general, FLAC__StreamEncoder functions which change the
  85364. * state should not be called on the \a encoder while in the callback.
  85365. *
  85366. * \param encoder The encoder instance calling the callback.
  85367. * \param bytes_written Bytes written so far.
  85368. * \param samples_written Samples written so far.
  85369. * \param frames_written Frames written so far.
  85370. * \param total_frames_estimate The estimate of the total number of
  85371. * frames to be written.
  85372. * \param client_data The callee's client data set through
  85373. * FLAC__stream_encoder_init_*().
  85374. */
  85375. 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);
  85376. /***********************************************************************
  85377. *
  85378. * Class constructor/destructor
  85379. *
  85380. ***********************************************************************/
  85381. /** Create a new stream encoder instance. The instance is created with
  85382. * default settings; see the individual FLAC__stream_encoder_set_*()
  85383. * functions for each setting's default.
  85384. *
  85385. * \retval FLAC__StreamEncoder*
  85386. * \c NULL if there was an error allocating memory, else the new instance.
  85387. */
  85388. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  85389. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  85390. *
  85391. * \param encoder A pointer to an existing encoder.
  85392. * \assert
  85393. * \code encoder != NULL \endcode
  85394. */
  85395. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  85396. /***********************************************************************
  85397. *
  85398. * Public class method prototypes
  85399. *
  85400. ***********************************************************************/
  85401. /** Set the serial number for the FLAC stream to use in the Ogg container.
  85402. *
  85403. * \note
  85404. * This does not need to be set for native FLAC encoding.
  85405. *
  85406. * \note
  85407. * It is recommended to set a serial number explicitly as the default of '0'
  85408. * may collide with other streams.
  85409. *
  85410. * \default \c 0
  85411. * \param encoder An encoder instance to set.
  85412. * \param serial_number See above.
  85413. * \assert
  85414. * \code encoder != NULL \endcode
  85415. * \retval FLAC__bool
  85416. * \c false if the encoder is already initialized, else \c true.
  85417. */
  85418. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  85419. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  85420. * encoded output by feeding it through an internal decoder and comparing
  85421. * the original signal against the decoded signal. If a mismatch occurs,
  85422. * the process call will return \c false. Note that this will slow the
  85423. * encoding process by the extra time required for decoding and comparison.
  85424. *
  85425. * \default \c false
  85426. * \param encoder An encoder instance to set.
  85427. * \param value Flag value (see above).
  85428. * \assert
  85429. * \code encoder != NULL \endcode
  85430. * \retval FLAC__bool
  85431. * \c false if the encoder is already initialized, else \c true.
  85432. */
  85433. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85434. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  85435. * the encoder will comply with the Subset and will check the
  85436. * settings during FLAC__stream_encoder_init_*() to see if all settings
  85437. * comply. If \c false, the settings may take advantage of the full
  85438. * range that the format allows.
  85439. *
  85440. * Make sure you know what it entails before setting this to \c false.
  85441. *
  85442. * \default \c true
  85443. * \param encoder An encoder instance to set.
  85444. * \param value Flag value (see above).
  85445. * \assert
  85446. * \code encoder != NULL \endcode
  85447. * \retval FLAC__bool
  85448. * \c false if the encoder is already initialized, else \c true.
  85449. */
  85450. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85451. /** Set the number of channels to be encoded.
  85452. *
  85453. * \default \c 2
  85454. * \param encoder An encoder instance to set.
  85455. * \param value See above.
  85456. * \assert
  85457. * \code encoder != NULL \endcode
  85458. * \retval FLAC__bool
  85459. * \c false if the encoder is already initialized, else \c true.
  85460. */
  85461. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  85462. /** Set the sample resolution of the input to be encoded.
  85463. *
  85464. * \warning
  85465. * Do not feed the encoder data that is wider than the value you
  85466. * set here or you will generate an invalid stream.
  85467. *
  85468. * \default \c 16
  85469. * \param encoder An encoder instance to set.
  85470. * \param value See above.
  85471. * \assert
  85472. * \code encoder != NULL \endcode
  85473. * \retval FLAC__bool
  85474. * \c false if the encoder is already initialized, else \c true.
  85475. */
  85476. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  85477. /** Set the sample rate (in Hz) of the input to be encoded.
  85478. *
  85479. * \default \c 44100
  85480. * \param encoder An encoder instance to set.
  85481. * \param value See above.
  85482. * \assert
  85483. * \code encoder != NULL \endcode
  85484. * \retval FLAC__bool
  85485. * \c false if the encoder is already initialized, else \c true.
  85486. */
  85487. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  85488. /** Set the compression level
  85489. *
  85490. * The compression level is roughly proportional to the amount of effort
  85491. * the encoder expends to compress the file. A higher level usually
  85492. * means more computation but higher compression. The default level is
  85493. * suitable for most applications.
  85494. *
  85495. * Currently the levels range from \c 0 (fastest, least compression) to
  85496. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  85497. * treated as \c 8.
  85498. *
  85499. * This function automatically calls the following other \c _set_
  85500. * functions with appropriate values, so the client does not need to
  85501. * unless it specifically wants to override them:
  85502. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  85503. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  85504. * - FLAC__stream_encoder_set_apodization()
  85505. * - FLAC__stream_encoder_set_max_lpc_order()
  85506. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  85507. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  85508. * - FLAC__stream_encoder_set_do_escape_coding()
  85509. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  85510. * - FLAC__stream_encoder_set_min_residual_partition_order()
  85511. * - FLAC__stream_encoder_set_max_residual_partition_order()
  85512. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  85513. *
  85514. * The actual values set for each level are:
  85515. * <table>
  85516. * <tr>
  85517. * <td><b>level</b><td>
  85518. * <td>do mid-side stereo<td>
  85519. * <td>loose mid-side stereo<td>
  85520. * <td>apodization<td>
  85521. * <td>max lpc order<td>
  85522. * <td>qlp coeff precision<td>
  85523. * <td>qlp coeff prec search<td>
  85524. * <td>escape coding<td>
  85525. * <td>exhaustive model search<td>
  85526. * <td>min residual partition order<td>
  85527. * <td>max residual partition order<td>
  85528. * <td>rice parameter search dist<td>
  85529. * </tr>
  85530. * <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>
  85531. * <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>
  85532. * <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>
  85533. * <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>
  85534. * <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>
  85535. * <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>
  85536. * <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>
  85537. * <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>
  85538. * <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>
  85539. * </table>
  85540. *
  85541. * \default \c 5
  85542. * \param encoder An encoder instance to set.
  85543. * \param value See above.
  85544. * \assert
  85545. * \code encoder != NULL \endcode
  85546. * \retval FLAC__bool
  85547. * \c false if the encoder is already initialized, else \c true.
  85548. */
  85549. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  85550. /** Set the blocksize to use while encoding.
  85551. *
  85552. * The number of samples to use per frame. Use \c 0 to let the encoder
  85553. * estimate a blocksize; this is usually best.
  85554. *
  85555. * \default \c 0
  85556. * \param encoder An encoder instance to set.
  85557. * \param value See above.
  85558. * \assert
  85559. * \code encoder != NULL \endcode
  85560. * \retval FLAC__bool
  85561. * \c false if the encoder is already initialized, else \c true.
  85562. */
  85563. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  85564. /** Set to \c true to enable mid-side encoding on stereo input. The
  85565. * number of channels must be 2 for this to have any effect. Set to
  85566. * \c false to use only independent channel coding.
  85567. *
  85568. * \default \c false
  85569. * \param encoder An encoder instance to set.
  85570. * \param value Flag value (see above).
  85571. * \assert
  85572. * \code encoder != NULL \endcode
  85573. * \retval FLAC__bool
  85574. * \c false if the encoder is already initialized, else \c true.
  85575. */
  85576. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85577. /** Set to \c true to enable adaptive switching between mid-side and
  85578. * left-right encoding on stereo input. Set to \c false to use
  85579. * exhaustive searching. Setting this to \c true requires
  85580. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  85581. * \c true in order to have any effect.
  85582. *
  85583. * \default \c false
  85584. * \param encoder An encoder instance to set.
  85585. * \param value Flag value (see above).
  85586. * \assert
  85587. * \code encoder != NULL \endcode
  85588. * \retval FLAC__bool
  85589. * \c false if the encoder is already initialized, else \c true.
  85590. */
  85591. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85592. /** Sets the apodization function(s) the encoder will use when windowing
  85593. * audio data for LPC analysis.
  85594. *
  85595. * The \a specification is a plain ASCII string which specifies exactly
  85596. * which functions to use. There may be more than one (up to 32),
  85597. * separated by \c ';' characters. Some functions take one or more
  85598. * comma-separated arguments in parentheses.
  85599. *
  85600. * The available functions are \c bartlett, \c bartlett_hann,
  85601. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  85602. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  85603. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  85604. *
  85605. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  85606. * (0<STDDEV<=0.5).
  85607. *
  85608. * For \c tukey(P), P specifies the fraction of the window that is
  85609. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  85610. * corresponds to \c hann.
  85611. *
  85612. * Example specifications are \c "blackman" or
  85613. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  85614. *
  85615. * Any function that is specified erroneously is silently dropped. Up
  85616. * to 32 functions are kept, the rest are dropped. If the specification
  85617. * is empty the encoder defaults to \c "tukey(0.5)".
  85618. *
  85619. * When more than one function is specified, then for every subframe the
  85620. * encoder will try each of them separately and choose the window that
  85621. * results in the smallest compressed subframe.
  85622. *
  85623. * Note that each function specified causes the encoder to occupy a
  85624. * floating point array in which to store the window.
  85625. *
  85626. * \default \c "tukey(0.5)"
  85627. * \param encoder An encoder instance to set.
  85628. * \param specification See above.
  85629. * \assert
  85630. * \code encoder != NULL \endcode
  85631. * \code specification != NULL \endcode
  85632. * \retval FLAC__bool
  85633. * \c false if the encoder is already initialized, else \c true.
  85634. */
  85635. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  85636. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  85637. *
  85638. * \default \c 0
  85639. * \param encoder An encoder instance to set.
  85640. * \param value See above.
  85641. * \assert
  85642. * \code encoder != NULL \endcode
  85643. * \retval FLAC__bool
  85644. * \c false if the encoder is already initialized, else \c true.
  85645. */
  85646. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  85647. /** Set the precision, in bits, of the quantized linear predictor
  85648. * coefficients, or \c 0 to let the encoder select it based on the
  85649. * blocksize.
  85650. *
  85651. * \note
  85652. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  85653. * be less than 32.
  85654. *
  85655. * \default \c 0
  85656. * \param encoder An encoder instance to set.
  85657. * \param value See above.
  85658. * \assert
  85659. * \code encoder != NULL \endcode
  85660. * \retval FLAC__bool
  85661. * \c false if the encoder is already initialized, else \c true.
  85662. */
  85663. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  85664. /** Set to \c false to use only the specified quantized linear predictor
  85665. * coefficient precision, or \c true to search neighboring precision
  85666. * values and use the best one.
  85667. *
  85668. * \default \c false
  85669. * \param encoder An encoder instance to set.
  85670. * \param value See above.
  85671. * \assert
  85672. * \code encoder != NULL \endcode
  85673. * \retval FLAC__bool
  85674. * \c false if the encoder is already initialized, else \c true.
  85675. */
  85676. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85677. /** Deprecated. Setting this value has no effect.
  85678. *
  85679. * \default \c false
  85680. * \param encoder An encoder instance to set.
  85681. * \param value See above.
  85682. * \assert
  85683. * \code encoder != NULL \endcode
  85684. * \retval FLAC__bool
  85685. * \c false if the encoder is already initialized, else \c true.
  85686. */
  85687. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85688. /** Set to \c false to let the encoder estimate the best model order
  85689. * based on the residual signal energy, or \c true to force the
  85690. * encoder to evaluate all order models and select the best.
  85691. *
  85692. * \default \c false
  85693. * \param encoder An encoder instance to set.
  85694. * \param value See above.
  85695. * \assert
  85696. * \code encoder != NULL \endcode
  85697. * \retval FLAC__bool
  85698. * \c false if the encoder is already initialized, else \c true.
  85699. */
  85700. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85701. /** Set the minimum partition order to search when coding the residual.
  85702. * This is used in tandem with
  85703. * FLAC__stream_encoder_set_max_residual_partition_order().
  85704. *
  85705. * The partition order determines the context size in the residual.
  85706. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  85707. *
  85708. * Set both min and max values to \c 0 to force a single context,
  85709. * whose Rice parameter is based on the residual signal variance.
  85710. * Otherwise, set a min and max order, and the encoder will search
  85711. * all orders, using the mean of each context for its Rice parameter,
  85712. * and use the best.
  85713. *
  85714. * \default \c 0
  85715. * \param encoder An encoder instance to set.
  85716. * \param value See above.
  85717. * \assert
  85718. * \code encoder != NULL \endcode
  85719. * \retval FLAC__bool
  85720. * \c false if the encoder is already initialized, else \c true.
  85721. */
  85722. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  85723. /** Set the maximum partition order to search when coding the residual.
  85724. * This is used in tandem with
  85725. * FLAC__stream_encoder_set_min_residual_partition_order().
  85726. *
  85727. * The partition order determines the context size in the residual.
  85728. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  85729. *
  85730. * Set both min and max values to \c 0 to force a single context,
  85731. * whose Rice parameter is based on the residual signal variance.
  85732. * Otherwise, set a min and max order, and the encoder will search
  85733. * all orders, using the mean of each context for its Rice parameter,
  85734. * and use the best.
  85735. *
  85736. * \default \c 0
  85737. * \param encoder An encoder instance to set.
  85738. * \param value See above.
  85739. * \assert
  85740. * \code encoder != NULL \endcode
  85741. * \retval FLAC__bool
  85742. * \c false if the encoder is already initialized, else \c true.
  85743. */
  85744. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  85745. /** Deprecated. Setting this value has no effect.
  85746. *
  85747. * \default \c 0
  85748. * \param encoder An encoder instance to set.
  85749. * \param value See above.
  85750. * \assert
  85751. * \code encoder != NULL \endcode
  85752. * \retval FLAC__bool
  85753. * \c false if the encoder is already initialized, else \c true.
  85754. */
  85755. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  85756. /** Set an estimate of the total samples that will be encoded.
  85757. * This is merely an estimate and may be set to \c 0 if unknown.
  85758. * This value will be written to the STREAMINFO block before encoding,
  85759. * and can remove the need for the caller to rewrite the value later
  85760. * if the value is known before encoding.
  85761. *
  85762. * \default \c 0
  85763. * \param encoder An encoder instance to set.
  85764. * \param value See above.
  85765. * \assert
  85766. * \code encoder != NULL \endcode
  85767. * \retval FLAC__bool
  85768. * \c false if the encoder is already initialized, else \c true.
  85769. */
  85770. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  85771. /** Set the metadata blocks to be emitted to the stream before encoding.
  85772. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  85773. * array of pointers to metadata blocks. The array is non-const since
  85774. * the encoder may need to change the \a is_last flag inside them, and
  85775. * in some cases update seek point offsets. Otherwise, the encoder will
  85776. * not modify or free the blocks. It is up to the caller to free the
  85777. * metadata blocks after encoding finishes.
  85778. *
  85779. * \note
  85780. * The encoder stores only copies of the pointers in the \a metadata array;
  85781. * the metadata blocks themselves must survive at least until after
  85782. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  85783. *
  85784. * \note
  85785. * The STREAMINFO block is always written and no STREAMINFO block may
  85786. * occur in the supplied array.
  85787. *
  85788. * \note
  85789. * By default the encoder does not create a SEEKTABLE. If one is supplied
  85790. * in the \a metadata array, but the client has specified that it does not
  85791. * support seeking, then the SEEKTABLE will be written verbatim. However
  85792. * by itself this is not very useful as the client will not know the stream
  85793. * offsets for the seekpoints ahead of time. In order to get a proper
  85794. * seektable the client must support seeking. See next note.
  85795. *
  85796. * \note
  85797. * SEEKTABLE blocks are handled specially. Since you will not know
  85798. * the values for the seek point stream offsets, you should pass in
  85799. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  85800. * required sample numbers (or placeholder points), with \c 0 for the
  85801. * \a frame_samples and \a stream_offset fields for each point. If the
  85802. * client has specified that it supports seeking by providing a seek
  85803. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  85804. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  85805. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  85806. * then while it is encoding the encoder will fill the stream offsets in
  85807. * for you and when encoding is finished, it will seek back and write the
  85808. * real values into the SEEKTABLE block in the stream. There are helper
  85809. * routines for manipulating seektable template blocks; see metadata.h:
  85810. * FLAC__metadata_object_seektable_template_*(). If the client does
  85811. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  85812. * will slow down or remove the ability to seek in the FLAC stream.
  85813. *
  85814. * \note
  85815. * The encoder instance \b will modify the first \c SEEKTABLE block
  85816. * as it transforms the template to a valid seektable while encoding,
  85817. * but it is still up to the caller to free all metadata blocks after
  85818. * encoding.
  85819. *
  85820. * \note
  85821. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  85822. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  85823. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  85824. * will simply write it's own into the stream. If no VORBIS_COMMENT
  85825. * block is present in the \a metadata array, libFLAC will write an
  85826. * empty one, containing only the vendor string.
  85827. *
  85828. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  85829. * the second metadata block of the stream. The encoder already supplies
  85830. * the STREAMINFO block automatically. If \a metadata does not contain a
  85831. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  85832. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  85833. * first, the init function will reorder \a metadata by moving the
  85834. * VORBIS_COMMENT block to the front; the relative ordering of the other
  85835. * blocks will remain as they were.
  85836. *
  85837. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  85838. * stream to \c 65535. If \a num_blocks exceeds this the function will
  85839. * return \c false.
  85840. *
  85841. * \default \c NULL, 0
  85842. * \param encoder An encoder instance to set.
  85843. * \param metadata See above.
  85844. * \param num_blocks See above.
  85845. * \assert
  85846. * \code encoder != NULL \endcode
  85847. * \retval FLAC__bool
  85848. * \c false if the encoder is already initialized, else \c true.
  85849. * \c false if the encoder is already initialized, or if
  85850. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  85851. */
  85852. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  85853. /** Get the current encoder state.
  85854. *
  85855. * \param encoder An encoder instance to query.
  85856. * \assert
  85857. * \code encoder != NULL \endcode
  85858. * \retval FLAC__StreamEncoderState
  85859. * The current encoder state.
  85860. */
  85861. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  85862. /** Get the state of the verify stream decoder.
  85863. * Useful when the stream encoder state is
  85864. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  85865. *
  85866. * \param encoder An encoder instance to query.
  85867. * \assert
  85868. * \code encoder != NULL \endcode
  85869. * \retval FLAC__StreamDecoderState
  85870. * The verify stream decoder state.
  85871. */
  85872. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  85873. /** Get the current encoder state as a C string.
  85874. * This version automatically resolves
  85875. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  85876. * verify decoder's state.
  85877. *
  85878. * \param encoder A encoder instance to query.
  85879. * \assert
  85880. * \code encoder != NULL \endcode
  85881. * \retval const char *
  85882. * The encoder state as a C string. Do not modify the contents.
  85883. */
  85884. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  85885. /** Get relevant values about the nature of a verify decoder error.
  85886. * Useful when the stream encoder state is
  85887. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  85888. * be addresses in which the stats will be returned, or NULL if value
  85889. * is not desired.
  85890. *
  85891. * \param encoder An encoder instance to query.
  85892. * \param absolute_sample The absolute sample number of the mismatch.
  85893. * \param frame_number The number of the frame in which the mismatch occurred.
  85894. * \param channel The channel in which the mismatch occurred.
  85895. * \param sample The number of the sample (relative to the frame) in
  85896. * which the mismatch occurred.
  85897. * \param expected The expected value for the sample in question.
  85898. * \param got The actual value returned by the decoder.
  85899. * \assert
  85900. * \code encoder != NULL \endcode
  85901. */
  85902. 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);
  85903. /** Get the "verify" flag.
  85904. *
  85905. * \param encoder An encoder instance to query.
  85906. * \assert
  85907. * \code encoder != NULL \endcode
  85908. * \retval FLAC__bool
  85909. * See FLAC__stream_encoder_set_verify().
  85910. */
  85911. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  85912. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  85913. *
  85914. * \param encoder An encoder instance to query.
  85915. * \assert
  85916. * \code encoder != NULL \endcode
  85917. * \retval FLAC__bool
  85918. * See FLAC__stream_encoder_set_streamable_subset().
  85919. */
  85920. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  85921. /** Get the number of input channels being processed.
  85922. *
  85923. * \param encoder An encoder instance to query.
  85924. * \assert
  85925. * \code encoder != NULL \endcode
  85926. * \retval unsigned
  85927. * See FLAC__stream_encoder_set_channels().
  85928. */
  85929. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  85930. /** Get the input sample resolution setting.
  85931. *
  85932. * \param encoder An encoder instance to query.
  85933. * \assert
  85934. * \code encoder != NULL \endcode
  85935. * \retval unsigned
  85936. * See FLAC__stream_encoder_set_bits_per_sample().
  85937. */
  85938. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  85939. /** Get the input sample rate setting.
  85940. *
  85941. * \param encoder An encoder instance to query.
  85942. * \assert
  85943. * \code encoder != NULL \endcode
  85944. * \retval unsigned
  85945. * See FLAC__stream_encoder_set_sample_rate().
  85946. */
  85947. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  85948. /** Get the blocksize setting.
  85949. *
  85950. * \param encoder An encoder instance to query.
  85951. * \assert
  85952. * \code encoder != NULL \endcode
  85953. * \retval unsigned
  85954. * See FLAC__stream_encoder_set_blocksize().
  85955. */
  85956. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  85957. /** Get the "mid/side stereo coding" flag.
  85958. *
  85959. * \param encoder An encoder instance to query.
  85960. * \assert
  85961. * \code encoder != NULL \endcode
  85962. * \retval FLAC__bool
  85963. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  85964. */
  85965. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  85966. /** Get the "adaptive mid/side switching" flag.
  85967. *
  85968. * \param encoder An encoder instance to query.
  85969. * \assert
  85970. * \code encoder != NULL \endcode
  85971. * \retval FLAC__bool
  85972. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  85973. */
  85974. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  85975. /** Get the maximum LPC order setting.
  85976. *
  85977. * \param encoder An encoder instance to query.
  85978. * \assert
  85979. * \code encoder != NULL \endcode
  85980. * \retval unsigned
  85981. * See FLAC__stream_encoder_set_max_lpc_order().
  85982. */
  85983. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  85984. /** Get the quantized linear predictor coefficient precision setting.
  85985. *
  85986. * \param encoder An encoder instance to query.
  85987. * \assert
  85988. * \code encoder != NULL \endcode
  85989. * \retval unsigned
  85990. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  85991. */
  85992. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  85993. /** Get the qlp coefficient precision search flag.
  85994. *
  85995. * \param encoder An encoder instance to query.
  85996. * \assert
  85997. * \code encoder != NULL \endcode
  85998. * \retval FLAC__bool
  85999. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  86000. */
  86001. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  86002. /** Get the "escape coding" flag.
  86003. *
  86004. * \param encoder An encoder instance to query.
  86005. * \assert
  86006. * \code encoder != NULL \endcode
  86007. * \retval FLAC__bool
  86008. * See FLAC__stream_encoder_set_do_escape_coding().
  86009. */
  86010. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  86011. /** Get the exhaustive model search flag.
  86012. *
  86013. * \param encoder An encoder instance to query.
  86014. * \assert
  86015. * \code encoder != NULL \endcode
  86016. * \retval FLAC__bool
  86017. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  86018. */
  86019. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  86020. /** Get the minimum residual partition order setting.
  86021. *
  86022. * \param encoder An encoder instance to query.
  86023. * \assert
  86024. * \code encoder != NULL \endcode
  86025. * \retval unsigned
  86026. * See FLAC__stream_encoder_set_min_residual_partition_order().
  86027. */
  86028. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  86029. /** Get maximum residual partition order setting.
  86030. *
  86031. * \param encoder An encoder instance to query.
  86032. * \assert
  86033. * \code encoder != NULL \endcode
  86034. * \retval unsigned
  86035. * See FLAC__stream_encoder_set_max_residual_partition_order().
  86036. */
  86037. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  86038. /** Get the Rice parameter search distance setting.
  86039. *
  86040. * \param encoder An encoder instance to query.
  86041. * \assert
  86042. * \code encoder != NULL \endcode
  86043. * \retval unsigned
  86044. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  86045. */
  86046. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  86047. /** Get the previously set estimate of the total samples to be encoded.
  86048. * The encoder merely mimics back the value given to
  86049. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  86050. * other way of knowing how many samples the client will encode.
  86051. *
  86052. * \param encoder An encoder instance to set.
  86053. * \assert
  86054. * \code encoder != NULL \endcode
  86055. * \retval FLAC__uint64
  86056. * See FLAC__stream_encoder_get_total_samples_estimate().
  86057. */
  86058. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  86059. /** Initialize the encoder instance to encode native FLAC streams.
  86060. *
  86061. * This flavor of initialization sets up the encoder to encode to a
  86062. * native FLAC stream. I/O is performed via callbacks to the client.
  86063. * For encoding to a plain file via filename or open \c FILE*,
  86064. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  86065. * provide a simpler interface.
  86066. *
  86067. * This function should be called after FLAC__stream_encoder_new() and
  86068. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86069. * or FLAC__stream_encoder_process_interleaved().
  86070. * initialization succeeded.
  86071. *
  86072. * The call to FLAC__stream_encoder_init_stream() currently will also
  86073. * immediately call the write callback several times, once with the \c fLaC
  86074. * signature, and once for each encoded metadata block.
  86075. *
  86076. * \param encoder An uninitialized encoder instance.
  86077. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  86078. * pointer must not be \c NULL.
  86079. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  86080. * pointer may be \c NULL if seeking is not
  86081. * supported. The encoder uses seeking to go back
  86082. * and write some some stream statistics to the
  86083. * STREAMINFO block; this is recommended but not
  86084. * necessary to create a valid FLAC stream. If
  86085. * \a seek_callback is not \c NULL then a
  86086. * \a tell_callback must also be supplied.
  86087. * Alternatively, a dummy seek callback that just
  86088. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  86089. * may also be supplied, all though this is slightly
  86090. * less efficient for the encoder.
  86091. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  86092. * pointer may be \c NULL if seeking is not
  86093. * supported. If \a seek_callback is \c NULL then
  86094. * this argument will be ignored. If
  86095. * \a seek_callback is not \c NULL then a
  86096. * \a tell_callback must also be supplied.
  86097. * Alternatively, a dummy tell callback that just
  86098. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  86099. * may also be supplied, all though this is slightly
  86100. * less efficient for the encoder.
  86101. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  86102. * pointer may be \c NULL if the callback is not
  86103. * desired. If the client provides a seek callback,
  86104. * this function is not necessary as the encoder
  86105. * will automatically seek back and update the
  86106. * STREAMINFO block. It may also be \c NULL if the
  86107. * client does not support seeking, since it will
  86108. * have no way of going back to update the
  86109. * STREAMINFO. However the client can still supply
  86110. * a callback if it would like to know the details
  86111. * from the STREAMINFO.
  86112. * \param client_data This value will be supplied to callbacks in their
  86113. * \a client_data argument.
  86114. * \assert
  86115. * \code encoder != NULL \endcode
  86116. * \retval FLAC__StreamEncoderInitStatus
  86117. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86118. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86119. */
  86120. 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);
  86121. /** Initialize the encoder instance to encode Ogg FLAC streams.
  86122. *
  86123. * This flavor of initialization sets up the encoder to encode to a FLAC
  86124. * stream in an Ogg container. I/O is performed via callbacks to the
  86125. * client. For encoding to a plain file via filename or open \c FILE*,
  86126. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  86127. * provide a simpler interface.
  86128. *
  86129. * This function should be called after FLAC__stream_encoder_new() and
  86130. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86131. * or FLAC__stream_encoder_process_interleaved().
  86132. * initialization succeeded.
  86133. *
  86134. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  86135. * immediately call the write callback several times to write the metadata
  86136. * packets.
  86137. *
  86138. * \param encoder An uninitialized encoder instance.
  86139. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  86140. * pointer must not be \c NULL if \a seek_callback
  86141. * is non-NULL since they are both needed to be
  86142. * able to write data back to the Ogg FLAC stream
  86143. * in the post-encode phase.
  86144. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  86145. * pointer must not be \c NULL.
  86146. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  86147. * pointer may be \c NULL if seeking is not
  86148. * supported. The encoder uses seeking to go back
  86149. * and write some some stream statistics to the
  86150. * STREAMINFO block; this is recommended but not
  86151. * necessary to create a valid FLAC stream. If
  86152. * \a seek_callback is not \c NULL then a
  86153. * \a tell_callback must also be supplied.
  86154. * Alternatively, a dummy seek callback that just
  86155. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  86156. * may also be supplied, all though this is slightly
  86157. * less efficient for the encoder.
  86158. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  86159. * pointer may be \c NULL if seeking is not
  86160. * supported. If \a seek_callback is \c NULL then
  86161. * this argument will be ignored. If
  86162. * \a seek_callback is not \c NULL then a
  86163. * \a tell_callback must also be supplied.
  86164. * Alternatively, a dummy tell callback that just
  86165. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  86166. * may also be supplied, all though this is slightly
  86167. * less efficient for the encoder.
  86168. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  86169. * pointer may be \c NULL if the callback is not
  86170. * desired. If the client provides a seek callback,
  86171. * this function is not necessary as the encoder
  86172. * will automatically seek back and update the
  86173. * STREAMINFO block. It may also be \c NULL if the
  86174. * client does not support seeking, since it will
  86175. * have no way of going back to update the
  86176. * STREAMINFO. However the client can still supply
  86177. * a callback if it would like to know the details
  86178. * from the STREAMINFO.
  86179. * \param client_data This value will be supplied to callbacks in their
  86180. * \a client_data argument.
  86181. * \assert
  86182. * \code encoder != NULL \endcode
  86183. * \retval FLAC__StreamEncoderInitStatus
  86184. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86185. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86186. */
  86187. 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);
  86188. /** Initialize the encoder instance to encode native FLAC files.
  86189. *
  86190. * This flavor of initialization sets up the encoder to encode to a
  86191. * plain native FLAC file. For non-stdio streams, you must use
  86192. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  86193. *
  86194. * This function should be called after FLAC__stream_encoder_new() and
  86195. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86196. * or FLAC__stream_encoder_process_interleaved().
  86197. * initialization succeeded.
  86198. *
  86199. * \param encoder An uninitialized encoder instance.
  86200. * \param file An open file. The file should have been opened
  86201. * with mode \c "w+b" and rewound. The file
  86202. * becomes owned by the encoder and should not be
  86203. * manipulated by the client while encoding.
  86204. * Unless \a file is \c stdout, it will be closed
  86205. * when FLAC__stream_encoder_finish() is called.
  86206. * Note however that a proper SEEKTABLE cannot be
  86207. * created when encoding to \c stdout since it is
  86208. * not seekable.
  86209. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  86210. * pointer may be \c NULL if the callback is not
  86211. * desired.
  86212. * \param client_data This value will be supplied to callbacks in their
  86213. * \a client_data argument.
  86214. * \assert
  86215. * \code encoder != NULL \endcode
  86216. * \code file != NULL \endcode
  86217. * \retval FLAC__StreamEncoderInitStatus
  86218. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86219. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86220. */
  86221. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  86222. /** Initialize the encoder instance to encode Ogg FLAC files.
  86223. *
  86224. * This flavor of initialization sets up the encoder to encode to a
  86225. * plain Ogg FLAC file. For non-stdio streams, you must use
  86226. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  86227. *
  86228. * This function should be called after FLAC__stream_encoder_new() and
  86229. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86230. * or FLAC__stream_encoder_process_interleaved().
  86231. * initialization succeeded.
  86232. *
  86233. * \param encoder An uninitialized encoder instance.
  86234. * \param file An open file. The file should have been opened
  86235. * with mode \c "w+b" and rewound. The file
  86236. * becomes owned by the encoder and should not be
  86237. * manipulated by the client while encoding.
  86238. * Unless \a file is \c stdout, it will be closed
  86239. * when FLAC__stream_encoder_finish() is called.
  86240. * Note however that a proper SEEKTABLE cannot be
  86241. * created when encoding to \c stdout since it is
  86242. * not seekable.
  86243. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  86244. * pointer may be \c NULL if the callback is not
  86245. * desired.
  86246. * \param client_data This value will be supplied to callbacks in their
  86247. * \a client_data argument.
  86248. * \assert
  86249. * \code encoder != NULL \endcode
  86250. * \code file != NULL \endcode
  86251. * \retval FLAC__StreamEncoderInitStatus
  86252. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86253. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86254. */
  86255. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  86256. /** Initialize the encoder instance to encode native FLAC files.
  86257. *
  86258. * This flavor of initialization sets up the encoder to encode to a plain
  86259. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  86260. * with Unicode filenames on Windows), you must use
  86261. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  86262. * and provide callbacks for the I/O.
  86263. *
  86264. * This function should be called after FLAC__stream_encoder_new() and
  86265. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86266. * or FLAC__stream_encoder_process_interleaved().
  86267. * initialization succeeded.
  86268. *
  86269. * \param encoder An uninitialized encoder instance.
  86270. * \param filename The name of the file to encode to. The file will
  86271. * be opened with fopen(). Use \c NULL to encode to
  86272. * \c stdout. Note however that a proper SEEKTABLE
  86273. * cannot be created when encoding to \c stdout since
  86274. * it is not seekable.
  86275. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  86276. * pointer may be \c NULL if the callback is not
  86277. * desired.
  86278. * \param client_data This value will be supplied to callbacks in their
  86279. * \a client_data argument.
  86280. * \assert
  86281. * \code encoder != NULL \endcode
  86282. * \retval FLAC__StreamEncoderInitStatus
  86283. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86284. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86285. */
  86286. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  86287. /** Initialize the encoder instance to encode Ogg FLAC files.
  86288. *
  86289. * This flavor of initialization sets up the encoder to encode to a plain
  86290. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  86291. * with Unicode filenames on Windows), you must use
  86292. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  86293. * and provide callbacks for the I/O.
  86294. *
  86295. * This function should be called after FLAC__stream_encoder_new() and
  86296. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86297. * or FLAC__stream_encoder_process_interleaved().
  86298. * initialization succeeded.
  86299. *
  86300. * \param encoder An uninitialized encoder instance.
  86301. * \param filename The name of the file to encode to. The file will
  86302. * be opened with fopen(). Use \c NULL to encode to
  86303. * \c stdout. Note however that a proper SEEKTABLE
  86304. * cannot be created when encoding to \c stdout since
  86305. * it is not seekable.
  86306. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  86307. * pointer may be \c NULL if the callback is not
  86308. * desired.
  86309. * \param client_data This value will be supplied to callbacks in their
  86310. * \a client_data argument.
  86311. * \assert
  86312. * \code encoder != NULL \endcode
  86313. * \retval FLAC__StreamEncoderInitStatus
  86314. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86315. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86316. */
  86317. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  86318. /** Finish the encoding process.
  86319. * Flushes the encoding buffer, releases resources, resets the encoder
  86320. * settings to their defaults, and returns the encoder state to
  86321. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  86322. * one or more write callbacks before returning, and will generate
  86323. * a metadata callback.
  86324. *
  86325. * Note that in the course of processing the last frame, errors can
  86326. * occur, so the caller should be sure to check the return value to
  86327. * ensure the file was encoded properly.
  86328. *
  86329. * In the event of a prematurely-terminated encode, it is not strictly
  86330. * necessary to call this immediately before FLAC__stream_encoder_delete()
  86331. * but it is good practice to match every FLAC__stream_encoder_init_*()
  86332. * with a FLAC__stream_encoder_finish().
  86333. *
  86334. * \param encoder An uninitialized encoder instance.
  86335. * \assert
  86336. * \code encoder != NULL \endcode
  86337. * \retval FLAC__bool
  86338. * \c false if an error occurred processing the last frame; or if verify
  86339. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  86340. * verify mismatch; else \c true. If \c false, caller should check the
  86341. * state with FLAC__stream_encoder_get_state() for more information
  86342. * about the error.
  86343. */
  86344. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  86345. /** Submit data for encoding.
  86346. * This version allows you to supply the input data via an array of
  86347. * pointers, each pointer pointing to an array of \a samples samples
  86348. * representing one channel. The samples need not be block-aligned,
  86349. * but each channel should have the same number of samples. Each sample
  86350. * should be a signed integer, right-justified to the resolution set by
  86351. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  86352. * resolution is 16 bits per sample, the samples should all be in the
  86353. * range [-32768,32767].
  86354. *
  86355. * For applications where channel order is important, channels must
  86356. * follow the order as described in the
  86357. * <A HREF="../format.html#frame_header">frame header</A>.
  86358. *
  86359. * \param encoder An initialized encoder instance in the OK state.
  86360. * \param buffer An array of pointers to each channel's signal.
  86361. * \param samples The number of samples in one channel.
  86362. * \assert
  86363. * \code encoder != NULL \endcode
  86364. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  86365. * \retval FLAC__bool
  86366. * \c true if successful, else \c false; in this case, check the
  86367. * encoder state with FLAC__stream_encoder_get_state() to see what
  86368. * went wrong.
  86369. */
  86370. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  86371. /** Submit data for encoding.
  86372. * This version allows you to supply the input data where the channels
  86373. * are interleaved into a single array (i.e. channel0_sample0,
  86374. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  86375. * The samples need not be block-aligned but they must be
  86376. * sample-aligned, i.e. the first value should be channel0_sample0
  86377. * and the last value channelN_sampleM. Each sample should be a signed
  86378. * integer, right-justified to the resolution set by
  86379. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  86380. * resolution is 16 bits per sample, the samples should all be in the
  86381. * range [-32768,32767].
  86382. *
  86383. * For applications where channel order is important, channels must
  86384. * follow the order as described in the
  86385. * <A HREF="../format.html#frame_header">frame header</A>.
  86386. *
  86387. * \param encoder An initialized encoder instance in the OK state.
  86388. * \param buffer An array of channel-interleaved data (see above).
  86389. * \param samples The number of samples in one channel, the same as for
  86390. * FLAC__stream_encoder_process(). For example, if
  86391. * encoding two channels, \c 1000 \a samples corresponds
  86392. * to a \a buffer of 2000 values.
  86393. * \assert
  86394. * \code encoder != NULL \endcode
  86395. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  86396. * \retval FLAC__bool
  86397. * \c true if successful, else \c false; in this case, check the
  86398. * encoder state with FLAC__stream_encoder_get_state() to see what
  86399. * went wrong.
  86400. */
  86401. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  86402. /* \} */
  86403. #ifdef __cplusplus
  86404. }
  86405. #endif
  86406. #endif
  86407. /********* End of inlined file: stream_encoder.h *********/
  86408. #ifdef _MSC_VER
  86409. /* OPT: an MSVC built-in would be better */
  86410. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  86411. {
  86412. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  86413. return (x>>16) | (x<<16);
  86414. }
  86415. #endif
  86416. #if defined(_MSC_VER) && defined(_X86_)
  86417. /* OPT: an MSVC built-in would be better */
  86418. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  86419. {
  86420. __asm {
  86421. mov edx, start
  86422. mov ecx, len
  86423. test ecx, ecx
  86424. loop1:
  86425. jz done1
  86426. mov eax, [edx]
  86427. bswap eax
  86428. mov [edx], eax
  86429. add edx, 4
  86430. dec ecx
  86431. jmp short loop1
  86432. done1:
  86433. }
  86434. }
  86435. #endif
  86436. /** \mainpage
  86437. *
  86438. * \section intro Introduction
  86439. *
  86440. * This is the documentation for the FLAC C and C++ APIs. It is
  86441. * highly interconnected; this introduction should give you a top
  86442. * level idea of the structure and how to find the information you
  86443. * need. As a prerequisite you should have at least a basic
  86444. * knowledge of the FLAC format, documented
  86445. * <A HREF="../format.html">here</A>.
  86446. *
  86447. * \section c_api FLAC C API
  86448. *
  86449. * The FLAC C API is the interface to libFLAC, a set of structures
  86450. * describing the components of FLAC streams, and functions for
  86451. * encoding and decoding streams, as well as manipulating FLAC
  86452. * metadata in files. The public include files will be installed
  86453. * in your include area (for example /usr/include/FLAC/...).
  86454. *
  86455. * By writing a little code and linking against libFLAC, it is
  86456. * relatively easy to add FLAC support to another program. The
  86457. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  86458. * Complete source code of libFLAC as well as the command-line
  86459. * encoder and plugins is available and is a useful source of
  86460. * examples.
  86461. *
  86462. * Aside from encoders and decoders, libFLAC provides a powerful
  86463. * metadata interface for manipulating metadata in FLAC files. It
  86464. * allows the user to add, delete, and modify FLAC metadata blocks
  86465. * and it can automatically take advantage of PADDING blocks to avoid
  86466. * rewriting the entire FLAC file when changing the size of the
  86467. * metadata.
  86468. *
  86469. * libFLAC usually only requires the standard C library and C math
  86470. * library. In particular, threading is not used so there is no
  86471. * dependency on a thread library. However, libFLAC does not use
  86472. * global variables and should be thread-safe.
  86473. *
  86474. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  86475. * However the metadata editing interfaces currently have limited
  86476. * read-only support for Ogg FLAC files.
  86477. *
  86478. * \section cpp_api FLAC C++ API
  86479. *
  86480. * The FLAC C++ API is a set of classes that encapsulate the
  86481. * structures and functions in libFLAC. They provide slightly more
  86482. * functionality with respect to metadata but are otherwise
  86483. * equivalent. For the most part, they share the same usage as
  86484. * their counterparts in libFLAC, and the FLAC C API documentation
  86485. * can be used as a supplement. The public include files
  86486. * for the C++ API will be installed in your include area (for
  86487. * example /usr/include/FLAC++/...).
  86488. *
  86489. * libFLAC++ is also licensed under
  86490. * <A HREF="../license.html">Xiph's BSD license</A>.
  86491. *
  86492. * \section getting_started Getting Started
  86493. *
  86494. * A good starting point for learning the API is to browse through
  86495. * the <A HREF="modules.html">modules</A>. Modules are logical
  86496. * groupings of related functions or classes, which correspond roughly
  86497. * to header files or sections of header files. Each module includes a
  86498. * detailed description of the general usage of its functions or
  86499. * classes.
  86500. *
  86501. * From there you can go on to look at the documentation of
  86502. * individual functions. You can see different views of the individual
  86503. * functions through the links in top bar across this page.
  86504. *
  86505. * If you prefer a more hands-on approach, you can jump right to some
  86506. * <A HREF="../documentation_example_code.html">example code</A>.
  86507. *
  86508. * \section porting_guide Porting Guide
  86509. *
  86510. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  86511. * has been introduced which gives detailed instructions on how to
  86512. * port your code to newer versions of FLAC.
  86513. *
  86514. * \section embedded_developers Embedded Developers
  86515. *
  86516. * libFLAC has grown larger over time as more functionality has been
  86517. * included, but much of it may be unnecessary for a particular embedded
  86518. * implementation. Unused parts may be pruned by some simple editing of
  86519. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  86520. * metadata interface are all independent from each other.
  86521. *
  86522. * It is easiest to just describe the dependencies:
  86523. *
  86524. * - All modules depend on the \link flac_format Format \endlink module.
  86525. * - The decoders and encoders depend on the bitbuffer.
  86526. * - The decoder is independent of the encoder. The encoder uses the
  86527. * decoder because of the verify feature, but this can be removed if
  86528. * not needed.
  86529. * - Parts of the metadata interface require the stream decoder (but not
  86530. * the encoder).
  86531. * - Ogg support is selectable through the compile time macro
  86532. * \c FLAC__HAS_OGG.
  86533. *
  86534. * For example, if your application only requires the stream decoder, no
  86535. * encoder, and no metadata interface, you can remove the stream encoder
  86536. * and the metadata interface, which will greatly reduce the size of the
  86537. * library.
  86538. *
  86539. * Also, there are several places in the libFLAC code with comments marked
  86540. * with "OPT:" where a #define can be changed to enable code that might be
  86541. * faster on a specific platform. Experimenting with these can yield faster
  86542. * binaries.
  86543. */
  86544. /** \defgroup porting Porting Guide for New Versions
  86545. *
  86546. * This module describes differences in the library interfaces from
  86547. * version to version. It assists in the porting of code that uses
  86548. * the libraries to newer versions of FLAC.
  86549. *
  86550. * One simple facility for making porting easier that has been added
  86551. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  86552. * library's includes (e.g. \c include/FLAC/export.h). The
  86553. * \c #defines mirror the libraries'
  86554. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  86555. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  86556. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  86557. * These can be used to support multiple versions of an API during the
  86558. * transition phase, e.g.
  86559. *
  86560. * \code
  86561. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  86562. * legacy code
  86563. * #else
  86564. * new code
  86565. * #endif
  86566. * \endcode
  86567. *
  86568. * The the source will work for multiple versions and the legacy code can
  86569. * easily be removed when the transition is complete.
  86570. *
  86571. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  86572. * include/FLAC/export.h), which can be used to determine whether or not
  86573. * the library has been compiled with support for Ogg FLAC. This is
  86574. * simpler than trying to call an Ogg init function and catching the
  86575. * error.
  86576. */
  86577. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  86578. * \ingroup porting
  86579. *
  86580. * \brief
  86581. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  86582. *
  86583. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  86584. * been simplified. First, libOggFLAC has been merged into libFLAC and
  86585. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  86586. * decoding layers and three encoding layers have been merged into a
  86587. * single stream decoder and stream encoder. That is, the functionality
  86588. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  86589. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  86590. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  86591. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  86592. * is there is now a single API that can be used to encode or decode
  86593. * streams to/from native FLAC or Ogg FLAC and the single API can work
  86594. * on both seekable and non-seekable streams.
  86595. *
  86596. * Instead of creating an encoder or decoder of a certain layer, now the
  86597. * client will always create a FLAC__StreamEncoder or
  86598. * FLAC__StreamDecoder. The old layers are now differentiated by the
  86599. * initialization function. For example, for the decoder,
  86600. * FLAC__stream_decoder_init() has been replaced by
  86601. * FLAC__stream_decoder_init_stream(). This init function takes
  86602. * callbacks for the I/O, and the seeking callbacks are optional. This
  86603. * allows the client to use the same object for seekable and
  86604. * non-seekable streams. For decoding a FLAC file directly, the client
  86605. * can use FLAC__stream_decoder_init_file() and pass just a filename
  86606. * and fewer callbacks; most of the other callbacks are supplied
  86607. * internally. For situations where fopen()ing by filename is not
  86608. * possible (e.g. Unicode filenames on Windows) the client can instead
  86609. * open the file itself and supply the FILE* to
  86610. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  86611. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  86612. * Since the callbacks and client data are now passed to the init
  86613. * function, the FLAC__stream_decoder_set_*_callback() functions and
  86614. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  86615. * rest of the calls to the decoder are the same as before.
  86616. *
  86617. * There are counterpart init functions for Ogg FLAC, e.g.
  86618. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  86619. * and callbacks are the same as for native FLAC.
  86620. *
  86621. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  86622. * been set up like so:
  86623. *
  86624. * \code
  86625. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  86626. * if(decoder == NULL) do_something;
  86627. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  86628. * [... other settings ...]
  86629. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  86630. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  86631. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  86632. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  86633. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  86634. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  86635. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  86636. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  86637. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  86638. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  86639. * \endcode
  86640. *
  86641. * In FLAC 1.1.3 it is like this:
  86642. *
  86643. * \code
  86644. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  86645. * if(decoder == NULL) do_something;
  86646. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  86647. * [... other settings ...]
  86648. * if(FLAC__stream_decoder_init_stream(
  86649. * decoder,
  86650. * my_read_callback,
  86651. * my_seek_callback, // or NULL
  86652. * my_tell_callback, // or NULL
  86653. * my_length_callback, // or NULL
  86654. * my_eof_callback, // or NULL
  86655. * my_write_callback,
  86656. * my_metadata_callback, // or NULL
  86657. * my_error_callback,
  86658. * my_client_data
  86659. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  86660. * \endcode
  86661. *
  86662. * or you could do;
  86663. *
  86664. * \code
  86665. * [...]
  86666. * FILE *file = fopen("somefile.flac","rb");
  86667. * if(file == NULL) do_somthing;
  86668. * if(FLAC__stream_decoder_init_FILE(
  86669. * decoder,
  86670. * file,
  86671. * my_write_callback,
  86672. * my_metadata_callback, // or NULL
  86673. * my_error_callback,
  86674. * my_client_data
  86675. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  86676. * \endcode
  86677. *
  86678. * or just:
  86679. *
  86680. * \code
  86681. * [...]
  86682. * if(FLAC__stream_decoder_init_file(
  86683. * decoder,
  86684. * "somefile.flac",
  86685. * my_write_callback,
  86686. * my_metadata_callback, // or NULL
  86687. * my_error_callback,
  86688. * my_client_data
  86689. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  86690. * \endcode
  86691. *
  86692. * Another small change to the decoder is in how it handles unparseable
  86693. * streams. Before, when the decoder found an unparseable stream
  86694. * (reserved for when the decoder encounters a stream from a future
  86695. * encoder that it can't parse), it changed the state to
  86696. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  86697. * drops sync and calls the error callback with a new error code
  86698. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  86699. * more robust. If your error callback does not discriminate on the the
  86700. * error state, your code does not need to be changed.
  86701. *
  86702. * The encoder now has a new setting:
  86703. * FLAC__stream_encoder_set_apodization(). This is for setting the
  86704. * method used to window the data before LPC analysis. You only need to
  86705. * add a call to this function if the default is not suitable. There
  86706. * are also two new convenience functions that may be useful:
  86707. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  86708. * FLAC__metadata_get_cuesheet().
  86709. *
  86710. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  86711. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  86712. * is now \c size_t instead of \c unsigned.
  86713. */
  86714. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  86715. * \ingroup porting
  86716. *
  86717. * \brief
  86718. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  86719. *
  86720. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  86721. * There was a slight change in the implementation of
  86722. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  86723. * of the \a metadata array of pointers so the client no longer needs
  86724. * to maintain it after the call. The objects themselves that are
  86725. * pointed to by the array are still not copied though and must be
  86726. * maintained until the call to FLAC__stream_encoder_finish().
  86727. */
  86728. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  86729. * \ingroup porting
  86730. *
  86731. * \brief
  86732. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  86733. *
  86734. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  86735. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  86736. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  86737. *
  86738. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  86739. * has changed to reflect the conversion of one of the reserved bits
  86740. * into active use. It used to be \c 2 and now is \c 1. However the
  86741. * FLAC frame header length has not changed, so to skip the proper
  86742. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  86743. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  86744. */
  86745. /** \defgroup flac FLAC C API
  86746. *
  86747. * The FLAC C API is the interface to libFLAC, a set of structures
  86748. * describing the components of FLAC streams, and functions for
  86749. * encoding and decoding streams, as well as manipulating FLAC
  86750. * metadata in files.
  86751. *
  86752. * You should start with the format components as all other modules
  86753. * are dependent on it.
  86754. */
  86755. #endif
  86756. /********* End of inlined file: all.h *********/
  86757. /********* Start of inlined file: bitmath.c *********/
  86758. /********* Start of inlined file: juce_FlacHeader.h *********/
  86759. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  86760. // tasks..
  86761. #define VERSION "1.2.1"
  86762. #define FLAC__NO_DLL 1
  86763. #ifdef _MSC_VER
  86764. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  86765. #endif
  86766. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  86767. #define FLAC__SYS_DARWIN 1
  86768. #endif
  86769. /********* End of inlined file: juce_FlacHeader.h *********/
  86770. #if JUCE_USE_FLAC
  86771. #if HAVE_CONFIG_H
  86772. # include <config.h>
  86773. #endif
  86774. /********* Start of inlined file: bitmath.h *********/
  86775. #ifndef FLAC__PRIVATE__BITMATH_H
  86776. #define FLAC__PRIVATE__BITMATH_H
  86777. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  86778. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  86779. unsigned FLAC__bitmath_silog2(int v);
  86780. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  86781. #endif
  86782. /********* End of inlined file: bitmath.h *********/
  86783. /* An example of what FLAC__bitmath_ilog2() computes:
  86784. *
  86785. * ilog2( 0) = assertion failure
  86786. * ilog2( 1) = 0
  86787. * ilog2( 2) = 1
  86788. * ilog2( 3) = 1
  86789. * ilog2( 4) = 2
  86790. * ilog2( 5) = 2
  86791. * ilog2( 6) = 2
  86792. * ilog2( 7) = 2
  86793. * ilog2( 8) = 3
  86794. * ilog2( 9) = 3
  86795. * ilog2(10) = 3
  86796. * ilog2(11) = 3
  86797. * ilog2(12) = 3
  86798. * ilog2(13) = 3
  86799. * ilog2(14) = 3
  86800. * ilog2(15) = 3
  86801. * ilog2(16) = 4
  86802. * ilog2(17) = 4
  86803. * ilog2(18) = 4
  86804. */
  86805. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  86806. {
  86807. unsigned l = 0;
  86808. FLAC__ASSERT(v > 0);
  86809. while(v >>= 1)
  86810. l++;
  86811. return l;
  86812. }
  86813. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  86814. {
  86815. unsigned l = 0;
  86816. FLAC__ASSERT(v > 0);
  86817. while(v >>= 1)
  86818. l++;
  86819. return l;
  86820. }
  86821. /* An example of what FLAC__bitmath_silog2() computes:
  86822. *
  86823. * silog2(-10) = 5
  86824. * silog2(- 9) = 5
  86825. * silog2(- 8) = 4
  86826. * silog2(- 7) = 4
  86827. * silog2(- 6) = 4
  86828. * silog2(- 5) = 4
  86829. * silog2(- 4) = 3
  86830. * silog2(- 3) = 3
  86831. * silog2(- 2) = 2
  86832. * silog2(- 1) = 2
  86833. * silog2( 0) = 0
  86834. * silog2( 1) = 2
  86835. * silog2( 2) = 3
  86836. * silog2( 3) = 3
  86837. * silog2( 4) = 4
  86838. * silog2( 5) = 4
  86839. * silog2( 6) = 4
  86840. * silog2( 7) = 4
  86841. * silog2( 8) = 5
  86842. * silog2( 9) = 5
  86843. * silog2( 10) = 5
  86844. */
  86845. unsigned FLAC__bitmath_silog2(int v)
  86846. {
  86847. while(1) {
  86848. if(v == 0) {
  86849. return 0;
  86850. }
  86851. else if(v > 0) {
  86852. unsigned l = 0;
  86853. while(v) {
  86854. l++;
  86855. v >>= 1;
  86856. }
  86857. return l+1;
  86858. }
  86859. else if(v == -1) {
  86860. return 2;
  86861. }
  86862. else {
  86863. v++;
  86864. v = -v;
  86865. }
  86866. }
  86867. }
  86868. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  86869. {
  86870. while(1) {
  86871. if(v == 0) {
  86872. return 0;
  86873. }
  86874. else if(v > 0) {
  86875. unsigned l = 0;
  86876. while(v) {
  86877. l++;
  86878. v >>= 1;
  86879. }
  86880. return l+1;
  86881. }
  86882. else if(v == -1) {
  86883. return 2;
  86884. }
  86885. else {
  86886. v++;
  86887. v = -v;
  86888. }
  86889. }
  86890. }
  86891. #endif
  86892. /********* End of inlined file: bitmath.c *********/
  86893. /********* Start of inlined file: bitreader.c *********/
  86894. /********* Start of inlined file: juce_FlacHeader.h *********/
  86895. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  86896. // tasks..
  86897. #define VERSION "1.2.1"
  86898. #define FLAC__NO_DLL 1
  86899. #ifdef _MSC_VER
  86900. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  86901. #endif
  86902. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  86903. #define FLAC__SYS_DARWIN 1
  86904. #endif
  86905. /********* End of inlined file: juce_FlacHeader.h *********/
  86906. #if JUCE_USE_FLAC
  86907. #if HAVE_CONFIG_H
  86908. # include <config.h>
  86909. #endif
  86910. #include <stdlib.h> /* for malloc() */
  86911. #include <string.h> /* for memcpy(), memset() */
  86912. #ifdef _MSC_VER
  86913. #include <winsock.h> /* for ntohl() */
  86914. #elif defined FLAC__SYS_DARWIN
  86915. #include <machine/endian.h> /* for ntohl() */
  86916. #elif defined __MINGW32__
  86917. #include <winsock.h> /* for ntohl() */
  86918. #else
  86919. #include <netinet/in.h> /* for ntohl() */
  86920. #endif
  86921. /********* Start of inlined file: bitreader.h *********/
  86922. #ifndef FLAC__PRIVATE__BITREADER_H
  86923. #define FLAC__PRIVATE__BITREADER_H
  86924. #include <stdio.h> /* for FILE */
  86925. /********* Start of inlined file: cpu.h *********/
  86926. #ifndef FLAC__PRIVATE__CPU_H
  86927. #define FLAC__PRIVATE__CPU_H
  86928. #ifdef HAVE_CONFIG_H
  86929. #include <config.h>
  86930. #endif
  86931. typedef enum {
  86932. FLAC__CPUINFO_TYPE_IA32,
  86933. FLAC__CPUINFO_TYPE_PPC,
  86934. FLAC__CPUINFO_TYPE_UNKNOWN
  86935. } FLAC__CPUInfo_Type;
  86936. typedef struct {
  86937. FLAC__bool cpuid;
  86938. FLAC__bool bswap;
  86939. FLAC__bool cmov;
  86940. FLAC__bool mmx;
  86941. FLAC__bool fxsr;
  86942. FLAC__bool sse;
  86943. FLAC__bool sse2;
  86944. FLAC__bool sse3;
  86945. FLAC__bool ssse3;
  86946. FLAC__bool _3dnow;
  86947. FLAC__bool ext3dnow;
  86948. FLAC__bool extmmx;
  86949. } FLAC__CPUInfo_IA32;
  86950. typedef struct {
  86951. FLAC__bool altivec;
  86952. FLAC__bool ppc64;
  86953. } FLAC__CPUInfo_PPC;
  86954. typedef struct {
  86955. FLAC__bool use_asm;
  86956. FLAC__CPUInfo_Type type;
  86957. union {
  86958. FLAC__CPUInfo_IA32 ia32;
  86959. FLAC__CPUInfo_PPC ppc;
  86960. } data;
  86961. } FLAC__CPUInfo;
  86962. void FLAC__cpu_info(FLAC__CPUInfo *info);
  86963. #ifndef FLAC__NO_ASM
  86964. #ifdef FLAC__CPU_IA32
  86965. #ifdef FLAC__HAS_NASM
  86966. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  86967. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  86968. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  86969. #endif
  86970. #endif
  86971. #endif
  86972. #endif
  86973. /********* End of inlined file: cpu.h *********/
  86974. /*
  86975. * opaque structure definition
  86976. */
  86977. struct FLAC__BitReader;
  86978. typedef struct FLAC__BitReader FLAC__BitReader;
  86979. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  86980. /*
  86981. * construction, deletion, initialization, etc functions
  86982. */
  86983. FLAC__BitReader *FLAC__bitreader_new(void);
  86984. void FLAC__bitreader_delete(FLAC__BitReader *br);
  86985. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  86986. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  86987. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  86988. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  86989. /*
  86990. * CRC functions
  86991. */
  86992. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  86993. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  86994. /*
  86995. * info functions
  86996. */
  86997. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  86998. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  86999. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  87000. /*
  87001. * read functions
  87002. */
  87003. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  87004. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  87005. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  87006. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  87007. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  87008. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  87009. 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! */
  87010. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  87011. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  87012. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  87013. #ifndef FLAC__NO_ASM
  87014. # ifdef FLAC__CPU_IA32
  87015. # ifdef FLAC__HAS_NASM
  87016. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  87017. # endif
  87018. # endif
  87019. #endif
  87020. #if 0 /* UNUSED */
  87021. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  87022. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  87023. #endif
  87024. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  87025. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  87026. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  87027. #endif
  87028. /********* End of inlined file: bitreader.h *********/
  87029. /********* Start of inlined file: crc.h *********/
  87030. #ifndef FLAC__PRIVATE__CRC_H
  87031. #define FLAC__PRIVATE__CRC_H
  87032. /* 8 bit CRC generator, MSB shifted first
  87033. ** polynomial = x^8 + x^2 + x^1 + x^0
  87034. ** init = 0
  87035. */
  87036. extern FLAC__byte const FLAC__crc8_table[256];
  87037. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  87038. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  87039. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  87040. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  87041. /* 16 bit CRC generator, MSB shifted first
  87042. ** polynomial = x^16 + x^15 + x^2 + x^0
  87043. ** init = 0
  87044. */
  87045. extern unsigned FLAC__crc16_table[256];
  87046. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  87047. /* this alternate may be faster on some systems/compilers */
  87048. #if 0
  87049. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  87050. #endif
  87051. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  87052. #endif
  87053. /********* End of inlined file: crc.h *********/
  87054. /* Things should be fastest when this matches the machine word size */
  87055. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  87056. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  87057. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  87058. typedef FLAC__uint32 brword;
  87059. #define FLAC__BYTES_PER_WORD 4
  87060. #define FLAC__BITS_PER_WORD 32
  87061. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  87062. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  87063. #if WORDS_BIGENDIAN
  87064. #define SWAP_BE_WORD_TO_HOST(x) (x)
  87065. #else
  87066. #if defined (_MSC_VER) && defined (_X86_)
  87067. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  87068. #else
  87069. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  87070. #endif
  87071. #endif
  87072. /* counts the # of zero MSBs in a word */
  87073. #define COUNT_ZERO_MSBS(word) ( \
  87074. (word) <= 0xffff ? \
  87075. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  87076. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  87077. )
  87078. /* this alternate might be slightly faster on some systems/compilers: */
  87079. #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])) )
  87080. /*
  87081. * This should be at least twice as large as the largest number of words
  87082. * required to represent any 'number' (in any encoding) you are going to
  87083. * read. With FLAC this is on the order of maybe a few hundred bits.
  87084. * If the buffer is smaller than that, the decoder won't be able to read
  87085. * in a whole number that is in a variable length encoding (e.g. Rice).
  87086. * But to be practical it should be at least 1K bytes.
  87087. *
  87088. * Increase this number to decrease the number of read callbacks, at the
  87089. * expense of using more memory. Or decrease for the reverse effect,
  87090. * keeping in mind the limit from the first paragraph. The optimal size
  87091. * also depends on the CPU cache size and other factors; some twiddling
  87092. * may be necessary to squeeze out the best performance.
  87093. */
  87094. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  87095. static const unsigned char byte_to_unary_table[] = {
  87096. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  87097. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  87098. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  87099. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  87100. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87101. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87102. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87103. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  87112. };
  87113. #ifdef min
  87114. #undef min
  87115. #endif
  87116. #define min(x,y) ((x)<(y)?(x):(y))
  87117. #ifdef max
  87118. #undef max
  87119. #endif
  87120. #define max(x,y) ((x)>(y)?(x):(y))
  87121. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  87122. #ifdef _MSC_VER
  87123. #define FLAC__U64L(x) x
  87124. #else
  87125. #define FLAC__U64L(x) x##LLU
  87126. #endif
  87127. #ifndef FLaC__INLINE
  87128. #define FLaC__INLINE
  87129. #endif
  87130. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  87131. struct FLAC__BitReader {
  87132. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  87133. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  87134. brword *buffer;
  87135. unsigned capacity; /* in words */
  87136. unsigned words; /* # of completed words in buffer */
  87137. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  87138. unsigned consumed_words; /* #words ... */
  87139. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  87140. unsigned read_crc16; /* the running frame CRC */
  87141. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  87142. FLAC__BitReaderReadCallback read_callback;
  87143. void *client_data;
  87144. FLAC__CPUInfo cpu_info;
  87145. };
  87146. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  87147. {
  87148. register unsigned crc = br->read_crc16;
  87149. #if FLAC__BYTES_PER_WORD == 4
  87150. switch(br->crc16_align) {
  87151. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  87152. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  87153. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  87154. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  87155. }
  87156. #elif FLAC__BYTES_PER_WORD == 8
  87157. switch(br->crc16_align) {
  87158. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  87159. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  87160. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  87161. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  87162. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  87163. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  87164. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  87165. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  87166. }
  87167. #else
  87168. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  87169. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  87170. br->read_crc16 = crc;
  87171. #endif
  87172. br->crc16_align = 0;
  87173. }
  87174. /* would be static except it needs to be called by asm routines */
  87175. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  87176. {
  87177. unsigned start, end;
  87178. size_t bytes;
  87179. FLAC__byte *target;
  87180. /* first shift the unconsumed buffer data toward the front as much as possible */
  87181. if(br->consumed_words > 0) {
  87182. start = br->consumed_words;
  87183. end = br->words + (br->bytes? 1:0);
  87184. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  87185. br->words -= start;
  87186. br->consumed_words = 0;
  87187. }
  87188. /*
  87189. * set the target for reading, taking into account word alignment and endianness
  87190. */
  87191. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  87192. if(bytes == 0)
  87193. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  87194. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  87195. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  87196. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  87197. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  87198. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  87199. * ^^-------target, bytes=3
  87200. * on LE machines, have to byteswap the odd tail word so nothing is
  87201. * overwritten:
  87202. */
  87203. #if WORDS_BIGENDIAN
  87204. #else
  87205. if(br->bytes)
  87206. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  87207. #endif
  87208. /* now it looks like:
  87209. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  87210. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  87211. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  87212. * ^^-------target, bytes=3
  87213. */
  87214. /* read in the data; note that the callback may return a smaller number of bytes */
  87215. if(!br->read_callback(target, &bytes, br->client_data))
  87216. return false;
  87217. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  87218. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  87219. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  87220. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  87221. * now have to byteswap on LE machines:
  87222. */
  87223. #if WORDS_BIGENDIAN
  87224. #else
  87225. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  87226. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  87227. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  87228. start = br->words;
  87229. local_swap32_block_(br->buffer + start, end - start);
  87230. }
  87231. else
  87232. # endif
  87233. for(start = br->words; start < end; start++)
  87234. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  87235. #endif
  87236. /* now it looks like:
  87237. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  87238. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  87239. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  87240. * finally we'll update the reader values:
  87241. */
  87242. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  87243. br->words = end / FLAC__BYTES_PER_WORD;
  87244. br->bytes = end % FLAC__BYTES_PER_WORD;
  87245. return true;
  87246. }
  87247. /***********************************************************************
  87248. *
  87249. * Class constructor/destructor
  87250. *
  87251. ***********************************************************************/
  87252. FLAC__BitReader *FLAC__bitreader_new(void)
  87253. {
  87254. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  87255. /* calloc() implies:
  87256. memset(br, 0, sizeof(FLAC__BitReader));
  87257. br->buffer = 0;
  87258. br->capacity = 0;
  87259. br->words = br->bytes = 0;
  87260. br->consumed_words = br->consumed_bits = 0;
  87261. br->read_callback = 0;
  87262. br->client_data = 0;
  87263. */
  87264. return br;
  87265. }
  87266. void FLAC__bitreader_delete(FLAC__BitReader *br)
  87267. {
  87268. FLAC__ASSERT(0 != br);
  87269. FLAC__bitreader_free(br);
  87270. free(br);
  87271. }
  87272. /***********************************************************************
  87273. *
  87274. * Public class methods
  87275. *
  87276. ***********************************************************************/
  87277. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  87278. {
  87279. FLAC__ASSERT(0 != br);
  87280. br->words = br->bytes = 0;
  87281. br->consumed_words = br->consumed_bits = 0;
  87282. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  87283. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  87284. if(br->buffer == 0)
  87285. return false;
  87286. br->read_callback = rcb;
  87287. br->client_data = cd;
  87288. br->cpu_info = cpu;
  87289. return true;
  87290. }
  87291. void FLAC__bitreader_free(FLAC__BitReader *br)
  87292. {
  87293. FLAC__ASSERT(0 != br);
  87294. if(0 != br->buffer)
  87295. free(br->buffer);
  87296. br->buffer = 0;
  87297. br->capacity = 0;
  87298. br->words = br->bytes = 0;
  87299. br->consumed_words = br->consumed_bits = 0;
  87300. br->read_callback = 0;
  87301. br->client_data = 0;
  87302. }
  87303. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  87304. {
  87305. br->words = br->bytes = 0;
  87306. br->consumed_words = br->consumed_bits = 0;
  87307. return true;
  87308. }
  87309. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  87310. {
  87311. unsigned i, j;
  87312. if(br == 0) {
  87313. fprintf(out, "bitreader is NULL\n");
  87314. }
  87315. else {
  87316. 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);
  87317. for(i = 0; i < br->words; i++) {
  87318. fprintf(out, "%08X: ", i);
  87319. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  87320. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  87321. fprintf(out, ".");
  87322. else
  87323. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  87324. fprintf(out, "\n");
  87325. }
  87326. if(br->bytes > 0) {
  87327. fprintf(out, "%08X: ", i);
  87328. for(j = 0; j < br->bytes*8; j++)
  87329. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  87330. fprintf(out, ".");
  87331. else
  87332. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  87333. fprintf(out, "\n");
  87334. }
  87335. }
  87336. }
  87337. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  87338. {
  87339. FLAC__ASSERT(0 != br);
  87340. FLAC__ASSERT(0 != br->buffer);
  87341. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  87342. br->read_crc16 = (unsigned)seed;
  87343. br->crc16_align = br->consumed_bits;
  87344. }
  87345. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  87346. {
  87347. FLAC__ASSERT(0 != br);
  87348. FLAC__ASSERT(0 != br->buffer);
  87349. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  87350. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  87351. /* CRC any tail bytes in a partially-consumed word */
  87352. if(br->consumed_bits) {
  87353. const brword tail = br->buffer[br->consumed_words];
  87354. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  87355. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  87356. }
  87357. return br->read_crc16;
  87358. }
  87359. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  87360. {
  87361. return ((br->consumed_bits & 7) == 0);
  87362. }
  87363. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  87364. {
  87365. return 8 - (br->consumed_bits & 7);
  87366. }
  87367. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  87368. {
  87369. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  87370. }
  87371. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  87372. {
  87373. FLAC__ASSERT(0 != br);
  87374. FLAC__ASSERT(0 != br->buffer);
  87375. FLAC__ASSERT(bits <= 32);
  87376. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  87377. FLAC__ASSERT(br->consumed_words <= br->words);
  87378. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  87379. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  87380. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  87381. *val = 0;
  87382. return true;
  87383. }
  87384. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  87385. if(!bitreader_read_from_client_(br))
  87386. return false;
  87387. }
  87388. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  87389. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  87390. if(br->consumed_bits) {
  87391. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  87392. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  87393. const brword word = br->buffer[br->consumed_words];
  87394. if(bits < n) {
  87395. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  87396. br->consumed_bits += bits;
  87397. return true;
  87398. }
  87399. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  87400. bits -= n;
  87401. crc16_update_word_(br, word);
  87402. br->consumed_words++;
  87403. br->consumed_bits = 0;
  87404. 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 */
  87405. *val <<= bits;
  87406. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  87407. br->consumed_bits = bits;
  87408. }
  87409. return true;
  87410. }
  87411. else {
  87412. const brword word = br->buffer[br->consumed_words];
  87413. if(bits < FLAC__BITS_PER_WORD) {
  87414. *val = word >> (FLAC__BITS_PER_WORD-bits);
  87415. br->consumed_bits = bits;
  87416. return true;
  87417. }
  87418. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  87419. *val = word;
  87420. crc16_update_word_(br, word);
  87421. br->consumed_words++;
  87422. return true;
  87423. }
  87424. }
  87425. else {
  87426. /* in this case we're starting our read at a partial tail word;
  87427. * the reader has guaranteed that we have at least 'bits' bits
  87428. * available to read, which makes this case simpler.
  87429. */
  87430. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  87431. if(br->consumed_bits) {
  87432. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  87433. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  87434. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  87435. br->consumed_bits += bits;
  87436. return true;
  87437. }
  87438. else {
  87439. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  87440. br->consumed_bits += bits;
  87441. return true;
  87442. }
  87443. }
  87444. }
  87445. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  87446. {
  87447. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  87448. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  87449. return false;
  87450. /* sign-extend: */
  87451. *val <<= (32-bits);
  87452. *val >>= (32-bits);
  87453. return true;
  87454. }
  87455. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  87456. {
  87457. FLAC__uint32 hi, lo;
  87458. if(bits > 32) {
  87459. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  87460. return false;
  87461. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  87462. return false;
  87463. *val = hi;
  87464. *val <<= 32;
  87465. *val |= lo;
  87466. }
  87467. else {
  87468. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  87469. return false;
  87470. *val = lo;
  87471. }
  87472. return true;
  87473. }
  87474. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  87475. {
  87476. FLAC__uint32 x8, x32 = 0;
  87477. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  87478. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  87479. return false;
  87480. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  87481. return false;
  87482. x32 |= (x8 << 8);
  87483. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  87484. return false;
  87485. x32 |= (x8 << 16);
  87486. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  87487. return false;
  87488. x32 |= (x8 << 24);
  87489. *val = x32;
  87490. return true;
  87491. }
  87492. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  87493. {
  87494. /*
  87495. * OPT: a faster implementation is possible but probably not that useful
  87496. * since this is only called a couple of times in the metadata readers.
  87497. */
  87498. FLAC__ASSERT(0 != br);
  87499. FLAC__ASSERT(0 != br->buffer);
  87500. if(bits > 0) {
  87501. const unsigned n = br->consumed_bits & 7;
  87502. unsigned m;
  87503. FLAC__uint32 x;
  87504. if(n != 0) {
  87505. m = min(8-n, bits);
  87506. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  87507. return false;
  87508. bits -= m;
  87509. }
  87510. m = bits / 8;
  87511. if(m > 0) {
  87512. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  87513. return false;
  87514. bits %= 8;
  87515. }
  87516. if(bits > 0) {
  87517. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  87518. return false;
  87519. }
  87520. }
  87521. return true;
  87522. }
  87523. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  87524. {
  87525. FLAC__uint32 x;
  87526. FLAC__ASSERT(0 != br);
  87527. FLAC__ASSERT(0 != br->buffer);
  87528. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  87529. /* step 1: skip over partial head word to get word aligned */
  87530. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  87531. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87532. return false;
  87533. nvals--;
  87534. }
  87535. if(0 == nvals)
  87536. return true;
  87537. /* step 2: skip whole words in chunks */
  87538. while(nvals >= FLAC__BYTES_PER_WORD) {
  87539. if(br->consumed_words < br->words) {
  87540. br->consumed_words++;
  87541. nvals -= FLAC__BYTES_PER_WORD;
  87542. }
  87543. else if(!bitreader_read_from_client_(br))
  87544. return false;
  87545. }
  87546. /* step 3: skip any remainder from partial tail bytes */
  87547. while(nvals) {
  87548. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87549. return false;
  87550. nvals--;
  87551. }
  87552. return true;
  87553. }
  87554. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  87555. {
  87556. FLAC__uint32 x;
  87557. FLAC__ASSERT(0 != br);
  87558. FLAC__ASSERT(0 != br->buffer);
  87559. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  87560. /* step 1: read from partial head word to get word aligned */
  87561. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  87562. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87563. return false;
  87564. *val++ = (FLAC__byte)x;
  87565. nvals--;
  87566. }
  87567. if(0 == nvals)
  87568. return true;
  87569. /* step 2: read whole words in chunks */
  87570. while(nvals >= FLAC__BYTES_PER_WORD) {
  87571. if(br->consumed_words < br->words) {
  87572. const brword word = br->buffer[br->consumed_words++];
  87573. #if FLAC__BYTES_PER_WORD == 4
  87574. val[0] = (FLAC__byte)(word >> 24);
  87575. val[1] = (FLAC__byte)(word >> 16);
  87576. val[2] = (FLAC__byte)(word >> 8);
  87577. val[3] = (FLAC__byte)word;
  87578. #elif FLAC__BYTES_PER_WORD == 8
  87579. val[0] = (FLAC__byte)(word >> 56);
  87580. val[1] = (FLAC__byte)(word >> 48);
  87581. val[2] = (FLAC__byte)(word >> 40);
  87582. val[3] = (FLAC__byte)(word >> 32);
  87583. val[4] = (FLAC__byte)(word >> 24);
  87584. val[5] = (FLAC__byte)(word >> 16);
  87585. val[6] = (FLAC__byte)(word >> 8);
  87586. val[7] = (FLAC__byte)word;
  87587. #else
  87588. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  87589. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  87590. #endif
  87591. val += FLAC__BYTES_PER_WORD;
  87592. nvals -= FLAC__BYTES_PER_WORD;
  87593. }
  87594. else if(!bitreader_read_from_client_(br))
  87595. return false;
  87596. }
  87597. /* step 3: read any remainder from partial tail bytes */
  87598. while(nvals) {
  87599. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87600. return false;
  87601. *val++ = (FLAC__byte)x;
  87602. nvals--;
  87603. }
  87604. return true;
  87605. }
  87606. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  87607. #if 0 /* slow but readable version */
  87608. {
  87609. unsigned bit;
  87610. FLAC__ASSERT(0 != br);
  87611. FLAC__ASSERT(0 != br->buffer);
  87612. *val = 0;
  87613. while(1) {
  87614. if(!FLAC__bitreader_read_bit(br, &bit))
  87615. return false;
  87616. if(bit)
  87617. break;
  87618. else
  87619. *val++;
  87620. }
  87621. return true;
  87622. }
  87623. #else
  87624. {
  87625. unsigned i;
  87626. FLAC__ASSERT(0 != br);
  87627. FLAC__ASSERT(0 != br->buffer);
  87628. *val = 0;
  87629. while(1) {
  87630. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  87631. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  87632. if(b) {
  87633. i = COUNT_ZERO_MSBS(b);
  87634. *val += i;
  87635. i++;
  87636. br->consumed_bits += i;
  87637. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  87638. crc16_update_word_(br, br->buffer[br->consumed_words]);
  87639. br->consumed_words++;
  87640. br->consumed_bits = 0;
  87641. }
  87642. return true;
  87643. }
  87644. else {
  87645. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  87646. crc16_update_word_(br, br->buffer[br->consumed_words]);
  87647. br->consumed_words++;
  87648. br->consumed_bits = 0;
  87649. /* didn't find stop bit yet, have to keep going... */
  87650. }
  87651. }
  87652. /* at this point we've eaten up all the whole words; have to try
  87653. * reading through any tail bytes before calling the read callback.
  87654. * this is a repeat of the above logic adjusted for the fact we
  87655. * don't have a whole word. note though if the client is feeding
  87656. * us data a byte at a time (unlikely), br->consumed_bits may not
  87657. * be zero.
  87658. */
  87659. if(br->bytes) {
  87660. const unsigned end = br->bytes * 8;
  87661. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  87662. if(b) {
  87663. i = COUNT_ZERO_MSBS(b);
  87664. *val += i;
  87665. i++;
  87666. br->consumed_bits += i;
  87667. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  87668. return true;
  87669. }
  87670. else {
  87671. *val += end - br->consumed_bits;
  87672. br->consumed_bits += end;
  87673. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  87674. /* didn't find stop bit yet, have to keep going... */
  87675. }
  87676. }
  87677. if(!bitreader_read_from_client_(br))
  87678. return false;
  87679. }
  87680. }
  87681. #endif
  87682. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  87683. {
  87684. FLAC__uint32 lsbs = 0, msbs = 0;
  87685. unsigned uval;
  87686. FLAC__ASSERT(0 != br);
  87687. FLAC__ASSERT(0 != br->buffer);
  87688. FLAC__ASSERT(parameter <= 31);
  87689. /* read the unary MSBs and end bit */
  87690. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  87691. return false;
  87692. /* read the binary LSBs */
  87693. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  87694. return false;
  87695. /* compose the value */
  87696. uval = (msbs << parameter) | lsbs;
  87697. if(uval & 1)
  87698. *val = -((int)(uval >> 1)) - 1;
  87699. else
  87700. *val = (int)(uval >> 1);
  87701. return true;
  87702. }
  87703. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  87704. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  87705. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  87706. /* OPT: possibly faster version for use with MSVC */
  87707. #ifdef _MSC_VER
  87708. {
  87709. unsigned i;
  87710. unsigned uval = 0;
  87711. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  87712. /* try and get br->consumed_words and br->consumed_bits into register;
  87713. * must remember to flush them back to *br before calling other
  87714. * bitwriter functions that use them, and before returning */
  87715. register unsigned cwords;
  87716. register unsigned cbits;
  87717. FLAC__ASSERT(0 != br);
  87718. FLAC__ASSERT(0 != br->buffer);
  87719. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  87720. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  87721. FLAC__ASSERT(parameter < 32);
  87722. /* 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 */
  87723. if(nvals == 0)
  87724. return true;
  87725. cbits = br->consumed_bits;
  87726. cwords = br->consumed_words;
  87727. while(1) {
  87728. /* read unary part */
  87729. while(1) {
  87730. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  87731. brword b = br->buffer[cwords] << cbits;
  87732. if(b) {
  87733. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  87734. __asm {
  87735. bsr eax, b
  87736. not eax
  87737. and eax, 31
  87738. mov i, eax
  87739. }
  87740. #else
  87741. i = COUNT_ZERO_MSBS(b);
  87742. #endif
  87743. uval += i;
  87744. bits = parameter;
  87745. i++;
  87746. cbits += i;
  87747. if(cbits == FLAC__BITS_PER_WORD) {
  87748. crc16_update_word_(br, br->buffer[cwords]);
  87749. cwords++;
  87750. cbits = 0;
  87751. }
  87752. goto break1;
  87753. }
  87754. else {
  87755. uval += FLAC__BITS_PER_WORD - cbits;
  87756. crc16_update_word_(br, br->buffer[cwords]);
  87757. cwords++;
  87758. cbits = 0;
  87759. /* didn't find stop bit yet, have to keep going... */
  87760. }
  87761. }
  87762. /* at this point we've eaten up all the whole words; have to try
  87763. * reading through any tail bytes before calling the read callback.
  87764. * this is a repeat of the above logic adjusted for the fact we
  87765. * don't have a whole word. note though if the client is feeding
  87766. * us data a byte at a time (unlikely), br->consumed_bits may not
  87767. * be zero.
  87768. */
  87769. if(br->bytes) {
  87770. const unsigned end = br->bytes * 8;
  87771. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  87772. if(b) {
  87773. i = COUNT_ZERO_MSBS(b);
  87774. uval += i;
  87775. bits = parameter;
  87776. i++;
  87777. cbits += i;
  87778. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  87779. goto break1;
  87780. }
  87781. else {
  87782. uval += end - cbits;
  87783. cbits += end;
  87784. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  87785. /* didn't find stop bit yet, have to keep going... */
  87786. }
  87787. }
  87788. /* flush registers and read; bitreader_read_from_client_() does
  87789. * not touch br->consumed_bits at all but we still need to set
  87790. * it in case it fails and we have to return false.
  87791. */
  87792. br->consumed_bits = cbits;
  87793. br->consumed_words = cwords;
  87794. if(!bitreader_read_from_client_(br))
  87795. return false;
  87796. cwords = br->consumed_words;
  87797. }
  87798. break1:
  87799. /* read binary part */
  87800. FLAC__ASSERT(cwords <= br->words);
  87801. if(bits) {
  87802. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  87803. /* flush registers and read; bitreader_read_from_client_() does
  87804. * not touch br->consumed_bits at all but we still need to set
  87805. * it in case it fails and we have to return false.
  87806. */
  87807. br->consumed_bits = cbits;
  87808. br->consumed_words = cwords;
  87809. if(!bitreader_read_from_client_(br))
  87810. return false;
  87811. cwords = br->consumed_words;
  87812. }
  87813. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  87814. if(cbits) {
  87815. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  87816. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  87817. const brword word = br->buffer[cwords];
  87818. if(bits < n) {
  87819. uval <<= bits;
  87820. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  87821. cbits += bits;
  87822. goto break2;
  87823. }
  87824. uval <<= n;
  87825. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  87826. bits -= n;
  87827. crc16_update_word_(br, word);
  87828. cwords++;
  87829. cbits = 0;
  87830. 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 */
  87831. uval <<= bits;
  87832. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  87833. cbits = bits;
  87834. }
  87835. goto break2;
  87836. }
  87837. else {
  87838. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  87839. uval <<= bits;
  87840. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  87841. cbits = bits;
  87842. goto break2;
  87843. }
  87844. }
  87845. else {
  87846. /* in this case we're starting our read at a partial tail word;
  87847. * the reader has guaranteed that we have at least 'bits' bits
  87848. * available to read, which makes this case simpler.
  87849. */
  87850. uval <<= bits;
  87851. if(cbits) {
  87852. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  87853. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  87854. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  87855. cbits += bits;
  87856. goto break2;
  87857. }
  87858. else {
  87859. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  87860. cbits += bits;
  87861. goto break2;
  87862. }
  87863. }
  87864. }
  87865. break2:
  87866. /* compose the value */
  87867. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  87868. /* are we done? */
  87869. --nvals;
  87870. if(nvals == 0) {
  87871. br->consumed_bits = cbits;
  87872. br->consumed_words = cwords;
  87873. return true;
  87874. }
  87875. uval = 0;
  87876. ++vals;
  87877. }
  87878. }
  87879. #else
  87880. {
  87881. unsigned i;
  87882. unsigned uval = 0;
  87883. /* try and get br->consumed_words and br->consumed_bits into register;
  87884. * must remember to flush them back to *br before calling other
  87885. * bitwriter functions that use them, and before returning */
  87886. register unsigned cwords;
  87887. register unsigned cbits;
  87888. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  87889. FLAC__ASSERT(0 != br);
  87890. FLAC__ASSERT(0 != br->buffer);
  87891. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  87892. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  87893. FLAC__ASSERT(parameter < 32);
  87894. /* 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 */
  87895. if(nvals == 0)
  87896. return true;
  87897. cbits = br->consumed_bits;
  87898. cwords = br->consumed_words;
  87899. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  87900. while(1) {
  87901. /* read unary part */
  87902. while(1) {
  87903. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  87904. brword b = br->buffer[cwords] << cbits;
  87905. if(b) {
  87906. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  87907. asm volatile (
  87908. "bsrl %1, %0;"
  87909. "notl %0;"
  87910. "andl $31, %0;"
  87911. : "=r"(i)
  87912. : "r"(b)
  87913. );
  87914. #else
  87915. i = COUNT_ZERO_MSBS(b);
  87916. #endif
  87917. uval += i;
  87918. cbits += i;
  87919. cbits++; /* skip over stop bit */
  87920. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  87921. crc16_update_word_(br, br->buffer[cwords]);
  87922. cwords++;
  87923. cbits = 0;
  87924. }
  87925. goto break1;
  87926. }
  87927. else {
  87928. uval += FLAC__BITS_PER_WORD - cbits;
  87929. crc16_update_word_(br, br->buffer[cwords]);
  87930. cwords++;
  87931. cbits = 0;
  87932. /* didn't find stop bit yet, have to keep going... */
  87933. }
  87934. }
  87935. /* at this point we've eaten up all the whole words; have to try
  87936. * reading through any tail bytes before calling the read callback.
  87937. * this is a repeat of the above logic adjusted for the fact we
  87938. * don't have a whole word. note though if the client is feeding
  87939. * us data a byte at a time (unlikely), br->consumed_bits may not
  87940. * be zero.
  87941. */
  87942. if(br->bytes) {
  87943. const unsigned end = br->bytes * 8;
  87944. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  87945. if(b) {
  87946. i = COUNT_ZERO_MSBS(b);
  87947. uval += i;
  87948. cbits += i;
  87949. cbits++; /* skip over stop bit */
  87950. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  87951. goto break1;
  87952. }
  87953. else {
  87954. uval += end - cbits;
  87955. cbits += end;
  87956. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  87957. /* didn't find stop bit yet, have to keep going... */
  87958. }
  87959. }
  87960. /* flush registers and read; bitreader_read_from_client_() does
  87961. * not touch br->consumed_bits at all but we still need to set
  87962. * it in case it fails and we have to return false.
  87963. */
  87964. br->consumed_bits = cbits;
  87965. br->consumed_words = cwords;
  87966. if(!bitreader_read_from_client_(br))
  87967. return false;
  87968. cwords = br->consumed_words;
  87969. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  87970. /* + uval to offset our count by the # of unary bits already
  87971. * consumed before the read, because we will add these back
  87972. * in all at once at break1
  87973. */
  87974. }
  87975. break1:
  87976. ucbits -= uval;
  87977. ucbits--; /* account for stop bit */
  87978. /* read binary part */
  87979. FLAC__ASSERT(cwords <= br->words);
  87980. if(parameter) {
  87981. while(ucbits < parameter) {
  87982. /* flush registers and read; bitreader_read_from_client_() does
  87983. * not touch br->consumed_bits at all but we still need to set
  87984. * it in case it fails and we have to return false.
  87985. */
  87986. br->consumed_bits = cbits;
  87987. br->consumed_words = cwords;
  87988. if(!bitreader_read_from_client_(br))
  87989. return false;
  87990. cwords = br->consumed_words;
  87991. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  87992. }
  87993. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  87994. if(cbits) {
  87995. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  87996. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  87997. const brword word = br->buffer[cwords];
  87998. if(parameter < n) {
  87999. uval <<= parameter;
  88000. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  88001. cbits += parameter;
  88002. }
  88003. else {
  88004. uval <<= n;
  88005. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  88006. crc16_update_word_(br, word);
  88007. cwords++;
  88008. cbits = parameter - n;
  88009. 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 */
  88010. uval <<= cbits;
  88011. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  88012. }
  88013. }
  88014. }
  88015. else {
  88016. cbits = parameter;
  88017. uval <<= parameter;
  88018. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  88019. }
  88020. }
  88021. else {
  88022. /* in this case we're starting our read at a partial tail word;
  88023. * the reader has guaranteed that we have at least 'parameter'
  88024. * bits available to read, which makes this case simpler.
  88025. */
  88026. uval <<= parameter;
  88027. if(cbits) {
  88028. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88029. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  88030. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  88031. cbits += parameter;
  88032. }
  88033. else {
  88034. cbits = parameter;
  88035. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  88036. }
  88037. }
  88038. }
  88039. ucbits -= parameter;
  88040. /* compose the value */
  88041. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  88042. /* are we done? */
  88043. --nvals;
  88044. if(nvals == 0) {
  88045. br->consumed_bits = cbits;
  88046. br->consumed_words = cwords;
  88047. return true;
  88048. }
  88049. uval = 0;
  88050. ++vals;
  88051. }
  88052. }
  88053. #endif
  88054. #if 0 /* UNUSED */
  88055. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  88056. {
  88057. FLAC__uint32 lsbs = 0, msbs = 0;
  88058. unsigned bit, uval, k;
  88059. FLAC__ASSERT(0 != br);
  88060. FLAC__ASSERT(0 != br->buffer);
  88061. k = FLAC__bitmath_ilog2(parameter);
  88062. /* read the unary MSBs and end bit */
  88063. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  88064. return false;
  88065. /* read the binary LSBs */
  88066. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  88067. return false;
  88068. if(parameter == 1u<<k) {
  88069. /* compose the value */
  88070. uval = (msbs << k) | lsbs;
  88071. }
  88072. else {
  88073. unsigned d = (1 << (k+1)) - parameter;
  88074. if(lsbs >= d) {
  88075. if(!FLAC__bitreader_read_bit(br, &bit))
  88076. return false;
  88077. lsbs <<= 1;
  88078. lsbs |= bit;
  88079. lsbs -= d;
  88080. }
  88081. /* compose the value */
  88082. uval = msbs * parameter + lsbs;
  88083. }
  88084. /* unfold unsigned to signed */
  88085. if(uval & 1)
  88086. *val = -((int)(uval >> 1)) - 1;
  88087. else
  88088. *val = (int)(uval >> 1);
  88089. return true;
  88090. }
  88091. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  88092. {
  88093. FLAC__uint32 lsbs, msbs = 0;
  88094. unsigned bit, k;
  88095. FLAC__ASSERT(0 != br);
  88096. FLAC__ASSERT(0 != br->buffer);
  88097. k = FLAC__bitmath_ilog2(parameter);
  88098. /* read the unary MSBs and end bit */
  88099. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  88100. return false;
  88101. /* read the binary LSBs */
  88102. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  88103. return false;
  88104. if(parameter == 1u<<k) {
  88105. /* compose the value */
  88106. *val = (msbs << k) | lsbs;
  88107. }
  88108. else {
  88109. unsigned d = (1 << (k+1)) - parameter;
  88110. if(lsbs >= d) {
  88111. if(!FLAC__bitreader_read_bit(br, &bit))
  88112. return false;
  88113. lsbs <<= 1;
  88114. lsbs |= bit;
  88115. lsbs -= d;
  88116. }
  88117. /* compose the value */
  88118. *val = msbs * parameter + lsbs;
  88119. }
  88120. return true;
  88121. }
  88122. #endif /* UNUSED */
  88123. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  88124. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  88125. {
  88126. FLAC__uint32 v = 0;
  88127. FLAC__uint32 x;
  88128. unsigned i;
  88129. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88130. return false;
  88131. if(raw)
  88132. raw[(*rawlen)++] = (FLAC__byte)x;
  88133. if(!(x & 0x80)) { /* 0xxxxxxx */
  88134. v = x;
  88135. i = 0;
  88136. }
  88137. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  88138. v = x & 0x1F;
  88139. i = 1;
  88140. }
  88141. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  88142. v = x & 0x0F;
  88143. i = 2;
  88144. }
  88145. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  88146. v = x & 0x07;
  88147. i = 3;
  88148. }
  88149. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  88150. v = x & 0x03;
  88151. i = 4;
  88152. }
  88153. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  88154. v = x & 0x01;
  88155. i = 5;
  88156. }
  88157. else {
  88158. *val = 0xffffffff;
  88159. return true;
  88160. }
  88161. for( ; i; i--) {
  88162. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88163. return false;
  88164. if(raw)
  88165. raw[(*rawlen)++] = (FLAC__byte)x;
  88166. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  88167. *val = 0xffffffff;
  88168. return true;
  88169. }
  88170. v <<= 6;
  88171. v |= (x & 0x3F);
  88172. }
  88173. *val = v;
  88174. return true;
  88175. }
  88176. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  88177. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  88178. {
  88179. FLAC__uint64 v = 0;
  88180. FLAC__uint32 x;
  88181. unsigned i;
  88182. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88183. return false;
  88184. if(raw)
  88185. raw[(*rawlen)++] = (FLAC__byte)x;
  88186. if(!(x & 0x80)) { /* 0xxxxxxx */
  88187. v = x;
  88188. i = 0;
  88189. }
  88190. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  88191. v = x & 0x1F;
  88192. i = 1;
  88193. }
  88194. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  88195. v = x & 0x0F;
  88196. i = 2;
  88197. }
  88198. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  88199. v = x & 0x07;
  88200. i = 3;
  88201. }
  88202. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  88203. v = x & 0x03;
  88204. i = 4;
  88205. }
  88206. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  88207. v = x & 0x01;
  88208. i = 5;
  88209. }
  88210. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  88211. v = 0;
  88212. i = 6;
  88213. }
  88214. else {
  88215. *val = FLAC__U64L(0xffffffffffffffff);
  88216. return true;
  88217. }
  88218. for( ; i; i--) {
  88219. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88220. return false;
  88221. if(raw)
  88222. raw[(*rawlen)++] = (FLAC__byte)x;
  88223. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  88224. *val = FLAC__U64L(0xffffffffffffffff);
  88225. return true;
  88226. }
  88227. v <<= 6;
  88228. v |= (x & 0x3F);
  88229. }
  88230. *val = v;
  88231. return true;
  88232. }
  88233. #endif
  88234. /********* End of inlined file: bitreader.c *********/
  88235. /********* Start of inlined file: bitwriter.c *********/
  88236. /********* Start of inlined file: juce_FlacHeader.h *********/
  88237. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  88238. // tasks..
  88239. #define VERSION "1.2.1"
  88240. #define FLAC__NO_DLL 1
  88241. #ifdef _MSC_VER
  88242. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  88243. #endif
  88244. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  88245. #define FLAC__SYS_DARWIN 1
  88246. #endif
  88247. /********* End of inlined file: juce_FlacHeader.h *********/
  88248. #if JUCE_USE_FLAC
  88249. #if HAVE_CONFIG_H
  88250. # include <config.h>
  88251. #endif
  88252. #include <stdlib.h> /* for malloc() */
  88253. #include <string.h> /* for memcpy(), memset() */
  88254. #ifdef _MSC_VER
  88255. #include <winsock.h> /* for ntohl() */
  88256. #elif defined FLAC__SYS_DARWIN
  88257. #include <machine/endian.h> /* for ntohl() */
  88258. #elif defined __MINGW32__
  88259. #include <winsock.h> /* for ntohl() */
  88260. #else
  88261. #include <netinet/in.h> /* for ntohl() */
  88262. #endif
  88263. #if 0 /* UNUSED */
  88264. #endif
  88265. /********* Start of inlined file: bitwriter.h *********/
  88266. #ifndef FLAC__PRIVATE__BITWRITER_H
  88267. #define FLAC__PRIVATE__BITWRITER_H
  88268. #include <stdio.h> /* for FILE */
  88269. /*
  88270. * opaque structure definition
  88271. */
  88272. struct FLAC__BitWriter;
  88273. typedef struct FLAC__BitWriter FLAC__BitWriter;
  88274. /*
  88275. * construction, deletion, initialization, etc functions
  88276. */
  88277. FLAC__BitWriter *FLAC__bitwriter_new(void);
  88278. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  88279. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  88280. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  88281. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  88282. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  88283. /*
  88284. * CRC functions
  88285. *
  88286. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  88287. */
  88288. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  88289. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  88290. /*
  88291. * info functions
  88292. */
  88293. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  88294. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  88295. /*
  88296. * direct buffer access
  88297. *
  88298. * there may be no calls on the bitwriter between get and release.
  88299. * the bitwriter continues to own the returned buffer.
  88300. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  88301. */
  88302. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  88303. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  88304. /*
  88305. * write functions
  88306. */
  88307. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  88308. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  88309. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  88310. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  88311. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  88312. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  88313. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  88314. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  88315. #if 0 /* UNUSED */
  88316. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  88317. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  88318. #endif
  88319. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  88320. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  88321. #if 0 /* UNUSED */
  88322. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  88323. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  88324. #endif
  88325. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  88326. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  88327. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  88328. #endif
  88329. /********* End of inlined file: bitwriter.h *********/
  88330. /********* Start of inlined file: alloc.h *********/
  88331. #ifndef FLAC__SHARE__ALLOC_H
  88332. #define FLAC__SHARE__ALLOC_H
  88333. #if HAVE_CONFIG_H
  88334. # include <config.h>
  88335. #endif
  88336. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  88337. * before #including this file, otherwise SIZE_MAX might not be defined
  88338. */
  88339. #include <limits.h> /* for SIZE_MAX */
  88340. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  88341. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  88342. #endif
  88343. #include <stdlib.h> /* for size_t, malloc(), etc */
  88344. #ifndef SIZE_MAX
  88345. # ifndef SIZE_T_MAX
  88346. # ifdef _MSC_VER
  88347. # define SIZE_T_MAX UINT_MAX
  88348. # else
  88349. # error
  88350. # endif
  88351. # endif
  88352. # define SIZE_MAX SIZE_T_MAX
  88353. #endif
  88354. #ifndef FLaC__INLINE
  88355. #define FLaC__INLINE
  88356. #endif
  88357. /* avoid malloc()ing 0 bytes, see:
  88358. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  88359. */
  88360. static FLaC__INLINE void *safe_malloc_(size_t size)
  88361. {
  88362. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  88363. if(!size)
  88364. size++;
  88365. return malloc(size);
  88366. }
  88367. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  88368. {
  88369. if(!nmemb || !size)
  88370. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  88371. return calloc(nmemb, size);
  88372. }
  88373. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  88374. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  88375. {
  88376. size2 += size1;
  88377. if(size2 < size1)
  88378. return 0;
  88379. return safe_malloc_(size2);
  88380. }
  88381. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  88382. {
  88383. size2 += size1;
  88384. if(size2 < size1)
  88385. return 0;
  88386. size3 += size2;
  88387. if(size3 < size2)
  88388. return 0;
  88389. return safe_malloc_(size3);
  88390. }
  88391. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  88392. {
  88393. size2 += size1;
  88394. if(size2 < size1)
  88395. return 0;
  88396. size3 += size2;
  88397. if(size3 < size2)
  88398. return 0;
  88399. size4 += size3;
  88400. if(size4 < size3)
  88401. return 0;
  88402. return safe_malloc_(size4);
  88403. }
  88404. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  88405. #if 0
  88406. needs support for cases where sizeof(size_t) != 4
  88407. {
  88408. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  88409. if(sizeof(size_t) == 4) {
  88410. if ((double)size1 * (double)size2 < 4294967296.0)
  88411. return malloc(size1*size2);
  88412. }
  88413. return 0;
  88414. }
  88415. #else
  88416. /* better? */
  88417. {
  88418. if(!size1 || !size2)
  88419. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  88420. if(size1 > SIZE_MAX / size2)
  88421. return 0;
  88422. return malloc(size1*size2);
  88423. }
  88424. #endif
  88425. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  88426. {
  88427. if(!size1 || !size2 || !size3)
  88428. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  88429. if(size1 > SIZE_MAX / size2)
  88430. return 0;
  88431. size1 *= size2;
  88432. if(size1 > SIZE_MAX / size3)
  88433. return 0;
  88434. return malloc(size1*size3);
  88435. }
  88436. /* size1*size2 + size3 */
  88437. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  88438. {
  88439. if(!size1 || !size2)
  88440. return safe_malloc_(size3);
  88441. if(size1 > SIZE_MAX / size2)
  88442. return 0;
  88443. return safe_malloc_add_2op_(size1*size2, size3);
  88444. }
  88445. /* size1 * (size2 + size3) */
  88446. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  88447. {
  88448. if(!size1 || (!size2 && !size3))
  88449. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  88450. size2 += size3;
  88451. if(size2 < size3)
  88452. return 0;
  88453. return safe_malloc_mul_2op_(size1, size2);
  88454. }
  88455. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  88456. {
  88457. size2 += size1;
  88458. if(size2 < size1)
  88459. return 0;
  88460. return realloc(ptr, size2);
  88461. }
  88462. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  88463. {
  88464. size2 += size1;
  88465. if(size2 < size1)
  88466. return 0;
  88467. size3 += size2;
  88468. if(size3 < size2)
  88469. return 0;
  88470. return realloc(ptr, size3);
  88471. }
  88472. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  88473. {
  88474. size2 += size1;
  88475. if(size2 < size1)
  88476. return 0;
  88477. size3 += size2;
  88478. if(size3 < size2)
  88479. return 0;
  88480. size4 += size3;
  88481. if(size4 < size3)
  88482. return 0;
  88483. return realloc(ptr, size4);
  88484. }
  88485. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  88486. {
  88487. if(!size1 || !size2)
  88488. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  88489. if(size1 > SIZE_MAX / size2)
  88490. return 0;
  88491. return realloc(ptr, size1*size2);
  88492. }
  88493. /* size1 * (size2 + size3) */
  88494. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  88495. {
  88496. if(!size1 || (!size2 && !size3))
  88497. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  88498. size2 += size3;
  88499. if(size2 < size3)
  88500. return 0;
  88501. return safe_realloc_mul_2op_(ptr, size1, size2);
  88502. }
  88503. #endif
  88504. /********* End of inlined file: alloc.h *********/
  88505. /* Things should be fastest when this matches the machine word size */
  88506. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  88507. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  88508. typedef FLAC__uint32 bwword;
  88509. #define FLAC__BYTES_PER_WORD 4
  88510. #define FLAC__BITS_PER_WORD 32
  88511. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  88512. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  88513. #if WORDS_BIGENDIAN
  88514. #define SWAP_BE_WORD_TO_HOST(x) (x)
  88515. #else
  88516. #ifdef _MSC_VER
  88517. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  88518. #else
  88519. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  88520. #endif
  88521. #endif
  88522. /*
  88523. * The default capacity here doesn't matter too much. The buffer always grows
  88524. * to hold whatever is written to it. Usually the encoder will stop adding at
  88525. * a frame or metadata block, then write that out and clear the buffer for the
  88526. * next one.
  88527. */
  88528. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  88529. /* When growing, increment 4K at a time */
  88530. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  88531. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  88532. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  88533. #ifdef min
  88534. #undef min
  88535. #endif
  88536. #define min(x,y) ((x)<(y)?(x):(y))
  88537. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  88538. #ifdef _MSC_VER
  88539. #define FLAC__U64L(x) x
  88540. #else
  88541. #define FLAC__U64L(x) x##LLU
  88542. #endif
  88543. #ifndef FLaC__INLINE
  88544. #define FLaC__INLINE
  88545. #endif
  88546. struct FLAC__BitWriter {
  88547. bwword *buffer;
  88548. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  88549. unsigned capacity; /* capacity of buffer in words */
  88550. unsigned words; /* # of complete words in buffer */
  88551. unsigned bits; /* # of used bits in accum */
  88552. };
  88553. /* * WATCHOUT: The current implementation only grows the buffer. */
  88554. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  88555. {
  88556. unsigned new_capacity;
  88557. bwword *new_buffer;
  88558. FLAC__ASSERT(0 != bw);
  88559. FLAC__ASSERT(0 != bw->buffer);
  88560. /* calculate total words needed to store 'bits_to_add' additional bits */
  88561. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  88562. /* it's possible (due to pessimism in the growth estimation that
  88563. * leads to this call) that we don't actually need to grow
  88564. */
  88565. if(bw->capacity >= new_capacity)
  88566. return true;
  88567. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  88568. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  88569. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  88570. /* make sure we got everything right */
  88571. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  88572. FLAC__ASSERT(new_capacity > bw->capacity);
  88573. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  88574. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  88575. if(new_buffer == 0)
  88576. return false;
  88577. bw->buffer = new_buffer;
  88578. bw->capacity = new_capacity;
  88579. return true;
  88580. }
  88581. /***********************************************************************
  88582. *
  88583. * Class constructor/destructor
  88584. *
  88585. ***********************************************************************/
  88586. FLAC__BitWriter *FLAC__bitwriter_new(void)
  88587. {
  88588. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  88589. /* note that calloc() sets all members to 0 for us */
  88590. return bw;
  88591. }
  88592. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  88593. {
  88594. FLAC__ASSERT(0 != bw);
  88595. FLAC__bitwriter_free(bw);
  88596. free(bw);
  88597. }
  88598. /***********************************************************************
  88599. *
  88600. * Public class methods
  88601. *
  88602. ***********************************************************************/
  88603. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  88604. {
  88605. FLAC__ASSERT(0 != bw);
  88606. bw->words = bw->bits = 0;
  88607. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  88608. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  88609. if(bw->buffer == 0)
  88610. return false;
  88611. return true;
  88612. }
  88613. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  88614. {
  88615. FLAC__ASSERT(0 != bw);
  88616. if(0 != bw->buffer)
  88617. free(bw->buffer);
  88618. bw->buffer = 0;
  88619. bw->capacity = 0;
  88620. bw->words = bw->bits = 0;
  88621. }
  88622. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  88623. {
  88624. bw->words = bw->bits = 0;
  88625. }
  88626. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  88627. {
  88628. unsigned i, j;
  88629. if(bw == 0) {
  88630. fprintf(out, "bitwriter is NULL\n");
  88631. }
  88632. else {
  88633. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  88634. for(i = 0; i < bw->words; i++) {
  88635. fprintf(out, "%08X: ", i);
  88636. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  88637. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  88638. fprintf(out, "\n");
  88639. }
  88640. if(bw->bits > 0) {
  88641. fprintf(out, "%08X: ", i);
  88642. for(j = 0; j < bw->bits; j++)
  88643. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  88644. fprintf(out, "\n");
  88645. }
  88646. }
  88647. }
  88648. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  88649. {
  88650. const FLAC__byte *buffer;
  88651. size_t bytes;
  88652. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  88653. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  88654. return false;
  88655. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  88656. FLAC__bitwriter_release_buffer(bw);
  88657. return true;
  88658. }
  88659. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  88660. {
  88661. const FLAC__byte *buffer;
  88662. size_t bytes;
  88663. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  88664. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  88665. return false;
  88666. *crc = FLAC__crc8(buffer, bytes);
  88667. FLAC__bitwriter_release_buffer(bw);
  88668. return true;
  88669. }
  88670. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  88671. {
  88672. return ((bw->bits & 7) == 0);
  88673. }
  88674. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  88675. {
  88676. return FLAC__TOTAL_BITS(bw);
  88677. }
  88678. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  88679. {
  88680. FLAC__ASSERT((bw->bits & 7) == 0);
  88681. /* double protection */
  88682. if(bw->bits & 7)
  88683. return false;
  88684. /* if we have bits in the accumulator we have to flush those to the buffer first */
  88685. if(bw->bits) {
  88686. FLAC__ASSERT(bw->words <= bw->capacity);
  88687. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  88688. return false;
  88689. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  88690. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  88691. }
  88692. /* now we can just return what we have */
  88693. *buffer = (FLAC__byte*)bw->buffer;
  88694. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  88695. return true;
  88696. }
  88697. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  88698. {
  88699. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  88700. * get-mode' flag could be added everywhere and then cleared here
  88701. */
  88702. (void)bw;
  88703. }
  88704. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  88705. {
  88706. unsigned n;
  88707. FLAC__ASSERT(0 != bw);
  88708. FLAC__ASSERT(0 != bw->buffer);
  88709. if(bits == 0)
  88710. return true;
  88711. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  88712. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  88713. return false;
  88714. /* first part gets to word alignment */
  88715. if(bw->bits) {
  88716. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  88717. bw->accum <<= n;
  88718. bits -= n;
  88719. bw->bits += n;
  88720. if(bw->bits == FLAC__BITS_PER_WORD) {
  88721. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88722. bw->bits = 0;
  88723. }
  88724. else
  88725. return true;
  88726. }
  88727. /* do whole words */
  88728. while(bits >= FLAC__BITS_PER_WORD) {
  88729. bw->buffer[bw->words++] = 0;
  88730. bits -= FLAC__BITS_PER_WORD;
  88731. }
  88732. /* do any leftovers */
  88733. if(bits > 0) {
  88734. bw->accum = 0;
  88735. bw->bits = bits;
  88736. }
  88737. return true;
  88738. }
  88739. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  88740. {
  88741. register unsigned left;
  88742. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88743. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88744. FLAC__ASSERT(0 != bw);
  88745. FLAC__ASSERT(0 != bw->buffer);
  88746. FLAC__ASSERT(bits <= 32);
  88747. if(bits == 0)
  88748. return true;
  88749. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  88750. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  88751. return false;
  88752. left = FLAC__BITS_PER_WORD - bw->bits;
  88753. if(bits < left) {
  88754. bw->accum <<= bits;
  88755. bw->accum |= val;
  88756. bw->bits += bits;
  88757. }
  88758. 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 */
  88759. bw->accum <<= left;
  88760. bw->accum |= val >> (bw->bits = bits - left);
  88761. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88762. bw->accum = val;
  88763. }
  88764. else {
  88765. bw->accum = val;
  88766. bw->bits = 0;
  88767. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  88768. }
  88769. return true;
  88770. }
  88771. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  88772. {
  88773. /* zero-out unused bits */
  88774. if(bits < 32)
  88775. val &= (~(0xffffffff << bits));
  88776. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  88777. }
  88778. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  88779. {
  88780. /* this could be a little faster but it's not used for much */
  88781. if(bits > 32) {
  88782. return
  88783. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  88784. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  88785. }
  88786. else
  88787. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  88788. }
  88789. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  88790. {
  88791. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  88792. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  88793. return false;
  88794. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  88795. return false;
  88796. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  88797. return false;
  88798. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  88799. return false;
  88800. return true;
  88801. }
  88802. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  88803. {
  88804. unsigned i;
  88805. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  88806. for(i = 0; i < nvals; i++) {
  88807. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  88808. return false;
  88809. }
  88810. return true;
  88811. }
  88812. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  88813. {
  88814. if(val < 32)
  88815. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  88816. else
  88817. return
  88818. FLAC__bitwriter_write_zeroes(bw, val) &&
  88819. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  88820. }
  88821. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  88822. {
  88823. FLAC__uint32 uval;
  88824. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  88825. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  88826. uval = (val<<1) ^ (val>>31);
  88827. return 1 + parameter + (uval >> parameter);
  88828. }
  88829. #if 0 /* UNUSED */
  88830. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  88831. {
  88832. unsigned bits, msbs, uval;
  88833. unsigned k;
  88834. FLAC__ASSERT(parameter > 0);
  88835. /* fold signed to unsigned */
  88836. if(val < 0)
  88837. uval = (unsigned)(((-(++val)) << 1) + 1);
  88838. else
  88839. uval = (unsigned)(val << 1);
  88840. k = FLAC__bitmath_ilog2(parameter);
  88841. if(parameter == 1u<<k) {
  88842. FLAC__ASSERT(k <= 30);
  88843. msbs = uval >> k;
  88844. bits = 1 + k + msbs;
  88845. }
  88846. else {
  88847. unsigned q, r, d;
  88848. d = (1 << (k+1)) - parameter;
  88849. q = uval / parameter;
  88850. r = uval - (q * parameter);
  88851. bits = 1 + q + k;
  88852. if(r >= d)
  88853. bits++;
  88854. }
  88855. return bits;
  88856. }
  88857. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  88858. {
  88859. unsigned bits, msbs;
  88860. unsigned k;
  88861. FLAC__ASSERT(parameter > 0);
  88862. k = FLAC__bitmath_ilog2(parameter);
  88863. if(parameter == 1u<<k) {
  88864. FLAC__ASSERT(k <= 30);
  88865. msbs = uval >> k;
  88866. bits = 1 + k + msbs;
  88867. }
  88868. else {
  88869. unsigned q, r, d;
  88870. d = (1 << (k+1)) - parameter;
  88871. q = uval / parameter;
  88872. r = uval - (q * parameter);
  88873. bits = 1 + q + k;
  88874. if(r >= d)
  88875. bits++;
  88876. }
  88877. return bits;
  88878. }
  88879. #endif /* UNUSED */
  88880. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  88881. {
  88882. unsigned total_bits, interesting_bits, msbs;
  88883. FLAC__uint32 uval, pattern;
  88884. FLAC__ASSERT(0 != bw);
  88885. FLAC__ASSERT(0 != bw->buffer);
  88886. FLAC__ASSERT(parameter < 8*sizeof(uval));
  88887. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  88888. uval = (val<<1) ^ (val>>31);
  88889. msbs = uval >> parameter;
  88890. interesting_bits = 1 + parameter;
  88891. total_bits = interesting_bits + msbs;
  88892. pattern = 1 << parameter; /* the unary end bit */
  88893. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  88894. if(total_bits <= 32)
  88895. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  88896. else
  88897. return
  88898. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  88899. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  88900. }
  88901. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  88902. {
  88903. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  88904. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  88905. FLAC__uint32 uval;
  88906. unsigned left;
  88907. const unsigned lsbits = 1 + parameter;
  88908. unsigned msbits;
  88909. FLAC__ASSERT(0 != bw);
  88910. FLAC__ASSERT(0 != bw->buffer);
  88911. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  88912. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88913. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88914. while(nvals) {
  88915. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  88916. uval = (*vals<<1) ^ (*vals>>31);
  88917. msbits = uval >> parameter;
  88918. #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) */
  88919. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  88920. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  88921. bw->bits = bw->bits + msbits + lsbits;
  88922. uval |= mask1; /* set stop bit */
  88923. uval &= mask2; /* mask off unused top bits */
  88924. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  88925. bw->accum <<= msbits;
  88926. bw->accum <<= lsbits;
  88927. bw->accum |= uval;
  88928. if(bw->bits == FLAC__BITS_PER_WORD) {
  88929. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88930. bw->bits = 0;
  88931. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  88932. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  88933. FLAC__ASSERT(bw->capacity == bw->words);
  88934. return false;
  88935. }
  88936. }
  88937. }
  88938. else {
  88939. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  88940. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  88941. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  88942. bw->bits = bw->bits + msbits + lsbits;
  88943. uval |= mask1; /* set stop bit */
  88944. uval &= mask2; /* mask off unused top bits */
  88945. bw->accum <<= msbits + lsbits;
  88946. bw->accum |= uval;
  88947. }
  88948. else {
  88949. #endif
  88950. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  88951. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  88952. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  88953. return false;
  88954. if(msbits) {
  88955. /* first part gets to word alignment */
  88956. if(bw->bits) {
  88957. left = FLAC__BITS_PER_WORD - bw->bits;
  88958. if(msbits < left) {
  88959. bw->accum <<= msbits;
  88960. bw->bits += msbits;
  88961. goto break1;
  88962. }
  88963. else {
  88964. bw->accum <<= left;
  88965. msbits -= left;
  88966. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88967. bw->bits = 0;
  88968. }
  88969. }
  88970. /* do whole words */
  88971. while(msbits >= FLAC__BITS_PER_WORD) {
  88972. bw->buffer[bw->words++] = 0;
  88973. msbits -= FLAC__BITS_PER_WORD;
  88974. }
  88975. /* do any leftovers */
  88976. if(msbits > 0) {
  88977. bw->accum = 0;
  88978. bw->bits = msbits;
  88979. }
  88980. }
  88981. break1:
  88982. uval |= mask1; /* set stop bit */
  88983. uval &= mask2; /* mask off unused top bits */
  88984. left = FLAC__BITS_PER_WORD - bw->bits;
  88985. if(lsbits < left) {
  88986. bw->accum <<= lsbits;
  88987. bw->accum |= uval;
  88988. bw->bits += lsbits;
  88989. }
  88990. else {
  88991. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  88992. * be > lsbits (because of previous assertions) so it would have
  88993. * triggered the (lsbits<left) case above.
  88994. */
  88995. FLAC__ASSERT(bw->bits);
  88996. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  88997. bw->accum <<= left;
  88998. bw->accum |= uval >> (bw->bits = lsbits - left);
  88999. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  89000. bw->accum = uval;
  89001. }
  89002. #if 1
  89003. }
  89004. #endif
  89005. vals++;
  89006. nvals--;
  89007. }
  89008. return true;
  89009. }
  89010. #if 0 /* UNUSED */
  89011. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  89012. {
  89013. unsigned total_bits, msbs, uval;
  89014. unsigned k;
  89015. FLAC__ASSERT(0 != bw);
  89016. FLAC__ASSERT(0 != bw->buffer);
  89017. FLAC__ASSERT(parameter > 0);
  89018. /* fold signed to unsigned */
  89019. if(val < 0)
  89020. uval = (unsigned)(((-(++val)) << 1) + 1);
  89021. else
  89022. uval = (unsigned)(val << 1);
  89023. k = FLAC__bitmath_ilog2(parameter);
  89024. if(parameter == 1u<<k) {
  89025. unsigned pattern;
  89026. FLAC__ASSERT(k <= 30);
  89027. msbs = uval >> k;
  89028. total_bits = 1 + k + msbs;
  89029. pattern = 1 << k; /* the unary end bit */
  89030. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  89031. if(total_bits <= 32) {
  89032. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  89033. return false;
  89034. }
  89035. else {
  89036. /* write the unary MSBs */
  89037. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  89038. return false;
  89039. /* write the unary end bit and binary LSBs */
  89040. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  89041. return false;
  89042. }
  89043. }
  89044. else {
  89045. unsigned q, r, d;
  89046. d = (1 << (k+1)) - parameter;
  89047. q = uval / parameter;
  89048. r = uval - (q * parameter);
  89049. /* write the unary MSBs */
  89050. if(!FLAC__bitwriter_write_zeroes(bw, q))
  89051. return false;
  89052. /* write the unary end bit */
  89053. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  89054. return false;
  89055. /* write the binary LSBs */
  89056. if(r >= d) {
  89057. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  89058. return false;
  89059. }
  89060. else {
  89061. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  89062. return false;
  89063. }
  89064. }
  89065. return true;
  89066. }
  89067. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  89068. {
  89069. unsigned total_bits, msbs;
  89070. unsigned k;
  89071. FLAC__ASSERT(0 != bw);
  89072. FLAC__ASSERT(0 != bw->buffer);
  89073. FLAC__ASSERT(parameter > 0);
  89074. k = FLAC__bitmath_ilog2(parameter);
  89075. if(parameter == 1u<<k) {
  89076. unsigned pattern;
  89077. FLAC__ASSERT(k <= 30);
  89078. msbs = uval >> k;
  89079. total_bits = 1 + k + msbs;
  89080. pattern = 1 << k; /* the unary end bit */
  89081. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  89082. if(total_bits <= 32) {
  89083. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  89084. return false;
  89085. }
  89086. else {
  89087. /* write the unary MSBs */
  89088. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  89089. return false;
  89090. /* write the unary end bit and binary LSBs */
  89091. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  89092. return false;
  89093. }
  89094. }
  89095. else {
  89096. unsigned q, r, d;
  89097. d = (1 << (k+1)) - parameter;
  89098. q = uval / parameter;
  89099. r = uval - (q * parameter);
  89100. /* write the unary MSBs */
  89101. if(!FLAC__bitwriter_write_zeroes(bw, q))
  89102. return false;
  89103. /* write the unary end bit */
  89104. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  89105. return false;
  89106. /* write the binary LSBs */
  89107. if(r >= d) {
  89108. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  89109. return false;
  89110. }
  89111. else {
  89112. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  89113. return false;
  89114. }
  89115. }
  89116. return true;
  89117. }
  89118. #endif /* UNUSED */
  89119. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  89120. {
  89121. FLAC__bool ok = 1;
  89122. FLAC__ASSERT(0 != bw);
  89123. FLAC__ASSERT(0 != bw->buffer);
  89124. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  89125. if(val < 0x80) {
  89126. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  89127. }
  89128. else if(val < 0x800) {
  89129. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  89130. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89131. }
  89132. else if(val < 0x10000) {
  89133. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  89134. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  89135. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89136. }
  89137. else if(val < 0x200000) {
  89138. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  89139. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  89140. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  89141. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89142. }
  89143. else if(val < 0x4000000) {
  89144. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  89145. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  89146. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  89147. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  89148. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89149. }
  89150. else {
  89151. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  89152. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  89153. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  89154. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  89155. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  89156. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89157. }
  89158. return ok;
  89159. }
  89160. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  89161. {
  89162. FLAC__bool ok = 1;
  89163. FLAC__ASSERT(0 != bw);
  89164. FLAC__ASSERT(0 != bw->buffer);
  89165. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  89166. if(val < 0x80) {
  89167. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  89168. }
  89169. else if(val < 0x800) {
  89170. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  89171. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  89172. }
  89173. else if(val < 0x10000) {
  89174. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  89175. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  89176. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  89177. }
  89178. else if(val < 0x200000) {
  89179. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  89180. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  89181. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  89182. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  89183. }
  89184. else if(val < 0x4000000) {
  89185. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  89186. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  89187. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  89188. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  89189. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  89190. }
  89191. else if(val < 0x80000000) {
  89192. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  89193. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  89194. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  89195. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  89196. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  89197. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  89198. }
  89199. else {
  89200. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  89201. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  89202. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  89203. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  89204. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  89205. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  89206. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  89207. }
  89208. return ok;
  89209. }
  89210. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  89211. {
  89212. /* 0-pad to byte boundary */
  89213. if(bw->bits & 7u)
  89214. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  89215. else
  89216. return true;
  89217. }
  89218. #endif
  89219. /********* End of inlined file: bitwriter.c *********/
  89220. /********* Start of inlined file: cpu.c *********/
  89221. /********* Start of inlined file: juce_FlacHeader.h *********/
  89222. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89223. // tasks..
  89224. #define VERSION "1.2.1"
  89225. #define FLAC__NO_DLL 1
  89226. #ifdef _MSC_VER
  89227. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89228. #endif
  89229. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89230. #define FLAC__SYS_DARWIN 1
  89231. #endif
  89232. /********* End of inlined file: juce_FlacHeader.h *********/
  89233. #if JUCE_USE_FLAC
  89234. #if HAVE_CONFIG_H
  89235. # include <config.h>
  89236. #endif
  89237. #include <stdlib.h>
  89238. #include <stdio.h>
  89239. #if defined FLAC__CPU_IA32
  89240. # include <signal.h>
  89241. #elif defined FLAC__CPU_PPC
  89242. # if !defined FLAC__NO_ASM
  89243. # if defined FLAC__SYS_DARWIN
  89244. # include <sys/sysctl.h>
  89245. # include <mach/mach.h>
  89246. # include <mach/mach_host.h>
  89247. # include <mach/host_info.h>
  89248. # include <mach/machine.h>
  89249. # ifndef CPU_SUBTYPE_POWERPC_970
  89250. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  89251. # endif
  89252. # else /* FLAC__SYS_DARWIN */
  89253. # include <signal.h>
  89254. # include <setjmp.h>
  89255. static sigjmp_buf jmpbuf;
  89256. static volatile sig_atomic_t canjump = 0;
  89257. static void sigill_handler (int sig)
  89258. {
  89259. if (!canjump) {
  89260. signal (sig, SIG_DFL);
  89261. raise (sig);
  89262. }
  89263. canjump = 0;
  89264. siglongjmp (jmpbuf, 1);
  89265. }
  89266. # endif /* FLAC__SYS_DARWIN */
  89267. # endif /* FLAC__NO_ASM */
  89268. #endif /* FLAC__CPU_PPC */
  89269. #if defined (__NetBSD__) || defined(__OpenBSD__)
  89270. #include <sys/param.h>
  89271. #include <sys/sysctl.h>
  89272. #include <machine/cpu.h>
  89273. #endif
  89274. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  89275. #include <sys/types.h>
  89276. #include <sys/sysctl.h>
  89277. #endif
  89278. #if defined(__APPLE__)
  89279. /* how to get sysctlbyname()? */
  89280. #endif
  89281. /* these are flags in EDX of CPUID AX=00000001 */
  89282. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  89283. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  89284. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  89285. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  89286. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  89287. /* these are flags in ECX of CPUID AX=00000001 */
  89288. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  89289. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  89290. /* these are flags in EDX of CPUID AX=80000001 */
  89291. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  89292. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  89293. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  89294. /*
  89295. * Extra stuff needed for detection of OS support for SSE on IA-32
  89296. */
  89297. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  89298. # if defined(__linux__)
  89299. /*
  89300. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  89301. * modify the return address to jump over the offending SSE instruction
  89302. * and also the operation following it that indicates the instruction
  89303. * executed successfully. In this way we use no global variables and
  89304. * stay thread-safe.
  89305. *
  89306. * 3 + 3 + 6:
  89307. * 3 bytes for "xorps xmm0,xmm0"
  89308. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  89309. * 6 bytes extra in case our estimate is wrong
  89310. * 12 bytes puts us in the NOP "landing zone"
  89311. */
  89312. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  89313. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  89314. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  89315. {
  89316. (void)signal;
  89317. sc.eip += 3 + 3 + 6;
  89318. }
  89319. # else
  89320. # include <sys/ucontext.h>
  89321. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  89322. {
  89323. (void)signal, (void)si;
  89324. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  89325. }
  89326. # endif
  89327. # elif defined(_MSC_VER)
  89328. # include <windows.h>
  89329. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  89330. # ifdef USE_TRY_CATCH_FLAVOR
  89331. # else
  89332. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  89333. {
  89334. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  89335. ep->ContextRecord->Eip += 3 + 3 + 6;
  89336. return EXCEPTION_CONTINUE_EXECUTION;
  89337. }
  89338. return EXCEPTION_CONTINUE_SEARCH;
  89339. }
  89340. # endif
  89341. # endif
  89342. #endif
  89343. void FLAC__cpu_info(FLAC__CPUInfo *info)
  89344. {
  89345. /*
  89346. * IA32-specific
  89347. */
  89348. #ifdef FLAC__CPU_IA32
  89349. info->type = FLAC__CPUINFO_TYPE_IA32;
  89350. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  89351. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  89352. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  89353. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  89354. info->data.ia32.cmov = false;
  89355. info->data.ia32.mmx = false;
  89356. info->data.ia32.fxsr = false;
  89357. info->data.ia32.sse = false;
  89358. info->data.ia32.sse2 = false;
  89359. info->data.ia32.sse3 = false;
  89360. info->data.ia32.ssse3 = false;
  89361. info->data.ia32._3dnow = false;
  89362. info->data.ia32.ext3dnow = false;
  89363. info->data.ia32.extmmx = false;
  89364. if(info->data.ia32.cpuid) {
  89365. /* http://www.sandpile.org/ia32/cpuid.htm */
  89366. FLAC__uint32 flags_edx, flags_ecx;
  89367. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  89368. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  89369. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  89370. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  89371. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  89372. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  89373. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  89374. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  89375. #ifdef FLAC__USE_3DNOW
  89376. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  89377. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  89378. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  89379. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  89380. #else
  89381. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  89382. #endif
  89383. #ifdef DEBUG
  89384. fprintf(stderr, "CPU info (IA-32):\n");
  89385. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  89386. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  89387. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  89388. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  89389. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  89390. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  89391. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  89392. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  89393. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  89394. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  89395. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  89396. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  89397. #endif
  89398. /*
  89399. * now have to check for OS support of SSE/SSE2
  89400. */
  89401. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  89402. #if defined FLAC__NO_SSE_OS
  89403. /* assume user knows better than us; turn it off */
  89404. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89405. #elif defined FLAC__SSE_OS
  89406. /* assume user knows better than us; leave as detected above */
  89407. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  89408. int sse = 0;
  89409. size_t len;
  89410. /* at least one of these must work: */
  89411. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  89412. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  89413. if(!sse)
  89414. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89415. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  89416. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  89417. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  89418. size_t len = sizeof(val);
  89419. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  89420. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89421. else { /* double-check SSE2 */
  89422. mib[1] = CPU_SSE2;
  89423. len = sizeof(val);
  89424. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  89425. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89426. }
  89427. # else
  89428. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89429. # endif
  89430. #elif defined(__linux__)
  89431. int sse = 0;
  89432. struct sigaction sigill_save;
  89433. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  89434. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  89435. #else
  89436. struct sigaction sigill_sse;
  89437. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  89438. __sigemptyset(&sigill_sse.sa_mask);
  89439. 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 */
  89440. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  89441. #endif
  89442. {
  89443. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  89444. /* see sigill_handler_sse_os() for an explanation of the following: */
  89445. asm volatile (
  89446. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  89447. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  89448. "incl %0\n\t" /* SIGILL handler will jump over this */
  89449. /* landing zone */
  89450. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  89451. "nop\n\t"
  89452. "nop\n\t"
  89453. "nop\n\t"
  89454. "nop\n\t"
  89455. "nop\n\t"
  89456. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  89457. "nop\n\t"
  89458. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  89459. : "=r"(sse)
  89460. : "r"(sse)
  89461. );
  89462. sigaction(SIGILL, &sigill_save, NULL);
  89463. }
  89464. if(!sse)
  89465. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89466. #elif defined(_MSC_VER)
  89467. # ifdef USE_TRY_CATCH_FLAVOR
  89468. _try {
  89469. __asm {
  89470. # if _MSC_VER <= 1200
  89471. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  89472. _emit 0x0F
  89473. _emit 0x57
  89474. _emit 0xC0
  89475. # else
  89476. xorps xmm0,xmm0
  89477. # endif
  89478. }
  89479. }
  89480. _except(EXCEPTION_EXECUTE_HANDLER) {
  89481. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  89482. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89483. }
  89484. # else
  89485. int sse = 0;
  89486. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  89487. /* see GCC version above for explanation */
  89488. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  89489. /* http://www.codeproject.com/cpp/gccasm.asp */
  89490. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  89491. __asm {
  89492. # if _MSC_VER <= 1200
  89493. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  89494. _emit 0x0F
  89495. _emit 0x57
  89496. _emit 0xC0
  89497. # else
  89498. xorps xmm0,xmm0
  89499. # endif
  89500. inc sse
  89501. nop
  89502. nop
  89503. nop
  89504. nop
  89505. nop
  89506. nop
  89507. nop
  89508. nop
  89509. nop
  89510. }
  89511. SetUnhandledExceptionFilter(save);
  89512. if(!sse)
  89513. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89514. # endif
  89515. #else
  89516. /* no way to test, disable to be safe */
  89517. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89518. #endif
  89519. #ifdef DEBUG
  89520. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  89521. #endif
  89522. }
  89523. }
  89524. #else
  89525. info->use_asm = false;
  89526. #endif
  89527. /*
  89528. * PPC-specific
  89529. */
  89530. #elif defined FLAC__CPU_PPC
  89531. info->type = FLAC__CPUINFO_TYPE_PPC;
  89532. # if !defined FLAC__NO_ASM
  89533. info->use_asm = true;
  89534. # ifdef FLAC__USE_ALTIVEC
  89535. # if defined FLAC__SYS_DARWIN
  89536. {
  89537. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  89538. size_t len = sizeof(val);
  89539. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  89540. }
  89541. {
  89542. host_basic_info_data_t hostInfo;
  89543. mach_msg_type_number_t infoCount;
  89544. infoCount = HOST_BASIC_INFO_COUNT;
  89545. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  89546. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  89547. }
  89548. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  89549. {
  89550. /* no Darwin, do it the brute-force way */
  89551. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  89552. info->data.ppc.altivec = 0;
  89553. info->data.ppc.ppc64 = 0;
  89554. signal (SIGILL, sigill_handler);
  89555. canjump = 0;
  89556. if (!sigsetjmp (jmpbuf, 1)) {
  89557. canjump = 1;
  89558. asm volatile (
  89559. "mtspr 256, %0\n\t"
  89560. "vand %%v0, %%v0, %%v0"
  89561. :
  89562. : "r" (-1)
  89563. );
  89564. info->data.ppc.altivec = 1;
  89565. }
  89566. canjump = 0;
  89567. if (!sigsetjmp (jmpbuf, 1)) {
  89568. int x = 0;
  89569. canjump = 1;
  89570. /* PPC64 hardware implements the cntlzd instruction */
  89571. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  89572. info->data.ppc.ppc64 = 1;
  89573. }
  89574. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  89575. }
  89576. # endif
  89577. # else /* !FLAC__USE_ALTIVEC */
  89578. info->data.ppc.altivec = 0;
  89579. info->data.ppc.ppc64 = 0;
  89580. # endif
  89581. # else
  89582. info->use_asm = false;
  89583. # endif
  89584. /*
  89585. * unknown CPI
  89586. */
  89587. #else
  89588. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  89589. info->use_asm = false;
  89590. #endif
  89591. }
  89592. #endif
  89593. /********* End of inlined file: cpu.c *********/
  89594. /********* Start of inlined file: crc.c *********/
  89595. /********* Start of inlined file: juce_FlacHeader.h *********/
  89596. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89597. // tasks..
  89598. #define VERSION "1.2.1"
  89599. #define FLAC__NO_DLL 1
  89600. #ifdef _MSC_VER
  89601. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89602. #endif
  89603. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89604. #define FLAC__SYS_DARWIN 1
  89605. #endif
  89606. /********* End of inlined file: juce_FlacHeader.h *********/
  89607. #if JUCE_USE_FLAC
  89608. #if HAVE_CONFIG_H
  89609. # include <config.h>
  89610. #endif
  89611. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  89612. FLAC__byte const FLAC__crc8_table[256] = {
  89613. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  89614. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  89615. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  89616. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  89617. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  89618. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  89619. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  89620. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  89621. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  89622. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  89623. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  89624. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  89625. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  89626. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  89627. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  89628. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  89629. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  89630. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  89631. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  89632. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  89633. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  89634. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  89635. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  89636. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  89637. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  89638. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  89639. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  89640. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  89641. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  89642. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  89643. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  89644. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  89645. };
  89646. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  89647. unsigned FLAC__crc16_table[256] = {
  89648. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  89649. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  89650. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  89651. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  89652. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  89653. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  89654. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  89655. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  89656. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  89657. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  89658. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  89659. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  89660. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  89661. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  89662. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  89663. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  89664. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  89665. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  89666. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  89667. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  89668. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  89669. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  89670. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  89671. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  89672. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  89673. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  89674. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  89675. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  89676. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  89677. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  89678. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  89679. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  89680. };
  89681. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  89682. {
  89683. *crc = FLAC__crc8_table[*crc ^ data];
  89684. }
  89685. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  89686. {
  89687. while(len--)
  89688. *crc = FLAC__crc8_table[*crc ^ *data++];
  89689. }
  89690. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  89691. {
  89692. FLAC__uint8 crc = 0;
  89693. while(len--)
  89694. crc = FLAC__crc8_table[crc ^ *data++];
  89695. return crc;
  89696. }
  89697. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  89698. {
  89699. unsigned crc = 0;
  89700. while(len--)
  89701. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  89702. return crc;
  89703. }
  89704. #endif
  89705. /********* End of inlined file: crc.c *********/
  89706. /********* Start of inlined file: fixed.c *********/
  89707. /********* Start of inlined file: juce_FlacHeader.h *********/
  89708. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89709. // tasks..
  89710. #define VERSION "1.2.1"
  89711. #define FLAC__NO_DLL 1
  89712. #ifdef _MSC_VER
  89713. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89714. #endif
  89715. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89716. #define FLAC__SYS_DARWIN 1
  89717. #endif
  89718. /********* End of inlined file: juce_FlacHeader.h *********/
  89719. #if JUCE_USE_FLAC
  89720. #if HAVE_CONFIG_H
  89721. # include <config.h>
  89722. #endif
  89723. #include <math.h>
  89724. #include <string.h>
  89725. /********* Start of inlined file: fixed.h *********/
  89726. #ifndef FLAC__PRIVATE__FIXED_H
  89727. #define FLAC__PRIVATE__FIXED_H
  89728. #ifdef HAVE_CONFIG_H
  89729. #include <config.h>
  89730. #endif
  89731. /********* Start of inlined file: float.h *********/
  89732. #ifndef FLAC__PRIVATE__FLOAT_H
  89733. #define FLAC__PRIVATE__FLOAT_H
  89734. #ifdef HAVE_CONFIG_H
  89735. #include <config.h>
  89736. #endif
  89737. /*
  89738. * These typedefs make it easier to ensure that integer versions of
  89739. * the library really only contain integer operations. All the code
  89740. * in libFLAC should use FLAC__float and FLAC__double in place of
  89741. * float and double, and be protected by checks of the macro
  89742. * FLAC__INTEGER_ONLY_LIBRARY.
  89743. *
  89744. * FLAC__real is the basic floating point type used in LPC analysis.
  89745. */
  89746. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  89747. typedef double FLAC__double;
  89748. typedef float FLAC__float;
  89749. /*
  89750. * WATCHOUT: changing FLAC__real will change the signatures of many
  89751. * functions that have assembly language equivalents and break them.
  89752. */
  89753. typedef float FLAC__real;
  89754. #else
  89755. /*
  89756. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  89757. * for the integer part and lower 16 bits for the fractional part.
  89758. */
  89759. typedef FLAC__int32 FLAC__fixedpoint;
  89760. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  89761. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  89762. extern const FLAC__fixedpoint FLAC__FP_ONE;
  89763. extern const FLAC__fixedpoint FLAC__FP_LN2;
  89764. extern const FLAC__fixedpoint FLAC__FP_E;
  89765. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  89766. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  89767. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  89768. /*
  89769. * FLAC__fixedpoint_log2()
  89770. * --------------------------------------------------------------------
  89771. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  89772. * algorithm by Knuth for x >= 1.0
  89773. *
  89774. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  89775. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  89776. *
  89777. * 'precision' roughly limits the number of iterations that are done;
  89778. * use (unsigned)(-1) for maximum precision.
  89779. *
  89780. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  89781. * function will punt and return 0.
  89782. *
  89783. * The return value will also have 'fracbits' fractional bits.
  89784. */
  89785. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  89786. #endif
  89787. #endif
  89788. /********* End of inlined file: float.h *********/
  89789. /********* Start of inlined file: format.h *********/
  89790. #ifndef FLAC__PRIVATE__FORMAT_H
  89791. #define FLAC__PRIVATE__FORMAT_H
  89792. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  89793. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  89794. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  89795. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  89796. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  89797. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  89798. #endif
  89799. /********* End of inlined file: format.h *********/
  89800. /*
  89801. * FLAC__fixed_compute_best_predictor()
  89802. * --------------------------------------------------------------------
  89803. * Compute the best fixed predictor and the expected bits-per-sample
  89804. * of the residual signal for each order. The _wide() version uses
  89805. * 64-bit integers which is statistically necessary when bits-per-
  89806. * sample + log2(blocksize) > 30
  89807. *
  89808. * IN data[0,data_len-1]
  89809. * IN data_len
  89810. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  89811. */
  89812. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  89813. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  89814. # ifndef FLAC__NO_ASM
  89815. # ifdef FLAC__CPU_IA32
  89816. # ifdef FLAC__HAS_NASM
  89817. 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]);
  89818. # endif
  89819. # endif
  89820. # endif
  89821. 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]);
  89822. #else
  89823. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  89824. 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]);
  89825. #endif
  89826. /*
  89827. * FLAC__fixed_compute_residual()
  89828. * --------------------------------------------------------------------
  89829. * Compute the residual signal obtained from sutracting the predicted
  89830. * signal from the original.
  89831. *
  89832. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  89833. * IN data_len length of original signal
  89834. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  89835. * OUT residual[0,data_len-1] residual signal
  89836. */
  89837. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  89838. /*
  89839. * FLAC__fixed_restore_signal()
  89840. * --------------------------------------------------------------------
  89841. * Restore the original signal by summing the residual and the
  89842. * predictor.
  89843. *
  89844. * IN residual[0,data_len-1] residual signal
  89845. * IN data_len length of original signal
  89846. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  89847. * *** IMPORTANT: the caller must pass in the historical samples:
  89848. * IN data[-order,-1] previously-reconstructed historical samples
  89849. * OUT data[0,data_len-1] original signal
  89850. */
  89851. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  89852. #endif
  89853. /********* End of inlined file: fixed.h *********/
  89854. #ifndef M_LN2
  89855. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  89856. #define M_LN2 0.69314718055994530942
  89857. #endif
  89858. #ifdef min
  89859. #undef min
  89860. #endif
  89861. #define min(x,y) ((x) < (y)? (x) : (y))
  89862. #ifdef local_abs
  89863. #undef local_abs
  89864. #endif
  89865. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  89866. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  89867. /* rbps stands for residual bits per sample
  89868. *
  89869. * (ln(2) * err)
  89870. * rbps = log (-----------)
  89871. * 2 ( n )
  89872. */
  89873. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  89874. {
  89875. FLAC__uint32 rbps;
  89876. unsigned bits; /* the number of bits required to represent a number */
  89877. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  89878. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  89879. FLAC__ASSERT(err > 0);
  89880. FLAC__ASSERT(n > 0);
  89881. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  89882. if(err <= n)
  89883. return 0;
  89884. /*
  89885. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  89886. * These allow us later to know we won't lose too much precision in the
  89887. * fixed-point division (err<<fracbits)/n.
  89888. */
  89889. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  89890. err <<= fracbits;
  89891. err /= n;
  89892. /* err now holds err/n with fracbits fractional bits */
  89893. /*
  89894. * Whittle err down to 16 bits max. 16 significant bits is enough for
  89895. * our purposes.
  89896. */
  89897. FLAC__ASSERT(err > 0);
  89898. bits = FLAC__bitmath_ilog2(err)+1;
  89899. if(bits > 16) {
  89900. err >>= (bits-16);
  89901. fracbits -= (bits-16);
  89902. }
  89903. rbps = (FLAC__uint32)err;
  89904. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  89905. rbps *= FLAC__FP_LN2;
  89906. fracbits += 16;
  89907. FLAC__ASSERT(fracbits >= 0);
  89908. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  89909. {
  89910. const int f = fracbits & 3;
  89911. if(f) {
  89912. rbps >>= f;
  89913. fracbits -= f;
  89914. }
  89915. }
  89916. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  89917. if(rbps == 0)
  89918. return 0;
  89919. /*
  89920. * The return value must have 16 fractional bits. Since the whole part
  89921. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  89922. * must be >= -3, these assertion allows us to be able to shift rbps
  89923. * left if necessary to get 16 fracbits without losing any bits of the
  89924. * whole part of rbps.
  89925. *
  89926. * There is a slight chance due to accumulated error that the whole part
  89927. * will require 6 bits, so we use 6 in the assertion. Really though as
  89928. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  89929. */
  89930. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  89931. FLAC__ASSERT(fracbits >= -3);
  89932. /* now shift the decimal point into place */
  89933. if(fracbits < 16)
  89934. return rbps << (16-fracbits);
  89935. else if(fracbits > 16)
  89936. return rbps >> (fracbits-16);
  89937. else
  89938. return rbps;
  89939. }
  89940. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  89941. {
  89942. FLAC__uint32 rbps;
  89943. unsigned bits; /* the number of bits required to represent a number */
  89944. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  89945. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  89946. FLAC__ASSERT(err > 0);
  89947. FLAC__ASSERT(n > 0);
  89948. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  89949. if(err <= n)
  89950. return 0;
  89951. /*
  89952. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  89953. * These allow us later to know we won't lose too much precision in the
  89954. * fixed-point division (err<<fracbits)/n.
  89955. */
  89956. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  89957. err <<= fracbits;
  89958. err /= n;
  89959. /* err now holds err/n with fracbits fractional bits */
  89960. /*
  89961. * Whittle err down to 16 bits max. 16 significant bits is enough for
  89962. * our purposes.
  89963. */
  89964. FLAC__ASSERT(err > 0);
  89965. bits = FLAC__bitmath_ilog2_wide(err)+1;
  89966. if(bits > 16) {
  89967. err >>= (bits-16);
  89968. fracbits -= (bits-16);
  89969. }
  89970. rbps = (FLAC__uint32)err;
  89971. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  89972. rbps *= FLAC__FP_LN2;
  89973. fracbits += 16;
  89974. FLAC__ASSERT(fracbits >= 0);
  89975. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  89976. {
  89977. const int f = fracbits & 3;
  89978. if(f) {
  89979. rbps >>= f;
  89980. fracbits -= f;
  89981. }
  89982. }
  89983. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  89984. if(rbps == 0)
  89985. return 0;
  89986. /*
  89987. * The return value must have 16 fractional bits. Since the whole part
  89988. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  89989. * must be >= -3, these assertion allows us to be able to shift rbps
  89990. * left if necessary to get 16 fracbits without losing any bits of the
  89991. * whole part of rbps.
  89992. *
  89993. * There is a slight chance due to accumulated error that the whole part
  89994. * will require 6 bits, so we use 6 in the assertion. Really though as
  89995. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  89996. */
  89997. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  89998. FLAC__ASSERT(fracbits >= -3);
  89999. /* now shift the decimal point into place */
  90000. if(fracbits < 16)
  90001. return rbps << (16-fracbits);
  90002. else if(fracbits > 16)
  90003. return rbps >> (fracbits-16);
  90004. else
  90005. return rbps;
  90006. }
  90007. #endif
  90008. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90009. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  90010. #else
  90011. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  90012. #endif
  90013. {
  90014. FLAC__int32 last_error_0 = data[-1];
  90015. FLAC__int32 last_error_1 = data[-1] - data[-2];
  90016. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  90017. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  90018. FLAC__int32 error, save;
  90019. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  90020. unsigned i, order;
  90021. for(i = 0; i < data_len; i++) {
  90022. error = data[i] ; total_error_0 += local_abs(error); save = error;
  90023. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  90024. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  90025. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  90026. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  90027. }
  90028. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  90029. order = 0;
  90030. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  90031. order = 1;
  90032. else if(total_error_2 < min(total_error_3, total_error_4))
  90033. order = 2;
  90034. else if(total_error_3 < total_error_4)
  90035. order = 3;
  90036. else
  90037. order = 4;
  90038. /* Estimate the expected number of bits per residual signal sample. */
  90039. /* 'total_error*' is linearly related to the variance of the residual */
  90040. /* signal, so we use it directly to compute E(|x|) */
  90041. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  90042. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  90043. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  90044. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  90045. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  90046. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90047. 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);
  90048. 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);
  90049. 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);
  90050. 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);
  90051. 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);
  90052. #else
  90053. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  90054. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  90055. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  90056. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  90057. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  90058. #endif
  90059. return order;
  90060. }
  90061. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90062. 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])
  90063. #else
  90064. 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])
  90065. #endif
  90066. {
  90067. FLAC__int32 last_error_0 = data[-1];
  90068. FLAC__int32 last_error_1 = data[-1] - data[-2];
  90069. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  90070. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  90071. FLAC__int32 error, save;
  90072. /* total_error_* are 64-bits to avoid overflow when encoding
  90073. * erratic signals when the bits-per-sample and blocksize are
  90074. * large.
  90075. */
  90076. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  90077. unsigned i, order;
  90078. for(i = 0; i < data_len; i++) {
  90079. error = data[i] ; total_error_0 += local_abs(error); save = error;
  90080. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  90081. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  90082. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  90083. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  90084. }
  90085. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  90086. order = 0;
  90087. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  90088. order = 1;
  90089. else if(total_error_2 < min(total_error_3, total_error_4))
  90090. order = 2;
  90091. else if(total_error_3 < total_error_4)
  90092. order = 3;
  90093. else
  90094. order = 4;
  90095. /* Estimate the expected number of bits per residual signal sample. */
  90096. /* 'total_error*' is linearly related to the variance of the residual */
  90097. /* signal, so we use it directly to compute E(|x|) */
  90098. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  90099. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  90100. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  90101. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  90102. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  90103. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90104. #if defined _MSC_VER || defined __MINGW32__
  90105. /* with MSVC you have to spoon feed it the casting */
  90106. 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);
  90107. 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);
  90108. 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);
  90109. 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);
  90110. 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);
  90111. #else
  90112. 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);
  90113. 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);
  90114. 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);
  90115. 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);
  90116. 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);
  90117. #endif
  90118. #else
  90119. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  90120. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  90121. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  90122. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  90123. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  90124. #endif
  90125. return order;
  90126. }
  90127. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  90128. {
  90129. const int idata_len = (int)data_len;
  90130. int i;
  90131. switch(order) {
  90132. case 0:
  90133. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  90134. memcpy(residual, data, sizeof(residual[0])*data_len);
  90135. break;
  90136. case 1:
  90137. for(i = 0; i < idata_len; i++)
  90138. residual[i] = data[i] - data[i-1];
  90139. break;
  90140. case 2:
  90141. for(i = 0; i < idata_len; i++)
  90142. #if 1 /* OPT: may be faster with some compilers on some systems */
  90143. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  90144. #else
  90145. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  90146. #endif
  90147. break;
  90148. case 3:
  90149. for(i = 0; i < idata_len; i++)
  90150. #if 1 /* OPT: may be faster with some compilers on some systems */
  90151. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  90152. #else
  90153. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  90154. #endif
  90155. break;
  90156. case 4:
  90157. for(i = 0; i < idata_len; i++)
  90158. #if 1 /* OPT: may be faster with some compilers on some systems */
  90159. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  90160. #else
  90161. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  90162. #endif
  90163. break;
  90164. default:
  90165. FLAC__ASSERT(0);
  90166. }
  90167. }
  90168. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  90169. {
  90170. int i, idata_len = (int)data_len;
  90171. switch(order) {
  90172. case 0:
  90173. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  90174. memcpy(data, residual, sizeof(residual[0])*data_len);
  90175. break;
  90176. case 1:
  90177. for(i = 0; i < idata_len; i++)
  90178. data[i] = residual[i] + data[i-1];
  90179. break;
  90180. case 2:
  90181. for(i = 0; i < idata_len; i++)
  90182. #if 1 /* OPT: may be faster with some compilers on some systems */
  90183. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  90184. #else
  90185. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  90186. #endif
  90187. break;
  90188. case 3:
  90189. for(i = 0; i < idata_len; i++)
  90190. #if 1 /* OPT: may be faster with some compilers on some systems */
  90191. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  90192. #else
  90193. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  90194. #endif
  90195. break;
  90196. case 4:
  90197. for(i = 0; i < idata_len; i++)
  90198. #if 1 /* OPT: may be faster with some compilers on some systems */
  90199. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  90200. #else
  90201. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  90202. #endif
  90203. break;
  90204. default:
  90205. FLAC__ASSERT(0);
  90206. }
  90207. }
  90208. #endif
  90209. /********* End of inlined file: fixed.c *********/
  90210. /********* Start of inlined file: float.c *********/
  90211. /********* Start of inlined file: juce_FlacHeader.h *********/
  90212. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90213. // tasks..
  90214. #define VERSION "1.2.1"
  90215. #define FLAC__NO_DLL 1
  90216. #ifdef _MSC_VER
  90217. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90218. #endif
  90219. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90220. #define FLAC__SYS_DARWIN 1
  90221. #endif
  90222. /********* End of inlined file: juce_FlacHeader.h *********/
  90223. #if JUCE_USE_FLAC
  90224. #if HAVE_CONFIG_H
  90225. # include <config.h>
  90226. #endif
  90227. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  90228. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  90229. #ifdef _MSC_VER
  90230. #define FLAC__U64L(x) x
  90231. #else
  90232. #define FLAC__U64L(x) x##LLU
  90233. #endif
  90234. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  90235. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  90236. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  90237. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  90238. const FLAC__fixedpoint FLAC__FP_E = 178145;
  90239. /* Lookup tables for Knuth's logarithm algorithm */
  90240. #define LOG2_LOOKUP_PRECISION 16
  90241. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  90242. {
  90243. /*
  90244. * 0 fraction bits
  90245. */
  90246. /* undefined */ 0x00000000,
  90247. /* lg(2/1) = */ 0x00000001,
  90248. /* lg(4/3) = */ 0x00000000,
  90249. /* lg(8/7) = */ 0x00000000,
  90250. /* lg(16/15) = */ 0x00000000,
  90251. /* lg(32/31) = */ 0x00000000,
  90252. /* lg(64/63) = */ 0x00000000,
  90253. /* lg(128/127) = */ 0x00000000,
  90254. /* lg(256/255) = */ 0x00000000,
  90255. /* lg(512/511) = */ 0x00000000,
  90256. /* lg(1024/1023) = */ 0x00000000,
  90257. /* lg(2048/2047) = */ 0x00000000,
  90258. /* lg(4096/4095) = */ 0x00000000,
  90259. /* lg(8192/8191) = */ 0x00000000,
  90260. /* lg(16384/16383) = */ 0x00000000,
  90261. /* lg(32768/32767) = */ 0x00000000
  90262. },
  90263. {
  90264. /*
  90265. * 4 fraction bits
  90266. */
  90267. /* undefined */ 0x00000000,
  90268. /* lg(2/1) = */ 0x00000010,
  90269. /* lg(4/3) = */ 0x00000007,
  90270. /* lg(8/7) = */ 0x00000003,
  90271. /* lg(16/15) = */ 0x00000001,
  90272. /* lg(32/31) = */ 0x00000001,
  90273. /* lg(64/63) = */ 0x00000000,
  90274. /* lg(128/127) = */ 0x00000000,
  90275. /* lg(256/255) = */ 0x00000000,
  90276. /* lg(512/511) = */ 0x00000000,
  90277. /* lg(1024/1023) = */ 0x00000000,
  90278. /* lg(2048/2047) = */ 0x00000000,
  90279. /* lg(4096/4095) = */ 0x00000000,
  90280. /* lg(8192/8191) = */ 0x00000000,
  90281. /* lg(16384/16383) = */ 0x00000000,
  90282. /* lg(32768/32767) = */ 0x00000000
  90283. },
  90284. {
  90285. /*
  90286. * 8 fraction bits
  90287. */
  90288. /* undefined */ 0x00000000,
  90289. /* lg(2/1) = */ 0x00000100,
  90290. /* lg(4/3) = */ 0x0000006a,
  90291. /* lg(8/7) = */ 0x00000031,
  90292. /* lg(16/15) = */ 0x00000018,
  90293. /* lg(32/31) = */ 0x0000000c,
  90294. /* lg(64/63) = */ 0x00000006,
  90295. /* lg(128/127) = */ 0x00000003,
  90296. /* lg(256/255) = */ 0x00000001,
  90297. /* lg(512/511) = */ 0x00000001,
  90298. /* lg(1024/1023) = */ 0x00000000,
  90299. /* lg(2048/2047) = */ 0x00000000,
  90300. /* lg(4096/4095) = */ 0x00000000,
  90301. /* lg(8192/8191) = */ 0x00000000,
  90302. /* lg(16384/16383) = */ 0x00000000,
  90303. /* lg(32768/32767) = */ 0x00000000
  90304. },
  90305. {
  90306. /*
  90307. * 12 fraction bits
  90308. */
  90309. /* undefined */ 0x00000000,
  90310. /* lg(2/1) = */ 0x00001000,
  90311. /* lg(4/3) = */ 0x000006a4,
  90312. /* lg(8/7) = */ 0x00000315,
  90313. /* lg(16/15) = */ 0x0000017d,
  90314. /* lg(32/31) = */ 0x000000bc,
  90315. /* lg(64/63) = */ 0x0000005d,
  90316. /* lg(128/127) = */ 0x0000002e,
  90317. /* lg(256/255) = */ 0x00000017,
  90318. /* lg(512/511) = */ 0x0000000c,
  90319. /* lg(1024/1023) = */ 0x00000006,
  90320. /* lg(2048/2047) = */ 0x00000003,
  90321. /* lg(4096/4095) = */ 0x00000001,
  90322. /* lg(8192/8191) = */ 0x00000001,
  90323. /* lg(16384/16383) = */ 0x00000000,
  90324. /* lg(32768/32767) = */ 0x00000000
  90325. },
  90326. {
  90327. /*
  90328. * 16 fraction bits
  90329. */
  90330. /* undefined */ 0x00000000,
  90331. /* lg(2/1) = */ 0x00010000,
  90332. /* lg(4/3) = */ 0x00006a40,
  90333. /* lg(8/7) = */ 0x00003151,
  90334. /* lg(16/15) = */ 0x000017d6,
  90335. /* lg(32/31) = */ 0x00000bba,
  90336. /* lg(64/63) = */ 0x000005d1,
  90337. /* lg(128/127) = */ 0x000002e6,
  90338. /* lg(256/255) = */ 0x00000172,
  90339. /* lg(512/511) = */ 0x000000b9,
  90340. /* lg(1024/1023) = */ 0x0000005c,
  90341. /* lg(2048/2047) = */ 0x0000002e,
  90342. /* lg(4096/4095) = */ 0x00000017,
  90343. /* lg(8192/8191) = */ 0x0000000c,
  90344. /* lg(16384/16383) = */ 0x00000006,
  90345. /* lg(32768/32767) = */ 0x00000003
  90346. },
  90347. {
  90348. /*
  90349. * 20 fraction bits
  90350. */
  90351. /* undefined */ 0x00000000,
  90352. /* lg(2/1) = */ 0x00100000,
  90353. /* lg(4/3) = */ 0x0006a3fe,
  90354. /* lg(8/7) = */ 0x00031513,
  90355. /* lg(16/15) = */ 0x00017d60,
  90356. /* lg(32/31) = */ 0x0000bb9d,
  90357. /* lg(64/63) = */ 0x00005d10,
  90358. /* lg(128/127) = */ 0x00002e59,
  90359. /* lg(256/255) = */ 0x00001721,
  90360. /* lg(512/511) = */ 0x00000b8e,
  90361. /* lg(1024/1023) = */ 0x000005c6,
  90362. /* lg(2048/2047) = */ 0x000002e3,
  90363. /* lg(4096/4095) = */ 0x00000171,
  90364. /* lg(8192/8191) = */ 0x000000b9,
  90365. /* lg(16384/16383) = */ 0x0000005c,
  90366. /* lg(32768/32767) = */ 0x0000002e
  90367. },
  90368. {
  90369. /*
  90370. * 24 fraction bits
  90371. */
  90372. /* undefined */ 0x00000000,
  90373. /* lg(2/1) = */ 0x01000000,
  90374. /* lg(4/3) = */ 0x006a3fe6,
  90375. /* lg(8/7) = */ 0x00315130,
  90376. /* lg(16/15) = */ 0x0017d605,
  90377. /* lg(32/31) = */ 0x000bb9ca,
  90378. /* lg(64/63) = */ 0x0005d0fc,
  90379. /* lg(128/127) = */ 0x0002e58f,
  90380. /* lg(256/255) = */ 0x0001720e,
  90381. /* lg(512/511) = */ 0x0000b8d8,
  90382. /* lg(1024/1023) = */ 0x00005c61,
  90383. /* lg(2048/2047) = */ 0x00002e2d,
  90384. /* lg(4096/4095) = */ 0x00001716,
  90385. /* lg(8192/8191) = */ 0x00000b8b,
  90386. /* lg(16384/16383) = */ 0x000005c5,
  90387. /* lg(32768/32767) = */ 0x000002e3
  90388. },
  90389. {
  90390. /*
  90391. * 28 fraction bits
  90392. */
  90393. /* undefined */ 0x00000000,
  90394. /* lg(2/1) = */ 0x10000000,
  90395. /* lg(4/3) = */ 0x06a3fe5c,
  90396. /* lg(8/7) = */ 0x03151301,
  90397. /* lg(16/15) = */ 0x017d6049,
  90398. /* lg(32/31) = */ 0x00bb9ca6,
  90399. /* lg(64/63) = */ 0x005d0fba,
  90400. /* lg(128/127) = */ 0x002e58f7,
  90401. /* lg(256/255) = */ 0x001720da,
  90402. /* lg(512/511) = */ 0x000b8d87,
  90403. /* lg(1024/1023) = */ 0x0005c60b,
  90404. /* lg(2048/2047) = */ 0x0002e2d7,
  90405. /* lg(4096/4095) = */ 0x00017160,
  90406. /* lg(8192/8191) = */ 0x0000b8ad,
  90407. /* lg(16384/16383) = */ 0x00005c56,
  90408. /* lg(32768/32767) = */ 0x00002e2b
  90409. }
  90410. };
  90411. #if 0
  90412. static const FLAC__uint64 log2_lookup_wide[] = {
  90413. {
  90414. /*
  90415. * 32 fraction bits
  90416. */
  90417. /* undefined */ 0x00000000,
  90418. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  90419. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  90420. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  90421. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  90422. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  90423. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  90424. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  90425. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  90426. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  90427. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  90428. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  90429. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  90430. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  90431. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  90432. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  90433. },
  90434. {
  90435. /*
  90436. * 48 fraction bits
  90437. */
  90438. /* undefined */ 0x00000000,
  90439. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  90440. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  90441. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  90442. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  90443. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  90444. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  90445. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  90446. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  90447. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  90448. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  90449. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  90450. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  90451. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  90452. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  90453. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  90454. }
  90455. };
  90456. #endif
  90457. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  90458. {
  90459. const FLAC__uint32 ONE = (1u << fracbits);
  90460. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  90461. FLAC__ASSERT(fracbits < 32);
  90462. FLAC__ASSERT((fracbits & 0x3) == 0);
  90463. if(x < ONE)
  90464. return 0;
  90465. if(precision > LOG2_LOOKUP_PRECISION)
  90466. precision = LOG2_LOOKUP_PRECISION;
  90467. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  90468. {
  90469. FLAC__uint32 y = 0;
  90470. FLAC__uint32 z = x >> 1, k = 1;
  90471. while (x > ONE && k < precision) {
  90472. if (x - z >= ONE) {
  90473. x -= z;
  90474. z = x >> k;
  90475. y += table[k];
  90476. }
  90477. else {
  90478. z >>= 1;
  90479. k++;
  90480. }
  90481. }
  90482. return y;
  90483. }
  90484. }
  90485. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  90486. #endif
  90487. /********* End of inlined file: float.c *********/
  90488. /********* Start of inlined file: format.c *********/
  90489. /********* Start of inlined file: juce_FlacHeader.h *********/
  90490. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90491. // tasks..
  90492. #define VERSION "1.2.1"
  90493. #define FLAC__NO_DLL 1
  90494. #ifdef _MSC_VER
  90495. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90496. #endif
  90497. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90498. #define FLAC__SYS_DARWIN 1
  90499. #endif
  90500. /********* End of inlined file: juce_FlacHeader.h *********/
  90501. #if JUCE_USE_FLAC
  90502. #if HAVE_CONFIG_H
  90503. # include <config.h>
  90504. #endif
  90505. #include <stdio.h>
  90506. #include <stdlib.h> /* for qsort() */
  90507. #include <string.h> /* for memset() */
  90508. #ifndef FLaC__INLINE
  90509. #define FLaC__INLINE
  90510. #endif
  90511. #ifdef min
  90512. #undef min
  90513. #endif
  90514. #define min(a,b) ((a)<(b)?(a):(b))
  90515. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  90516. #ifdef _MSC_VER
  90517. #define FLAC__U64L(x) x
  90518. #else
  90519. #define FLAC__U64L(x) x##LLU
  90520. #endif
  90521. /* VERSION should come from configure */
  90522. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  90523. ;
  90524. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  90525. /* yet one more hack because of MSVC6: */
  90526. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  90527. #else
  90528. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  90529. #endif
  90530. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  90531. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  90532. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  90533. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  90534. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  90535. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  90536. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  90537. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  90538. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  90539. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  90540. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  90541. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  90542. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  90543. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  90544. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  90545. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  90546. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  90547. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  90548. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  90549. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  90550. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  90551. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  90552. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  90553. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  90554. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  90555. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  90556. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  90557. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  90558. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  90559. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  90560. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  90561. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  90562. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  90563. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  90564. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  90565. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  90566. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  90567. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  90568. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  90569. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  90570. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  90571. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  90572. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  90573. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  90574. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  90575. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  90576. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  90577. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  90578. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  90579. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  90580. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  90581. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  90582. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  90583. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  90584. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  90585. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  90586. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  90587. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  90588. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  90589. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  90590. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  90591. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  90592. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  90593. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  90594. "PARTITIONED_RICE",
  90595. "PARTITIONED_RICE2"
  90596. };
  90597. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  90598. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  90599. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  90600. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  90601. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  90602. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  90603. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  90604. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  90605. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  90606. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  90607. "CONSTANT",
  90608. "VERBATIM",
  90609. "FIXED",
  90610. "LPC"
  90611. };
  90612. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  90613. "INDEPENDENT",
  90614. "LEFT_SIDE",
  90615. "RIGHT_SIDE",
  90616. "MID_SIDE"
  90617. };
  90618. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  90619. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  90620. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  90621. };
  90622. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  90623. "STREAMINFO",
  90624. "PADDING",
  90625. "APPLICATION",
  90626. "SEEKTABLE",
  90627. "VORBIS_COMMENT",
  90628. "CUESHEET",
  90629. "PICTURE"
  90630. };
  90631. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  90632. "Other",
  90633. "32x32 pixels 'file icon' (PNG only)",
  90634. "Other file icon",
  90635. "Cover (front)",
  90636. "Cover (back)",
  90637. "Leaflet page",
  90638. "Media (e.g. label side of CD)",
  90639. "Lead artist/lead performer/soloist",
  90640. "Artist/performer",
  90641. "Conductor",
  90642. "Band/Orchestra",
  90643. "Composer",
  90644. "Lyricist/text writer",
  90645. "Recording Location",
  90646. "During recording",
  90647. "During performance",
  90648. "Movie/video screen capture",
  90649. "A bright coloured fish",
  90650. "Illustration",
  90651. "Band/artist logotype",
  90652. "Publisher/Studio logotype"
  90653. };
  90654. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  90655. {
  90656. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  90657. return false;
  90658. }
  90659. else
  90660. return true;
  90661. }
  90662. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  90663. {
  90664. if(
  90665. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  90666. (
  90667. sample_rate >= (1u << 16) &&
  90668. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  90669. )
  90670. ) {
  90671. return false;
  90672. }
  90673. else
  90674. return true;
  90675. }
  90676. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  90677. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  90678. {
  90679. unsigned i;
  90680. FLAC__uint64 prev_sample_number = 0;
  90681. FLAC__bool got_prev = false;
  90682. FLAC__ASSERT(0 != seek_table);
  90683. for(i = 0; i < seek_table->num_points; i++) {
  90684. if(got_prev) {
  90685. if(
  90686. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  90687. seek_table->points[i].sample_number <= prev_sample_number
  90688. )
  90689. return false;
  90690. }
  90691. prev_sample_number = seek_table->points[i].sample_number;
  90692. got_prev = true;
  90693. }
  90694. return true;
  90695. }
  90696. /* used as the sort predicate for qsort() */
  90697. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  90698. {
  90699. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  90700. if(l->sample_number == r->sample_number)
  90701. return 0;
  90702. else if(l->sample_number < r->sample_number)
  90703. return -1;
  90704. else
  90705. return 1;
  90706. }
  90707. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  90708. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  90709. {
  90710. unsigned i, j;
  90711. FLAC__bool first;
  90712. FLAC__ASSERT(0 != seek_table);
  90713. /* sort the seekpoints */
  90714. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  90715. /* uniquify the seekpoints */
  90716. first = true;
  90717. for(i = j = 0; i < seek_table->num_points; i++) {
  90718. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  90719. if(!first) {
  90720. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  90721. continue;
  90722. }
  90723. }
  90724. first = false;
  90725. seek_table->points[j++] = seek_table->points[i];
  90726. }
  90727. for(i = j; i < seek_table->num_points; i++) {
  90728. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  90729. seek_table->points[i].stream_offset = 0;
  90730. seek_table->points[i].frame_samples = 0;
  90731. }
  90732. return j;
  90733. }
  90734. /*
  90735. * also disallows non-shortest-form encodings, c.f.
  90736. * http://www.unicode.org/versions/corrigendum1.html
  90737. * and a more clear explanation at the end of this section:
  90738. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  90739. */
  90740. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  90741. {
  90742. FLAC__ASSERT(0 != utf8);
  90743. if ((utf8[0] & 0x80) == 0) {
  90744. return 1;
  90745. }
  90746. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  90747. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  90748. return 0;
  90749. return 2;
  90750. }
  90751. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  90752. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  90753. return 0;
  90754. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  90755. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  90756. return 0;
  90757. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  90758. return 0;
  90759. return 3;
  90760. }
  90761. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  90762. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  90763. return 0;
  90764. return 4;
  90765. }
  90766. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  90767. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  90768. return 0;
  90769. return 5;
  90770. }
  90771. 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) {
  90772. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  90773. return 0;
  90774. return 6;
  90775. }
  90776. else {
  90777. return 0;
  90778. }
  90779. }
  90780. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  90781. {
  90782. char c;
  90783. for(c = *name; c; c = *(++name))
  90784. if(c < 0x20 || c == 0x3d || c > 0x7d)
  90785. return false;
  90786. return true;
  90787. }
  90788. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  90789. {
  90790. if(length == (unsigned)(-1)) {
  90791. while(*value) {
  90792. unsigned n = utf8len_(value);
  90793. if(n == 0)
  90794. return false;
  90795. value += n;
  90796. }
  90797. }
  90798. else {
  90799. const FLAC__byte *end = value + length;
  90800. while(value < end) {
  90801. unsigned n = utf8len_(value);
  90802. if(n == 0)
  90803. return false;
  90804. value += n;
  90805. }
  90806. if(value != end)
  90807. return false;
  90808. }
  90809. return true;
  90810. }
  90811. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  90812. {
  90813. const FLAC__byte *s, *end;
  90814. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  90815. if(*s < 0x20 || *s > 0x7D)
  90816. return false;
  90817. }
  90818. if(s == end)
  90819. return false;
  90820. s++; /* skip '=' */
  90821. while(s < end) {
  90822. unsigned n = utf8len_(s);
  90823. if(n == 0)
  90824. return false;
  90825. s += n;
  90826. }
  90827. if(s != end)
  90828. return false;
  90829. return true;
  90830. }
  90831. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  90832. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  90833. {
  90834. unsigned i, j;
  90835. if(check_cd_da_subset) {
  90836. if(cue_sheet->lead_in < 2 * 44100) {
  90837. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  90838. return false;
  90839. }
  90840. if(cue_sheet->lead_in % 588 != 0) {
  90841. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  90842. return false;
  90843. }
  90844. }
  90845. if(cue_sheet->num_tracks == 0) {
  90846. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  90847. return false;
  90848. }
  90849. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  90850. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  90851. return false;
  90852. }
  90853. for(i = 0; i < cue_sheet->num_tracks; i++) {
  90854. if(cue_sheet->tracks[i].number == 0) {
  90855. if(violation) *violation = "cue sheet may not have a track number 0";
  90856. return false;
  90857. }
  90858. if(check_cd_da_subset) {
  90859. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  90860. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  90861. return false;
  90862. }
  90863. }
  90864. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  90865. if(violation) {
  90866. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  90867. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  90868. else
  90869. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  90870. }
  90871. return false;
  90872. }
  90873. if(i < cue_sheet->num_tracks - 1) {
  90874. if(cue_sheet->tracks[i].num_indices == 0) {
  90875. if(violation) *violation = "cue sheet track must have at least one index point";
  90876. return false;
  90877. }
  90878. if(cue_sheet->tracks[i].indices[0].number > 1) {
  90879. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  90880. return false;
  90881. }
  90882. }
  90883. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  90884. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  90885. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  90886. return false;
  90887. }
  90888. if(j > 0) {
  90889. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  90890. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  90891. return false;
  90892. }
  90893. }
  90894. }
  90895. }
  90896. return true;
  90897. }
  90898. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  90899. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  90900. {
  90901. char *p;
  90902. FLAC__byte *b;
  90903. for(p = picture->mime_type; *p; p++) {
  90904. if(*p < 0x20 || *p > 0x7e) {
  90905. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  90906. return false;
  90907. }
  90908. }
  90909. for(b = picture->description; *b; ) {
  90910. unsigned n = utf8len_(b);
  90911. if(n == 0) {
  90912. if(violation) *violation = "description string must be valid UTF-8";
  90913. return false;
  90914. }
  90915. b += n;
  90916. }
  90917. return true;
  90918. }
  90919. /*
  90920. * These routines are private to libFLAC
  90921. */
  90922. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  90923. {
  90924. return
  90925. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  90926. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  90927. blocksize,
  90928. predictor_order
  90929. );
  90930. }
  90931. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  90932. {
  90933. unsigned max_rice_partition_order = 0;
  90934. while(!(blocksize & 1)) {
  90935. max_rice_partition_order++;
  90936. blocksize >>= 1;
  90937. }
  90938. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  90939. }
  90940. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  90941. {
  90942. unsigned max_rice_partition_order = limit;
  90943. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  90944. max_rice_partition_order--;
  90945. FLAC__ASSERT(
  90946. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  90947. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  90948. );
  90949. return max_rice_partition_order;
  90950. }
  90951. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  90952. {
  90953. FLAC__ASSERT(0 != object);
  90954. object->parameters = 0;
  90955. object->raw_bits = 0;
  90956. object->capacity_by_order = 0;
  90957. }
  90958. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  90959. {
  90960. FLAC__ASSERT(0 != object);
  90961. if(0 != object->parameters)
  90962. free(object->parameters);
  90963. if(0 != object->raw_bits)
  90964. free(object->raw_bits);
  90965. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  90966. }
  90967. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  90968. {
  90969. FLAC__ASSERT(0 != object);
  90970. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  90971. if(object->capacity_by_order < max_partition_order) {
  90972. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  90973. return false;
  90974. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  90975. return false;
  90976. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  90977. object->capacity_by_order = max_partition_order;
  90978. }
  90979. return true;
  90980. }
  90981. #endif
  90982. /********* End of inlined file: format.c *********/
  90983. /********* Start of inlined file: lpc_flac.c *********/
  90984. /********* Start of inlined file: juce_FlacHeader.h *********/
  90985. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90986. // tasks..
  90987. #define VERSION "1.2.1"
  90988. #define FLAC__NO_DLL 1
  90989. #ifdef _MSC_VER
  90990. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90991. #endif
  90992. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90993. #define FLAC__SYS_DARWIN 1
  90994. #endif
  90995. /********* End of inlined file: juce_FlacHeader.h *********/
  90996. #if JUCE_USE_FLAC
  90997. #if HAVE_CONFIG_H
  90998. # include <config.h>
  90999. #endif
  91000. #include <math.h>
  91001. /********* Start of inlined file: lpc.h *********/
  91002. #ifndef FLAC__PRIVATE__LPC_H
  91003. #define FLAC__PRIVATE__LPC_H
  91004. #ifdef HAVE_CONFIG_H
  91005. #include <config.h>
  91006. #endif
  91007. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91008. /*
  91009. * FLAC__lpc_window_data()
  91010. * --------------------------------------------------------------------
  91011. * Applies the given window to the data.
  91012. * OPT: asm implementation
  91013. *
  91014. * IN in[0,data_len-1]
  91015. * IN window[0,data_len-1]
  91016. * OUT out[0,lag-1]
  91017. * IN data_len
  91018. */
  91019. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  91020. /*
  91021. * FLAC__lpc_compute_autocorrelation()
  91022. * --------------------------------------------------------------------
  91023. * Compute the autocorrelation for lags between 0 and lag-1.
  91024. * Assumes data[] outside of [0,data_len-1] == 0.
  91025. * Asserts that lag > 0.
  91026. *
  91027. * IN data[0,data_len-1]
  91028. * IN data_len
  91029. * IN 0 < lag <= data_len
  91030. * OUT autoc[0,lag-1]
  91031. */
  91032. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91033. #ifndef FLAC__NO_ASM
  91034. # ifdef FLAC__CPU_IA32
  91035. # ifdef FLAC__HAS_NASM
  91036. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91037. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91038. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91039. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91040. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91041. # endif
  91042. # endif
  91043. #endif
  91044. /*
  91045. * FLAC__lpc_compute_lp_coefficients()
  91046. * --------------------------------------------------------------------
  91047. * Computes LP coefficients for orders 1..max_order.
  91048. * Do not call if autoc[0] == 0.0. This means the signal is zero
  91049. * and there is no point in calculating a predictor.
  91050. *
  91051. * IN autoc[0,max_order] autocorrelation values
  91052. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  91053. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  91054. * *** IMPORTANT:
  91055. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  91056. * OUT error[0,max_order-1] error for each order (more
  91057. * specifically, the variance of
  91058. * the error signal times # of
  91059. * samples in the signal)
  91060. *
  91061. * Example: if max_order is 9, the LP coefficients for order 9 will be
  91062. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  91063. * in lp_coeff[7][0,7], etc.
  91064. */
  91065. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  91066. /*
  91067. * FLAC__lpc_quantize_coefficients()
  91068. * --------------------------------------------------------------------
  91069. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  91070. * must be less than 32 (sizeof(FLAC__int32)*8).
  91071. *
  91072. * IN lp_coeff[0,order-1] LP coefficients
  91073. * IN order LP order
  91074. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  91075. * desired precision (in bits, including sign
  91076. * bit) of largest coefficient
  91077. * OUT qlp_coeff[0,order-1] quantized coefficients
  91078. * OUT shift # of bits to shift right to get approximated
  91079. * LP coefficients. NOTE: could be negative.
  91080. * RETURN 0 => quantization OK
  91081. * 1 => coefficients require too much shifting for *shift to
  91082. * fit in the LPC subframe header. 'shift' is unset.
  91083. * 2 => coefficients are all zero, which is bad. 'shift' is
  91084. * unset.
  91085. */
  91086. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  91087. /*
  91088. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  91089. * --------------------------------------------------------------------
  91090. * Compute the residual signal obtained from sutracting the predicted
  91091. * signal from the original.
  91092. *
  91093. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  91094. * IN data_len length of original signal
  91095. * IN qlp_coeff[0,order-1] quantized LP coefficients
  91096. * IN order > 0 LP order
  91097. * IN lp_quantization quantization of LP coefficients in bits
  91098. * OUT residual[0,data_len-1] residual signal
  91099. */
  91100. 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[]);
  91101. 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[]);
  91102. #ifndef FLAC__NO_ASM
  91103. # ifdef FLAC__CPU_IA32
  91104. # ifdef FLAC__HAS_NASM
  91105. 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[]);
  91106. 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[]);
  91107. # endif
  91108. # endif
  91109. #endif
  91110. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  91111. /*
  91112. * FLAC__lpc_restore_signal()
  91113. * --------------------------------------------------------------------
  91114. * Restore the original signal by summing the residual and the
  91115. * predictor.
  91116. *
  91117. * IN residual[0,data_len-1] residual signal
  91118. * IN data_len length of original signal
  91119. * IN qlp_coeff[0,order-1] quantized LP coefficients
  91120. * IN order > 0 LP order
  91121. * IN lp_quantization quantization of LP coefficients in bits
  91122. * *** IMPORTANT: the caller must pass in the historical samples:
  91123. * IN data[-order,-1] previously-reconstructed historical samples
  91124. * OUT data[0,data_len-1] original signal
  91125. */
  91126. 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[]);
  91127. 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[]);
  91128. #ifndef FLAC__NO_ASM
  91129. # ifdef FLAC__CPU_IA32
  91130. # ifdef FLAC__HAS_NASM
  91131. 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[]);
  91132. 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[]);
  91133. # endif /* FLAC__HAS_NASM */
  91134. # elif defined FLAC__CPU_PPC
  91135. 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[]);
  91136. 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[]);
  91137. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  91138. #endif /* FLAC__NO_ASM */
  91139. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91140. /*
  91141. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  91142. * --------------------------------------------------------------------
  91143. * Compute the expected number of bits per residual signal sample
  91144. * based on the LP error (which is related to the residual variance).
  91145. *
  91146. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  91147. * IN total_samples > 0 # of samples in residual signal
  91148. * RETURN expected bits per sample
  91149. */
  91150. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  91151. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  91152. /*
  91153. * FLAC__lpc_compute_best_order()
  91154. * --------------------------------------------------------------------
  91155. * Compute the best order from the array of signal errors returned
  91156. * during coefficient computation.
  91157. *
  91158. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  91159. * IN max_order > 0 max LP order
  91160. * IN total_samples > 0 # of samples in residual signal
  91161. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  91162. * (includes warmup sample size and quantized LP coefficient)
  91163. * RETURN [1,max_order] best order
  91164. */
  91165. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  91166. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  91167. #endif
  91168. /********* End of inlined file: lpc.h *********/
  91169. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  91170. #include <stdio.h>
  91171. #endif
  91172. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91173. #ifndef M_LN2
  91174. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  91175. #define M_LN2 0.69314718055994530942
  91176. #endif
  91177. /* OPT: #undef'ing this may improve the speed on some architectures */
  91178. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  91179. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  91180. {
  91181. unsigned i;
  91182. for(i = 0; i < data_len; i++)
  91183. out[i] = in[i] * window[i];
  91184. }
  91185. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  91186. {
  91187. /* a readable, but slower, version */
  91188. #if 0
  91189. FLAC__real d;
  91190. unsigned i;
  91191. FLAC__ASSERT(lag > 0);
  91192. FLAC__ASSERT(lag <= data_len);
  91193. /*
  91194. * Technically we should subtract the mean first like so:
  91195. * for(i = 0; i < data_len; i++)
  91196. * data[i] -= mean;
  91197. * but it appears not to make enough of a difference to matter, and
  91198. * most signals are already closely centered around zero
  91199. */
  91200. while(lag--) {
  91201. for(i = lag, d = 0.0; i < data_len; i++)
  91202. d += data[i] * data[i - lag];
  91203. autoc[lag] = d;
  91204. }
  91205. #endif
  91206. /*
  91207. * this version tends to run faster because of better data locality
  91208. * ('data_len' is usually much larger than 'lag')
  91209. */
  91210. FLAC__real d;
  91211. unsigned sample, coeff;
  91212. const unsigned limit = data_len - lag;
  91213. FLAC__ASSERT(lag > 0);
  91214. FLAC__ASSERT(lag <= data_len);
  91215. for(coeff = 0; coeff < lag; coeff++)
  91216. autoc[coeff] = 0.0;
  91217. for(sample = 0; sample <= limit; sample++) {
  91218. d = data[sample];
  91219. for(coeff = 0; coeff < lag; coeff++)
  91220. autoc[coeff] += d * data[sample+coeff];
  91221. }
  91222. for(; sample < data_len; sample++) {
  91223. d = data[sample];
  91224. for(coeff = 0; coeff < data_len - sample; coeff++)
  91225. autoc[coeff] += d * data[sample+coeff];
  91226. }
  91227. }
  91228. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  91229. {
  91230. unsigned i, j;
  91231. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  91232. FLAC__ASSERT(0 != max_order);
  91233. FLAC__ASSERT(0 < *max_order);
  91234. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  91235. FLAC__ASSERT(autoc[0] != 0.0);
  91236. err = autoc[0];
  91237. for(i = 0; i < *max_order; i++) {
  91238. /* Sum up this iteration's reflection coefficient. */
  91239. r = -autoc[i+1];
  91240. for(j = 0; j < i; j++)
  91241. r -= lpc[j] * autoc[i-j];
  91242. ref[i] = (r/=err);
  91243. /* Update LPC coefficients and total error. */
  91244. lpc[i]=r;
  91245. for(j = 0; j < (i>>1); j++) {
  91246. FLAC__double tmp = lpc[j];
  91247. lpc[j] += r * lpc[i-1-j];
  91248. lpc[i-1-j] += r * tmp;
  91249. }
  91250. if(i & 1)
  91251. lpc[j] += lpc[j] * r;
  91252. err *= (1.0 - r * r);
  91253. /* save this order */
  91254. for(j = 0; j <= i; j++)
  91255. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  91256. error[i] = err;
  91257. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  91258. if(err == 0.0) {
  91259. *max_order = i+1;
  91260. return;
  91261. }
  91262. }
  91263. }
  91264. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  91265. {
  91266. unsigned i;
  91267. FLAC__double cmax;
  91268. FLAC__int32 qmax, qmin;
  91269. FLAC__ASSERT(precision > 0);
  91270. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  91271. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  91272. precision--;
  91273. qmax = 1 << precision;
  91274. qmin = -qmax;
  91275. qmax--;
  91276. /* calc cmax = max( |lp_coeff[i]| ) */
  91277. cmax = 0.0;
  91278. for(i = 0; i < order; i++) {
  91279. const FLAC__double d = fabs(lp_coeff[i]);
  91280. if(d > cmax)
  91281. cmax = d;
  91282. }
  91283. if(cmax <= 0.0) {
  91284. /* => coefficients are all 0, which means our constant-detect didn't work */
  91285. return 2;
  91286. }
  91287. else {
  91288. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  91289. const int min_shiftlimit = -max_shiftlimit - 1;
  91290. int log2cmax;
  91291. (void)frexp(cmax, &log2cmax);
  91292. log2cmax--;
  91293. *shift = (int)precision - log2cmax - 1;
  91294. if(*shift > max_shiftlimit)
  91295. *shift = max_shiftlimit;
  91296. else if(*shift < min_shiftlimit)
  91297. return 1;
  91298. }
  91299. if(*shift >= 0) {
  91300. FLAC__double error = 0.0;
  91301. FLAC__int32 q;
  91302. for(i = 0; i < order; i++) {
  91303. error += lp_coeff[i] * (1 << *shift);
  91304. #if 1 /* unfortunately lround() is C99 */
  91305. if(error >= 0.0)
  91306. q = (FLAC__int32)(error + 0.5);
  91307. else
  91308. q = (FLAC__int32)(error - 0.5);
  91309. #else
  91310. q = lround(error);
  91311. #endif
  91312. #ifdef FLAC__OVERFLOW_DETECT
  91313. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  91314. 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]);
  91315. else if(q < qmin)
  91316. 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]);
  91317. #endif
  91318. if(q > qmax)
  91319. q = qmax;
  91320. else if(q < qmin)
  91321. q = qmin;
  91322. error -= q;
  91323. qlp_coeff[i] = q;
  91324. }
  91325. }
  91326. /* negative shift is very rare but due to design flaw, negative shift is
  91327. * a NOP in the decoder, so it must be handled specially by scaling down
  91328. * coeffs
  91329. */
  91330. else {
  91331. const int nshift = -(*shift);
  91332. FLAC__double error = 0.0;
  91333. FLAC__int32 q;
  91334. #ifdef DEBUG
  91335. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  91336. #endif
  91337. for(i = 0; i < order; i++) {
  91338. error += lp_coeff[i] / (1 << nshift);
  91339. #if 1 /* unfortunately lround() is C99 */
  91340. if(error >= 0.0)
  91341. q = (FLAC__int32)(error + 0.5);
  91342. else
  91343. q = (FLAC__int32)(error - 0.5);
  91344. #else
  91345. q = lround(error);
  91346. #endif
  91347. #ifdef FLAC__OVERFLOW_DETECT
  91348. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  91349. 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]);
  91350. else if(q < qmin)
  91351. 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]);
  91352. #endif
  91353. if(q > qmax)
  91354. q = qmax;
  91355. else if(q < qmin)
  91356. q = qmin;
  91357. error -= q;
  91358. qlp_coeff[i] = q;
  91359. }
  91360. *shift = 0;
  91361. }
  91362. return 0;
  91363. }
  91364. 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[])
  91365. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  91366. {
  91367. FLAC__int64 sumo;
  91368. unsigned i, j;
  91369. FLAC__int32 sum;
  91370. const FLAC__int32 *history;
  91371. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  91372. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  91373. for(i=0;i<order;i++)
  91374. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  91375. fprintf(stderr,"\n");
  91376. #endif
  91377. FLAC__ASSERT(order > 0);
  91378. for(i = 0; i < data_len; i++) {
  91379. sumo = 0;
  91380. sum = 0;
  91381. history = data;
  91382. for(j = 0; j < order; j++) {
  91383. sum += qlp_coeff[j] * (*(--history));
  91384. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  91385. #if defined _MSC_VER
  91386. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  91387. 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);
  91388. #else
  91389. if(sumo > 2147483647ll || sumo < -2147483648ll)
  91390. 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);
  91391. #endif
  91392. }
  91393. *(residual++) = *(data++) - (sum >> lp_quantization);
  91394. }
  91395. /* Here's a slower but clearer version:
  91396. for(i = 0; i < data_len; i++) {
  91397. sum = 0;
  91398. for(j = 0; j < order; j++)
  91399. sum += qlp_coeff[j] * data[i-j-1];
  91400. residual[i] = data[i] - (sum >> lp_quantization);
  91401. }
  91402. */
  91403. }
  91404. #else /* fully unrolled version for normal use */
  91405. {
  91406. int i;
  91407. FLAC__int32 sum;
  91408. FLAC__ASSERT(order > 0);
  91409. FLAC__ASSERT(order <= 32);
  91410. /*
  91411. * We do unique versions up to 12th order since that's the subset limit.
  91412. * Also they are roughly ordered to match frequency of occurrence to
  91413. * minimize branching.
  91414. */
  91415. if(order <= 12) {
  91416. if(order > 8) {
  91417. if(order > 10) {
  91418. if(order == 12) {
  91419. for(i = 0; i < (int)data_len; i++) {
  91420. sum = 0;
  91421. sum += qlp_coeff[11] * data[i-12];
  91422. sum += qlp_coeff[10] * data[i-11];
  91423. sum += qlp_coeff[9] * data[i-10];
  91424. sum += qlp_coeff[8] * data[i-9];
  91425. sum += qlp_coeff[7] * data[i-8];
  91426. sum += qlp_coeff[6] * data[i-7];
  91427. sum += qlp_coeff[5] * data[i-6];
  91428. sum += qlp_coeff[4] * data[i-5];
  91429. sum += qlp_coeff[3] * data[i-4];
  91430. sum += qlp_coeff[2] * data[i-3];
  91431. sum += qlp_coeff[1] * data[i-2];
  91432. sum += qlp_coeff[0] * data[i-1];
  91433. residual[i] = data[i] - (sum >> lp_quantization);
  91434. }
  91435. }
  91436. else { /* order == 11 */
  91437. for(i = 0; i < (int)data_len; i++) {
  91438. sum = 0;
  91439. sum += qlp_coeff[10] * data[i-11];
  91440. sum += qlp_coeff[9] * data[i-10];
  91441. sum += qlp_coeff[8] * data[i-9];
  91442. sum += qlp_coeff[7] * data[i-8];
  91443. sum += qlp_coeff[6] * data[i-7];
  91444. sum += qlp_coeff[5] * data[i-6];
  91445. sum += qlp_coeff[4] * data[i-5];
  91446. sum += qlp_coeff[3] * data[i-4];
  91447. sum += qlp_coeff[2] * data[i-3];
  91448. sum += qlp_coeff[1] * data[i-2];
  91449. sum += qlp_coeff[0] * data[i-1];
  91450. residual[i] = data[i] - (sum >> lp_quantization);
  91451. }
  91452. }
  91453. }
  91454. else {
  91455. if(order == 10) {
  91456. for(i = 0; i < (int)data_len; i++) {
  91457. sum = 0;
  91458. sum += qlp_coeff[9] * data[i-10];
  91459. sum += qlp_coeff[8] * data[i-9];
  91460. sum += qlp_coeff[7] * data[i-8];
  91461. sum += qlp_coeff[6] * data[i-7];
  91462. sum += qlp_coeff[5] * data[i-6];
  91463. sum += qlp_coeff[4] * data[i-5];
  91464. sum += qlp_coeff[3] * data[i-4];
  91465. sum += qlp_coeff[2] * data[i-3];
  91466. sum += qlp_coeff[1] * data[i-2];
  91467. sum += qlp_coeff[0] * data[i-1];
  91468. residual[i] = data[i] - (sum >> lp_quantization);
  91469. }
  91470. }
  91471. else { /* order == 9 */
  91472. for(i = 0; i < (int)data_len; i++) {
  91473. sum = 0;
  91474. sum += qlp_coeff[8] * data[i-9];
  91475. sum += qlp_coeff[7] * data[i-8];
  91476. sum += qlp_coeff[6] * data[i-7];
  91477. sum += qlp_coeff[5] * data[i-6];
  91478. sum += qlp_coeff[4] * data[i-5];
  91479. sum += qlp_coeff[3] * data[i-4];
  91480. sum += qlp_coeff[2] * data[i-3];
  91481. sum += qlp_coeff[1] * data[i-2];
  91482. sum += qlp_coeff[0] * data[i-1];
  91483. residual[i] = data[i] - (sum >> lp_quantization);
  91484. }
  91485. }
  91486. }
  91487. }
  91488. else if(order > 4) {
  91489. if(order > 6) {
  91490. if(order == 8) {
  91491. for(i = 0; i < (int)data_len; i++) {
  91492. sum = 0;
  91493. sum += qlp_coeff[7] * data[i-8];
  91494. sum += qlp_coeff[6] * data[i-7];
  91495. sum += qlp_coeff[5] * data[i-6];
  91496. sum += qlp_coeff[4] * data[i-5];
  91497. sum += qlp_coeff[3] * data[i-4];
  91498. sum += qlp_coeff[2] * data[i-3];
  91499. sum += qlp_coeff[1] * data[i-2];
  91500. sum += qlp_coeff[0] * data[i-1];
  91501. residual[i] = data[i] - (sum >> lp_quantization);
  91502. }
  91503. }
  91504. else { /* order == 7 */
  91505. for(i = 0; i < (int)data_len; i++) {
  91506. sum = 0;
  91507. sum += qlp_coeff[6] * data[i-7];
  91508. sum += qlp_coeff[5] * data[i-6];
  91509. sum += qlp_coeff[4] * data[i-5];
  91510. sum += qlp_coeff[3] * data[i-4];
  91511. sum += qlp_coeff[2] * data[i-3];
  91512. sum += qlp_coeff[1] * data[i-2];
  91513. sum += qlp_coeff[0] * data[i-1];
  91514. residual[i] = data[i] - (sum >> lp_quantization);
  91515. }
  91516. }
  91517. }
  91518. else {
  91519. if(order == 6) {
  91520. for(i = 0; i < (int)data_len; i++) {
  91521. sum = 0;
  91522. sum += qlp_coeff[5] * data[i-6];
  91523. sum += qlp_coeff[4] * data[i-5];
  91524. sum += qlp_coeff[3] * data[i-4];
  91525. sum += qlp_coeff[2] * data[i-3];
  91526. sum += qlp_coeff[1] * data[i-2];
  91527. sum += qlp_coeff[0] * data[i-1];
  91528. residual[i] = data[i] - (sum >> lp_quantization);
  91529. }
  91530. }
  91531. else { /* order == 5 */
  91532. for(i = 0; i < (int)data_len; i++) {
  91533. sum = 0;
  91534. sum += qlp_coeff[4] * data[i-5];
  91535. sum += qlp_coeff[3] * data[i-4];
  91536. sum += qlp_coeff[2] * data[i-3];
  91537. sum += qlp_coeff[1] * data[i-2];
  91538. sum += qlp_coeff[0] * data[i-1];
  91539. residual[i] = data[i] - (sum >> lp_quantization);
  91540. }
  91541. }
  91542. }
  91543. }
  91544. else {
  91545. if(order > 2) {
  91546. if(order == 4) {
  91547. for(i = 0; i < (int)data_len; i++) {
  91548. sum = 0;
  91549. sum += qlp_coeff[3] * data[i-4];
  91550. sum += qlp_coeff[2] * data[i-3];
  91551. sum += qlp_coeff[1] * data[i-2];
  91552. sum += qlp_coeff[0] * data[i-1];
  91553. residual[i] = data[i] - (sum >> lp_quantization);
  91554. }
  91555. }
  91556. else { /* order == 3 */
  91557. for(i = 0; i < (int)data_len; i++) {
  91558. sum = 0;
  91559. sum += qlp_coeff[2] * data[i-3];
  91560. sum += qlp_coeff[1] * data[i-2];
  91561. sum += qlp_coeff[0] * data[i-1];
  91562. residual[i] = data[i] - (sum >> lp_quantization);
  91563. }
  91564. }
  91565. }
  91566. else {
  91567. if(order == 2) {
  91568. for(i = 0; i < (int)data_len; i++) {
  91569. sum = 0;
  91570. sum += qlp_coeff[1] * data[i-2];
  91571. sum += qlp_coeff[0] * data[i-1];
  91572. residual[i] = data[i] - (sum >> lp_quantization);
  91573. }
  91574. }
  91575. else { /* order == 1 */
  91576. for(i = 0; i < (int)data_len; i++)
  91577. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  91578. }
  91579. }
  91580. }
  91581. }
  91582. else { /* order > 12 */
  91583. for(i = 0; i < (int)data_len; i++) {
  91584. sum = 0;
  91585. switch(order) {
  91586. case 32: sum += qlp_coeff[31] * data[i-32];
  91587. case 31: sum += qlp_coeff[30] * data[i-31];
  91588. case 30: sum += qlp_coeff[29] * data[i-30];
  91589. case 29: sum += qlp_coeff[28] * data[i-29];
  91590. case 28: sum += qlp_coeff[27] * data[i-28];
  91591. case 27: sum += qlp_coeff[26] * data[i-27];
  91592. case 26: sum += qlp_coeff[25] * data[i-26];
  91593. case 25: sum += qlp_coeff[24] * data[i-25];
  91594. case 24: sum += qlp_coeff[23] * data[i-24];
  91595. case 23: sum += qlp_coeff[22] * data[i-23];
  91596. case 22: sum += qlp_coeff[21] * data[i-22];
  91597. case 21: sum += qlp_coeff[20] * data[i-21];
  91598. case 20: sum += qlp_coeff[19] * data[i-20];
  91599. case 19: sum += qlp_coeff[18] * data[i-19];
  91600. case 18: sum += qlp_coeff[17] * data[i-18];
  91601. case 17: sum += qlp_coeff[16] * data[i-17];
  91602. case 16: sum += qlp_coeff[15] * data[i-16];
  91603. case 15: sum += qlp_coeff[14] * data[i-15];
  91604. case 14: sum += qlp_coeff[13] * data[i-14];
  91605. case 13: sum += qlp_coeff[12] * data[i-13];
  91606. sum += qlp_coeff[11] * data[i-12];
  91607. sum += qlp_coeff[10] * data[i-11];
  91608. sum += qlp_coeff[ 9] * data[i-10];
  91609. sum += qlp_coeff[ 8] * data[i- 9];
  91610. sum += qlp_coeff[ 7] * data[i- 8];
  91611. sum += qlp_coeff[ 6] * data[i- 7];
  91612. sum += qlp_coeff[ 5] * data[i- 6];
  91613. sum += qlp_coeff[ 4] * data[i- 5];
  91614. sum += qlp_coeff[ 3] * data[i- 4];
  91615. sum += qlp_coeff[ 2] * data[i- 3];
  91616. sum += qlp_coeff[ 1] * data[i- 2];
  91617. sum += qlp_coeff[ 0] * data[i- 1];
  91618. }
  91619. residual[i] = data[i] - (sum >> lp_quantization);
  91620. }
  91621. }
  91622. }
  91623. #endif
  91624. 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[])
  91625. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  91626. {
  91627. unsigned i, j;
  91628. FLAC__int64 sum;
  91629. const FLAC__int32 *history;
  91630. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  91631. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  91632. for(i=0;i<order;i++)
  91633. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  91634. fprintf(stderr,"\n");
  91635. #endif
  91636. FLAC__ASSERT(order > 0);
  91637. for(i = 0; i < data_len; i++) {
  91638. sum = 0;
  91639. history = data;
  91640. for(j = 0; j < order; j++)
  91641. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  91642. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  91643. #if defined _MSC_VER
  91644. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  91645. #else
  91646. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  91647. #endif
  91648. break;
  91649. }
  91650. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  91651. #if defined _MSC_VER
  91652. 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));
  91653. #else
  91654. 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)));
  91655. #endif
  91656. break;
  91657. }
  91658. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  91659. }
  91660. }
  91661. #else /* fully unrolled version for normal use */
  91662. {
  91663. int i;
  91664. FLAC__int64 sum;
  91665. FLAC__ASSERT(order > 0);
  91666. FLAC__ASSERT(order <= 32);
  91667. /*
  91668. * We do unique versions up to 12th order since that's the subset limit.
  91669. * Also they are roughly ordered to match frequency of occurrence to
  91670. * minimize branching.
  91671. */
  91672. if(order <= 12) {
  91673. if(order > 8) {
  91674. if(order > 10) {
  91675. if(order == 12) {
  91676. for(i = 0; i < (int)data_len; i++) {
  91677. sum = 0;
  91678. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  91679. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  91680. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  91681. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91682. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91683. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91684. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91685. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91686. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91687. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91688. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91689. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91690. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91691. }
  91692. }
  91693. else { /* order == 11 */
  91694. for(i = 0; i < (int)data_len; i++) {
  91695. sum = 0;
  91696. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  91697. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  91698. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91699. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91700. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91701. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91702. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91703. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91704. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91705. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91706. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91707. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91708. }
  91709. }
  91710. }
  91711. else {
  91712. if(order == 10) {
  91713. for(i = 0; i < (int)data_len; i++) {
  91714. sum = 0;
  91715. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  91716. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91717. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91718. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91719. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91720. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91721. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91722. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91723. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91724. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91725. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91726. }
  91727. }
  91728. else { /* order == 9 */
  91729. for(i = 0; i < (int)data_len; i++) {
  91730. sum = 0;
  91731. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91732. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91733. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91734. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91735. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91736. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91737. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91738. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91739. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91740. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91741. }
  91742. }
  91743. }
  91744. }
  91745. else if(order > 4) {
  91746. if(order > 6) {
  91747. if(order == 8) {
  91748. for(i = 0; i < (int)data_len; i++) {
  91749. sum = 0;
  91750. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91751. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91752. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91753. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91754. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91755. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91756. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91757. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91758. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91759. }
  91760. }
  91761. else { /* order == 7 */
  91762. for(i = 0; i < (int)data_len; i++) {
  91763. sum = 0;
  91764. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91765. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91766. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91767. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91768. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91769. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91770. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91771. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91772. }
  91773. }
  91774. }
  91775. else {
  91776. if(order == 6) {
  91777. for(i = 0; i < (int)data_len; i++) {
  91778. sum = 0;
  91779. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91780. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91781. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91782. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91783. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91784. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91785. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91786. }
  91787. }
  91788. else { /* order == 5 */
  91789. for(i = 0; i < (int)data_len; i++) {
  91790. sum = 0;
  91791. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91792. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91793. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91794. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91795. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91796. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91797. }
  91798. }
  91799. }
  91800. }
  91801. else {
  91802. if(order > 2) {
  91803. if(order == 4) {
  91804. for(i = 0; i < (int)data_len; i++) {
  91805. sum = 0;
  91806. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91807. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91808. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91809. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91810. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91811. }
  91812. }
  91813. else { /* order == 3 */
  91814. for(i = 0; i < (int)data_len; i++) {
  91815. sum = 0;
  91816. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91817. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91818. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91819. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91820. }
  91821. }
  91822. }
  91823. else {
  91824. if(order == 2) {
  91825. for(i = 0; i < (int)data_len; i++) {
  91826. sum = 0;
  91827. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91828. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91829. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91830. }
  91831. }
  91832. else { /* order == 1 */
  91833. for(i = 0; i < (int)data_len; i++)
  91834. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  91835. }
  91836. }
  91837. }
  91838. }
  91839. else { /* order > 12 */
  91840. for(i = 0; i < (int)data_len; i++) {
  91841. sum = 0;
  91842. switch(order) {
  91843. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  91844. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  91845. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  91846. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  91847. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  91848. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  91849. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  91850. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  91851. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  91852. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  91853. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  91854. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  91855. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  91856. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  91857. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  91858. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  91859. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  91860. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  91861. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  91862. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  91863. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  91864. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  91865. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  91866. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  91867. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  91868. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  91869. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  91870. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  91871. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  91872. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  91873. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  91874. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  91875. }
  91876. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91877. }
  91878. }
  91879. }
  91880. #endif
  91881. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  91882. 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[])
  91883. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  91884. {
  91885. FLAC__int64 sumo;
  91886. unsigned i, j;
  91887. FLAC__int32 sum;
  91888. const FLAC__int32 *r = residual, *history;
  91889. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  91890. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  91891. for(i=0;i<order;i++)
  91892. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  91893. fprintf(stderr,"\n");
  91894. #endif
  91895. FLAC__ASSERT(order > 0);
  91896. for(i = 0; i < data_len; i++) {
  91897. sumo = 0;
  91898. sum = 0;
  91899. history = data;
  91900. for(j = 0; j < order; j++) {
  91901. sum += qlp_coeff[j] * (*(--history));
  91902. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  91903. #if defined _MSC_VER
  91904. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  91905. 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);
  91906. #else
  91907. if(sumo > 2147483647ll || sumo < -2147483648ll)
  91908. 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);
  91909. #endif
  91910. }
  91911. *(data++) = *(r++) + (sum >> lp_quantization);
  91912. }
  91913. /* Here's a slower but clearer version:
  91914. for(i = 0; i < data_len; i++) {
  91915. sum = 0;
  91916. for(j = 0; j < order; j++)
  91917. sum += qlp_coeff[j] * data[i-j-1];
  91918. data[i] = residual[i] + (sum >> lp_quantization);
  91919. }
  91920. */
  91921. }
  91922. #else /* fully unrolled version for normal use */
  91923. {
  91924. int i;
  91925. FLAC__int32 sum;
  91926. FLAC__ASSERT(order > 0);
  91927. FLAC__ASSERT(order <= 32);
  91928. /*
  91929. * We do unique versions up to 12th order since that's the subset limit.
  91930. * Also they are roughly ordered to match frequency of occurrence to
  91931. * minimize branching.
  91932. */
  91933. if(order <= 12) {
  91934. if(order > 8) {
  91935. if(order > 10) {
  91936. if(order == 12) {
  91937. for(i = 0; i < (int)data_len; i++) {
  91938. sum = 0;
  91939. sum += qlp_coeff[11] * data[i-12];
  91940. sum += qlp_coeff[10] * data[i-11];
  91941. sum += qlp_coeff[9] * data[i-10];
  91942. sum += qlp_coeff[8] * data[i-9];
  91943. sum += qlp_coeff[7] * data[i-8];
  91944. sum += qlp_coeff[6] * data[i-7];
  91945. sum += qlp_coeff[5] * data[i-6];
  91946. sum += qlp_coeff[4] * data[i-5];
  91947. sum += qlp_coeff[3] * data[i-4];
  91948. sum += qlp_coeff[2] * data[i-3];
  91949. sum += qlp_coeff[1] * data[i-2];
  91950. sum += qlp_coeff[0] * data[i-1];
  91951. data[i] = residual[i] + (sum >> lp_quantization);
  91952. }
  91953. }
  91954. else { /* order == 11 */
  91955. for(i = 0; i < (int)data_len; i++) {
  91956. sum = 0;
  91957. sum += qlp_coeff[10] * data[i-11];
  91958. sum += qlp_coeff[9] * data[i-10];
  91959. sum += qlp_coeff[8] * data[i-9];
  91960. sum += qlp_coeff[7] * data[i-8];
  91961. sum += qlp_coeff[6] * data[i-7];
  91962. sum += qlp_coeff[5] * data[i-6];
  91963. sum += qlp_coeff[4] * data[i-5];
  91964. sum += qlp_coeff[3] * data[i-4];
  91965. sum += qlp_coeff[2] * data[i-3];
  91966. sum += qlp_coeff[1] * data[i-2];
  91967. sum += qlp_coeff[0] * data[i-1];
  91968. data[i] = residual[i] + (sum >> lp_quantization);
  91969. }
  91970. }
  91971. }
  91972. else {
  91973. if(order == 10) {
  91974. for(i = 0; i < (int)data_len; i++) {
  91975. sum = 0;
  91976. sum += qlp_coeff[9] * data[i-10];
  91977. sum += qlp_coeff[8] * data[i-9];
  91978. sum += qlp_coeff[7] * data[i-8];
  91979. sum += qlp_coeff[6] * data[i-7];
  91980. sum += qlp_coeff[5] * data[i-6];
  91981. sum += qlp_coeff[4] * data[i-5];
  91982. sum += qlp_coeff[3] * data[i-4];
  91983. sum += qlp_coeff[2] * data[i-3];
  91984. sum += qlp_coeff[1] * data[i-2];
  91985. sum += qlp_coeff[0] * data[i-1];
  91986. data[i] = residual[i] + (sum >> lp_quantization);
  91987. }
  91988. }
  91989. else { /* order == 9 */
  91990. for(i = 0; i < (int)data_len; i++) {
  91991. sum = 0;
  91992. sum += qlp_coeff[8] * data[i-9];
  91993. sum += qlp_coeff[7] * data[i-8];
  91994. sum += qlp_coeff[6] * data[i-7];
  91995. sum += qlp_coeff[5] * data[i-6];
  91996. sum += qlp_coeff[4] * data[i-5];
  91997. sum += qlp_coeff[3] * data[i-4];
  91998. sum += qlp_coeff[2] * data[i-3];
  91999. sum += qlp_coeff[1] * data[i-2];
  92000. sum += qlp_coeff[0] * data[i-1];
  92001. data[i] = residual[i] + (sum >> lp_quantization);
  92002. }
  92003. }
  92004. }
  92005. }
  92006. else if(order > 4) {
  92007. if(order > 6) {
  92008. if(order == 8) {
  92009. for(i = 0; i < (int)data_len; i++) {
  92010. sum = 0;
  92011. sum += qlp_coeff[7] * data[i-8];
  92012. sum += qlp_coeff[6] * data[i-7];
  92013. sum += qlp_coeff[5] * data[i-6];
  92014. sum += qlp_coeff[4] * data[i-5];
  92015. sum += qlp_coeff[3] * data[i-4];
  92016. sum += qlp_coeff[2] * data[i-3];
  92017. sum += qlp_coeff[1] * data[i-2];
  92018. sum += qlp_coeff[0] * data[i-1];
  92019. data[i] = residual[i] + (sum >> lp_quantization);
  92020. }
  92021. }
  92022. else { /* order == 7 */
  92023. for(i = 0; i < (int)data_len; i++) {
  92024. sum = 0;
  92025. sum += qlp_coeff[6] * data[i-7];
  92026. sum += qlp_coeff[5] * data[i-6];
  92027. sum += qlp_coeff[4] * data[i-5];
  92028. sum += qlp_coeff[3] * data[i-4];
  92029. sum += qlp_coeff[2] * data[i-3];
  92030. sum += qlp_coeff[1] * data[i-2];
  92031. sum += qlp_coeff[0] * data[i-1];
  92032. data[i] = residual[i] + (sum >> lp_quantization);
  92033. }
  92034. }
  92035. }
  92036. else {
  92037. if(order == 6) {
  92038. for(i = 0; i < (int)data_len; i++) {
  92039. sum = 0;
  92040. sum += qlp_coeff[5] * data[i-6];
  92041. sum += qlp_coeff[4] * data[i-5];
  92042. sum += qlp_coeff[3] * data[i-4];
  92043. sum += qlp_coeff[2] * data[i-3];
  92044. sum += qlp_coeff[1] * data[i-2];
  92045. sum += qlp_coeff[0] * data[i-1];
  92046. data[i] = residual[i] + (sum >> lp_quantization);
  92047. }
  92048. }
  92049. else { /* order == 5 */
  92050. for(i = 0; i < (int)data_len; i++) {
  92051. sum = 0;
  92052. sum += qlp_coeff[4] * data[i-5];
  92053. sum += qlp_coeff[3] * data[i-4];
  92054. sum += qlp_coeff[2] * data[i-3];
  92055. sum += qlp_coeff[1] * data[i-2];
  92056. sum += qlp_coeff[0] * data[i-1];
  92057. data[i] = residual[i] + (sum >> lp_quantization);
  92058. }
  92059. }
  92060. }
  92061. }
  92062. else {
  92063. if(order > 2) {
  92064. if(order == 4) {
  92065. for(i = 0; i < (int)data_len; i++) {
  92066. sum = 0;
  92067. sum += qlp_coeff[3] * data[i-4];
  92068. sum += qlp_coeff[2] * data[i-3];
  92069. sum += qlp_coeff[1] * data[i-2];
  92070. sum += qlp_coeff[0] * data[i-1];
  92071. data[i] = residual[i] + (sum >> lp_quantization);
  92072. }
  92073. }
  92074. else { /* order == 3 */
  92075. for(i = 0; i < (int)data_len; i++) {
  92076. sum = 0;
  92077. sum += qlp_coeff[2] * data[i-3];
  92078. sum += qlp_coeff[1] * data[i-2];
  92079. sum += qlp_coeff[0] * data[i-1];
  92080. data[i] = residual[i] + (sum >> lp_quantization);
  92081. }
  92082. }
  92083. }
  92084. else {
  92085. if(order == 2) {
  92086. for(i = 0; i < (int)data_len; i++) {
  92087. sum = 0;
  92088. sum += qlp_coeff[1] * data[i-2];
  92089. sum += qlp_coeff[0] * data[i-1];
  92090. data[i] = residual[i] + (sum >> lp_quantization);
  92091. }
  92092. }
  92093. else { /* order == 1 */
  92094. for(i = 0; i < (int)data_len; i++)
  92095. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  92096. }
  92097. }
  92098. }
  92099. }
  92100. else { /* order > 12 */
  92101. for(i = 0; i < (int)data_len; i++) {
  92102. sum = 0;
  92103. switch(order) {
  92104. case 32: sum += qlp_coeff[31] * data[i-32];
  92105. case 31: sum += qlp_coeff[30] * data[i-31];
  92106. case 30: sum += qlp_coeff[29] * data[i-30];
  92107. case 29: sum += qlp_coeff[28] * data[i-29];
  92108. case 28: sum += qlp_coeff[27] * data[i-28];
  92109. case 27: sum += qlp_coeff[26] * data[i-27];
  92110. case 26: sum += qlp_coeff[25] * data[i-26];
  92111. case 25: sum += qlp_coeff[24] * data[i-25];
  92112. case 24: sum += qlp_coeff[23] * data[i-24];
  92113. case 23: sum += qlp_coeff[22] * data[i-23];
  92114. case 22: sum += qlp_coeff[21] * data[i-22];
  92115. case 21: sum += qlp_coeff[20] * data[i-21];
  92116. case 20: sum += qlp_coeff[19] * data[i-20];
  92117. case 19: sum += qlp_coeff[18] * data[i-19];
  92118. case 18: sum += qlp_coeff[17] * data[i-18];
  92119. case 17: sum += qlp_coeff[16] * data[i-17];
  92120. case 16: sum += qlp_coeff[15] * data[i-16];
  92121. case 15: sum += qlp_coeff[14] * data[i-15];
  92122. case 14: sum += qlp_coeff[13] * data[i-14];
  92123. case 13: sum += qlp_coeff[12] * data[i-13];
  92124. sum += qlp_coeff[11] * data[i-12];
  92125. sum += qlp_coeff[10] * data[i-11];
  92126. sum += qlp_coeff[ 9] * data[i-10];
  92127. sum += qlp_coeff[ 8] * data[i- 9];
  92128. sum += qlp_coeff[ 7] * data[i- 8];
  92129. sum += qlp_coeff[ 6] * data[i- 7];
  92130. sum += qlp_coeff[ 5] * data[i- 6];
  92131. sum += qlp_coeff[ 4] * data[i- 5];
  92132. sum += qlp_coeff[ 3] * data[i- 4];
  92133. sum += qlp_coeff[ 2] * data[i- 3];
  92134. sum += qlp_coeff[ 1] * data[i- 2];
  92135. sum += qlp_coeff[ 0] * data[i- 1];
  92136. }
  92137. data[i] = residual[i] + (sum >> lp_quantization);
  92138. }
  92139. }
  92140. }
  92141. #endif
  92142. 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[])
  92143. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  92144. {
  92145. unsigned i, j;
  92146. FLAC__int64 sum;
  92147. const FLAC__int32 *r = residual, *history;
  92148. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  92149. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  92150. for(i=0;i<order;i++)
  92151. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  92152. fprintf(stderr,"\n");
  92153. #endif
  92154. FLAC__ASSERT(order > 0);
  92155. for(i = 0; i < data_len; i++) {
  92156. sum = 0;
  92157. history = data;
  92158. for(j = 0; j < order; j++)
  92159. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  92160. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  92161. #ifdef _MSC_VER
  92162. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  92163. #else
  92164. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  92165. #endif
  92166. break;
  92167. }
  92168. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  92169. #ifdef _MSC_VER
  92170. 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));
  92171. #else
  92172. 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)));
  92173. #endif
  92174. break;
  92175. }
  92176. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  92177. }
  92178. }
  92179. #else /* fully unrolled version for normal use */
  92180. {
  92181. int i;
  92182. FLAC__int64 sum;
  92183. FLAC__ASSERT(order > 0);
  92184. FLAC__ASSERT(order <= 32);
  92185. /*
  92186. * We do unique versions up to 12th order since that's the subset limit.
  92187. * Also they are roughly ordered to match frequency of occurrence to
  92188. * minimize branching.
  92189. */
  92190. if(order <= 12) {
  92191. if(order > 8) {
  92192. if(order > 10) {
  92193. if(order == 12) {
  92194. for(i = 0; i < (int)data_len; i++) {
  92195. sum = 0;
  92196. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  92197. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  92198. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  92199. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92200. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92201. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92202. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92203. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92204. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92205. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92206. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92207. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92208. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92209. }
  92210. }
  92211. else { /* order == 11 */
  92212. for(i = 0; i < (int)data_len; i++) {
  92213. sum = 0;
  92214. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  92215. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  92216. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92217. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92218. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92219. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92220. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92221. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92222. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92223. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92224. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92225. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92226. }
  92227. }
  92228. }
  92229. else {
  92230. if(order == 10) {
  92231. for(i = 0; i < (int)data_len; i++) {
  92232. sum = 0;
  92233. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  92234. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92235. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92236. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92237. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92238. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92239. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92240. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92241. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92242. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92243. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92244. }
  92245. }
  92246. else { /* order == 9 */
  92247. for(i = 0; i < (int)data_len; i++) {
  92248. sum = 0;
  92249. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92250. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92251. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92252. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92253. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92254. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92255. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92256. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92257. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92258. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92259. }
  92260. }
  92261. }
  92262. }
  92263. else if(order > 4) {
  92264. if(order > 6) {
  92265. if(order == 8) {
  92266. for(i = 0; i < (int)data_len; i++) {
  92267. sum = 0;
  92268. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92269. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92270. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92271. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92272. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92273. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92274. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92275. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92276. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92277. }
  92278. }
  92279. else { /* order == 7 */
  92280. for(i = 0; i < (int)data_len; i++) {
  92281. sum = 0;
  92282. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92283. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92284. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92285. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92286. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92287. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92288. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92289. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92290. }
  92291. }
  92292. }
  92293. else {
  92294. if(order == 6) {
  92295. for(i = 0; i < (int)data_len; i++) {
  92296. sum = 0;
  92297. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92298. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92299. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92300. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92301. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92302. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92303. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92304. }
  92305. }
  92306. else { /* order == 5 */
  92307. for(i = 0; i < (int)data_len; i++) {
  92308. sum = 0;
  92309. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92310. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92311. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92312. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92313. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92314. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92315. }
  92316. }
  92317. }
  92318. }
  92319. else {
  92320. if(order > 2) {
  92321. if(order == 4) {
  92322. for(i = 0; i < (int)data_len; i++) {
  92323. sum = 0;
  92324. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92325. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92326. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92327. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92328. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92329. }
  92330. }
  92331. else { /* order == 3 */
  92332. for(i = 0; i < (int)data_len; i++) {
  92333. sum = 0;
  92334. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92335. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92336. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92337. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92338. }
  92339. }
  92340. }
  92341. else {
  92342. if(order == 2) {
  92343. for(i = 0; i < (int)data_len; i++) {
  92344. sum = 0;
  92345. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92346. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92347. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92348. }
  92349. }
  92350. else { /* order == 1 */
  92351. for(i = 0; i < (int)data_len; i++)
  92352. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  92353. }
  92354. }
  92355. }
  92356. }
  92357. else { /* order > 12 */
  92358. for(i = 0; i < (int)data_len; i++) {
  92359. sum = 0;
  92360. switch(order) {
  92361. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  92362. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  92363. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  92364. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  92365. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  92366. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  92367. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  92368. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  92369. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  92370. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  92371. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  92372. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  92373. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  92374. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  92375. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  92376. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  92377. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  92378. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  92379. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  92380. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  92381. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  92382. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  92383. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  92384. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  92385. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  92386. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  92387. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  92388. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  92389. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  92390. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  92391. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  92392. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  92393. }
  92394. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92395. }
  92396. }
  92397. }
  92398. #endif
  92399. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92400. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  92401. {
  92402. FLAC__double error_scale;
  92403. FLAC__ASSERT(total_samples > 0);
  92404. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  92405. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  92406. }
  92407. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  92408. {
  92409. if(lpc_error > 0.0) {
  92410. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  92411. if(bps >= 0.0)
  92412. return bps;
  92413. else
  92414. return 0.0;
  92415. }
  92416. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  92417. return 1e32;
  92418. }
  92419. else {
  92420. return 0.0;
  92421. }
  92422. }
  92423. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  92424. {
  92425. 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 */
  92426. FLAC__double bits, best_bits, error_scale;
  92427. FLAC__ASSERT(max_order > 0);
  92428. FLAC__ASSERT(total_samples > 0);
  92429. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  92430. best_index = 0;
  92431. best_bits = (unsigned)(-1);
  92432. for(index = 0, order = 1; index < max_order; index++, order++) {
  92433. 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);
  92434. if(bits < best_bits) {
  92435. best_index = index;
  92436. best_bits = bits;
  92437. }
  92438. }
  92439. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  92440. }
  92441. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  92442. #endif
  92443. /********* End of inlined file: lpc_flac.c *********/
  92444. /********* Start of inlined file: md5.c *********/
  92445. /********* Start of inlined file: juce_FlacHeader.h *********/
  92446. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92447. // tasks..
  92448. #define VERSION "1.2.1"
  92449. #define FLAC__NO_DLL 1
  92450. #ifdef _MSC_VER
  92451. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92452. #endif
  92453. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  92454. #define FLAC__SYS_DARWIN 1
  92455. #endif
  92456. /********* End of inlined file: juce_FlacHeader.h *********/
  92457. #if JUCE_USE_FLAC
  92458. #if HAVE_CONFIG_H
  92459. # include <config.h>
  92460. #endif
  92461. #include <stdlib.h> /* for malloc() */
  92462. #include <string.h> /* for memcpy() */
  92463. /********* Start of inlined file: md5.h *********/
  92464. #ifndef FLAC__PRIVATE__MD5_H
  92465. #define FLAC__PRIVATE__MD5_H
  92466. /*
  92467. * This is the header file for the MD5 message-digest algorithm.
  92468. * The algorithm is due to Ron Rivest. This code was
  92469. * written by Colin Plumb in 1993, no copyright is claimed.
  92470. * This code is in the public domain; do with it what you wish.
  92471. *
  92472. * Equivalent code is available from RSA Data Security, Inc.
  92473. * This code has been tested against that, and is equivalent,
  92474. * except that you don't need to include two pages of legalese
  92475. * with every copy.
  92476. *
  92477. * To compute the message digest of a chunk of bytes, declare an
  92478. * MD5Context structure, pass it to MD5Init, call MD5Update as
  92479. * needed on buffers full of bytes, and then call MD5Final, which
  92480. * will fill a supplied 16-byte array with the digest.
  92481. *
  92482. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  92483. * header definitions; now uses stuff from dpkg's config.h
  92484. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  92485. * Still in the public domain.
  92486. *
  92487. * Josh Coalson: made some changes to integrate with libFLAC.
  92488. * Still in the public domain, with no warranty.
  92489. */
  92490. typedef struct {
  92491. FLAC__uint32 in[16];
  92492. FLAC__uint32 buf[4];
  92493. FLAC__uint32 bytes[2];
  92494. FLAC__byte *internal_buf;
  92495. size_t capacity;
  92496. } FLAC__MD5Context;
  92497. void FLAC__MD5Init(FLAC__MD5Context *context);
  92498. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  92499. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  92500. #endif
  92501. /********* End of inlined file: md5.h *********/
  92502. #ifndef FLaC__INLINE
  92503. #define FLaC__INLINE
  92504. #endif
  92505. /*
  92506. * This code implements the MD5 message-digest algorithm.
  92507. * The algorithm is due to Ron Rivest. This code was
  92508. * written by Colin Plumb in 1993, no copyright is claimed.
  92509. * This code is in the public domain; do with it what you wish.
  92510. *
  92511. * Equivalent code is available from RSA Data Security, Inc.
  92512. * This code has been tested against that, and is equivalent,
  92513. * except that you don't need to include two pages of legalese
  92514. * with every copy.
  92515. *
  92516. * To compute the message digest of a chunk of bytes, declare an
  92517. * MD5Context structure, pass it to MD5Init, call MD5Update as
  92518. * needed on buffers full of bytes, and then call MD5Final, which
  92519. * will fill a supplied 16-byte array with the digest.
  92520. *
  92521. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  92522. * definitions; now uses stuff from dpkg's config.h.
  92523. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  92524. * Still in the public domain.
  92525. *
  92526. * Josh Coalson: made some changes to integrate with libFLAC.
  92527. * Still in the public domain.
  92528. */
  92529. /* The four core functions - F1 is optimized somewhat */
  92530. /* #define F1(x, y, z) (x & y | ~x & z) */
  92531. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  92532. #define F2(x, y, z) F1(z, x, y)
  92533. #define F3(x, y, z) (x ^ y ^ z)
  92534. #define F4(x, y, z) (y ^ (x | ~z))
  92535. /* This is the central step in the MD5 algorithm. */
  92536. #define MD5STEP(f,w,x,y,z,in,s) \
  92537. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  92538. /*
  92539. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  92540. * reflect the addition of 16 longwords of new data. MD5Update blocks
  92541. * the data and converts bytes into longwords for this routine.
  92542. */
  92543. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  92544. {
  92545. register FLAC__uint32 a, b, c, d;
  92546. a = buf[0];
  92547. b = buf[1];
  92548. c = buf[2];
  92549. d = buf[3];
  92550. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  92551. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  92552. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  92553. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  92554. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  92555. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  92556. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  92557. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  92558. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  92559. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  92560. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  92561. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  92562. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  92563. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  92564. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  92565. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  92566. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  92567. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  92568. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  92569. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  92570. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  92571. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  92572. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  92573. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  92574. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  92575. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  92576. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  92577. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  92578. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  92579. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  92580. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  92581. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  92582. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  92583. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  92584. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  92585. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  92586. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  92587. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  92588. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  92589. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  92590. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  92591. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  92592. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  92593. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  92594. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  92595. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  92596. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  92597. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  92598. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  92599. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  92600. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  92601. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  92602. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  92603. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  92604. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  92605. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  92606. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  92607. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  92608. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  92609. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  92610. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  92611. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  92612. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  92613. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  92614. buf[0] += a;
  92615. buf[1] += b;
  92616. buf[2] += c;
  92617. buf[3] += d;
  92618. }
  92619. #if WORDS_BIGENDIAN
  92620. //@@@@@@ OPT: use bswap/intrinsics
  92621. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  92622. {
  92623. register FLAC__uint32 x;
  92624. do {
  92625. x = *buf;
  92626. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  92627. *buf++ = (x >> 16) | (x << 16);
  92628. } while (--words);
  92629. }
  92630. static void byteSwapX16(FLAC__uint32 *buf)
  92631. {
  92632. register FLAC__uint32 x;
  92633. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92634. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92635. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92636. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92637. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92638. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92639. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92640. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92641. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92642. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92643. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92644. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92645. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92646. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92647. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92648. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  92649. }
  92650. #else
  92651. #define byteSwap(buf, words)
  92652. #define byteSwapX16(buf)
  92653. #endif
  92654. /*
  92655. * Update context to reflect the concatenation of another buffer full
  92656. * of bytes.
  92657. */
  92658. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  92659. {
  92660. FLAC__uint32 t;
  92661. /* Update byte count */
  92662. t = ctx->bytes[0];
  92663. if ((ctx->bytes[0] = t + len) < t)
  92664. ctx->bytes[1]++; /* Carry from low to high */
  92665. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  92666. if (t > len) {
  92667. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  92668. return;
  92669. }
  92670. /* First chunk is an odd size */
  92671. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  92672. byteSwapX16(ctx->in);
  92673. FLAC__MD5Transform(ctx->buf, ctx->in);
  92674. buf += t;
  92675. len -= t;
  92676. /* Process data in 64-byte chunks */
  92677. while (len >= 64) {
  92678. memcpy(ctx->in, buf, 64);
  92679. byteSwapX16(ctx->in);
  92680. FLAC__MD5Transform(ctx->buf, ctx->in);
  92681. buf += 64;
  92682. len -= 64;
  92683. }
  92684. /* Handle any remaining bytes of data. */
  92685. memcpy(ctx->in, buf, len);
  92686. }
  92687. /*
  92688. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  92689. * initialization constants.
  92690. */
  92691. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  92692. {
  92693. ctx->buf[0] = 0x67452301;
  92694. ctx->buf[1] = 0xefcdab89;
  92695. ctx->buf[2] = 0x98badcfe;
  92696. ctx->buf[3] = 0x10325476;
  92697. ctx->bytes[0] = 0;
  92698. ctx->bytes[1] = 0;
  92699. ctx->internal_buf = 0;
  92700. ctx->capacity = 0;
  92701. }
  92702. /*
  92703. * Final wrapup - pad to 64-byte boundary with the bit pattern
  92704. * 1 0* (64-bit count of bits processed, MSB-first)
  92705. */
  92706. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  92707. {
  92708. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  92709. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  92710. /* Set the first char of padding to 0x80. There is always room. */
  92711. *p++ = 0x80;
  92712. /* Bytes of padding needed to make 56 bytes (-8..55) */
  92713. count = 56 - 1 - count;
  92714. if (count < 0) { /* Padding forces an extra block */
  92715. memset(p, 0, count + 8);
  92716. byteSwapX16(ctx->in);
  92717. FLAC__MD5Transform(ctx->buf, ctx->in);
  92718. p = (FLAC__byte *)ctx->in;
  92719. count = 56;
  92720. }
  92721. memset(p, 0, count);
  92722. byteSwap(ctx->in, 14);
  92723. /* Append length in bits and transform */
  92724. ctx->in[14] = ctx->bytes[0] << 3;
  92725. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  92726. FLAC__MD5Transform(ctx->buf, ctx->in);
  92727. byteSwap(ctx->buf, 4);
  92728. memcpy(digest, ctx->buf, 16);
  92729. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  92730. if(0 != ctx->internal_buf) {
  92731. free(ctx->internal_buf);
  92732. ctx->internal_buf = 0;
  92733. ctx->capacity = 0;
  92734. }
  92735. }
  92736. /*
  92737. * Convert the incoming audio signal to a byte stream
  92738. */
  92739. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  92740. {
  92741. unsigned channel, sample;
  92742. register FLAC__int32 a_word;
  92743. register FLAC__byte *buf_ = buf;
  92744. #if WORDS_BIGENDIAN
  92745. #else
  92746. if(channels == 2 && bytes_per_sample == 2) {
  92747. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  92748. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  92749. for(sample = 0; sample < samples; sample++, buf1_+=2)
  92750. *buf1_ = (FLAC__int16)signal[1][sample];
  92751. }
  92752. else if(channels == 1 && bytes_per_sample == 2) {
  92753. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  92754. for(sample = 0; sample < samples; sample++)
  92755. *buf1_++ = (FLAC__int16)signal[0][sample];
  92756. }
  92757. else
  92758. #endif
  92759. if(bytes_per_sample == 2) {
  92760. if(channels == 2) {
  92761. for(sample = 0; sample < samples; sample++) {
  92762. a_word = signal[0][sample];
  92763. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92764. *buf_++ = (FLAC__byte)a_word;
  92765. a_word = signal[1][sample];
  92766. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92767. *buf_++ = (FLAC__byte)a_word;
  92768. }
  92769. }
  92770. else if(channels == 1) {
  92771. for(sample = 0; sample < samples; sample++) {
  92772. a_word = signal[0][sample];
  92773. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92774. *buf_++ = (FLAC__byte)a_word;
  92775. }
  92776. }
  92777. else {
  92778. for(sample = 0; sample < samples; sample++) {
  92779. for(channel = 0; channel < channels; channel++) {
  92780. a_word = signal[channel][sample];
  92781. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92782. *buf_++ = (FLAC__byte)a_word;
  92783. }
  92784. }
  92785. }
  92786. }
  92787. else if(bytes_per_sample == 3) {
  92788. if(channels == 2) {
  92789. for(sample = 0; sample < samples; sample++) {
  92790. a_word = signal[0][sample];
  92791. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92792. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92793. *buf_++ = (FLAC__byte)a_word;
  92794. a_word = signal[1][sample];
  92795. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92796. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92797. *buf_++ = (FLAC__byte)a_word;
  92798. }
  92799. }
  92800. else if(channels == 1) {
  92801. for(sample = 0; sample < samples; sample++) {
  92802. a_word = signal[0][sample];
  92803. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92804. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92805. *buf_++ = (FLAC__byte)a_word;
  92806. }
  92807. }
  92808. else {
  92809. for(sample = 0; sample < samples; sample++) {
  92810. for(channel = 0; channel < channels; channel++) {
  92811. a_word = signal[channel][sample];
  92812. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92813. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92814. *buf_++ = (FLAC__byte)a_word;
  92815. }
  92816. }
  92817. }
  92818. }
  92819. else if(bytes_per_sample == 1) {
  92820. if(channels == 2) {
  92821. for(sample = 0; sample < samples; sample++) {
  92822. a_word = signal[0][sample];
  92823. *buf_++ = (FLAC__byte)a_word;
  92824. a_word = signal[1][sample];
  92825. *buf_++ = (FLAC__byte)a_word;
  92826. }
  92827. }
  92828. else if(channels == 1) {
  92829. for(sample = 0; sample < samples; sample++) {
  92830. a_word = signal[0][sample];
  92831. *buf_++ = (FLAC__byte)a_word;
  92832. }
  92833. }
  92834. else {
  92835. for(sample = 0; sample < samples; sample++) {
  92836. for(channel = 0; channel < channels; channel++) {
  92837. a_word = signal[channel][sample];
  92838. *buf_++ = (FLAC__byte)a_word;
  92839. }
  92840. }
  92841. }
  92842. }
  92843. else { /* bytes_per_sample == 4, maybe optimize more later */
  92844. for(sample = 0; sample < samples; sample++) {
  92845. for(channel = 0; channel < channels; channel++) {
  92846. a_word = signal[channel][sample];
  92847. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92848. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92849. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92850. *buf_++ = (FLAC__byte)a_word;
  92851. }
  92852. }
  92853. }
  92854. }
  92855. /*
  92856. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  92857. */
  92858. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  92859. {
  92860. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  92861. /* overflow check */
  92862. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  92863. return false;
  92864. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  92865. return false;
  92866. if(ctx->capacity < bytes_needed) {
  92867. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  92868. if(0 == tmp) {
  92869. free(ctx->internal_buf);
  92870. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  92871. return false;
  92872. }
  92873. ctx->internal_buf = tmp;
  92874. ctx->capacity = bytes_needed;
  92875. }
  92876. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  92877. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  92878. return true;
  92879. }
  92880. #endif
  92881. /********* End of inlined file: md5.c *********/
  92882. /********* Start of inlined file: memory.c *********/
  92883. /********* Start of inlined file: juce_FlacHeader.h *********/
  92884. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92885. // tasks..
  92886. #define VERSION "1.2.1"
  92887. #define FLAC__NO_DLL 1
  92888. #ifdef _MSC_VER
  92889. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92890. #endif
  92891. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  92892. #define FLAC__SYS_DARWIN 1
  92893. #endif
  92894. /********* End of inlined file: juce_FlacHeader.h *********/
  92895. #if JUCE_USE_FLAC
  92896. #if HAVE_CONFIG_H
  92897. # include <config.h>
  92898. #endif
  92899. /********* Start of inlined file: memory.h *********/
  92900. #ifndef FLAC__PRIVATE__MEMORY_H
  92901. #define FLAC__PRIVATE__MEMORY_H
  92902. #ifdef HAVE_CONFIG_H
  92903. #include <config.h>
  92904. #endif
  92905. #include <stdlib.h> /* for size_t */
  92906. /* Returns the unaligned address returned by malloc.
  92907. * Use free() on this address to deallocate.
  92908. */
  92909. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  92910. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  92911. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  92912. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  92913. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  92914. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92915. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  92916. #endif
  92917. #endif
  92918. /********* End of inlined file: memory.h *********/
  92919. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  92920. {
  92921. void *x;
  92922. FLAC__ASSERT(0 != aligned_address);
  92923. #ifdef FLAC__ALIGN_MALLOC_DATA
  92924. /* align on 32-byte (256-bit) boundary */
  92925. x = safe_malloc_add_2op_(bytes, /*+*/31);
  92926. #ifdef SIZEOF_VOIDP
  92927. #if SIZEOF_VOIDP == 4
  92928. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  92929. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  92930. #elif SIZEOF_VOIDP == 8
  92931. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  92932. #else
  92933. # error Unsupported sizeof(void*)
  92934. #endif
  92935. #else
  92936. /* there's got to be a better way to do this right for all archs */
  92937. if(sizeof(void*) == sizeof(unsigned))
  92938. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  92939. else if(sizeof(void*) == sizeof(FLAC__uint64))
  92940. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  92941. else
  92942. return 0;
  92943. #endif
  92944. #else
  92945. x = safe_malloc_(bytes);
  92946. *aligned_address = x;
  92947. #endif
  92948. return x;
  92949. }
  92950. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  92951. {
  92952. FLAC__int32 *pu; /* unaligned pointer */
  92953. union { /* union needed to comply with C99 pointer aliasing rules */
  92954. FLAC__int32 *pa; /* aligned pointer */
  92955. void *pv; /* aligned pointer alias */
  92956. } u;
  92957. FLAC__ASSERT(elements > 0);
  92958. FLAC__ASSERT(0 != unaligned_pointer);
  92959. FLAC__ASSERT(0 != aligned_pointer);
  92960. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  92961. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  92962. return false;
  92963. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  92964. if(0 == pu) {
  92965. return false;
  92966. }
  92967. else {
  92968. if(*unaligned_pointer != 0)
  92969. free(*unaligned_pointer);
  92970. *unaligned_pointer = pu;
  92971. *aligned_pointer = u.pa;
  92972. return true;
  92973. }
  92974. }
  92975. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  92976. {
  92977. FLAC__uint32 *pu; /* unaligned pointer */
  92978. union { /* union needed to comply with C99 pointer aliasing rules */
  92979. FLAC__uint32 *pa; /* aligned pointer */
  92980. void *pv; /* aligned pointer alias */
  92981. } u;
  92982. FLAC__ASSERT(elements > 0);
  92983. FLAC__ASSERT(0 != unaligned_pointer);
  92984. FLAC__ASSERT(0 != aligned_pointer);
  92985. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  92986. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  92987. return false;
  92988. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  92989. if(0 == pu) {
  92990. return false;
  92991. }
  92992. else {
  92993. if(*unaligned_pointer != 0)
  92994. free(*unaligned_pointer);
  92995. *unaligned_pointer = pu;
  92996. *aligned_pointer = u.pa;
  92997. return true;
  92998. }
  92999. }
  93000. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  93001. {
  93002. FLAC__uint64 *pu; /* unaligned pointer */
  93003. union { /* union needed to comply with C99 pointer aliasing rules */
  93004. FLAC__uint64 *pa; /* aligned pointer */
  93005. void *pv; /* aligned pointer alias */
  93006. } u;
  93007. FLAC__ASSERT(elements > 0);
  93008. FLAC__ASSERT(0 != unaligned_pointer);
  93009. FLAC__ASSERT(0 != aligned_pointer);
  93010. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  93011. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  93012. return false;
  93013. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  93014. if(0 == pu) {
  93015. return false;
  93016. }
  93017. else {
  93018. if(*unaligned_pointer != 0)
  93019. free(*unaligned_pointer);
  93020. *unaligned_pointer = pu;
  93021. *aligned_pointer = u.pa;
  93022. return true;
  93023. }
  93024. }
  93025. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  93026. {
  93027. unsigned *pu; /* unaligned pointer */
  93028. union { /* union needed to comply with C99 pointer aliasing rules */
  93029. unsigned *pa; /* aligned pointer */
  93030. void *pv; /* aligned pointer alias */
  93031. } u;
  93032. FLAC__ASSERT(elements > 0);
  93033. FLAC__ASSERT(0 != unaligned_pointer);
  93034. FLAC__ASSERT(0 != aligned_pointer);
  93035. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  93036. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  93037. return false;
  93038. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  93039. if(0 == pu) {
  93040. return false;
  93041. }
  93042. else {
  93043. if(*unaligned_pointer != 0)
  93044. free(*unaligned_pointer);
  93045. *unaligned_pointer = pu;
  93046. *aligned_pointer = u.pa;
  93047. return true;
  93048. }
  93049. }
  93050. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93051. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  93052. {
  93053. FLAC__real *pu; /* unaligned pointer */
  93054. union { /* union needed to comply with C99 pointer aliasing rules */
  93055. FLAC__real *pa; /* aligned pointer */
  93056. void *pv; /* aligned pointer alias */
  93057. } u;
  93058. FLAC__ASSERT(elements > 0);
  93059. FLAC__ASSERT(0 != unaligned_pointer);
  93060. FLAC__ASSERT(0 != aligned_pointer);
  93061. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  93062. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  93063. return false;
  93064. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  93065. if(0 == pu) {
  93066. return false;
  93067. }
  93068. else {
  93069. if(*unaligned_pointer != 0)
  93070. free(*unaligned_pointer);
  93071. *unaligned_pointer = pu;
  93072. *aligned_pointer = u.pa;
  93073. return true;
  93074. }
  93075. }
  93076. #endif
  93077. #endif
  93078. /********* End of inlined file: memory.c *********/
  93079. /********* Start of inlined file: stream_decoder.c *********/
  93080. /********* Start of inlined file: juce_FlacHeader.h *********/
  93081. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93082. // tasks..
  93083. #define VERSION "1.2.1"
  93084. #define FLAC__NO_DLL 1
  93085. #ifdef _MSC_VER
  93086. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93087. #endif
  93088. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  93089. #define FLAC__SYS_DARWIN 1
  93090. #endif
  93091. /********* End of inlined file: juce_FlacHeader.h *********/
  93092. #if JUCE_USE_FLAC
  93093. #if HAVE_CONFIG_H
  93094. # include <config.h>
  93095. #endif
  93096. #if defined _MSC_VER || defined __MINGW32__
  93097. #include <io.h> /* for _setmode() */
  93098. #include <fcntl.h> /* for _O_BINARY */
  93099. #endif
  93100. #if defined __CYGWIN__ || defined __EMX__
  93101. #include <io.h> /* for setmode(), O_BINARY */
  93102. #include <fcntl.h> /* for _O_BINARY */
  93103. #endif
  93104. #include <stdio.h>
  93105. #include <stdlib.h> /* for malloc() */
  93106. #include <string.h> /* for memset/memcpy() */
  93107. #include <sys/stat.h> /* for stat() */
  93108. #include <sys/types.h> /* for off_t */
  93109. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  93110. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  93111. #define fseeko fseek
  93112. #define ftello ftell
  93113. #endif
  93114. #endif
  93115. /********* Start of inlined file: stream_decoder.h *********/
  93116. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  93117. #define FLAC__PROTECTED__STREAM_DECODER_H
  93118. #if FLAC__HAS_OGG
  93119. #include "include/private/ogg_decoder_aspect.h"
  93120. #endif
  93121. typedef struct FLAC__StreamDecoderProtected {
  93122. FLAC__StreamDecoderState state;
  93123. unsigned channels;
  93124. FLAC__ChannelAssignment channel_assignment;
  93125. unsigned bits_per_sample;
  93126. unsigned sample_rate; /* in Hz */
  93127. unsigned blocksize; /* in samples (per channel) */
  93128. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  93129. #if FLAC__HAS_OGG
  93130. FLAC__OggDecoderAspect ogg_decoder_aspect;
  93131. #endif
  93132. } FLAC__StreamDecoderProtected;
  93133. /*
  93134. * return the number of input bytes consumed
  93135. */
  93136. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  93137. #endif
  93138. /********* End of inlined file: stream_decoder.h *********/
  93139. #ifdef max
  93140. #undef max
  93141. #endif
  93142. #define max(a,b) ((a)>(b)?(a):(b))
  93143. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93144. #ifdef _MSC_VER
  93145. #define FLAC__U64L(x) x
  93146. #else
  93147. #define FLAC__U64L(x) x##LLU
  93148. #endif
  93149. /* technically this should be in an "export.c" but this is convenient enough */
  93150. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  93151. #if FLAC__HAS_OGG
  93152. 1
  93153. #else
  93154. 0
  93155. #endif
  93156. ;
  93157. /***********************************************************************
  93158. *
  93159. * Private static data
  93160. *
  93161. ***********************************************************************/
  93162. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  93163. /***********************************************************************
  93164. *
  93165. * Private class method prototypes
  93166. *
  93167. ***********************************************************************/
  93168. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  93169. static FILE *get_binary_stdin_(void);
  93170. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  93171. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  93172. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  93173. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  93174. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  93175. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  93176. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  93177. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  93178. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  93179. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  93180. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  93181. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  93182. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  93183. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  93184. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  93185. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  93186. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  93187. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  93188. 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);
  93189. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  93190. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  93191. #if FLAC__HAS_OGG
  93192. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  93193. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  93194. #endif
  93195. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  93196. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  93197. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  93198. #if FLAC__HAS_OGG
  93199. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  93200. #endif
  93201. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  93202. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  93203. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  93204. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  93205. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  93206. /***********************************************************************
  93207. *
  93208. * Private class data
  93209. *
  93210. ***********************************************************************/
  93211. typedef struct FLAC__StreamDecoderPrivate {
  93212. #if FLAC__HAS_OGG
  93213. FLAC__bool is_ogg;
  93214. #endif
  93215. FLAC__StreamDecoderReadCallback read_callback;
  93216. FLAC__StreamDecoderSeekCallback seek_callback;
  93217. FLAC__StreamDecoderTellCallback tell_callback;
  93218. FLAC__StreamDecoderLengthCallback length_callback;
  93219. FLAC__StreamDecoderEofCallback eof_callback;
  93220. FLAC__StreamDecoderWriteCallback write_callback;
  93221. FLAC__StreamDecoderMetadataCallback metadata_callback;
  93222. FLAC__StreamDecoderErrorCallback error_callback;
  93223. /* generic 32-bit datapath: */
  93224. 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[]);
  93225. /* generic 64-bit datapath: */
  93226. 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[]);
  93227. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  93228. 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[]);
  93229. /* 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: */
  93230. 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[]);
  93231. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  93232. void *client_data;
  93233. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  93234. FLAC__BitReader *input;
  93235. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  93236. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  93237. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  93238. unsigned output_capacity, output_channels;
  93239. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  93240. FLAC__uint64 samples_decoded;
  93241. FLAC__bool has_stream_info, has_seek_table;
  93242. FLAC__StreamMetadata stream_info;
  93243. FLAC__StreamMetadata seek_table;
  93244. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  93245. FLAC__byte *metadata_filter_ids;
  93246. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  93247. FLAC__Frame frame;
  93248. FLAC__bool cached; /* true if there is a byte in lookahead */
  93249. FLAC__CPUInfo cpuinfo;
  93250. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  93251. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  93252. /* unaligned (original) pointers to allocated data */
  93253. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  93254. 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 */
  93255. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  93256. FLAC__bool is_seeking;
  93257. FLAC__MD5Context md5context;
  93258. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  93259. /* (the rest of these are only used for seeking) */
  93260. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  93261. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  93262. FLAC__uint64 target_sample;
  93263. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  93264. #if FLAC__HAS_OGG
  93265. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  93266. #endif
  93267. } FLAC__StreamDecoderPrivate;
  93268. /***********************************************************************
  93269. *
  93270. * Public static class data
  93271. *
  93272. ***********************************************************************/
  93273. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  93274. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  93275. "FLAC__STREAM_DECODER_READ_METADATA",
  93276. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  93277. "FLAC__STREAM_DECODER_READ_FRAME",
  93278. "FLAC__STREAM_DECODER_END_OF_STREAM",
  93279. "FLAC__STREAM_DECODER_OGG_ERROR",
  93280. "FLAC__STREAM_DECODER_SEEK_ERROR",
  93281. "FLAC__STREAM_DECODER_ABORTED",
  93282. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  93283. "FLAC__STREAM_DECODER_UNINITIALIZED"
  93284. };
  93285. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  93286. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  93287. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  93288. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  93289. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  93290. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  93291. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  93292. };
  93293. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  93294. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  93295. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  93296. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  93297. };
  93298. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  93299. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  93300. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  93301. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  93302. };
  93303. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  93304. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  93305. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  93306. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  93307. };
  93308. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  93309. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  93310. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  93311. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  93312. };
  93313. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  93314. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  93315. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  93316. };
  93317. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  93318. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  93319. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  93320. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  93321. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  93322. };
  93323. /***********************************************************************
  93324. *
  93325. * Class constructor/destructor
  93326. *
  93327. ***********************************************************************/
  93328. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  93329. {
  93330. FLAC__StreamDecoder *decoder;
  93331. unsigned i;
  93332. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  93333. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  93334. if(decoder == 0) {
  93335. return 0;
  93336. }
  93337. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  93338. if(decoder->protected_ == 0) {
  93339. free(decoder);
  93340. return 0;
  93341. }
  93342. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  93343. if(decoder->private_ == 0) {
  93344. free(decoder->protected_);
  93345. free(decoder);
  93346. return 0;
  93347. }
  93348. decoder->private_->input = FLAC__bitreader_new();
  93349. if(decoder->private_->input == 0) {
  93350. free(decoder->private_);
  93351. free(decoder->protected_);
  93352. free(decoder);
  93353. return 0;
  93354. }
  93355. decoder->private_->metadata_filter_ids_capacity = 16;
  93356. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  93357. FLAC__bitreader_delete(decoder->private_->input);
  93358. free(decoder->private_);
  93359. free(decoder->protected_);
  93360. free(decoder);
  93361. return 0;
  93362. }
  93363. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  93364. decoder->private_->output[i] = 0;
  93365. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  93366. }
  93367. decoder->private_->output_capacity = 0;
  93368. decoder->private_->output_channels = 0;
  93369. decoder->private_->has_seek_table = false;
  93370. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  93371. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  93372. decoder->private_->file = 0;
  93373. set_defaults_dec(decoder);
  93374. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  93375. return decoder;
  93376. }
  93377. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  93378. {
  93379. unsigned i;
  93380. FLAC__ASSERT(0 != decoder);
  93381. FLAC__ASSERT(0 != decoder->protected_);
  93382. FLAC__ASSERT(0 != decoder->private_);
  93383. FLAC__ASSERT(0 != decoder->private_->input);
  93384. (void)FLAC__stream_decoder_finish(decoder);
  93385. if(0 != decoder->private_->metadata_filter_ids)
  93386. free(decoder->private_->metadata_filter_ids);
  93387. FLAC__bitreader_delete(decoder->private_->input);
  93388. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  93389. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  93390. free(decoder->private_);
  93391. free(decoder->protected_);
  93392. free(decoder);
  93393. }
  93394. /***********************************************************************
  93395. *
  93396. * Public class methods
  93397. *
  93398. ***********************************************************************/
  93399. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  93400. FLAC__StreamDecoder *decoder,
  93401. FLAC__StreamDecoderReadCallback read_callback,
  93402. FLAC__StreamDecoderSeekCallback seek_callback,
  93403. FLAC__StreamDecoderTellCallback tell_callback,
  93404. FLAC__StreamDecoderLengthCallback length_callback,
  93405. FLAC__StreamDecoderEofCallback eof_callback,
  93406. FLAC__StreamDecoderWriteCallback write_callback,
  93407. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93408. FLAC__StreamDecoderErrorCallback error_callback,
  93409. void *client_data,
  93410. FLAC__bool is_ogg
  93411. )
  93412. {
  93413. FLAC__ASSERT(0 != decoder);
  93414. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93415. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  93416. #if !FLAC__HAS_OGG
  93417. if(is_ogg)
  93418. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  93419. #endif
  93420. if(
  93421. 0 == read_callback ||
  93422. 0 == write_callback ||
  93423. 0 == error_callback ||
  93424. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  93425. )
  93426. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  93427. #if FLAC__HAS_OGG
  93428. decoder->private_->is_ogg = is_ogg;
  93429. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  93430. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  93431. #endif
  93432. /*
  93433. * get the CPU info and set the function pointers
  93434. */
  93435. FLAC__cpu_info(&decoder->private_->cpuinfo);
  93436. /* first default to the non-asm routines */
  93437. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  93438. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  93439. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  93440. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  93441. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  93442. /* now override with asm where appropriate */
  93443. #ifndef FLAC__NO_ASM
  93444. if(decoder->private_->cpuinfo.use_asm) {
  93445. #ifdef FLAC__CPU_IA32
  93446. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  93447. #ifdef FLAC__HAS_NASM
  93448. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  93449. if(decoder->private_->cpuinfo.data.ia32.bswap)
  93450. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  93451. #endif
  93452. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  93453. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  93454. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  93455. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  93456. }
  93457. else {
  93458. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  93459. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  93460. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  93461. }
  93462. #endif
  93463. #elif defined FLAC__CPU_PPC
  93464. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  93465. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  93466. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  93467. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  93468. }
  93469. #endif
  93470. }
  93471. #endif
  93472. /* from here on, errors are fatal */
  93473. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  93474. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93475. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  93476. }
  93477. decoder->private_->read_callback = read_callback;
  93478. decoder->private_->seek_callback = seek_callback;
  93479. decoder->private_->tell_callback = tell_callback;
  93480. decoder->private_->length_callback = length_callback;
  93481. decoder->private_->eof_callback = eof_callback;
  93482. decoder->private_->write_callback = write_callback;
  93483. decoder->private_->metadata_callback = metadata_callback;
  93484. decoder->private_->error_callback = error_callback;
  93485. decoder->private_->client_data = client_data;
  93486. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  93487. decoder->private_->samples_decoded = 0;
  93488. decoder->private_->has_stream_info = false;
  93489. decoder->private_->cached = false;
  93490. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  93491. decoder->private_->is_seeking = false;
  93492. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  93493. if(!FLAC__stream_decoder_reset(decoder)) {
  93494. /* above call sets the state for us */
  93495. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  93496. }
  93497. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  93498. }
  93499. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  93500. FLAC__StreamDecoder *decoder,
  93501. FLAC__StreamDecoderReadCallback read_callback,
  93502. FLAC__StreamDecoderSeekCallback seek_callback,
  93503. FLAC__StreamDecoderTellCallback tell_callback,
  93504. FLAC__StreamDecoderLengthCallback length_callback,
  93505. FLAC__StreamDecoderEofCallback eof_callback,
  93506. FLAC__StreamDecoderWriteCallback write_callback,
  93507. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93508. FLAC__StreamDecoderErrorCallback error_callback,
  93509. void *client_data
  93510. )
  93511. {
  93512. return init_stream_internal_dec(
  93513. decoder,
  93514. read_callback,
  93515. seek_callback,
  93516. tell_callback,
  93517. length_callback,
  93518. eof_callback,
  93519. write_callback,
  93520. metadata_callback,
  93521. error_callback,
  93522. client_data,
  93523. /*is_ogg=*/false
  93524. );
  93525. }
  93526. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  93527. FLAC__StreamDecoder *decoder,
  93528. FLAC__StreamDecoderReadCallback read_callback,
  93529. FLAC__StreamDecoderSeekCallback seek_callback,
  93530. FLAC__StreamDecoderTellCallback tell_callback,
  93531. FLAC__StreamDecoderLengthCallback length_callback,
  93532. FLAC__StreamDecoderEofCallback eof_callback,
  93533. FLAC__StreamDecoderWriteCallback write_callback,
  93534. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93535. FLAC__StreamDecoderErrorCallback error_callback,
  93536. void *client_data
  93537. )
  93538. {
  93539. return init_stream_internal_dec(
  93540. decoder,
  93541. read_callback,
  93542. seek_callback,
  93543. tell_callback,
  93544. length_callback,
  93545. eof_callback,
  93546. write_callback,
  93547. metadata_callback,
  93548. error_callback,
  93549. client_data,
  93550. /*is_ogg=*/true
  93551. );
  93552. }
  93553. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  93554. FLAC__StreamDecoder *decoder,
  93555. FILE *file,
  93556. FLAC__StreamDecoderWriteCallback write_callback,
  93557. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93558. FLAC__StreamDecoderErrorCallback error_callback,
  93559. void *client_data,
  93560. FLAC__bool is_ogg
  93561. )
  93562. {
  93563. FLAC__ASSERT(0 != decoder);
  93564. FLAC__ASSERT(0 != file);
  93565. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93566. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  93567. if(0 == write_callback || 0 == error_callback)
  93568. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  93569. /*
  93570. * To make sure that our file does not go unclosed after an error, we
  93571. * must assign the FILE pointer before any further error can occur in
  93572. * this routine.
  93573. */
  93574. if(file == stdin)
  93575. file = get_binary_stdin_(); /* just to be safe */
  93576. decoder->private_->file = file;
  93577. return init_stream_internal_dec(
  93578. decoder,
  93579. file_read_callback_dec,
  93580. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  93581. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  93582. decoder->private_->file == stdin? 0: file_length_callback_,
  93583. file_eof_callback_,
  93584. write_callback,
  93585. metadata_callback,
  93586. error_callback,
  93587. client_data,
  93588. is_ogg
  93589. );
  93590. }
  93591. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  93592. FLAC__StreamDecoder *decoder,
  93593. FILE *file,
  93594. FLAC__StreamDecoderWriteCallback write_callback,
  93595. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93596. FLAC__StreamDecoderErrorCallback error_callback,
  93597. void *client_data
  93598. )
  93599. {
  93600. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  93601. }
  93602. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  93603. FLAC__StreamDecoder *decoder,
  93604. FILE *file,
  93605. FLAC__StreamDecoderWriteCallback write_callback,
  93606. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93607. FLAC__StreamDecoderErrorCallback error_callback,
  93608. void *client_data
  93609. )
  93610. {
  93611. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  93612. }
  93613. static FLAC__StreamDecoderInitStatus init_file_internal_(
  93614. FLAC__StreamDecoder *decoder,
  93615. const char *filename,
  93616. FLAC__StreamDecoderWriteCallback write_callback,
  93617. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93618. FLAC__StreamDecoderErrorCallback error_callback,
  93619. void *client_data,
  93620. FLAC__bool is_ogg
  93621. )
  93622. {
  93623. FILE *file;
  93624. FLAC__ASSERT(0 != decoder);
  93625. /*
  93626. * To make sure that our file does not go unclosed after an error, we
  93627. * have to do the same entrance checks here that are later performed
  93628. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  93629. */
  93630. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93631. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  93632. if(0 == write_callback || 0 == error_callback)
  93633. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  93634. file = filename? fopen(filename, "rb") : stdin;
  93635. if(0 == file)
  93636. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  93637. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  93638. }
  93639. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  93640. FLAC__StreamDecoder *decoder,
  93641. const char *filename,
  93642. FLAC__StreamDecoderWriteCallback write_callback,
  93643. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93644. FLAC__StreamDecoderErrorCallback error_callback,
  93645. void *client_data
  93646. )
  93647. {
  93648. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  93649. }
  93650. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  93651. FLAC__StreamDecoder *decoder,
  93652. const char *filename,
  93653. FLAC__StreamDecoderWriteCallback write_callback,
  93654. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93655. FLAC__StreamDecoderErrorCallback error_callback,
  93656. void *client_data
  93657. )
  93658. {
  93659. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  93660. }
  93661. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  93662. {
  93663. FLAC__bool md5_failed = false;
  93664. unsigned i;
  93665. FLAC__ASSERT(0 != decoder);
  93666. FLAC__ASSERT(0 != decoder->private_);
  93667. FLAC__ASSERT(0 != decoder->protected_);
  93668. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  93669. return true;
  93670. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  93671. * always call FLAC__MD5Final()
  93672. */
  93673. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  93674. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  93675. free(decoder->private_->seek_table.data.seek_table.points);
  93676. decoder->private_->seek_table.data.seek_table.points = 0;
  93677. decoder->private_->has_seek_table = false;
  93678. }
  93679. FLAC__bitreader_free(decoder->private_->input);
  93680. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  93681. /* WATCHOUT:
  93682. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  93683. * output arrays have a buffer of up to 3 zeroes in front
  93684. * (at negative indices) for alignment purposes; we use 4
  93685. * to keep the data well-aligned.
  93686. */
  93687. if(0 != decoder->private_->output[i]) {
  93688. free(decoder->private_->output[i]-4);
  93689. decoder->private_->output[i] = 0;
  93690. }
  93691. if(0 != decoder->private_->residual_unaligned[i]) {
  93692. free(decoder->private_->residual_unaligned[i]);
  93693. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  93694. }
  93695. }
  93696. decoder->private_->output_capacity = 0;
  93697. decoder->private_->output_channels = 0;
  93698. #if FLAC__HAS_OGG
  93699. if(decoder->private_->is_ogg)
  93700. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  93701. #endif
  93702. if(0 != decoder->private_->file) {
  93703. if(decoder->private_->file != stdin)
  93704. fclose(decoder->private_->file);
  93705. decoder->private_->file = 0;
  93706. }
  93707. if(decoder->private_->do_md5_checking) {
  93708. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  93709. md5_failed = true;
  93710. }
  93711. decoder->private_->is_seeking = false;
  93712. set_defaults_dec(decoder);
  93713. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  93714. return !md5_failed;
  93715. }
  93716. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  93717. {
  93718. FLAC__ASSERT(0 != decoder);
  93719. FLAC__ASSERT(0 != decoder->private_);
  93720. FLAC__ASSERT(0 != decoder->protected_);
  93721. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93722. return false;
  93723. #if FLAC__HAS_OGG
  93724. /* can't check decoder->private_->is_ogg since that's not set until init time */
  93725. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  93726. return true;
  93727. #else
  93728. (void)value;
  93729. return false;
  93730. #endif
  93731. }
  93732. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  93733. {
  93734. FLAC__ASSERT(0 != decoder);
  93735. FLAC__ASSERT(0 != decoder->protected_);
  93736. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93737. return false;
  93738. decoder->protected_->md5_checking = value;
  93739. return true;
  93740. }
  93741. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  93742. {
  93743. FLAC__ASSERT(0 != decoder);
  93744. FLAC__ASSERT(0 != decoder->private_);
  93745. FLAC__ASSERT(0 != decoder->protected_);
  93746. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  93747. /* double protection */
  93748. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  93749. return false;
  93750. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93751. return false;
  93752. decoder->private_->metadata_filter[type] = true;
  93753. if(type == FLAC__METADATA_TYPE_APPLICATION)
  93754. decoder->private_->metadata_filter_ids_count = 0;
  93755. return true;
  93756. }
  93757. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  93758. {
  93759. FLAC__ASSERT(0 != decoder);
  93760. FLAC__ASSERT(0 != decoder->private_);
  93761. FLAC__ASSERT(0 != decoder->protected_);
  93762. FLAC__ASSERT(0 != id);
  93763. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93764. return false;
  93765. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  93766. return true;
  93767. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  93768. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  93769. 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))) {
  93770. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93771. return false;
  93772. }
  93773. decoder->private_->metadata_filter_ids_capacity *= 2;
  93774. }
  93775. 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));
  93776. decoder->private_->metadata_filter_ids_count++;
  93777. return true;
  93778. }
  93779. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  93780. {
  93781. unsigned i;
  93782. FLAC__ASSERT(0 != decoder);
  93783. FLAC__ASSERT(0 != decoder->private_);
  93784. FLAC__ASSERT(0 != decoder->protected_);
  93785. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93786. return false;
  93787. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  93788. decoder->private_->metadata_filter[i] = true;
  93789. decoder->private_->metadata_filter_ids_count = 0;
  93790. return true;
  93791. }
  93792. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  93793. {
  93794. FLAC__ASSERT(0 != decoder);
  93795. FLAC__ASSERT(0 != decoder->private_);
  93796. FLAC__ASSERT(0 != decoder->protected_);
  93797. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  93798. /* double protection */
  93799. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  93800. return false;
  93801. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93802. return false;
  93803. decoder->private_->metadata_filter[type] = false;
  93804. if(type == FLAC__METADATA_TYPE_APPLICATION)
  93805. decoder->private_->metadata_filter_ids_count = 0;
  93806. return true;
  93807. }
  93808. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  93809. {
  93810. FLAC__ASSERT(0 != decoder);
  93811. FLAC__ASSERT(0 != decoder->private_);
  93812. FLAC__ASSERT(0 != decoder->protected_);
  93813. FLAC__ASSERT(0 != id);
  93814. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93815. return false;
  93816. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  93817. return true;
  93818. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  93819. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  93820. 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))) {
  93821. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93822. return false;
  93823. }
  93824. decoder->private_->metadata_filter_ids_capacity *= 2;
  93825. }
  93826. 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));
  93827. decoder->private_->metadata_filter_ids_count++;
  93828. return true;
  93829. }
  93830. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  93831. {
  93832. FLAC__ASSERT(0 != decoder);
  93833. FLAC__ASSERT(0 != decoder->private_);
  93834. FLAC__ASSERT(0 != decoder->protected_);
  93835. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93836. return false;
  93837. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  93838. decoder->private_->metadata_filter_ids_count = 0;
  93839. return true;
  93840. }
  93841. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  93842. {
  93843. FLAC__ASSERT(0 != decoder);
  93844. FLAC__ASSERT(0 != decoder->protected_);
  93845. return decoder->protected_->state;
  93846. }
  93847. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  93848. {
  93849. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  93850. }
  93851. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  93852. {
  93853. FLAC__ASSERT(0 != decoder);
  93854. FLAC__ASSERT(0 != decoder->protected_);
  93855. return decoder->protected_->md5_checking;
  93856. }
  93857. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  93858. {
  93859. FLAC__ASSERT(0 != decoder);
  93860. FLAC__ASSERT(0 != decoder->protected_);
  93861. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  93862. }
  93863. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  93864. {
  93865. FLAC__ASSERT(0 != decoder);
  93866. FLAC__ASSERT(0 != decoder->protected_);
  93867. return decoder->protected_->channels;
  93868. }
  93869. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  93870. {
  93871. FLAC__ASSERT(0 != decoder);
  93872. FLAC__ASSERT(0 != decoder->protected_);
  93873. return decoder->protected_->channel_assignment;
  93874. }
  93875. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  93876. {
  93877. FLAC__ASSERT(0 != decoder);
  93878. FLAC__ASSERT(0 != decoder->protected_);
  93879. return decoder->protected_->bits_per_sample;
  93880. }
  93881. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  93882. {
  93883. FLAC__ASSERT(0 != decoder);
  93884. FLAC__ASSERT(0 != decoder->protected_);
  93885. return decoder->protected_->sample_rate;
  93886. }
  93887. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  93888. {
  93889. FLAC__ASSERT(0 != decoder);
  93890. FLAC__ASSERT(0 != decoder->protected_);
  93891. return decoder->protected_->blocksize;
  93892. }
  93893. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  93894. {
  93895. FLAC__ASSERT(0 != decoder);
  93896. FLAC__ASSERT(0 != decoder->private_);
  93897. FLAC__ASSERT(0 != position);
  93898. #if FLAC__HAS_OGG
  93899. if(decoder->private_->is_ogg)
  93900. return false;
  93901. #endif
  93902. if(0 == decoder->private_->tell_callback)
  93903. return false;
  93904. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  93905. return false;
  93906. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  93907. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  93908. return false;
  93909. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  93910. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  93911. return true;
  93912. }
  93913. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  93914. {
  93915. FLAC__ASSERT(0 != decoder);
  93916. FLAC__ASSERT(0 != decoder->private_);
  93917. FLAC__ASSERT(0 != decoder->protected_);
  93918. decoder->private_->samples_decoded = 0;
  93919. decoder->private_->do_md5_checking = false;
  93920. #if FLAC__HAS_OGG
  93921. if(decoder->private_->is_ogg)
  93922. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  93923. #endif
  93924. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  93925. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93926. return false;
  93927. }
  93928. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  93929. return true;
  93930. }
  93931. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  93932. {
  93933. FLAC__ASSERT(0 != decoder);
  93934. FLAC__ASSERT(0 != decoder->private_);
  93935. FLAC__ASSERT(0 != decoder->protected_);
  93936. if(!FLAC__stream_decoder_flush(decoder)) {
  93937. /* above call sets the state for us */
  93938. return false;
  93939. }
  93940. #if FLAC__HAS_OGG
  93941. /*@@@ could go in !internal_reset_hack block below */
  93942. if(decoder->private_->is_ogg)
  93943. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  93944. #endif
  93945. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  93946. * (internal_reset_hack) don't try to rewind since we are already at
  93947. * the beginning of the stream and don't want to fail if the input is
  93948. * not seekable.
  93949. */
  93950. if(!decoder->private_->internal_reset_hack) {
  93951. if(decoder->private_->file == stdin)
  93952. return false; /* can't rewind stdin, reset fails */
  93953. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  93954. return false; /* seekable and seek fails, reset fails */
  93955. }
  93956. else
  93957. decoder->private_->internal_reset_hack = false;
  93958. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  93959. decoder->private_->has_stream_info = false;
  93960. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  93961. free(decoder->private_->seek_table.data.seek_table.points);
  93962. decoder->private_->seek_table.data.seek_table.points = 0;
  93963. decoder->private_->has_seek_table = false;
  93964. }
  93965. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  93966. /*
  93967. * This goes in reset() and not flush() because according to the spec, a
  93968. * fixed-blocksize stream must stay that way through the whole stream.
  93969. */
  93970. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  93971. /* We initialize the FLAC__MD5Context even though we may never use it. This
  93972. * is because md5 checking may be turned on to start and then turned off if
  93973. * a seek occurs. So we init the context here and finalize it in
  93974. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  93975. * properly.
  93976. */
  93977. FLAC__MD5Init(&decoder->private_->md5context);
  93978. decoder->private_->first_frame_offset = 0;
  93979. decoder->private_->unparseable_frame_count = 0;
  93980. return true;
  93981. }
  93982. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  93983. {
  93984. FLAC__bool got_a_frame;
  93985. FLAC__ASSERT(0 != decoder);
  93986. FLAC__ASSERT(0 != decoder->protected_);
  93987. while(1) {
  93988. switch(decoder->protected_->state) {
  93989. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  93990. if(!find_metadata_(decoder))
  93991. return false; /* above function sets the status for us */
  93992. break;
  93993. case FLAC__STREAM_DECODER_READ_METADATA:
  93994. if(!read_metadata_(decoder))
  93995. return false; /* above function sets the status for us */
  93996. else
  93997. return true;
  93998. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  93999. if(!frame_sync_(decoder))
  94000. return true; /* above function sets the status for us */
  94001. break;
  94002. case FLAC__STREAM_DECODER_READ_FRAME:
  94003. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  94004. return false; /* above function sets the status for us */
  94005. if(got_a_frame)
  94006. return true; /* above function sets the status for us */
  94007. break;
  94008. case FLAC__STREAM_DECODER_END_OF_STREAM:
  94009. case FLAC__STREAM_DECODER_ABORTED:
  94010. return true;
  94011. default:
  94012. FLAC__ASSERT(0);
  94013. return false;
  94014. }
  94015. }
  94016. }
  94017. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  94018. {
  94019. FLAC__ASSERT(0 != decoder);
  94020. FLAC__ASSERT(0 != decoder->protected_);
  94021. while(1) {
  94022. switch(decoder->protected_->state) {
  94023. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  94024. if(!find_metadata_(decoder))
  94025. return false; /* above function sets the status for us */
  94026. break;
  94027. case FLAC__STREAM_DECODER_READ_METADATA:
  94028. if(!read_metadata_(decoder))
  94029. return false; /* above function sets the status for us */
  94030. break;
  94031. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  94032. case FLAC__STREAM_DECODER_READ_FRAME:
  94033. case FLAC__STREAM_DECODER_END_OF_STREAM:
  94034. case FLAC__STREAM_DECODER_ABORTED:
  94035. return true;
  94036. default:
  94037. FLAC__ASSERT(0);
  94038. return false;
  94039. }
  94040. }
  94041. }
  94042. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  94043. {
  94044. FLAC__bool dummy;
  94045. FLAC__ASSERT(0 != decoder);
  94046. FLAC__ASSERT(0 != decoder->protected_);
  94047. while(1) {
  94048. switch(decoder->protected_->state) {
  94049. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  94050. if(!find_metadata_(decoder))
  94051. return false; /* above function sets the status for us */
  94052. break;
  94053. case FLAC__STREAM_DECODER_READ_METADATA:
  94054. if(!read_metadata_(decoder))
  94055. return false; /* above function sets the status for us */
  94056. break;
  94057. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  94058. if(!frame_sync_(decoder))
  94059. return true; /* above function sets the status for us */
  94060. break;
  94061. case FLAC__STREAM_DECODER_READ_FRAME:
  94062. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  94063. return false; /* above function sets the status for us */
  94064. break;
  94065. case FLAC__STREAM_DECODER_END_OF_STREAM:
  94066. case FLAC__STREAM_DECODER_ABORTED:
  94067. return true;
  94068. default:
  94069. FLAC__ASSERT(0);
  94070. return false;
  94071. }
  94072. }
  94073. }
  94074. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  94075. {
  94076. FLAC__bool got_a_frame;
  94077. FLAC__ASSERT(0 != decoder);
  94078. FLAC__ASSERT(0 != decoder->protected_);
  94079. while(1) {
  94080. switch(decoder->protected_->state) {
  94081. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  94082. case FLAC__STREAM_DECODER_READ_METADATA:
  94083. return false; /* above function sets the status for us */
  94084. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  94085. if(!frame_sync_(decoder))
  94086. return true; /* above function sets the status for us */
  94087. break;
  94088. case FLAC__STREAM_DECODER_READ_FRAME:
  94089. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  94090. return false; /* above function sets the status for us */
  94091. if(got_a_frame)
  94092. return true; /* above function sets the status for us */
  94093. break;
  94094. case FLAC__STREAM_DECODER_END_OF_STREAM:
  94095. case FLAC__STREAM_DECODER_ABORTED:
  94096. return true;
  94097. default:
  94098. FLAC__ASSERT(0);
  94099. return false;
  94100. }
  94101. }
  94102. }
  94103. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  94104. {
  94105. FLAC__uint64 length;
  94106. FLAC__ASSERT(0 != decoder);
  94107. if(
  94108. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  94109. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  94110. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  94111. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  94112. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  94113. )
  94114. return false;
  94115. if(0 == decoder->private_->seek_callback)
  94116. return false;
  94117. FLAC__ASSERT(decoder->private_->seek_callback);
  94118. FLAC__ASSERT(decoder->private_->tell_callback);
  94119. FLAC__ASSERT(decoder->private_->length_callback);
  94120. FLAC__ASSERT(decoder->private_->eof_callback);
  94121. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  94122. return false;
  94123. decoder->private_->is_seeking = true;
  94124. /* turn off md5 checking if a seek is attempted */
  94125. decoder->private_->do_md5_checking = false;
  94126. /* 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) */
  94127. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  94128. decoder->private_->is_seeking = false;
  94129. return false;
  94130. }
  94131. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  94132. if(
  94133. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  94134. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  94135. ) {
  94136. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  94137. /* above call sets the state for us */
  94138. decoder->private_->is_seeking = false;
  94139. return false;
  94140. }
  94141. /* check this again in case we didn't know total_samples the first time */
  94142. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  94143. decoder->private_->is_seeking = false;
  94144. return false;
  94145. }
  94146. }
  94147. {
  94148. const FLAC__bool ok =
  94149. #if FLAC__HAS_OGG
  94150. decoder->private_->is_ogg?
  94151. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  94152. #endif
  94153. seek_to_absolute_sample_(decoder, length, sample)
  94154. ;
  94155. decoder->private_->is_seeking = false;
  94156. return ok;
  94157. }
  94158. }
  94159. /***********************************************************************
  94160. *
  94161. * Protected class methods
  94162. *
  94163. ***********************************************************************/
  94164. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  94165. {
  94166. FLAC__ASSERT(0 != decoder);
  94167. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94168. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  94169. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  94170. }
  94171. /***********************************************************************
  94172. *
  94173. * Private class methods
  94174. *
  94175. ***********************************************************************/
  94176. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  94177. {
  94178. #if FLAC__HAS_OGG
  94179. decoder->private_->is_ogg = false;
  94180. #endif
  94181. decoder->private_->read_callback = 0;
  94182. decoder->private_->seek_callback = 0;
  94183. decoder->private_->tell_callback = 0;
  94184. decoder->private_->length_callback = 0;
  94185. decoder->private_->eof_callback = 0;
  94186. decoder->private_->write_callback = 0;
  94187. decoder->private_->metadata_callback = 0;
  94188. decoder->private_->error_callback = 0;
  94189. decoder->private_->client_data = 0;
  94190. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  94191. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  94192. decoder->private_->metadata_filter_ids_count = 0;
  94193. decoder->protected_->md5_checking = false;
  94194. #if FLAC__HAS_OGG
  94195. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  94196. #endif
  94197. }
  94198. /*
  94199. * This will forcibly set stdin to binary mode (for OSes that require it)
  94200. */
  94201. FILE *get_binary_stdin_(void)
  94202. {
  94203. /* if something breaks here it is probably due to the presence or
  94204. * absence of an underscore before the identifiers 'setmode',
  94205. * 'fileno', and/or 'O_BINARY'; check your system header files.
  94206. */
  94207. #if defined _MSC_VER || defined __MINGW32__
  94208. _setmode(_fileno(stdin), _O_BINARY);
  94209. #elif defined __CYGWIN__
  94210. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  94211. setmode(_fileno(stdin), _O_BINARY);
  94212. #elif defined __EMX__
  94213. setmode(fileno(stdin), O_BINARY);
  94214. #endif
  94215. return stdin;
  94216. }
  94217. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  94218. {
  94219. unsigned i;
  94220. FLAC__int32 *tmp;
  94221. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  94222. return true;
  94223. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  94224. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  94225. if(0 != decoder->private_->output[i]) {
  94226. free(decoder->private_->output[i]-4);
  94227. decoder->private_->output[i] = 0;
  94228. }
  94229. if(0 != decoder->private_->residual_unaligned[i]) {
  94230. free(decoder->private_->residual_unaligned[i]);
  94231. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  94232. }
  94233. }
  94234. for(i = 0; i < channels; i++) {
  94235. /* WATCHOUT:
  94236. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  94237. * output arrays have a buffer of up to 3 zeroes in front
  94238. * (at negative indices) for alignment purposes; we use 4
  94239. * to keep the data well-aligned.
  94240. */
  94241. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  94242. if(tmp == 0) {
  94243. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94244. return false;
  94245. }
  94246. memset(tmp, 0, sizeof(FLAC__int32)*4);
  94247. decoder->private_->output[i] = tmp + 4;
  94248. /* WATCHOUT:
  94249. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  94250. */
  94251. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  94252. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94253. return false;
  94254. }
  94255. }
  94256. decoder->private_->output_capacity = size;
  94257. decoder->private_->output_channels = channels;
  94258. return true;
  94259. }
  94260. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  94261. {
  94262. size_t i;
  94263. FLAC__ASSERT(0 != decoder);
  94264. FLAC__ASSERT(0 != decoder->private_);
  94265. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  94266. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  94267. return true;
  94268. return false;
  94269. }
  94270. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  94271. {
  94272. FLAC__uint32 x;
  94273. unsigned i, id_;
  94274. FLAC__bool first = true;
  94275. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94276. for(i = id_ = 0; i < 4; ) {
  94277. if(decoder->private_->cached) {
  94278. x = (FLAC__uint32)decoder->private_->lookahead;
  94279. decoder->private_->cached = false;
  94280. }
  94281. else {
  94282. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94283. return false; /* read_callback_ sets the state for us */
  94284. }
  94285. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  94286. first = true;
  94287. i++;
  94288. id_ = 0;
  94289. continue;
  94290. }
  94291. if(x == ID3V2_TAG_[id_]) {
  94292. id_++;
  94293. i = 0;
  94294. if(id_ == 3) {
  94295. if(!skip_id3v2_tag_(decoder))
  94296. return false; /* skip_id3v2_tag_ sets the state for us */
  94297. }
  94298. continue;
  94299. }
  94300. id_ = 0;
  94301. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94302. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  94303. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94304. return false; /* read_callback_ sets the state for us */
  94305. /* 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 */
  94306. /* else we have to check if the second byte is the end of a sync code */
  94307. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94308. decoder->private_->lookahead = (FLAC__byte)x;
  94309. decoder->private_->cached = true;
  94310. }
  94311. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  94312. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  94313. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  94314. return true;
  94315. }
  94316. }
  94317. i = 0;
  94318. if(first) {
  94319. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  94320. first = false;
  94321. }
  94322. }
  94323. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  94324. return true;
  94325. }
  94326. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  94327. {
  94328. FLAC__bool is_last;
  94329. FLAC__uint32 i, x, type, length;
  94330. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94331. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  94332. return false; /* read_callback_ sets the state for us */
  94333. is_last = x? true : false;
  94334. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  94335. return false; /* read_callback_ sets the state for us */
  94336. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  94337. return false; /* read_callback_ sets the state for us */
  94338. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  94339. if(!read_metadata_streaminfo_(decoder, is_last, length))
  94340. return false;
  94341. decoder->private_->has_stream_info = true;
  94342. 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))
  94343. decoder->private_->do_md5_checking = false;
  94344. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  94345. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  94346. }
  94347. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  94348. if(!read_metadata_seektable_(decoder, is_last, length))
  94349. return false;
  94350. decoder->private_->has_seek_table = true;
  94351. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  94352. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  94353. }
  94354. else {
  94355. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  94356. unsigned real_length = length;
  94357. FLAC__StreamMetadata block;
  94358. block.is_last = is_last;
  94359. block.type = (FLAC__MetadataType)type;
  94360. block.length = length;
  94361. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  94362. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  94363. return false; /* read_callback_ sets the state for us */
  94364. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  94365. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  94366. return false;
  94367. }
  94368. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  94369. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  94370. skip_it = !skip_it;
  94371. }
  94372. if(skip_it) {
  94373. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  94374. return false; /* read_callback_ sets the state for us */
  94375. }
  94376. else {
  94377. switch(type) {
  94378. case FLAC__METADATA_TYPE_PADDING:
  94379. /* skip the padding bytes */
  94380. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  94381. return false; /* read_callback_ sets the state for us */
  94382. break;
  94383. case FLAC__METADATA_TYPE_APPLICATION:
  94384. /* remember, we read the ID already */
  94385. if(real_length > 0) {
  94386. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  94387. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94388. return false;
  94389. }
  94390. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  94391. return false; /* read_callback_ sets the state for us */
  94392. }
  94393. else
  94394. block.data.application.data = 0;
  94395. break;
  94396. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  94397. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  94398. return false;
  94399. break;
  94400. case FLAC__METADATA_TYPE_CUESHEET:
  94401. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  94402. return false;
  94403. break;
  94404. case FLAC__METADATA_TYPE_PICTURE:
  94405. if(!read_metadata_picture_(decoder, &block.data.picture))
  94406. return false;
  94407. break;
  94408. case FLAC__METADATA_TYPE_STREAMINFO:
  94409. case FLAC__METADATA_TYPE_SEEKTABLE:
  94410. FLAC__ASSERT(0);
  94411. break;
  94412. default:
  94413. if(real_length > 0) {
  94414. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  94415. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94416. return false;
  94417. }
  94418. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  94419. return false; /* read_callback_ sets the state for us */
  94420. }
  94421. else
  94422. block.data.unknown.data = 0;
  94423. break;
  94424. }
  94425. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  94426. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  94427. /* now we have to free any malloc()ed data in the block */
  94428. switch(type) {
  94429. case FLAC__METADATA_TYPE_PADDING:
  94430. break;
  94431. case FLAC__METADATA_TYPE_APPLICATION:
  94432. if(0 != block.data.application.data)
  94433. free(block.data.application.data);
  94434. break;
  94435. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  94436. if(0 != block.data.vorbis_comment.vendor_string.entry)
  94437. free(block.data.vorbis_comment.vendor_string.entry);
  94438. if(block.data.vorbis_comment.num_comments > 0)
  94439. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  94440. if(0 != block.data.vorbis_comment.comments[i].entry)
  94441. free(block.data.vorbis_comment.comments[i].entry);
  94442. if(0 != block.data.vorbis_comment.comments)
  94443. free(block.data.vorbis_comment.comments);
  94444. break;
  94445. case FLAC__METADATA_TYPE_CUESHEET:
  94446. if(block.data.cue_sheet.num_tracks > 0)
  94447. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  94448. if(0 != block.data.cue_sheet.tracks[i].indices)
  94449. free(block.data.cue_sheet.tracks[i].indices);
  94450. if(0 != block.data.cue_sheet.tracks)
  94451. free(block.data.cue_sheet.tracks);
  94452. break;
  94453. case FLAC__METADATA_TYPE_PICTURE:
  94454. if(0 != block.data.picture.mime_type)
  94455. free(block.data.picture.mime_type);
  94456. if(0 != block.data.picture.description)
  94457. free(block.data.picture.description);
  94458. if(0 != block.data.picture.data)
  94459. free(block.data.picture.data);
  94460. break;
  94461. case FLAC__METADATA_TYPE_STREAMINFO:
  94462. case FLAC__METADATA_TYPE_SEEKTABLE:
  94463. FLAC__ASSERT(0);
  94464. default:
  94465. if(0 != block.data.unknown.data)
  94466. free(block.data.unknown.data);
  94467. break;
  94468. }
  94469. }
  94470. }
  94471. if(is_last) {
  94472. /* if this fails, it's OK, it's just a hint for the seek routine */
  94473. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  94474. decoder->private_->first_frame_offset = 0;
  94475. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94476. }
  94477. return true;
  94478. }
  94479. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  94480. {
  94481. FLAC__uint32 x;
  94482. unsigned bits, used_bits = 0;
  94483. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94484. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  94485. decoder->private_->stream_info.is_last = is_last;
  94486. decoder->private_->stream_info.length = length;
  94487. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  94488. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  94489. return false; /* read_callback_ sets the state for us */
  94490. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  94491. used_bits += bits;
  94492. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  94493. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  94494. return false; /* read_callback_ sets the state for us */
  94495. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  94496. used_bits += bits;
  94497. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  94498. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  94499. return false; /* read_callback_ sets the state for us */
  94500. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  94501. used_bits += bits;
  94502. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  94503. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  94504. return false; /* read_callback_ sets the state for us */
  94505. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  94506. used_bits += bits;
  94507. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  94508. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  94509. return false; /* read_callback_ sets the state for us */
  94510. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  94511. used_bits += bits;
  94512. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  94513. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  94514. return false; /* read_callback_ sets the state for us */
  94515. decoder->private_->stream_info.data.stream_info.channels = x+1;
  94516. used_bits += bits;
  94517. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  94518. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  94519. return false; /* read_callback_ sets the state for us */
  94520. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  94521. used_bits += bits;
  94522. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  94523. 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))
  94524. return false; /* read_callback_ sets the state for us */
  94525. used_bits += bits;
  94526. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  94527. return false; /* read_callback_ sets the state for us */
  94528. used_bits += 16*8;
  94529. /* skip the rest of the block */
  94530. FLAC__ASSERT(used_bits % 8 == 0);
  94531. length -= (used_bits / 8);
  94532. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  94533. return false; /* read_callback_ sets the state for us */
  94534. return true;
  94535. }
  94536. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  94537. {
  94538. FLAC__uint32 i, x;
  94539. FLAC__uint64 xx;
  94540. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94541. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  94542. decoder->private_->seek_table.is_last = is_last;
  94543. decoder->private_->seek_table.length = length;
  94544. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  94545. /* use realloc since we may pass through here several times (e.g. after seeking) */
  94546. 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)))) {
  94547. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94548. return false;
  94549. }
  94550. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  94551. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  94552. return false; /* read_callback_ sets the state for us */
  94553. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  94554. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  94555. return false; /* read_callback_ sets the state for us */
  94556. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  94557. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  94558. return false; /* read_callback_ sets the state for us */
  94559. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  94560. }
  94561. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  94562. /* if there is a partial point left, skip over it */
  94563. if(length > 0) {
  94564. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  94565. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  94566. return false; /* read_callback_ sets the state for us */
  94567. }
  94568. return true;
  94569. }
  94570. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  94571. {
  94572. FLAC__uint32 i;
  94573. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94574. /* read vendor string */
  94575. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  94576. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  94577. return false; /* read_callback_ sets the state for us */
  94578. if(obj->vendor_string.length > 0) {
  94579. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  94580. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94581. return false;
  94582. }
  94583. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  94584. return false; /* read_callback_ sets the state for us */
  94585. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  94586. }
  94587. else
  94588. obj->vendor_string.entry = 0;
  94589. /* read num comments */
  94590. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  94591. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  94592. return false; /* read_callback_ sets the state for us */
  94593. /* read comments */
  94594. if(obj->num_comments > 0) {
  94595. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  94596. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94597. return false;
  94598. }
  94599. for(i = 0; i < obj->num_comments; i++) {
  94600. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  94601. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  94602. return false; /* read_callback_ sets the state for us */
  94603. if(obj->comments[i].length > 0) {
  94604. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  94605. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94606. return false;
  94607. }
  94608. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  94609. return false; /* read_callback_ sets the state for us */
  94610. obj->comments[i].entry[obj->comments[i].length] = '\0';
  94611. }
  94612. else
  94613. obj->comments[i].entry = 0;
  94614. }
  94615. }
  94616. else {
  94617. obj->comments = 0;
  94618. }
  94619. return true;
  94620. }
  94621. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  94622. {
  94623. FLAC__uint32 i, j, x;
  94624. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94625. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  94626. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  94627. 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))
  94628. return false; /* read_callback_ sets the state for us */
  94629. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  94630. return false; /* read_callback_ sets the state for us */
  94631. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  94632. return false; /* read_callback_ sets the state for us */
  94633. obj->is_cd = x? true : false;
  94634. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  94635. return false; /* read_callback_ sets the state for us */
  94636. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  94637. return false; /* read_callback_ sets the state for us */
  94638. obj->num_tracks = x;
  94639. if(obj->num_tracks > 0) {
  94640. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  94641. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94642. return false;
  94643. }
  94644. for(i = 0; i < obj->num_tracks; i++) {
  94645. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  94646. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  94647. return false; /* read_callback_ sets the state for us */
  94648. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  94649. return false; /* read_callback_ sets the state for us */
  94650. track->number = (FLAC__byte)x;
  94651. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  94652. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  94653. return false; /* read_callback_ sets the state for us */
  94654. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  94655. return false; /* read_callback_ sets the state for us */
  94656. track->type = x;
  94657. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  94658. return false; /* read_callback_ sets the state for us */
  94659. track->pre_emphasis = x;
  94660. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  94661. return false; /* read_callback_ sets the state for us */
  94662. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  94663. return false; /* read_callback_ sets the state for us */
  94664. track->num_indices = (FLAC__byte)x;
  94665. if(track->num_indices > 0) {
  94666. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  94667. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94668. return false;
  94669. }
  94670. for(j = 0; j < track->num_indices; j++) {
  94671. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  94672. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  94673. return false; /* read_callback_ sets the state for us */
  94674. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  94675. return false; /* read_callback_ sets the state for us */
  94676. index->number = (FLAC__byte)x;
  94677. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  94678. return false; /* read_callback_ sets the state for us */
  94679. }
  94680. }
  94681. }
  94682. }
  94683. return true;
  94684. }
  94685. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  94686. {
  94687. FLAC__uint32 x;
  94688. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94689. /* read type */
  94690. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  94691. return false; /* read_callback_ sets the state for us */
  94692. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  94693. /* read MIME type */
  94694. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  94695. return false; /* read_callback_ sets the state for us */
  94696. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  94697. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94698. return false;
  94699. }
  94700. if(x > 0) {
  94701. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  94702. return false; /* read_callback_ sets the state for us */
  94703. }
  94704. obj->mime_type[x] = '\0';
  94705. /* read description */
  94706. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  94707. return false; /* read_callback_ sets the state for us */
  94708. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  94709. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94710. return false;
  94711. }
  94712. if(x > 0) {
  94713. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  94714. return false; /* read_callback_ sets the state for us */
  94715. }
  94716. obj->description[x] = '\0';
  94717. /* read width */
  94718. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  94719. return false; /* read_callback_ sets the state for us */
  94720. /* read height */
  94721. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  94722. return false; /* read_callback_ sets the state for us */
  94723. /* read depth */
  94724. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  94725. return false; /* read_callback_ sets the state for us */
  94726. /* read colors */
  94727. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  94728. return false; /* read_callback_ sets the state for us */
  94729. /* read data */
  94730. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  94731. return false; /* read_callback_ sets the state for us */
  94732. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  94733. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94734. return false;
  94735. }
  94736. if(obj->data_length > 0) {
  94737. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  94738. return false; /* read_callback_ sets the state for us */
  94739. }
  94740. return true;
  94741. }
  94742. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  94743. {
  94744. FLAC__uint32 x;
  94745. unsigned i, skip;
  94746. /* skip the version and flags bytes */
  94747. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  94748. return false; /* read_callback_ sets the state for us */
  94749. /* get the size (in bytes) to skip */
  94750. skip = 0;
  94751. for(i = 0; i < 4; i++) {
  94752. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94753. return false; /* read_callback_ sets the state for us */
  94754. skip <<= 7;
  94755. skip |= (x & 0x7f);
  94756. }
  94757. /* skip the rest of the tag */
  94758. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  94759. return false; /* read_callback_ sets the state for us */
  94760. return true;
  94761. }
  94762. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  94763. {
  94764. FLAC__uint32 x;
  94765. FLAC__bool first = true;
  94766. /* If we know the total number of samples in the stream, stop if we've read that many. */
  94767. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  94768. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  94769. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  94770. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  94771. return true;
  94772. }
  94773. }
  94774. /* make sure we're byte aligned */
  94775. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  94776. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  94777. return false; /* read_callback_ sets the state for us */
  94778. }
  94779. while(1) {
  94780. if(decoder->private_->cached) {
  94781. x = (FLAC__uint32)decoder->private_->lookahead;
  94782. decoder->private_->cached = false;
  94783. }
  94784. else {
  94785. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94786. return false; /* read_callback_ sets the state for us */
  94787. }
  94788. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94789. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  94790. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94791. return false; /* read_callback_ sets the state for us */
  94792. /* 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 */
  94793. /* else we have to check if the second byte is the end of a sync code */
  94794. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94795. decoder->private_->lookahead = (FLAC__byte)x;
  94796. decoder->private_->cached = true;
  94797. }
  94798. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  94799. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  94800. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  94801. return true;
  94802. }
  94803. }
  94804. if(first) {
  94805. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  94806. first = false;
  94807. }
  94808. }
  94809. return true;
  94810. }
  94811. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  94812. {
  94813. unsigned channel;
  94814. unsigned i;
  94815. FLAC__int32 mid, side;
  94816. unsigned frame_crc; /* the one we calculate from the input stream */
  94817. FLAC__uint32 x;
  94818. *got_a_frame = false;
  94819. /* init the CRC */
  94820. frame_crc = 0;
  94821. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  94822. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  94823. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  94824. if(!read_frame_header_(decoder))
  94825. return false;
  94826. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  94827. return true;
  94828. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  94829. return false;
  94830. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  94831. /*
  94832. * first figure the correct bits-per-sample of the subframe
  94833. */
  94834. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  94835. switch(decoder->private_->frame.header.channel_assignment) {
  94836. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  94837. /* no adjustment needed */
  94838. break;
  94839. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  94840. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94841. if(channel == 1)
  94842. bps++;
  94843. break;
  94844. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  94845. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94846. if(channel == 0)
  94847. bps++;
  94848. break;
  94849. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  94850. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94851. if(channel == 1)
  94852. bps++;
  94853. break;
  94854. default:
  94855. FLAC__ASSERT(0);
  94856. }
  94857. /*
  94858. * now read it
  94859. */
  94860. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  94861. return false;
  94862. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  94863. return true;
  94864. }
  94865. if(!read_zero_padding_(decoder))
  94866. return false;
  94867. 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) */
  94868. return true;
  94869. /*
  94870. * Read the frame CRC-16 from the footer and check
  94871. */
  94872. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  94873. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  94874. return false; /* read_callback_ sets the state for us */
  94875. if(frame_crc == x) {
  94876. if(do_full_decode) {
  94877. /* Undo any special channel coding */
  94878. switch(decoder->private_->frame.header.channel_assignment) {
  94879. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  94880. /* do nothing */
  94881. break;
  94882. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  94883. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94884. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  94885. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  94886. break;
  94887. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  94888. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94889. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  94890. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  94891. break;
  94892. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  94893. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94894. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  94895. #if 1
  94896. mid = decoder->private_->output[0][i];
  94897. side = decoder->private_->output[1][i];
  94898. mid <<= 1;
  94899. mid |= (side & 1); /* i.e. if 'side' is odd... */
  94900. decoder->private_->output[0][i] = (mid + side) >> 1;
  94901. decoder->private_->output[1][i] = (mid - side) >> 1;
  94902. #else
  94903. /* OPT: without 'side' temp variable */
  94904. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  94905. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  94906. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  94907. #endif
  94908. }
  94909. break;
  94910. default:
  94911. FLAC__ASSERT(0);
  94912. break;
  94913. }
  94914. }
  94915. }
  94916. else {
  94917. /* Bad frame, emit error and zero the output signal */
  94918. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  94919. if(do_full_decode) {
  94920. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  94921. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  94922. }
  94923. }
  94924. }
  94925. *got_a_frame = true;
  94926. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  94927. if(decoder->private_->next_fixed_block_size)
  94928. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  94929. /* put the latest values into the public section of the decoder instance */
  94930. decoder->protected_->channels = decoder->private_->frame.header.channels;
  94931. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  94932. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  94933. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  94934. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  94935. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  94936. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  94937. /* write it */
  94938. if(do_full_decode) {
  94939. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  94940. return false;
  94941. }
  94942. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94943. return true;
  94944. }
  94945. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  94946. {
  94947. FLAC__uint32 x;
  94948. FLAC__uint64 xx;
  94949. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  94950. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  94951. unsigned raw_header_len;
  94952. FLAC__bool is_unparseable = false;
  94953. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94954. /* init the raw header with the saved bits from synchronization */
  94955. raw_header[0] = decoder->private_->header_warmup[0];
  94956. raw_header[1] = decoder->private_->header_warmup[1];
  94957. raw_header_len = 2;
  94958. /* check to make sure that reserved bit is 0 */
  94959. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  94960. is_unparseable = true;
  94961. /*
  94962. * Note that along the way as we read the header, we look for a sync
  94963. * code inside. If we find one it would indicate that our original
  94964. * sync was bad since there cannot be a sync code in a valid header.
  94965. *
  94966. * Three kinds of things can go wrong when reading the frame header:
  94967. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  94968. * If we don't find a sync code, it can end up looking like we read
  94969. * a valid but unparseable header, until getting to the frame header
  94970. * CRC. Even then we could get a false positive on the CRC.
  94971. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  94972. * future encoder).
  94973. * 3) We may be on a damaged frame which appears valid but unparseable.
  94974. *
  94975. * For all these reasons, we try and read a complete frame header as
  94976. * long as it seems valid, even if unparseable, up until the frame
  94977. * header CRC.
  94978. */
  94979. /*
  94980. * read in the raw header as bytes so we can CRC it, and parse it on the way
  94981. */
  94982. for(i = 0; i < 2; i++) {
  94983. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94984. return false; /* read_callback_ sets the state for us */
  94985. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94986. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  94987. decoder->private_->lookahead = (FLAC__byte)x;
  94988. decoder->private_->cached = true;
  94989. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  94990. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94991. return true;
  94992. }
  94993. raw_header[raw_header_len++] = (FLAC__byte)x;
  94994. }
  94995. switch(x = raw_header[2] >> 4) {
  94996. case 0:
  94997. is_unparseable = true;
  94998. break;
  94999. case 1:
  95000. decoder->private_->frame.header.blocksize = 192;
  95001. break;
  95002. case 2:
  95003. case 3:
  95004. case 4:
  95005. case 5:
  95006. decoder->private_->frame.header.blocksize = 576 << (x-2);
  95007. break;
  95008. case 6:
  95009. case 7:
  95010. blocksize_hint = x;
  95011. break;
  95012. case 8:
  95013. case 9:
  95014. case 10:
  95015. case 11:
  95016. case 12:
  95017. case 13:
  95018. case 14:
  95019. case 15:
  95020. decoder->private_->frame.header.blocksize = 256 << (x-8);
  95021. break;
  95022. default:
  95023. FLAC__ASSERT(0);
  95024. break;
  95025. }
  95026. switch(x = raw_header[2] & 0x0f) {
  95027. case 0:
  95028. if(decoder->private_->has_stream_info)
  95029. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  95030. else
  95031. is_unparseable = true;
  95032. break;
  95033. case 1:
  95034. decoder->private_->frame.header.sample_rate = 88200;
  95035. break;
  95036. case 2:
  95037. decoder->private_->frame.header.sample_rate = 176400;
  95038. break;
  95039. case 3:
  95040. decoder->private_->frame.header.sample_rate = 192000;
  95041. break;
  95042. case 4:
  95043. decoder->private_->frame.header.sample_rate = 8000;
  95044. break;
  95045. case 5:
  95046. decoder->private_->frame.header.sample_rate = 16000;
  95047. break;
  95048. case 6:
  95049. decoder->private_->frame.header.sample_rate = 22050;
  95050. break;
  95051. case 7:
  95052. decoder->private_->frame.header.sample_rate = 24000;
  95053. break;
  95054. case 8:
  95055. decoder->private_->frame.header.sample_rate = 32000;
  95056. break;
  95057. case 9:
  95058. decoder->private_->frame.header.sample_rate = 44100;
  95059. break;
  95060. case 10:
  95061. decoder->private_->frame.header.sample_rate = 48000;
  95062. break;
  95063. case 11:
  95064. decoder->private_->frame.header.sample_rate = 96000;
  95065. break;
  95066. case 12:
  95067. case 13:
  95068. case 14:
  95069. sample_rate_hint = x;
  95070. break;
  95071. case 15:
  95072. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  95073. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95074. return true;
  95075. default:
  95076. FLAC__ASSERT(0);
  95077. }
  95078. x = (unsigned)(raw_header[3] >> 4);
  95079. if(x & 8) {
  95080. decoder->private_->frame.header.channels = 2;
  95081. switch(x & 7) {
  95082. case 0:
  95083. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  95084. break;
  95085. case 1:
  95086. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  95087. break;
  95088. case 2:
  95089. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  95090. break;
  95091. default:
  95092. is_unparseable = true;
  95093. break;
  95094. }
  95095. }
  95096. else {
  95097. decoder->private_->frame.header.channels = (unsigned)x + 1;
  95098. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  95099. }
  95100. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  95101. case 0:
  95102. if(decoder->private_->has_stream_info)
  95103. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  95104. else
  95105. is_unparseable = true;
  95106. break;
  95107. case 1:
  95108. decoder->private_->frame.header.bits_per_sample = 8;
  95109. break;
  95110. case 2:
  95111. decoder->private_->frame.header.bits_per_sample = 12;
  95112. break;
  95113. case 4:
  95114. decoder->private_->frame.header.bits_per_sample = 16;
  95115. break;
  95116. case 5:
  95117. decoder->private_->frame.header.bits_per_sample = 20;
  95118. break;
  95119. case 6:
  95120. decoder->private_->frame.header.bits_per_sample = 24;
  95121. break;
  95122. case 3:
  95123. case 7:
  95124. is_unparseable = true;
  95125. break;
  95126. default:
  95127. FLAC__ASSERT(0);
  95128. break;
  95129. }
  95130. /* check to make sure that reserved bit is 0 */
  95131. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  95132. is_unparseable = true;
  95133. /* read the frame's starting sample number (or frame number as the case may be) */
  95134. if(
  95135. raw_header[1] & 0x01 ||
  95136. /*@@@ 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 */
  95137. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  95138. ) { /* variable blocksize */
  95139. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  95140. return false; /* read_callback_ sets the state for us */
  95141. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  95142. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  95143. decoder->private_->cached = true;
  95144. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  95145. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95146. return true;
  95147. }
  95148. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  95149. decoder->private_->frame.header.number.sample_number = xx;
  95150. }
  95151. else { /* fixed blocksize */
  95152. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  95153. return false; /* read_callback_ sets the state for us */
  95154. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  95155. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  95156. decoder->private_->cached = true;
  95157. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  95158. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95159. return true;
  95160. }
  95161. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  95162. decoder->private_->frame.header.number.frame_number = x;
  95163. }
  95164. if(blocksize_hint) {
  95165. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95166. return false; /* read_callback_ sets the state for us */
  95167. raw_header[raw_header_len++] = (FLAC__byte)x;
  95168. if(blocksize_hint == 7) {
  95169. FLAC__uint32 _x;
  95170. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  95171. return false; /* read_callback_ sets the state for us */
  95172. raw_header[raw_header_len++] = (FLAC__byte)_x;
  95173. x = (x << 8) | _x;
  95174. }
  95175. decoder->private_->frame.header.blocksize = x+1;
  95176. }
  95177. if(sample_rate_hint) {
  95178. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95179. return false; /* read_callback_ sets the state for us */
  95180. raw_header[raw_header_len++] = (FLAC__byte)x;
  95181. if(sample_rate_hint != 12) {
  95182. FLAC__uint32 _x;
  95183. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  95184. return false; /* read_callback_ sets the state for us */
  95185. raw_header[raw_header_len++] = (FLAC__byte)_x;
  95186. x = (x << 8) | _x;
  95187. }
  95188. if(sample_rate_hint == 12)
  95189. decoder->private_->frame.header.sample_rate = x*1000;
  95190. else if(sample_rate_hint == 13)
  95191. decoder->private_->frame.header.sample_rate = x;
  95192. else
  95193. decoder->private_->frame.header.sample_rate = x*10;
  95194. }
  95195. /* read the CRC-8 byte */
  95196. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95197. return false; /* read_callback_ sets the state for us */
  95198. crc8 = (FLAC__byte)x;
  95199. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  95200. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  95201. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95202. return true;
  95203. }
  95204. /* calculate the sample number from the frame number if needed */
  95205. decoder->private_->next_fixed_block_size = 0;
  95206. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  95207. x = decoder->private_->frame.header.number.frame_number;
  95208. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  95209. if(decoder->private_->fixed_block_size)
  95210. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  95211. else if(decoder->private_->has_stream_info) {
  95212. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  95213. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  95214. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  95215. }
  95216. else
  95217. is_unparseable = true;
  95218. }
  95219. else if(x == 0) {
  95220. decoder->private_->frame.header.number.sample_number = 0;
  95221. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  95222. }
  95223. else {
  95224. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  95225. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  95226. }
  95227. }
  95228. if(is_unparseable) {
  95229. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  95230. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95231. return true;
  95232. }
  95233. return true;
  95234. }
  95235. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  95236. {
  95237. FLAC__uint32 x;
  95238. FLAC__bool wasted_bits;
  95239. unsigned i;
  95240. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  95241. return false; /* read_callback_ sets the state for us */
  95242. wasted_bits = (x & 1);
  95243. x &= 0xfe;
  95244. if(wasted_bits) {
  95245. unsigned u;
  95246. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  95247. return false; /* read_callback_ sets the state for us */
  95248. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  95249. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  95250. }
  95251. else
  95252. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  95253. /*
  95254. * Lots of magic numbers here
  95255. */
  95256. if(x & 0x80) {
  95257. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95258. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95259. return true;
  95260. }
  95261. else if(x == 0) {
  95262. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  95263. return false;
  95264. }
  95265. else if(x == 2) {
  95266. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  95267. return false;
  95268. }
  95269. else if(x < 16) {
  95270. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  95271. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95272. return true;
  95273. }
  95274. else if(x <= 24) {
  95275. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  95276. return false;
  95277. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  95278. return true;
  95279. }
  95280. else if(x < 64) {
  95281. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  95282. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95283. return true;
  95284. }
  95285. else {
  95286. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  95287. return false;
  95288. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  95289. return true;
  95290. }
  95291. if(wasted_bits && do_full_decode) {
  95292. x = decoder->private_->frame.subframes[channel].wasted_bits;
  95293. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  95294. decoder->private_->output[channel][i] <<= x;
  95295. }
  95296. return true;
  95297. }
  95298. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  95299. {
  95300. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  95301. FLAC__int32 x;
  95302. unsigned i;
  95303. FLAC__int32 *output = decoder->private_->output[channel];
  95304. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  95305. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  95306. return false; /* read_callback_ sets the state for us */
  95307. subframe->value = x;
  95308. /* decode the subframe */
  95309. if(do_full_decode) {
  95310. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  95311. output[i] = x;
  95312. }
  95313. return true;
  95314. }
  95315. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  95316. {
  95317. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  95318. FLAC__int32 i32;
  95319. FLAC__uint32 u32;
  95320. unsigned u;
  95321. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  95322. subframe->residual = decoder->private_->residual[channel];
  95323. subframe->order = order;
  95324. /* read warm-up samples */
  95325. for(u = 0; u < order; u++) {
  95326. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  95327. return false; /* read_callback_ sets the state for us */
  95328. subframe->warmup[u] = i32;
  95329. }
  95330. /* read entropy coding method info */
  95331. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  95332. return false; /* read_callback_ sets the state for us */
  95333. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  95334. switch(subframe->entropy_coding_method.type) {
  95335. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  95336. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  95337. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  95338. return false; /* read_callback_ sets the state for us */
  95339. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  95340. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  95341. break;
  95342. default:
  95343. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  95344. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95345. return true;
  95346. }
  95347. /* read residual */
  95348. switch(subframe->entropy_coding_method.type) {
  95349. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  95350. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  95351. 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))
  95352. return false;
  95353. break;
  95354. default:
  95355. FLAC__ASSERT(0);
  95356. }
  95357. /* decode the subframe */
  95358. if(do_full_decode) {
  95359. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  95360. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  95361. }
  95362. return true;
  95363. }
  95364. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  95365. {
  95366. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  95367. FLAC__int32 i32;
  95368. FLAC__uint32 u32;
  95369. unsigned u;
  95370. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  95371. subframe->residual = decoder->private_->residual[channel];
  95372. subframe->order = order;
  95373. /* read warm-up samples */
  95374. for(u = 0; u < order; u++) {
  95375. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  95376. return false; /* read_callback_ sets the state for us */
  95377. subframe->warmup[u] = i32;
  95378. }
  95379. /* read qlp coeff precision */
  95380. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  95381. return false; /* read_callback_ sets the state for us */
  95382. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  95383. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95384. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95385. return true;
  95386. }
  95387. subframe->qlp_coeff_precision = u32+1;
  95388. /* read qlp shift */
  95389. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  95390. return false; /* read_callback_ sets the state for us */
  95391. subframe->quantization_level = i32;
  95392. /* read quantized lp coefficiencts */
  95393. for(u = 0; u < order; u++) {
  95394. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  95395. return false; /* read_callback_ sets the state for us */
  95396. subframe->qlp_coeff[u] = i32;
  95397. }
  95398. /* read entropy coding method info */
  95399. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  95400. return false; /* read_callback_ sets the state for us */
  95401. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  95402. switch(subframe->entropy_coding_method.type) {
  95403. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  95404. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  95405. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  95406. return false; /* read_callback_ sets the state for us */
  95407. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  95408. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  95409. break;
  95410. default:
  95411. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  95412. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95413. return true;
  95414. }
  95415. /* read residual */
  95416. switch(subframe->entropy_coding_method.type) {
  95417. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  95418. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  95419. 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))
  95420. return false;
  95421. break;
  95422. default:
  95423. FLAC__ASSERT(0);
  95424. }
  95425. /* decode the subframe */
  95426. if(do_full_decode) {
  95427. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  95428. /*@@@@@@ technically not pessimistic enough, should be more like
  95429. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  95430. */
  95431. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  95432. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  95433. if(order <= 8)
  95434. 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);
  95435. else
  95436. 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);
  95437. }
  95438. else
  95439. 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);
  95440. else
  95441. 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);
  95442. }
  95443. return true;
  95444. }
  95445. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  95446. {
  95447. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  95448. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  95449. unsigned i;
  95450. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  95451. subframe->data = residual;
  95452. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  95453. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  95454. return false; /* read_callback_ sets the state for us */
  95455. residual[i] = x;
  95456. }
  95457. /* decode the subframe */
  95458. if(do_full_decode)
  95459. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  95460. return true;
  95461. }
  95462. 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)
  95463. {
  95464. FLAC__uint32 rice_parameter;
  95465. int i;
  95466. unsigned partition, sample, u;
  95467. const unsigned partitions = 1u << partition_order;
  95468. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  95469. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  95470. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  95471. /* sanity checks */
  95472. if(partition_order == 0) {
  95473. if(decoder->private_->frame.header.blocksize < predictor_order) {
  95474. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95475. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95476. return true;
  95477. }
  95478. }
  95479. else {
  95480. if(partition_samples < predictor_order) {
  95481. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95482. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95483. return true;
  95484. }
  95485. }
  95486. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  95487. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95488. return false;
  95489. }
  95490. sample = 0;
  95491. for(partition = 0; partition < partitions; partition++) {
  95492. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  95493. return false; /* read_callback_ sets the state for us */
  95494. partitioned_rice_contents->parameters[partition] = rice_parameter;
  95495. if(rice_parameter < pesc) {
  95496. partitioned_rice_contents->raw_bits[partition] = 0;
  95497. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  95498. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  95499. return false; /* read_callback_ sets the state for us */
  95500. sample += u;
  95501. }
  95502. else {
  95503. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  95504. return false; /* read_callback_ sets the state for us */
  95505. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  95506. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  95507. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  95508. return false; /* read_callback_ sets the state for us */
  95509. residual[sample] = i;
  95510. }
  95511. }
  95512. }
  95513. return true;
  95514. }
  95515. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  95516. {
  95517. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  95518. FLAC__uint32 zero = 0;
  95519. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  95520. return false; /* read_callback_ sets the state for us */
  95521. if(zero != 0) {
  95522. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95523. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95524. }
  95525. }
  95526. return true;
  95527. }
  95528. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  95529. {
  95530. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  95531. if(
  95532. #if FLAC__HAS_OGG
  95533. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  95534. !decoder->private_->is_ogg &&
  95535. #endif
  95536. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  95537. ) {
  95538. *bytes = 0;
  95539. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  95540. return false;
  95541. }
  95542. else if(*bytes > 0) {
  95543. /* While seeking, it is possible for our seek to land in the
  95544. * middle of audio data that looks exactly like a frame header
  95545. * from a future version of an encoder. When that happens, our
  95546. * error callback will get an
  95547. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  95548. * unparseable_frame_count. But there is a remote possibility
  95549. * that it is properly synced at such a "future-codec frame",
  95550. * so to make sure, we wait to see many "unparseable" errors in
  95551. * a row before bailing out.
  95552. */
  95553. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  95554. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  95555. return false;
  95556. }
  95557. else {
  95558. const FLAC__StreamDecoderReadStatus status =
  95559. #if FLAC__HAS_OGG
  95560. decoder->private_->is_ogg?
  95561. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  95562. #endif
  95563. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  95564. ;
  95565. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  95566. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  95567. return false;
  95568. }
  95569. else if(*bytes == 0) {
  95570. if(
  95571. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  95572. (
  95573. #if FLAC__HAS_OGG
  95574. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  95575. !decoder->private_->is_ogg &&
  95576. #endif
  95577. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  95578. )
  95579. ) {
  95580. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  95581. return false;
  95582. }
  95583. else
  95584. return true;
  95585. }
  95586. else
  95587. return true;
  95588. }
  95589. }
  95590. else {
  95591. /* abort to avoid a deadlock */
  95592. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  95593. return false;
  95594. }
  95595. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  95596. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  95597. * and at the same time hit the end of the stream (for example, seeking
  95598. * to a point that is after the beginning of the last Ogg page). There
  95599. * is no way to report an Ogg sync loss through the callbacks (see note
  95600. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  95601. * So to keep the decoder from stopping at this point we gate the call
  95602. * to the eof_callback and let the Ogg decoder aspect set the
  95603. * end-of-stream state when it is needed.
  95604. */
  95605. }
  95606. #if FLAC__HAS_OGG
  95607. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  95608. {
  95609. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  95610. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  95611. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  95612. /* we don't really have a way to handle lost sync via read
  95613. * callback so we'll let it pass and let the underlying
  95614. * FLAC decoder catch the error
  95615. */
  95616. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  95617. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  95618. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  95619. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  95620. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  95621. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  95622. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  95623. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  95624. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  95625. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  95626. default:
  95627. FLAC__ASSERT(0);
  95628. /* double protection */
  95629. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  95630. }
  95631. }
  95632. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  95633. {
  95634. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  95635. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  95636. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  95637. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  95638. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  95639. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  95640. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  95641. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  95642. default:
  95643. /* double protection: */
  95644. FLAC__ASSERT(0);
  95645. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  95646. }
  95647. }
  95648. #endif
  95649. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  95650. {
  95651. if(decoder->private_->is_seeking) {
  95652. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  95653. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  95654. FLAC__uint64 target_sample = decoder->private_->target_sample;
  95655. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  95656. #if FLAC__HAS_OGG
  95657. decoder->private_->got_a_frame = true;
  95658. #endif
  95659. decoder->private_->last_frame = *frame; /* save the frame */
  95660. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  95661. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  95662. /* kick out of seek mode */
  95663. decoder->private_->is_seeking = false;
  95664. /* shift out the samples before target_sample */
  95665. if(delta > 0) {
  95666. unsigned channel;
  95667. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  95668. for(channel = 0; channel < frame->header.channels; channel++)
  95669. newbuffer[channel] = buffer[channel] + delta;
  95670. decoder->private_->last_frame.header.blocksize -= delta;
  95671. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  95672. /* write the relevant samples */
  95673. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  95674. }
  95675. else {
  95676. /* write the relevant samples */
  95677. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  95678. }
  95679. }
  95680. else {
  95681. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  95682. }
  95683. }
  95684. else {
  95685. /*
  95686. * If we never got STREAMINFO, turn off MD5 checking to save
  95687. * cycles since we don't have a sum to compare to anyway
  95688. */
  95689. if(!decoder->private_->has_stream_info)
  95690. decoder->private_->do_md5_checking = false;
  95691. if(decoder->private_->do_md5_checking) {
  95692. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  95693. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  95694. }
  95695. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  95696. }
  95697. }
  95698. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  95699. {
  95700. if(!decoder->private_->is_seeking)
  95701. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  95702. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  95703. decoder->private_->unparseable_frame_count++;
  95704. }
  95705. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  95706. {
  95707. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  95708. FLAC__int64 pos = -1;
  95709. int i;
  95710. unsigned approx_bytes_per_frame;
  95711. FLAC__bool first_seek = true;
  95712. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  95713. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  95714. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  95715. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  95716. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  95717. /* take these from the current frame in case they've changed mid-stream */
  95718. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  95719. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  95720. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  95721. /* use values from stream info if we didn't decode a frame */
  95722. if(channels == 0)
  95723. channels = decoder->private_->stream_info.data.stream_info.channels;
  95724. if(bps == 0)
  95725. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  95726. /* we are just guessing here */
  95727. if(max_framesize > 0)
  95728. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  95729. /*
  95730. * Check if it's a known fixed-blocksize stream. Note that though
  95731. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  95732. * never get a STREAMINFO block when decoding so the value of
  95733. * min_blocksize might be zero.
  95734. */
  95735. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  95736. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  95737. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  95738. }
  95739. else
  95740. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  95741. /*
  95742. * First, we set an upper and lower bound on where in the
  95743. * stream we will search. For now we assume the worst case
  95744. * scenario, which is our best guess at the beginning of
  95745. * the first frame and end of the stream.
  95746. */
  95747. lower_bound = first_frame_offset;
  95748. lower_bound_sample = 0;
  95749. upper_bound = stream_length;
  95750. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  95751. /*
  95752. * Now we refine the bounds if we have a seektable with
  95753. * suitable points. Note that according to the spec they
  95754. * must be ordered by ascending sample number.
  95755. *
  95756. * Note: to protect against invalid seek tables we will ignore points
  95757. * that have frame_samples==0 or sample_number>=total_samples
  95758. */
  95759. if(seek_table) {
  95760. FLAC__uint64 new_lower_bound = lower_bound;
  95761. FLAC__uint64 new_upper_bound = upper_bound;
  95762. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  95763. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  95764. /* find the closest seek point <= target_sample, if it exists */
  95765. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  95766. if(
  95767. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  95768. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  95769. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  95770. seek_table->points[i].sample_number <= target_sample
  95771. )
  95772. break;
  95773. }
  95774. if(i >= 0) { /* i.e. we found a suitable seek point... */
  95775. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  95776. new_lower_bound_sample = seek_table->points[i].sample_number;
  95777. }
  95778. /* find the closest seek point > target_sample, if it exists */
  95779. for(i = 0; i < (int)seek_table->num_points; i++) {
  95780. if(
  95781. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  95782. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  95783. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  95784. seek_table->points[i].sample_number > target_sample
  95785. )
  95786. break;
  95787. }
  95788. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  95789. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  95790. new_upper_bound_sample = seek_table->points[i].sample_number;
  95791. }
  95792. /* final protection against unsorted seek tables; keep original values if bogus */
  95793. if(new_upper_bound >= new_lower_bound) {
  95794. lower_bound = new_lower_bound;
  95795. upper_bound = new_upper_bound;
  95796. lower_bound_sample = new_lower_bound_sample;
  95797. upper_bound_sample = new_upper_bound_sample;
  95798. }
  95799. }
  95800. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  95801. /* there are 2 insidious ways that the following equality occurs, which
  95802. * we need to fix:
  95803. * 1) total_samples is 0 (unknown) and target_sample is 0
  95804. * 2) total_samples is 0 (unknown) and target_sample happens to be
  95805. * exactly equal to the last seek point in the seek table; this
  95806. * means there is no seek point above it, and upper_bound_samples
  95807. * remains equal to the estimate (of target_samples) we made above
  95808. * in either case it does not hurt to move upper_bound_sample up by 1
  95809. */
  95810. if(upper_bound_sample == lower_bound_sample)
  95811. upper_bound_sample++;
  95812. decoder->private_->target_sample = target_sample;
  95813. while(1) {
  95814. /* check if the bounds are still ok */
  95815. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  95816. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95817. return false;
  95818. }
  95819. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95820. #if defined _MSC_VER || defined __MINGW32__
  95821. /* with VC++ you have to spoon feed it the casting */
  95822. 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;
  95823. #else
  95824. 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;
  95825. #endif
  95826. #else
  95827. /* a little less accurate: */
  95828. if(upper_bound - lower_bound < 0xffffffff)
  95829. 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;
  95830. else /* @@@ WATCHOUT, ~2TB limit */
  95831. 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;
  95832. #endif
  95833. if(pos >= (FLAC__int64)upper_bound)
  95834. pos = (FLAC__int64)upper_bound - 1;
  95835. if(pos < (FLAC__int64)lower_bound)
  95836. pos = (FLAC__int64)lower_bound;
  95837. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  95838. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95839. return false;
  95840. }
  95841. if(!FLAC__stream_decoder_flush(decoder)) {
  95842. /* above call sets the state for us */
  95843. return false;
  95844. }
  95845. /* Now we need to get a frame. First we need to reset our
  95846. * unparseable_frame_count; if we get too many unparseable
  95847. * frames in a row, the read callback will return
  95848. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  95849. * FLAC__stream_decoder_process_single() to return false.
  95850. */
  95851. decoder->private_->unparseable_frame_count = 0;
  95852. if(!FLAC__stream_decoder_process_single(decoder)) {
  95853. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95854. return false;
  95855. }
  95856. /* our write callback will change the state when it gets to the target frame */
  95857. /* 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 */
  95858. #if 0
  95859. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  95860. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  95861. break;
  95862. #endif
  95863. if(!decoder->private_->is_seeking)
  95864. break;
  95865. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  95866. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  95867. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  95868. if (pos == (FLAC__int64)lower_bound) {
  95869. /* can't move back any more than the first frame, something is fatally wrong */
  95870. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95871. return false;
  95872. }
  95873. /* our last move backwards wasn't big enough, try again */
  95874. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  95875. continue;
  95876. }
  95877. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  95878. first_seek = false;
  95879. /* make sure we are not seeking in corrupted stream */
  95880. if (this_frame_sample < lower_bound_sample) {
  95881. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95882. return false;
  95883. }
  95884. /* we need to narrow the search */
  95885. if(target_sample < this_frame_sample) {
  95886. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  95887. /*@@@@@@ what will decode position be if at end of stream? */
  95888. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  95889. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95890. return false;
  95891. }
  95892. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  95893. }
  95894. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  95895. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  95896. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  95897. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95898. return false;
  95899. }
  95900. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  95901. }
  95902. }
  95903. return true;
  95904. }
  95905. #if FLAC__HAS_OGG
  95906. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  95907. {
  95908. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  95909. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  95910. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  95911. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  95912. FLAC__bool did_a_seek;
  95913. unsigned iteration = 0;
  95914. /* In the first iterations, we will calculate the target byte position
  95915. * by the distance from the target sample to left_sample and
  95916. * right_sample (let's call it "proportional search"). After that, we
  95917. * will switch to binary search.
  95918. */
  95919. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  95920. /* We will switch to a linear search once our current sample is less
  95921. * than this number of samples ahead of the target sample
  95922. */
  95923. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  95924. /* If the total number of samples is unknown, use a large value, and
  95925. * force binary search immediately.
  95926. */
  95927. if(right_sample == 0) {
  95928. right_sample = (FLAC__uint64)(-1);
  95929. BINARY_SEARCH_AFTER_ITERATION = 0;
  95930. }
  95931. decoder->private_->target_sample = target_sample;
  95932. for( ; ; iteration++) {
  95933. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  95934. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  95935. pos = (right_pos + left_pos) / 2;
  95936. }
  95937. else {
  95938. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95939. #if defined _MSC_VER || defined __MINGW32__
  95940. /* with MSVC you have to spoon feed it the casting */
  95941. 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));
  95942. #else
  95943. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  95944. #endif
  95945. #else
  95946. /* a little less accurate: */
  95947. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  95948. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  95949. else /* @@@ WATCHOUT, ~2TB limit */
  95950. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  95951. #endif
  95952. /* @@@ TODO: might want to limit pos to some distance
  95953. * before EOF, to make sure we land before the last frame,
  95954. * thereby getting a this_frame_sample and so having a better
  95955. * estimate.
  95956. */
  95957. }
  95958. /* physical seek */
  95959. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  95960. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95961. return false;
  95962. }
  95963. if(!FLAC__stream_decoder_flush(decoder)) {
  95964. /* above call sets the state for us */
  95965. return false;
  95966. }
  95967. did_a_seek = true;
  95968. }
  95969. else
  95970. did_a_seek = false;
  95971. decoder->private_->got_a_frame = false;
  95972. if(!FLAC__stream_decoder_process_single(decoder)) {
  95973. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95974. return false;
  95975. }
  95976. if(!decoder->private_->got_a_frame) {
  95977. if(did_a_seek) {
  95978. /* this can happen if we seek to a point after the last frame; we drop
  95979. * to binary search right away in this case to avoid any wasted
  95980. * iterations of proportional search.
  95981. */
  95982. right_pos = pos;
  95983. BINARY_SEARCH_AFTER_ITERATION = 0;
  95984. }
  95985. else {
  95986. /* this can probably only happen if total_samples is unknown and the
  95987. * target_sample is past the end of the stream
  95988. */
  95989. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95990. return false;
  95991. }
  95992. }
  95993. /* our write callback will change the state when it gets to the target frame */
  95994. else if(!decoder->private_->is_seeking) {
  95995. break;
  95996. }
  95997. else {
  95998. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  95999. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  96000. if (did_a_seek) {
  96001. if (this_frame_sample <= target_sample) {
  96002. /* The 'equal' case should not happen, since
  96003. * FLAC__stream_decoder_process_single()
  96004. * should recognize that it has hit the
  96005. * target sample and we would exit through
  96006. * the 'break' above.
  96007. */
  96008. FLAC__ASSERT(this_frame_sample != target_sample);
  96009. left_sample = this_frame_sample;
  96010. /* sanity check to avoid infinite loop */
  96011. if (left_pos == pos) {
  96012. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96013. return false;
  96014. }
  96015. left_pos = pos;
  96016. }
  96017. else if(this_frame_sample > target_sample) {
  96018. right_sample = this_frame_sample;
  96019. /* sanity check to avoid infinite loop */
  96020. if (right_pos == pos) {
  96021. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96022. return false;
  96023. }
  96024. right_pos = pos;
  96025. }
  96026. }
  96027. }
  96028. }
  96029. return true;
  96030. }
  96031. #endif
  96032. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  96033. {
  96034. (void)client_data;
  96035. if(*bytes > 0) {
  96036. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  96037. if(ferror(decoder->private_->file))
  96038. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  96039. else if(*bytes == 0)
  96040. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  96041. else
  96042. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  96043. }
  96044. else
  96045. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  96046. }
  96047. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  96048. {
  96049. (void)client_data;
  96050. if(decoder->private_->file == stdin)
  96051. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  96052. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  96053. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  96054. else
  96055. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  96056. }
  96057. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  96058. {
  96059. off_t pos;
  96060. (void)client_data;
  96061. if(decoder->private_->file == stdin)
  96062. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  96063. else if((pos = ftello(decoder->private_->file)) < 0)
  96064. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  96065. else {
  96066. *absolute_byte_offset = (FLAC__uint64)pos;
  96067. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  96068. }
  96069. }
  96070. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  96071. {
  96072. struct stat filestats;
  96073. (void)client_data;
  96074. if(decoder->private_->file == stdin)
  96075. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  96076. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  96077. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  96078. else {
  96079. *stream_length = (FLAC__uint64)filestats.st_size;
  96080. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  96081. }
  96082. }
  96083. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  96084. {
  96085. (void)client_data;
  96086. return feof(decoder->private_->file)? true : false;
  96087. }
  96088. #endif
  96089. /********* End of inlined file: stream_decoder.c *********/
  96090. /********* Start of inlined file: stream_encoder.c *********/
  96091. /********* Start of inlined file: juce_FlacHeader.h *********/
  96092. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96093. // tasks..
  96094. #define VERSION "1.2.1"
  96095. #define FLAC__NO_DLL 1
  96096. #ifdef _MSC_VER
  96097. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96098. #endif
  96099. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  96100. #define FLAC__SYS_DARWIN 1
  96101. #endif
  96102. /********* End of inlined file: juce_FlacHeader.h *********/
  96103. #if JUCE_USE_FLAC
  96104. #if HAVE_CONFIG_H
  96105. # include <config.h>
  96106. #endif
  96107. #if defined _MSC_VER || defined __MINGW32__
  96108. #include <io.h> /* for _setmode() */
  96109. #include <fcntl.h> /* for _O_BINARY */
  96110. #endif
  96111. #if defined __CYGWIN__ || defined __EMX__
  96112. #include <io.h> /* for setmode(), O_BINARY */
  96113. #include <fcntl.h> /* for _O_BINARY */
  96114. #endif
  96115. #include <limits.h>
  96116. #include <stdio.h>
  96117. #include <stdlib.h> /* for malloc() */
  96118. #include <string.h> /* for memcpy() */
  96119. #include <sys/types.h> /* for off_t */
  96120. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  96121. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  96122. #define fseeko fseek
  96123. #define ftello ftell
  96124. #endif
  96125. #endif
  96126. /********* Start of inlined file: stream_encoder.h *********/
  96127. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  96128. #define FLAC__PROTECTED__STREAM_ENCODER_H
  96129. #if FLAC__HAS_OGG
  96130. #include "private/ogg_encoder_aspect.h"
  96131. #endif
  96132. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96133. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  96134. typedef enum {
  96135. FLAC__APODIZATION_BARTLETT,
  96136. FLAC__APODIZATION_BARTLETT_HANN,
  96137. FLAC__APODIZATION_BLACKMAN,
  96138. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  96139. FLAC__APODIZATION_CONNES,
  96140. FLAC__APODIZATION_FLATTOP,
  96141. FLAC__APODIZATION_GAUSS,
  96142. FLAC__APODIZATION_HAMMING,
  96143. FLAC__APODIZATION_HANN,
  96144. FLAC__APODIZATION_KAISER_BESSEL,
  96145. FLAC__APODIZATION_NUTTALL,
  96146. FLAC__APODIZATION_RECTANGLE,
  96147. FLAC__APODIZATION_TRIANGLE,
  96148. FLAC__APODIZATION_TUKEY,
  96149. FLAC__APODIZATION_WELCH
  96150. } FLAC__ApodizationFunction;
  96151. typedef struct {
  96152. FLAC__ApodizationFunction type;
  96153. union {
  96154. struct {
  96155. FLAC__real stddev;
  96156. } gauss;
  96157. struct {
  96158. FLAC__real p;
  96159. } tukey;
  96160. } parameters;
  96161. } FLAC__ApodizationSpecification;
  96162. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96163. typedef struct FLAC__StreamEncoderProtected {
  96164. FLAC__StreamEncoderState state;
  96165. FLAC__bool verify;
  96166. FLAC__bool streamable_subset;
  96167. FLAC__bool do_md5;
  96168. FLAC__bool do_mid_side_stereo;
  96169. FLAC__bool loose_mid_side_stereo;
  96170. unsigned channels;
  96171. unsigned bits_per_sample;
  96172. unsigned sample_rate;
  96173. unsigned blocksize;
  96174. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96175. unsigned num_apodizations;
  96176. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  96177. #endif
  96178. unsigned max_lpc_order;
  96179. unsigned qlp_coeff_precision;
  96180. FLAC__bool do_qlp_coeff_prec_search;
  96181. FLAC__bool do_exhaustive_model_search;
  96182. FLAC__bool do_escape_coding;
  96183. unsigned min_residual_partition_order;
  96184. unsigned max_residual_partition_order;
  96185. unsigned rice_parameter_search_dist;
  96186. FLAC__uint64 total_samples_estimate;
  96187. FLAC__StreamMetadata **metadata;
  96188. unsigned num_metadata_blocks;
  96189. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  96190. #if FLAC__HAS_OGG
  96191. FLAC__OggEncoderAspect ogg_encoder_aspect;
  96192. #endif
  96193. } FLAC__StreamEncoderProtected;
  96194. #endif
  96195. /********* End of inlined file: stream_encoder.h *********/
  96196. #if FLAC__HAS_OGG
  96197. #include "include/private/ogg_helper.h"
  96198. #include "include/private/ogg_mapping.h"
  96199. #endif
  96200. /********* Start of inlined file: stream_encoder_framing.h *********/
  96201. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  96202. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  96203. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  96204. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  96205. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  96206. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  96207. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  96208. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  96209. #endif
  96210. /********* End of inlined file: stream_encoder_framing.h *********/
  96211. /********* Start of inlined file: window.h *********/
  96212. #ifndef FLAC__PRIVATE__WINDOW_H
  96213. #define FLAC__PRIVATE__WINDOW_H
  96214. #ifdef HAVE_CONFIG_H
  96215. #include <config.h>
  96216. #endif
  96217. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96218. /*
  96219. * FLAC__window_*()
  96220. * --------------------------------------------------------------------
  96221. * Calculates window coefficients according to different apodization
  96222. * functions.
  96223. *
  96224. * OUT window[0,L-1]
  96225. * IN L (number of points in window)
  96226. */
  96227. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  96228. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  96229. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  96230. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  96231. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  96232. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  96233. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  96234. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  96235. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  96236. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  96237. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  96238. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  96239. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  96240. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  96241. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  96242. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96243. #endif
  96244. /********* End of inlined file: window.h *********/
  96245. #ifndef FLaC__INLINE
  96246. #define FLaC__INLINE
  96247. #endif
  96248. #ifdef min
  96249. #undef min
  96250. #endif
  96251. #define min(x,y) ((x)<(y)?(x):(y))
  96252. #ifdef max
  96253. #undef max
  96254. #endif
  96255. #define max(x,y) ((x)>(y)?(x):(y))
  96256. /* Exact Rice codeword length calculation is off by default. The simple
  96257. * (and fast) estimation (of how many bits a residual value will be
  96258. * encoded with) in this encoder is very good, almost always yielding
  96259. * compression within 0.1% of exact calculation.
  96260. */
  96261. #undef EXACT_RICE_BITS_CALCULATION
  96262. /* Rice parameter searching is off by default. The simple (and fast)
  96263. * parameter estimation in this encoder is very good, almost always
  96264. * yielding compression within 0.1% of the optimal parameters.
  96265. */
  96266. #undef ENABLE_RICE_PARAMETER_SEARCH
  96267. typedef struct {
  96268. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  96269. unsigned size; /* of each data[] in samples */
  96270. unsigned tail;
  96271. } verify_input_fifo;
  96272. typedef struct {
  96273. const FLAC__byte *data;
  96274. unsigned capacity;
  96275. unsigned bytes;
  96276. } verify_output;
  96277. typedef enum {
  96278. ENCODER_IN_MAGIC = 0,
  96279. ENCODER_IN_METADATA = 1,
  96280. ENCODER_IN_AUDIO = 2
  96281. } EncoderStateHint;
  96282. static struct CompressionLevels {
  96283. FLAC__bool do_mid_side_stereo;
  96284. FLAC__bool loose_mid_side_stereo;
  96285. unsigned max_lpc_order;
  96286. unsigned qlp_coeff_precision;
  96287. FLAC__bool do_qlp_coeff_prec_search;
  96288. FLAC__bool do_escape_coding;
  96289. FLAC__bool do_exhaustive_model_search;
  96290. unsigned min_residual_partition_order;
  96291. unsigned max_residual_partition_order;
  96292. unsigned rice_parameter_search_dist;
  96293. } compression_levels_[] = {
  96294. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  96295. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  96296. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  96297. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  96298. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  96299. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  96300. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  96301. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  96302. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  96303. };
  96304. /***********************************************************************
  96305. *
  96306. * Private class method prototypes
  96307. *
  96308. ***********************************************************************/
  96309. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  96310. static void free_(FLAC__StreamEncoder *encoder);
  96311. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  96312. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  96313. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  96314. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  96315. #if FLAC__HAS_OGG
  96316. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  96317. #endif
  96318. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  96319. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  96320. static FLAC__bool process_subframe_(
  96321. FLAC__StreamEncoder *encoder,
  96322. unsigned min_partition_order,
  96323. unsigned max_partition_order,
  96324. const FLAC__FrameHeader *frame_header,
  96325. unsigned subframe_bps,
  96326. const FLAC__int32 integer_signal[],
  96327. FLAC__Subframe *subframe[2],
  96328. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  96329. FLAC__int32 *residual[2],
  96330. unsigned *best_subframe,
  96331. unsigned *best_bits
  96332. );
  96333. static FLAC__bool add_subframe_(
  96334. FLAC__StreamEncoder *encoder,
  96335. unsigned blocksize,
  96336. unsigned subframe_bps,
  96337. const FLAC__Subframe *subframe,
  96338. FLAC__BitWriter *frame
  96339. );
  96340. static unsigned evaluate_constant_subframe_(
  96341. FLAC__StreamEncoder *encoder,
  96342. const FLAC__int32 signal,
  96343. unsigned blocksize,
  96344. unsigned subframe_bps,
  96345. FLAC__Subframe *subframe
  96346. );
  96347. static unsigned evaluate_fixed_subframe_(
  96348. FLAC__StreamEncoder *encoder,
  96349. const FLAC__int32 signal[],
  96350. FLAC__int32 residual[],
  96351. FLAC__uint64 abs_residual_partition_sums[],
  96352. unsigned raw_bits_per_partition[],
  96353. unsigned blocksize,
  96354. unsigned subframe_bps,
  96355. unsigned order,
  96356. unsigned rice_parameter,
  96357. unsigned rice_parameter_limit,
  96358. unsigned min_partition_order,
  96359. unsigned max_partition_order,
  96360. FLAC__bool do_escape_coding,
  96361. unsigned rice_parameter_search_dist,
  96362. FLAC__Subframe *subframe,
  96363. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  96364. );
  96365. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96366. static unsigned evaluate_lpc_subframe_(
  96367. FLAC__StreamEncoder *encoder,
  96368. const FLAC__int32 signal[],
  96369. FLAC__int32 residual[],
  96370. FLAC__uint64 abs_residual_partition_sums[],
  96371. unsigned raw_bits_per_partition[],
  96372. const FLAC__real lp_coeff[],
  96373. unsigned blocksize,
  96374. unsigned subframe_bps,
  96375. unsigned order,
  96376. unsigned qlp_coeff_precision,
  96377. unsigned rice_parameter,
  96378. unsigned rice_parameter_limit,
  96379. unsigned min_partition_order,
  96380. unsigned max_partition_order,
  96381. FLAC__bool do_escape_coding,
  96382. unsigned rice_parameter_search_dist,
  96383. FLAC__Subframe *subframe,
  96384. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  96385. );
  96386. #endif
  96387. static unsigned evaluate_verbatim_subframe_(
  96388. FLAC__StreamEncoder *encoder,
  96389. const FLAC__int32 signal[],
  96390. unsigned blocksize,
  96391. unsigned subframe_bps,
  96392. FLAC__Subframe *subframe
  96393. );
  96394. static unsigned find_best_partition_order_(
  96395. struct FLAC__StreamEncoderPrivate *private_,
  96396. const FLAC__int32 residual[],
  96397. FLAC__uint64 abs_residual_partition_sums[],
  96398. unsigned raw_bits_per_partition[],
  96399. unsigned residual_samples,
  96400. unsigned predictor_order,
  96401. unsigned rice_parameter,
  96402. unsigned rice_parameter_limit,
  96403. unsigned min_partition_order,
  96404. unsigned max_partition_order,
  96405. unsigned bps,
  96406. FLAC__bool do_escape_coding,
  96407. unsigned rice_parameter_search_dist,
  96408. FLAC__EntropyCodingMethod *best_ecm
  96409. );
  96410. static void precompute_partition_info_sums_(
  96411. const FLAC__int32 residual[],
  96412. FLAC__uint64 abs_residual_partition_sums[],
  96413. unsigned residual_samples,
  96414. unsigned predictor_order,
  96415. unsigned min_partition_order,
  96416. unsigned max_partition_order,
  96417. unsigned bps
  96418. );
  96419. static void precompute_partition_info_escapes_(
  96420. const FLAC__int32 residual[],
  96421. unsigned raw_bits_per_partition[],
  96422. unsigned residual_samples,
  96423. unsigned predictor_order,
  96424. unsigned min_partition_order,
  96425. unsigned max_partition_order
  96426. );
  96427. static FLAC__bool set_partitioned_rice_(
  96428. #ifdef EXACT_RICE_BITS_CALCULATION
  96429. const FLAC__int32 residual[],
  96430. #endif
  96431. const FLAC__uint64 abs_residual_partition_sums[],
  96432. const unsigned raw_bits_per_partition[],
  96433. const unsigned residual_samples,
  96434. const unsigned predictor_order,
  96435. const unsigned suggested_rice_parameter,
  96436. const unsigned rice_parameter_limit,
  96437. const unsigned rice_parameter_search_dist,
  96438. const unsigned partition_order,
  96439. const FLAC__bool search_for_escapes,
  96440. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  96441. unsigned *bits
  96442. );
  96443. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  96444. /* verify-related routines: */
  96445. static void append_to_verify_fifo_(
  96446. verify_input_fifo *fifo,
  96447. const FLAC__int32 * const input[],
  96448. unsigned input_offset,
  96449. unsigned channels,
  96450. unsigned wide_samples
  96451. );
  96452. static void append_to_verify_fifo_interleaved_(
  96453. verify_input_fifo *fifo,
  96454. const FLAC__int32 input[],
  96455. unsigned input_offset,
  96456. unsigned channels,
  96457. unsigned wide_samples
  96458. );
  96459. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  96460. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  96461. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  96462. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  96463. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  96464. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  96465. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  96466. 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);
  96467. static FILE *get_binary_stdout_(void);
  96468. /***********************************************************************
  96469. *
  96470. * Private class data
  96471. *
  96472. ***********************************************************************/
  96473. typedef struct FLAC__StreamEncoderPrivate {
  96474. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  96475. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  96476. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  96477. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96478. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  96479. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  96480. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  96481. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  96482. #endif
  96483. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  96484. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  96485. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  96486. FLAC__int32 *residual_workspace_mid_side[2][2];
  96487. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  96488. FLAC__Subframe subframe_workspace_mid_side[2][2];
  96489. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  96490. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  96491. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  96492. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  96493. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  96494. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  96495. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  96496. unsigned best_subframe_mid_side[2];
  96497. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  96498. unsigned best_subframe_bits_mid_side[2];
  96499. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  96500. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  96501. FLAC__BitWriter *frame; /* the current frame being worked on */
  96502. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  96503. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  96504. FLAC__ChannelAssignment last_channel_assignment;
  96505. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  96506. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  96507. unsigned current_sample_number;
  96508. unsigned current_frame_number;
  96509. FLAC__MD5Context md5context;
  96510. FLAC__CPUInfo cpuinfo;
  96511. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96512. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  96513. #else
  96514. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  96515. #endif
  96516. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96517. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96518. 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[]);
  96519. 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[]);
  96520. 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[]);
  96521. #endif
  96522. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  96523. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  96524. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  96525. FLAC__bool disable_constant_subframes;
  96526. FLAC__bool disable_fixed_subframes;
  96527. FLAC__bool disable_verbatim_subframes;
  96528. #if FLAC__HAS_OGG
  96529. FLAC__bool is_ogg;
  96530. #endif
  96531. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  96532. FLAC__StreamEncoderSeekCallback seek_callback;
  96533. FLAC__StreamEncoderTellCallback tell_callback;
  96534. FLAC__StreamEncoderWriteCallback write_callback;
  96535. FLAC__StreamEncoderMetadataCallback metadata_callback;
  96536. FLAC__StreamEncoderProgressCallback progress_callback;
  96537. void *client_data;
  96538. unsigned first_seekpoint_to_check;
  96539. FILE *file; /* only used when encoding to a file */
  96540. FLAC__uint64 bytes_written;
  96541. FLAC__uint64 samples_written;
  96542. unsigned frames_written;
  96543. unsigned total_frames_estimate;
  96544. /* unaligned (original) pointers to allocated data */
  96545. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  96546. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  96547. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96548. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  96549. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  96550. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  96551. FLAC__real *windowed_signal_unaligned;
  96552. #endif
  96553. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  96554. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  96555. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  96556. unsigned *raw_bits_per_partition_unaligned;
  96557. /*
  96558. * These fields have been moved here from private function local
  96559. * declarations merely to save stack space during encoding.
  96560. */
  96561. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96562. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  96563. #endif
  96564. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  96565. /*
  96566. * The data for the verify section
  96567. */
  96568. struct {
  96569. FLAC__StreamDecoder *decoder;
  96570. EncoderStateHint state_hint;
  96571. FLAC__bool needs_magic_hack;
  96572. verify_input_fifo input_fifo;
  96573. verify_output output;
  96574. struct {
  96575. FLAC__uint64 absolute_sample;
  96576. unsigned frame_number;
  96577. unsigned channel;
  96578. unsigned sample;
  96579. FLAC__int32 expected;
  96580. FLAC__int32 got;
  96581. } error_stats;
  96582. } verify;
  96583. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  96584. } FLAC__StreamEncoderPrivate;
  96585. /***********************************************************************
  96586. *
  96587. * Public static class data
  96588. *
  96589. ***********************************************************************/
  96590. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  96591. "FLAC__STREAM_ENCODER_OK",
  96592. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  96593. "FLAC__STREAM_ENCODER_OGG_ERROR",
  96594. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  96595. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  96596. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  96597. "FLAC__STREAM_ENCODER_IO_ERROR",
  96598. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  96599. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  96600. };
  96601. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  96602. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  96603. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  96604. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  96605. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  96606. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  96607. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  96608. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  96609. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  96610. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  96611. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  96612. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  96613. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  96614. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  96615. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  96616. };
  96617. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  96618. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  96619. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  96620. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  96621. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  96622. };
  96623. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  96624. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  96625. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  96626. };
  96627. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  96628. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  96629. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  96630. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  96631. };
  96632. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  96633. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  96634. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  96635. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  96636. };
  96637. /* Number of samples that will be overread to watch for end of stream. By
  96638. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  96639. * always try to read blocksize+1 samples before encoding a block, so that
  96640. * even if the stream has a total sample count that is an integral multiple
  96641. * of the blocksize, we will still notice when we are encoding the last
  96642. * block. This is needed, for example, to correctly set the end-of-stream
  96643. * marker in Ogg FLAC.
  96644. *
  96645. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  96646. * not really any reason to change it.
  96647. */
  96648. static const unsigned OVERREAD_ = 1;
  96649. /***********************************************************************
  96650. *
  96651. * Class constructor/destructor
  96652. *
  96653. */
  96654. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  96655. {
  96656. FLAC__StreamEncoder *encoder;
  96657. unsigned i;
  96658. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  96659. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  96660. if(encoder == 0) {
  96661. return 0;
  96662. }
  96663. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  96664. if(encoder->protected_ == 0) {
  96665. free(encoder);
  96666. return 0;
  96667. }
  96668. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  96669. if(encoder->private_ == 0) {
  96670. free(encoder->protected_);
  96671. free(encoder);
  96672. return 0;
  96673. }
  96674. encoder->private_->frame = FLAC__bitwriter_new();
  96675. if(encoder->private_->frame == 0) {
  96676. free(encoder->private_);
  96677. free(encoder->protected_);
  96678. free(encoder);
  96679. return 0;
  96680. }
  96681. encoder->private_->file = 0;
  96682. set_defaults_enc(encoder);
  96683. encoder->private_->is_being_deleted = false;
  96684. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96685. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  96686. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  96687. }
  96688. for(i = 0; i < 2; i++) {
  96689. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  96690. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  96691. }
  96692. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96693. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  96694. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  96695. }
  96696. for(i = 0; i < 2; i++) {
  96697. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  96698. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  96699. }
  96700. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96701. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  96702. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  96703. }
  96704. for(i = 0; i < 2; i++) {
  96705. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  96706. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  96707. }
  96708. for(i = 0; i < 2; i++)
  96709. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  96710. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  96711. return encoder;
  96712. }
  96713. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  96714. {
  96715. unsigned i;
  96716. FLAC__ASSERT(0 != encoder);
  96717. FLAC__ASSERT(0 != encoder->protected_);
  96718. FLAC__ASSERT(0 != encoder->private_);
  96719. FLAC__ASSERT(0 != encoder->private_->frame);
  96720. encoder->private_->is_being_deleted = true;
  96721. (void)FLAC__stream_encoder_finish(encoder);
  96722. if(0 != encoder->private_->verify.decoder)
  96723. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  96724. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96725. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  96726. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  96727. }
  96728. for(i = 0; i < 2; i++) {
  96729. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  96730. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  96731. }
  96732. for(i = 0; i < 2; i++)
  96733. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  96734. FLAC__bitwriter_delete(encoder->private_->frame);
  96735. free(encoder->private_);
  96736. free(encoder->protected_);
  96737. free(encoder);
  96738. }
  96739. /***********************************************************************
  96740. *
  96741. * Public class methods
  96742. *
  96743. ***********************************************************************/
  96744. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  96745. FLAC__StreamEncoder *encoder,
  96746. FLAC__StreamEncoderReadCallback read_callback,
  96747. FLAC__StreamEncoderWriteCallback write_callback,
  96748. FLAC__StreamEncoderSeekCallback seek_callback,
  96749. FLAC__StreamEncoderTellCallback tell_callback,
  96750. FLAC__StreamEncoderMetadataCallback metadata_callback,
  96751. void *client_data,
  96752. FLAC__bool is_ogg
  96753. )
  96754. {
  96755. unsigned i;
  96756. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  96757. FLAC__ASSERT(0 != encoder);
  96758. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96759. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  96760. #if !FLAC__HAS_OGG
  96761. if(is_ogg)
  96762. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  96763. #endif
  96764. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  96765. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  96766. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  96767. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  96768. if(encoder->protected_->channels != 2) {
  96769. encoder->protected_->do_mid_side_stereo = false;
  96770. encoder->protected_->loose_mid_side_stereo = false;
  96771. }
  96772. else if(!encoder->protected_->do_mid_side_stereo)
  96773. encoder->protected_->loose_mid_side_stereo = false;
  96774. if(encoder->protected_->bits_per_sample >= 32)
  96775. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  96776. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  96777. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  96778. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  96779. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  96780. if(encoder->protected_->blocksize == 0) {
  96781. if(encoder->protected_->max_lpc_order == 0)
  96782. encoder->protected_->blocksize = 1152;
  96783. else
  96784. encoder->protected_->blocksize = 4096;
  96785. }
  96786. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  96787. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  96788. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  96789. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  96790. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  96791. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  96792. if(encoder->protected_->qlp_coeff_precision == 0) {
  96793. if(encoder->protected_->bits_per_sample < 16) {
  96794. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  96795. /* @@@ until then we'll make a guess */
  96796. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  96797. }
  96798. else if(encoder->protected_->bits_per_sample == 16) {
  96799. if(encoder->protected_->blocksize <= 192)
  96800. encoder->protected_->qlp_coeff_precision = 7;
  96801. else if(encoder->protected_->blocksize <= 384)
  96802. encoder->protected_->qlp_coeff_precision = 8;
  96803. else if(encoder->protected_->blocksize <= 576)
  96804. encoder->protected_->qlp_coeff_precision = 9;
  96805. else if(encoder->protected_->blocksize <= 1152)
  96806. encoder->protected_->qlp_coeff_precision = 10;
  96807. else if(encoder->protected_->blocksize <= 2304)
  96808. encoder->protected_->qlp_coeff_precision = 11;
  96809. else if(encoder->protected_->blocksize <= 4608)
  96810. encoder->protected_->qlp_coeff_precision = 12;
  96811. else
  96812. encoder->protected_->qlp_coeff_precision = 13;
  96813. }
  96814. else {
  96815. if(encoder->protected_->blocksize <= 384)
  96816. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  96817. else if(encoder->protected_->blocksize <= 1152)
  96818. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  96819. else
  96820. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  96821. }
  96822. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  96823. }
  96824. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  96825. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  96826. if(encoder->protected_->streamable_subset) {
  96827. if(
  96828. encoder->protected_->blocksize != 192 &&
  96829. encoder->protected_->blocksize != 576 &&
  96830. encoder->protected_->blocksize != 1152 &&
  96831. encoder->protected_->blocksize != 2304 &&
  96832. encoder->protected_->blocksize != 4608 &&
  96833. encoder->protected_->blocksize != 256 &&
  96834. encoder->protected_->blocksize != 512 &&
  96835. encoder->protected_->blocksize != 1024 &&
  96836. encoder->protected_->blocksize != 2048 &&
  96837. encoder->protected_->blocksize != 4096 &&
  96838. encoder->protected_->blocksize != 8192 &&
  96839. encoder->protected_->blocksize != 16384
  96840. )
  96841. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96842. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  96843. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96844. if(
  96845. encoder->protected_->bits_per_sample != 8 &&
  96846. encoder->protected_->bits_per_sample != 12 &&
  96847. encoder->protected_->bits_per_sample != 16 &&
  96848. encoder->protected_->bits_per_sample != 20 &&
  96849. encoder->protected_->bits_per_sample != 24
  96850. )
  96851. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96852. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  96853. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96854. if(
  96855. encoder->protected_->sample_rate <= 48000 &&
  96856. (
  96857. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  96858. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  96859. )
  96860. ) {
  96861. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96862. }
  96863. }
  96864. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  96865. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  96866. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  96867. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  96868. #if FLAC__HAS_OGG
  96869. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  96870. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  96871. unsigned i;
  96872. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  96873. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  96874. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  96875. for( ; i > 0; i--)
  96876. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  96877. encoder->protected_->metadata[0] = vc;
  96878. break;
  96879. }
  96880. }
  96881. }
  96882. #endif
  96883. /* keep track of any SEEKTABLE block */
  96884. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  96885. unsigned i;
  96886. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  96887. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  96888. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  96889. break; /* take only the first one */
  96890. }
  96891. }
  96892. }
  96893. /* validate metadata */
  96894. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  96895. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96896. metadata_has_seektable = false;
  96897. metadata_has_vorbis_comment = false;
  96898. metadata_picture_has_type1 = false;
  96899. metadata_picture_has_type2 = false;
  96900. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  96901. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  96902. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  96903. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96904. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  96905. if(metadata_has_seektable) /* only one is allowed */
  96906. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96907. metadata_has_seektable = true;
  96908. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  96909. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96910. }
  96911. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  96912. if(metadata_has_vorbis_comment) /* only one is allowed */
  96913. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96914. metadata_has_vorbis_comment = true;
  96915. }
  96916. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  96917. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  96918. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96919. }
  96920. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  96921. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  96922. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96923. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  96924. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  96925. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96926. metadata_picture_has_type1 = true;
  96927. /* standard icon must be 32x32 pixel PNG */
  96928. if(
  96929. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  96930. (
  96931. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  96932. m->data.picture.width != 32 ||
  96933. m->data.picture.height != 32
  96934. )
  96935. )
  96936. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96937. }
  96938. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  96939. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  96940. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96941. metadata_picture_has_type2 = true;
  96942. }
  96943. }
  96944. }
  96945. encoder->private_->input_capacity = 0;
  96946. for(i = 0; i < encoder->protected_->channels; i++) {
  96947. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  96948. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96949. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  96950. #endif
  96951. }
  96952. for(i = 0; i < 2; i++) {
  96953. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  96954. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96955. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  96956. #endif
  96957. }
  96958. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96959. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  96960. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  96961. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  96962. #endif
  96963. for(i = 0; i < encoder->protected_->channels; i++) {
  96964. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  96965. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  96966. encoder->private_->best_subframe[i] = 0;
  96967. }
  96968. for(i = 0; i < 2; i++) {
  96969. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  96970. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  96971. encoder->private_->best_subframe_mid_side[i] = 0;
  96972. }
  96973. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  96974. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  96975. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96976. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  96977. #else
  96978. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  96979. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  96980. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  96981. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  96982. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  96983. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  96984. 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);
  96985. #endif
  96986. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  96987. encoder->private_->loose_mid_side_stereo_frames = 1;
  96988. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  96989. encoder->private_->current_sample_number = 0;
  96990. encoder->private_->current_frame_number = 0;
  96991. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  96992. 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? */
  96993. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  96994. /*
  96995. * get the CPU info and set the function pointers
  96996. */
  96997. FLAC__cpu_info(&encoder->private_->cpuinfo);
  96998. /* first default to the non-asm routines */
  96999. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97000. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  97001. #endif
  97002. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  97003. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97004. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  97005. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  97006. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  97007. #endif
  97008. /* now override with asm where appropriate */
  97009. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97010. # ifndef FLAC__NO_ASM
  97011. if(encoder->private_->cpuinfo.use_asm) {
  97012. # ifdef FLAC__CPU_IA32
  97013. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  97014. # ifdef FLAC__HAS_NASM
  97015. if(encoder->private_->cpuinfo.data.ia32.sse) {
  97016. if(encoder->protected_->max_lpc_order < 4)
  97017. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  97018. else if(encoder->protected_->max_lpc_order < 8)
  97019. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  97020. else if(encoder->protected_->max_lpc_order < 12)
  97021. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  97022. else
  97023. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  97024. }
  97025. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  97026. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  97027. else
  97028. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  97029. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  97030. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  97031. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  97032. }
  97033. else {
  97034. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  97035. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  97036. }
  97037. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  97038. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  97039. # endif /* FLAC__HAS_NASM */
  97040. # endif /* FLAC__CPU_IA32 */
  97041. }
  97042. # endif /* !FLAC__NO_ASM */
  97043. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  97044. /* finally override based on wide-ness if necessary */
  97045. if(encoder->private_->use_wide_by_block) {
  97046. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  97047. }
  97048. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  97049. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  97050. #if FLAC__HAS_OGG
  97051. encoder->private_->is_ogg = is_ogg;
  97052. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  97053. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  97054. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97055. }
  97056. #endif
  97057. encoder->private_->read_callback = read_callback;
  97058. encoder->private_->write_callback = write_callback;
  97059. encoder->private_->seek_callback = seek_callback;
  97060. encoder->private_->tell_callback = tell_callback;
  97061. encoder->private_->metadata_callback = metadata_callback;
  97062. encoder->private_->client_data = client_data;
  97063. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  97064. /* the above function sets the state for us in case of an error */
  97065. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97066. }
  97067. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  97068. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  97069. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97070. }
  97071. /*
  97072. * Set up the verify stuff if necessary
  97073. */
  97074. if(encoder->protected_->verify) {
  97075. /*
  97076. * First, set up the fifo which will hold the
  97077. * original signal to compare against
  97078. */
  97079. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  97080. for(i = 0; i < encoder->protected_->channels; i++) {
  97081. 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))) {
  97082. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  97083. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97084. }
  97085. }
  97086. encoder->private_->verify.input_fifo.tail = 0;
  97087. /*
  97088. * Now set up a stream decoder for verification
  97089. */
  97090. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  97091. if(0 == encoder->private_->verify.decoder) {
  97092. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  97093. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97094. }
  97095. 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) {
  97096. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  97097. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97098. }
  97099. }
  97100. encoder->private_->verify.error_stats.absolute_sample = 0;
  97101. encoder->private_->verify.error_stats.frame_number = 0;
  97102. encoder->private_->verify.error_stats.channel = 0;
  97103. encoder->private_->verify.error_stats.sample = 0;
  97104. encoder->private_->verify.error_stats.expected = 0;
  97105. encoder->private_->verify.error_stats.got = 0;
  97106. /*
  97107. * These must be done before we write any metadata, because that
  97108. * calls the write_callback, which uses these values.
  97109. */
  97110. encoder->private_->first_seekpoint_to_check = 0;
  97111. encoder->private_->samples_written = 0;
  97112. encoder->protected_->streaminfo_offset = 0;
  97113. encoder->protected_->seektable_offset = 0;
  97114. encoder->protected_->audio_offset = 0;
  97115. /*
  97116. * write the stream header
  97117. */
  97118. if(encoder->protected_->verify)
  97119. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  97120. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  97121. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  97122. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97123. }
  97124. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  97125. /* the above function sets the state for us in case of an error */
  97126. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97127. }
  97128. /*
  97129. * write the STREAMINFO metadata block
  97130. */
  97131. if(encoder->protected_->verify)
  97132. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  97133. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  97134. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  97135. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  97136. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  97137. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  97138. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  97139. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  97140. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  97141. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  97142. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  97143. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  97144. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  97145. if(encoder->protected_->do_md5)
  97146. FLAC__MD5Init(&encoder->private_->md5context);
  97147. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  97148. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  97149. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97150. }
  97151. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  97152. /* the above function sets the state for us in case of an error */
  97153. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97154. }
  97155. /*
  97156. * Now that the STREAMINFO block is written, we can init this to an
  97157. * absurdly-high value...
  97158. */
  97159. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  97160. /* ... and clear this to 0 */
  97161. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  97162. /*
  97163. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  97164. * if not, we will write an empty one (FLAC__add_metadata_block()
  97165. * automatically supplies the vendor string).
  97166. *
  97167. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  97168. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  97169. * true it will have already insured that the metadata list is properly
  97170. * ordered.)
  97171. */
  97172. if(!metadata_has_vorbis_comment) {
  97173. FLAC__StreamMetadata vorbis_comment;
  97174. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  97175. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  97176. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  97177. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  97178. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  97179. vorbis_comment.data.vorbis_comment.num_comments = 0;
  97180. vorbis_comment.data.vorbis_comment.comments = 0;
  97181. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  97182. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  97183. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97184. }
  97185. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  97186. /* the above function sets the state for us in case of an error */
  97187. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97188. }
  97189. }
  97190. /*
  97191. * write the user's metadata blocks
  97192. */
  97193. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  97194. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  97195. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  97196. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  97197. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97198. }
  97199. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  97200. /* the above function sets the state for us in case of an error */
  97201. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97202. }
  97203. }
  97204. /* now that all the metadata is written, we save the stream offset */
  97205. 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 */
  97206. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97207. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97208. }
  97209. if(encoder->protected_->verify)
  97210. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  97211. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  97212. }
  97213. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  97214. FLAC__StreamEncoder *encoder,
  97215. FLAC__StreamEncoderWriteCallback write_callback,
  97216. FLAC__StreamEncoderSeekCallback seek_callback,
  97217. FLAC__StreamEncoderTellCallback tell_callback,
  97218. FLAC__StreamEncoderMetadataCallback metadata_callback,
  97219. void *client_data
  97220. )
  97221. {
  97222. return init_stream_internal_enc(
  97223. encoder,
  97224. /*read_callback=*/0,
  97225. write_callback,
  97226. seek_callback,
  97227. tell_callback,
  97228. metadata_callback,
  97229. client_data,
  97230. /*is_ogg=*/false
  97231. );
  97232. }
  97233. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  97234. FLAC__StreamEncoder *encoder,
  97235. FLAC__StreamEncoderReadCallback read_callback,
  97236. FLAC__StreamEncoderWriteCallback write_callback,
  97237. FLAC__StreamEncoderSeekCallback seek_callback,
  97238. FLAC__StreamEncoderTellCallback tell_callback,
  97239. FLAC__StreamEncoderMetadataCallback metadata_callback,
  97240. void *client_data
  97241. )
  97242. {
  97243. return init_stream_internal_enc(
  97244. encoder,
  97245. read_callback,
  97246. write_callback,
  97247. seek_callback,
  97248. tell_callback,
  97249. metadata_callback,
  97250. client_data,
  97251. /*is_ogg=*/true
  97252. );
  97253. }
  97254. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  97255. FLAC__StreamEncoder *encoder,
  97256. FILE *file,
  97257. FLAC__StreamEncoderProgressCallback progress_callback,
  97258. void *client_data,
  97259. FLAC__bool is_ogg
  97260. )
  97261. {
  97262. FLAC__StreamEncoderInitStatus init_status;
  97263. FLAC__ASSERT(0 != encoder);
  97264. FLAC__ASSERT(0 != file);
  97265. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97266. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  97267. /* double protection */
  97268. if(file == 0) {
  97269. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  97270. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97271. }
  97272. /*
  97273. * To make sure that our file does not go unclosed after an error, we
  97274. * must assign the FILE pointer before any further error can occur in
  97275. * this routine.
  97276. */
  97277. if(file == stdout)
  97278. file = get_binary_stdout_(); /* just to be safe */
  97279. encoder->private_->file = file;
  97280. encoder->private_->progress_callback = progress_callback;
  97281. encoder->private_->bytes_written = 0;
  97282. encoder->private_->samples_written = 0;
  97283. encoder->private_->frames_written = 0;
  97284. init_status = init_stream_internal_enc(
  97285. encoder,
  97286. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  97287. file_write_callback_,
  97288. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  97289. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  97290. /*metadata_callback=*/0,
  97291. client_data,
  97292. is_ogg
  97293. );
  97294. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  97295. /* the above function sets the state for us in case of an error */
  97296. return init_status;
  97297. }
  97298. {
  97299. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  97300. FLAC__ASSERT(blocksize != 0);
  97301. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  97302. }
  97303. return init_status;
  97304. }
  97305. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  97306. FLAC__StreamEncoder *encoder,
  97307. FILE *file,
  97308. FLAC__StreamEncoderProgressCallback progress_callback,
  97309. void *client_data
  97310. )
  97311. {
  97312. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  97313. }
  97314. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  97315. FLAC__StreamEncoder *encoder,
  97316. FILE *file,
  97317. FLAC__StreamEncoderProgressCallback progress_callback,
  97318. void *client_data
  97319. )
  97320. {
  97321. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  97322. }
  97323. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  97324. FLAC__StreamEncoder *encoder,
  97325. const char *filename,
  97326. FLAC__StreamEncoderProgressCallback progress_callback,
  97327. void *client_data,
  97328. FLAC__bool is_ogg
  97329. )
  97330. {
  97331. FILE *file;
  97332. FLAC__ASSERT(0 != encoder);
  97333. /*
  97334. * To make sure that our file does not go unclosed after an error, we
  97335. * have to do the same entrance checks here that are later performed
  97336. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  97337. */
  97338. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97339. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  97340. file = filename? fopen(filename, "w+b") : stdout;
  97341. if(file == 0) {
  97342. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  97343. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97344. }
  97345. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  97346. }
  97347. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  97348. FLAC__StreamEncoder *encoder,
  97349. const char *filename,
  97350. FLAC__StreamEncoderProgressCallback progress_callback,
  97351. void *client_data
  97352. )
  97353. {
  97354. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  97355. }
  97356. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  97357. FLAC__StreamEncoder *encoder,
  97358. const char *filename,
  97359. FLAC__StreamEncoderProgressCallback progress_callback,
  97360. void *client_data
  97361. )
  97362. {
  97363. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  97364. }
  97365. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  97366. {
  97367. FLAC__bool error = false;
  97368. FLAC__ASSERT(0 != encoder);
  97369. FLAC__ASSERT(0 != encoder->private_);
  97370. FLAC__ASSERT(0 != encoder->protected_);
  97371. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  97372. return true;
  97373. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  97374. if(encoder->private_->current_sample_number != 0) {
  97375. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  97376. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  97377. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  97378. error = true;
  97379. }
  97380. }
  97381. if(encoder->protected_->do_md5)
  97382. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  97383. if(!encoder->private_->is_being_deleted) {
  97384. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  97385. if(encoder->private_->seek_callback) {
  97386. #if FLAC__HAS_OGG
  97387. if(encoder->private_->is_ogg)
  97388. update_ogg_metadata_(encoder);
  97389. else
  97390. #endif
  97391. update_metadata_(encoder);
  97392. /* check if an error occurred while updating metadata */
  97393. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  97394. error = true;
  97395. }
  97396. if(encoder->private_->metadata_callback)
  97397. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  97398. }
  97399. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  97400. if(!error)
  97401. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  97402. error = true;
  97403. }
  97404. }
  97405. if(0 != encoder->private_->file) {
  97406. if(encoder->private_->file != stdout)
  97407. fclose(encoder->private_->file);
  97408. encoder->private_->file = 0;
  97409. }
  97410. #if FLAC__HAS_OGG
  97411. if(encoder->private_->is_ogg)
  97412. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  97413. #endif
  97414. free_(encoder);
  97415. set_defaults_enc(encoder);
  97416. if(!error)
  97417. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  97418. return !error;
  97419. }
  97420. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  97421. {
  97422. FLAC__ASSERT(0 != encoder);
  97423. FLAC__ASSERT(0 != encoder->private_);
  97424. FLAC__ASSERT(0 != encoder->protected_);
  97425. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97426. return false;
  97427. #if FLAC__HAS_OGG
  97428. /* can't check encoder->private_->is_ogg since that's not set until init time */
  97429. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  97430. return true;
  97431. #else
  97432. (void)value;
  97433. return false;
  97434. #endif
  97435. }
  97436. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97437. {
  97438. FLAC__ASSERT(0 != encoder);
  97439. FLAC__ASSERT(0 != encoder->private_);
  97440. FLAC__ASSERT(0 != encoder->protected_);
  97441. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97442. return false;
  97443. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  97444. encoder->protected_->verify = value;
  97445. #endif
  97446. return true;
  97447. }
  97448. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97449. {
  97450. FLAC__ASSERT(0 != encoder);
  97451. FLAC__ASSERT(0 != encoder->private_);
  97452. FLAC__ASSERT(0 != encoder->protected_);
  97453. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97454. return false;
  97455. encoder->protected_->streamable_subset = value;
  97456. return true;
  97457. }
  97458. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97459. {
  97460. FLAC__ASSERT(0 != encoder);
  97461. FLAC__ASSERT(0 != encoder->private_);
  97462. FLAC__ASSERT(0 != encoder->protected_);
  97463. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97464. return false;
  97465. encoder->protected_->do_md5 = value;
  97466. return true;
  97467. }
  97468. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  97469. {
  97470. FLAC__ASSERT(0 != encoder);
  97471. FLAC__ASSERT(0 != encoder->private_);
  97472. FLAC__ASSERT(0 != encoder->protected_);
  97473. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97474. return false;
  97475. encoder->protected_->channels = value;
  97476. return true;
  97477. }
  97478. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  97479. {
  97480. FLAC__ASSERT(0 != encoder);
  97481. FLAC__ASSERT(0 != encoder->private_);
  97482. FLAC__ASSERT(0 != encoder->protected_);
  97483. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97484. return false;
  97485. encoder->protected_->bits_per_sample = value;
  97486. return true;
  97487. }
  97488. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  97489. {
  97490. FLAC__ASSERT(0 != encoder);
  97491. FLAC__ASSERT(0 != encoder->private_);
  97492. FLAC__ASSERT(0 != encoder->protected_);
  97493. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97494. return false;
  97495. encoder->protected_->sample_rate = value;
  97496. return true;
  97497. }
  97498. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  97499. {
  97500. FLAC__bool ok = true;
  97501. FLAC__ASSERT(0 != encoder);
  97502. FLAC__ASSERT(0 != encoder->private_);
  97503. FLAC__ASSERT(0 != encoder->protected_);
  97504. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97505. return false;
  97506. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  97507. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  97508. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  97509. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  97510. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97511. #if 0
  97512. /* was: */
  97513. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  97514. /* but it's too hard to specify the string in a locale-specific way */
  97515. #else
  97516. encoder->protected_->num_apodizations = 1;
  97517. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  97518. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  97519. #endif
  97520. #endif
  97521. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  97522. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  97523. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  97524. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  97525. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  97526. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  97527. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  97528. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  97529. return ok;
  97530. }
  97531. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  97532. {
  97533. FLAC__ASSERT(0 != encoder);
  97534. FLAC__ASSERT(0 != encoder->private_);
  97535. FLAC__ASSERT(0 != encoder->protected_);
  97536. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97537. return false;
  97538. encoder->protected_->blocksize = value;
  97539. return true;
  97540. }
  97541. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97542. {
  97543. FLAC__ASSERT(0 != encoder);
  97544. FLAC__ASSERT(0 != encoder->private_);
  97545. FLAC__ASSERT(0 != encoder->protected_);
  97546. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97547. return false;
  97548. encoder->protected_->do_mid_side_stereo = value;
  97549. return true;
  97550. }
  97551. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97552. {
  97553. FLAC__ASSERT(0 != encoder);
  97554. FLAC__ASSERT(0 != encoder->private_);
  97555. FLAC__ASSERT(0 != encoder->protected_);
  97556. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97557. return false;
  97558. encoder->protected_->loose_mid_side_stereo = value;
  97559. return true;
  97560. }
  97561. /*@@@@add to tests*/
  97562. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  97563. {
  97564. FLAC__ASSERT(0 != encoder);
  97565. FLAC__ASSERT(0 != encoder->private_);
  97566. FLAC__ASSERT(0 != encoder->protected_);
  97567. FLAC__ASSERT(0 != specification);
  97568. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97569. return false;
  97570. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  97571. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  97572. #else
  97573. encoder->protected_->num_apodizations = 0;
  97574. while(1) {
  97575. const char *s = strchr(specification, ';');
  97576. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  97577. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  97578. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  97579. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  97580. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  97581. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  97582. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  97583. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  97584. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  97585. else if(n==6 && 0 == strncmp("connes" , specification, n))
  97586. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  97587. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  97588. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  97589. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  97590. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  97591. if (stddev > 0.0 && stddev <= 0.5) {
  97592. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  97593. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  97594. }
  97595. }
  97596. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  97597. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  97598. else if(n==4 && 0 == strncmp("hann" , specification, n))
  97599. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  97600. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  97601. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  97602. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  97603. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  97604. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  97605. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  97606. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  97607. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  97608. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  97609. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  97610. if (p >= 0.0 && p <= 1.0) {
  97611. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  97612. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  97613. }
  97614. }
  97615. else if(n==5 && 0 == strncmp("welch" , specification, n))
  97616. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  97617. if (encoder->protected_->num_apodizations == 32)
  97618. break;
  97619. if (s)
  97620. specification = s+1;
  97621. else
  97622. break;
  97623. }
  97624. if(encoder->protected_->num_apodizations == 0) {
  97625. encoder->protected_->num_apodizations = 1;
  97626. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  97627. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  97628. }
  97629. #endif
  97630. return true;
  97631. }
  97632. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  97633. {
  97634. FLAC__ASSERT(0 != encoder);
  97635. FLAC__ASSERT(0 != encoder->private_);
  97636. FLAC__ASSERT(0 != encoder->protected_);
  97637. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97638. return false;
  97639. encoder->protected_->max_lpc_order = value;
  97640. return true;
  97641. }
  97642. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  97643. {
  97644. FLAC__ASSERT(0 != encoder);
  97645. FLAC__ASSERT(0 != encoder->private_);
  97646. FLAC__ASSERT(0 != encoder->protected_);
  97647. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97648. return false;
  97649. encoder->protected_->qlp_coeff_precision = value;
  97650. return true;
  97651. }
  97652. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97653. {
  97654. FLAC__ASSERT(0 != encoder);
  97655. FLAC__ASSERT(0 != encoder->private_);
  97656. FLAC__ASSERT(0 != encoder->protected_);
  97657. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97658. return false;
  97659. encoder->protected_->do_qlp_coeff_prec_search = value;
  97660. return true;
  97661. }
  97662. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97663. {
  97664. FLAC__ASSERT(0 != encoder);
  97665. FLAC__ASSERT(0 != encoder->private_);
  97666. FLAC__ASSERT(0 != encoder->protected_);
  97667. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97668. return false;
  97669. #if 0
  97670. /*@@@ deprecated: */
  97671. encoder->protected_->do_escape_coding = value;
  97672. #else
  97673. (void)value;
  97674. #endif
  97675. return true;
  97676. }
  97677. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97678. {
  97679. FLAC__ASSERT(0 != encoder);
  97680. FLAC__ASSERT(0 != encoder->private_);
  97681. FLAC__ASSERT(0 != encoder->protected_);
  97682. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97683. return false;
  97684. encoder->protected_->do_exhaustive_model_search = value;
  97685. return true;
  97686. }
  97687. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  97688. {
  97689. FLAC__ASSERT(0 != encoder);
  97690. FLAC__ASSERT(0 != encoder->private_);
  97691. FLAC__ASSERT(0 != encoder->protected_);
  97692. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97693. return false;
  97694. encoder->protected_->min_residual_partition_order = value;
  97695. return true;
  97696. }
  97697. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  97698. {
  97699. FLAC__ASSERT(0 != encoder);
  97700. FLAC__ASSERT(0 != encoder->private_);
  97701. FLAC__ASSERT(0 != encoder->protected_);
  97702. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97703. return false;
  97704. encoder->protected_->max_residual_partition_order = value;
  97705. return true;
  97706. }
  97707. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  97708. {
  97709. FLAC__ASSERT(0 != encoder);
  97710. FLAC__ASSERT(0 != encoder->private_);
  97711. FLAC__ASSERT(0 != encoder->protected_);
  97712. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97713. return false;
  97714. #if 0
  97715. /*@@@ deprecated: */
  97716. encoder->protected_->rice_parameter_search_dist = value;
  97717. #else
  97718. (void)value;
  97719. #endif
  97720. return true;
  97721. }
  97722. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  97723. {
  97724. FLAC__ASSERT(0 != encoder);
  97725. FLAC__ASSERT(0 != encoder->private_);
  97726. FLAC__ASSERT(0 != encoder->protected_);
  97727. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97728. return false;
  97729. encoder->protected_->total_samples_estimate = value;
  97730. return true;
  97731. }
  97732. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  97733. {
  97734. FLAC__ASSERT(0 != encoder);
  97735. FLAC__ASSERT(0 != encoder->private_);
  97736. FLAC__ASSERT(0 != encoder->protected_);
  97737. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97738. return false;
  97739. if(0 == metadata)
  97740. num_blocks = 0;
  97741. if(0 == num_blocks)
  97742. metadata = 0;
  97743. /* realloc() does not do exactly what we want so... */
  97744. if(encoder->protected_->metadata) {
  97745. free(encoder->protected_->metadata);
  97746. encoder->protected_->metadata = 0;
  97747. encoder->protected_->num_metadata_blocks = 0;
  97748. }
  97749. if(num_blocks) {
  97750. FLAC__StreamMetadata **m;
  97751. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  97752. return false;
  97753. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  97754. encoder->protected_->metadata = m;
  97755. encoder->protected_->num_metadata_blocks = num_blocks;
  97756. }
  97757. #if FLAC__HAS_OGG
  97758. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  97759. return false;
  97760. #endif
  97761. return true;
  97762. }
  97763. /*
  97764. * These three functions are not static, but not publically exposed in
  97765. * include/FLAC/ either. They are used by the test suite.
  97766. */
  97767. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97768. {
  97769. FLAC__ASSERT(0 != encoder);
  97770. FLAC__ASSERT(0 != encoder->private_);
  97771. FLAC__ASSERT(0 != encoder->protected_);
  97772. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97773. return false;
  97774. encoder->private_->disable_constant_subframes = value;
  97775. return true;
  97776. }
  97777. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97778. {
  97779. FLAC__ASSERT(0 != encoder);
  97780. FLAC__ASSERT(0 != encoder->private_);
  97781. FLAC__ASSERT(0 != encoder->protected_);
  97782. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97783. return false;
  97784. encoder->private_->disable_fixed_subframes = value;
  97785. return true;
  97786. }
  97787. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97788. {
  97789. FLAC__ASSERT(0 != encoder);
  97790. FLAC__ASSERT(0 != encoder->private_);
  97791. FLAC__ASSERT(0 != encoder->protected_);
  97792. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97793. return false;
  97794. encoder->private_->disable_verbatim_subframes = value;
  97795. return true;
  97796. }
  97797. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  97798. {
  97799. FLAC__ASSERT(0 != encoder);
  97800. FLAC__ASSERT(0 != encoder->private_);
  97801. FLAC__ASSERT(0 != encoder->protected_);
  97802. return encoder->protected_->state;
  97803. }
  97804. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  97805. {
  97806. FLAC__ASSERT(0 != encoder);
  97807. FLAC__ASSERT(0 != encoder->private_);
  97808. FLAC__ASSERT(0 != encoder->protected_);
  97809. if(encoder->protected_->verify)
  97810. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  97811. else
  97812. return FLAC__STREAM_DECODER_UNINITIALIZED;
  97813. }
  97814. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  97815. {
  97816. FLAC__ASSERT(0 != encoder);
  97817. FLAC__ASSERT(0 != encoder->private_);
  97818. FLAC__ASSERT(0 != encoder->protected_);
  97819. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  97820. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  97821. else
  97822. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  97823. }
  97824. 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)
  97825. {
  97826. FLAC__ASSERT(0 != encoder);
  97827. FLAC__ASSERT(0 != encoder->private_);
  97828. FLAC__ASSERT(0 != encoder->protected_);
  97829. if(0 != absolute_sample)
  97830. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  97831. if(0 != frame_number)
  97832. *frame_number = encoder->private_->verify.error_stats.frame_number;
  97833. if(0 != channel)
  97834. *channel = encoder->private_->verify.error_stats.channel;
  97835. if(0 != sample)
  97836. *sample = encoder->private_->verify.error_stats.sample;
  97837. if(0 != expected)
  97838. *expected = encoder->private_->verify.error_stats.expected;
  97839. if(0 != got)
  97840. *got = encoder->private_->verify.error_stats.got;
  97841. }
  97842. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  97843. {
  97844. FLAC__ASSERT(0 != encoder);
  97845. FLAC__ASSERT(0 != encoder->private_);
  97846. FLAC__ASSERT(0 != encoder->protected_);
  97847. return encoder->protected_->verify;
  97848. }
  97849. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  97850. {
  97851. FLAC__ASSERT(0 != encoder);
  97852. FLAC__ASSERT(0 != encoder->private_);
  97853. FLAC__ASSERT(0 != encoder->protected_);
  97854. return encoder->protected_->streamable_subset;
  97855. }
  97856. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  97857. {
  97858. FLAC__ASSERT(0 != encoder);
  97859. FLAC__ASSERT(0 != encoder->private_);
  97860. FLAC__ASSERT(0 != encoder->protected_);
  97861. return encoder->protected_->do_md5;
  97862. }
  97863. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  97864. {
  97865. FLAC__ASSERT(0 != encoder);
  97866. FLAC__ASSERT(0 != encoder->private_);
  97867. FLAC__ASSERT(0 != encoder->protected_);
  97868. return encoder->protected_->channels;
  97869. }
  97870. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  97871. {
  97872. FLAC__ASSERT(0 != encoder);
  97873. FLAC__ASSERT(0 != encoder->private_);
  97874. FLAC__ASSERT(0 != encoder->protected_);
  97875. return encoder->protected_->bits_per_sample;
  97876. }
  97877. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  97878. {
  97879. FLAC__ASSERT(0 != encoder);
  97880. FLAC__ASSERT(0 != encoder->private_);
  97881. FLAC__ASSERT(0 != encoder->protected_);
  97882. return encoder->protected_->sample_rate;
  97883. }
  97884. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  97885. {
  97886. FLAC__ASSERT(0 != encoder);
  97887. FLAC__ASSERT(0 != encoder->private_);
  97888. FLAC__ASSERT(0 != encoder->protected_);
  97889. return encoder->protected_->blocksize;
  97890. }
  97891. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  97892. {
  97893. FLAC__ASSERT(0 != encoder);
  97894. FLAC__ASSERT(0 != encoder->private_);
  97895. FLAC__ASSERT(0 != encoder->protected_);
  97896. return encoder->protected_->do_mid_side_stereo;
  97897. }
  97898. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  97899. {
  97900. FLAC__ASSERT(0 != encoder);
  97901. FLAC__ASSERT(0 != encoder->private_);
  97902. FLAC__ASSERT(0 != encoder->protected_);
  97903. return encoder->protected_->loose_mid_side_stereo;
  97904. }
  97905. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  97906. {
  97907. FLAC__ASSERT(0 != encoder);
  97908. FLAC__ASSERT(0 != encoder->private_);
  97909. FLAC__ASSERT(0 != encoder->protected_);
  97910. return encoder->protected_->max_lpc_order;
  97911. }
  97912. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  97913. {
  97914. FLAC__ASSERT(0 != encoder);
  97915. FLAC__ASSERT(0 != encoder->private_);
  97916. FLAC__ASSERT(0 != encoder->protected_);
  97917. return encoder->protected_->qlp_coeff_precision;
  97918. }
  97919. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  97920. {
  97921. FLAC__ASSERT(0 != encoder);
  97922. FLAC__ASSERT(0 != encoder->private_);
  97923. FLAC__ASSERT(0 != encoder->protected_);
  97924. return encoder->protected_->do_qlp_coeff_prec_search;
  97925. }
  97926. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  97927. {
  97928. FLAC__ASSERT(0 != encoder);
  97929. FLAC__ASSERT(0 != encoder->private_);
  97930. FLAC__ASSERT(0 != encoder->protected_);
  97931. return encoder->protected_->do_escape_coding;
  97932. }
  97933. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  97934. {
  97935. FLAC__ASSERT(0 != encoder);
  97936. FLAC__ASSERT(0 != encoder->private_);
  97937. FLAC__ASSERT(0 != encoder->protected_);
  97938. return encoder->protected_->do_exhaustive_model_search;
  97939. }
  97940. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  97941. {
  97942. FLAC__ASSERT(0 != encoder);
  97943. FLAC__ASSERT(0 != encoder->private_);
  97944. FLAC__ASSERT(0 != encoder->protected_);
  97945. return encoder->protected_->min_residual_partition_order;
  97946. }
  97947. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  97948. {
  97949. FLAC__ASSERT(0 != encoder);
  97950. FLAC__ASSERT(0 != encoder->private_);
  97951. FLAC__ASSERT(0 != encoder->protected_);
  97952. return encoder->protected_->max_residual_partition_order;
  97953. }
  97954. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  97955. {
  97956. FLAC__ASSERT(0 != encoder);
  97957. FLAC__ASSERT(0 != encoder->private_);
  97958. FLAC__ASSERT(0 != encoder->protected_);
  97959. return encoder->protected_->rice_parameter_search_dist;
  97960. }
  97961. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  97962. {
  97963. FLAC__ASSERT(0 != encoder);
  97964. FLAC__ASSERT(0 != encoder->private_);
  97965. FLAC__ASSERT(0 != encoder->protected_);
  97966. return encoder->protected_->total_samples_estimate;
  97967. }
  97968. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  97969. {
  97970. unsigned i, j = 0, channel;
  97971. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  97972. FLAC__ASSERT(0 != encoder);
  97973. FLAC__ASSERT(0 != encoder->private_);
  97974. FLAC__ASSERT(0 != encoder->protected_);
  97975. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  97976. do {
  97977. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  97978. if(encoder->protected_->verify)
  97979. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  97980. for(channel = 0; channel < channels; channel++)
  97981. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  97982. if(encoder->protected_->do_mid_side_stereo) {
  97983. FLAC__ASSERT(channels == 2);
  97984. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  97985. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  97986. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  97987. 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' ! */
  97988. }
  97989. }
  97990. else
  97991. j += n;
  97992. encoder->private_->current_sample_number += n;
  97993. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  97994. if(encoder->private_->current_sample_number > blocksize) {
  97995. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  97996. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  97997. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  97998. return false;
  97999. /* move unprocessed overread samples to beginnings of arrays */
  98000. for(channel = 0; channel < channels; channel++)
  98001. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  98002. if(encoder->protected_->do_mid_side_stereo) {
  98003. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  98004. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  98005. }
  98006. encoder->private_->current_sample_number = 1;
  98007. }
  98008. } while(j < samples);
  98009. return true;
  98010. }
  98011. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  98012. {
  98013. unsigned i, j, k, channel;
  98014. FLAC__int32 x, mid, side;
  98015. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  98016. FLAC__ASSERT(0 != encoder);
  98017. FLAC__ASSERT(0 != encoder->private_);
  98018. FLAC__ASSERT(0 != encoder->protected_);
  98019. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  98020. j = k = 0;
  98021. /*
  98022. * we have several flavors of the same basic loop, optimized for
  98023. * different conditions:
  98024. */
  98025. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  98026. /*
  98027. * stereo coding: unroll channel loop
  98028. */
  98029. do {
  98030. if(encoder->protected_->verify)
  98031. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  98032. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  98033. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  98034. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  98035. x = buffer[k++];
  98036. encoder->private_->integer_signal[1][i] = x;
  98037. mid += x;
  98038. side -= x;
  98039. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  98040. encoder->private_->integer_signal_mid_side[1][i] = side;
  98041. encoder->private_->integer_signal_mid_side[0][i] = mid;
  98042. }
  98043. encoder->private_->current_sample_number = i;
  98044. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  98045. if(i > blocksize) {
  98046. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  98047. return false;
  98048. /* move unprocessed overread samples to beginnings of arrays */
  98049. FLAC__ASSERT(i == blocksize+OVERREAD_);
  98050. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  98051. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  98052. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  98053. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  98054. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  98055. encoder->private_->current_sample_number = 1;
  98056. }
  98057. } while(j < samples);
  98058. }
  98059. else {
  98060. /*
  98061. * independent channel coding: buffer each channel in inner loop
  98062. */
  98063. do {
  98064. if(encoder->protected_->verify)
  98065. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  98066. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  98067. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  98068. for(channel = 0; channel < channels; channel++)
  98069. encoder->private_->integer_signal[channel][i] = buffer[k++];
  98070. }
  98071. encoder->private_->current_sample_number = i;
  98072. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  98073. if(i > blocksize) {
  98074. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  98075. return false;
  98076. /* move unprocessed overread samples to beginnings of arrays */
  98077. FLAC__ASSERT(i == blocksize+OVERREAD_);
  98078. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  98079. for(channel = 0; channel < channels; channel++)
  98080. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  98081. encoder->private_->current_sample_number = 1;
  98082. }
  98083. } while(j < samples);
  98084. }
  98085. return true;
  98086. }
  98087. /***********************************************************************
  98088. *
  98089. * Private class methods
  98090. *
  98091. ***********************************************************************/
  98092. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  98093. {
  98094. FLAC__ASSERT(0 != encoder);
  98095. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  98096. encoder->protected_->verify = true;
  98097. #else
  98098. encoder->protected_->verify = false;
  98099. #endif
  98100. encoder->protected_->streamable_subset = true;
  98101. encoder->protected_->do_md5 = true;
  98102. encoder->protected_->do_mid_side_stereo = false;
  98103. encoder->protected_->loose_mid_side_stereo = false;
  98104. encoder->protected_->channels = 2;
  98105. encoder->protected_->bits_per_sample = 16;
  98106. encoder->protected_->sample_rate = 44100;
  98107. encoder->protected_->blocksize = 0;
  98108. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98109. encoder->protected_->num_apodizations = 1;
  98110. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  98111. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  98112. #endif
  98113. encoder->protected_->max_lpc_order = 0;
  98114. encoder->protected_->qlp_coeff_precision = 0;
  98115. encoder->protected_->do_qlp_coeff_prec_search = false;
  98116. encoder->protected_->do_exhaustive_model_search = false;
  98117. encoder->protected_->do_escape_coding = false;
  98118. encoder->protected_->min_residual_partition_order = 0;
  98119. encoder->protected_->max_residual_partition_order = 0;
  98120. encoder->protected_->rice_parameter_search_dist = 0;
  98121. encoder->protected_->total_samples_estimate = 0;
  98122. encoder->protected_->metadata = 0;
  98123. encoder->protected_->num_metadata_blocks = 0;
  98124. encoder->private_->seek_table = 0;
  98125. encoder->private_->disable_constant_subframes = false;
  98126. encoder->private_->disable_fixed_subframes = false;
  98127. encoder->private_->disable_verbatim_subframes = false;
  98128. #if FLAC__HAS_OGG
  98129. encoder->private_->is_ogg = false;
  98130. #endif
  98131. encoder->private_->read_callback = 0;
  98132. encoder->private_->write_callback = 0;
  98133. encoder->private_->seek_callback = 0;
  98134. encoder->private_->tell_callback = 0;
  98135. encoder->private_->metadata_callback = 0;
  98136. encoder->private_->progress_callback = 0;
  98137. encoder->private_->client_data = 0;
  98138. #if FLAC__HAS_OGG
  98139. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  98140. #endif
  98141. }
  98142. void free_(FLAC__StreamEncoder *encoder)
  98143. {
  98144. unsigned i, channel;
  98145. FLAC__ASSERT(0 != encoder);
  98146. if(encoder->protected_->metadata) {
  98147. free(encoder->protected_->metadata);
  98148. encoder->protected_->metadata = 0;
  98149. encoder->protected_->num_metadata_blocks = 0;
  98150. }
  98151. for(i = 0; i < encoder->protected_->channels; i++) {
  98152. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  98153. free(encoder->private_->integer_signal_unaligned[i]);
  98154. encoder->private_->integer_signal_unaligned[i] = 0;
  98155. }
  98156. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98157. if(0 != encoder->private_->real_signal_unaligned[i]) {
  98158. free(encoder->private_->real_signal_unaligned[i]);
  98159. encoder->private_->real_signal_unaligned[i] = 0;
  98160. }
  98161. #endif
  98162. }
  98163. for(i = 0; i < 2; i++) {
  98164. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  98165. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  98166. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  98167. }
  98168. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98169. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  98170. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  98171. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  98172. }
  98173. #endif
  98174. }
  98175. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98176. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  98177. if(0 != encoder->private_->window_unaligned[i]) {
  98178. free(encoder->private_->window_unaligned[i]);
  98179. encoder->private_->window_unaligned[i] = 0;
  98180. }
  98181. }
  98182. if(0 != encoder->private_->windowed_signal_unaligned) {
  98183. free(encoder->private_->windowed_signal_unaligned);
  98184. encoder->private_->windowed_signal_unaligned = 0;
  98185. }
  98186. #endif
  98187. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  98188. for(i = 0; i < 2; i++) {
  98189. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  98190. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  98191. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  98192. }
  98193. }
  98194. }
  98195. for(channel = 0; channel < 2; channel++) {
  98196. for(i = 0; i < 2; i++) {
  98197. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  98198. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  98199. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  98200. }
  98201. }
  98202. }
  98203. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  98204. free(encoder->private_->abs_residual_partition_sums_unaligned);
  98205. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  98206. }
  98207. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  98208. free(encoder->private_->raw_bits_per_partition_unaligned);
  98209. encoder->private_->raw_bits_per_partition_unaligned = 0;
  98210. }
  98211. if(encoder->protected_->verify) {
  98212. for(i = 0; i < encoder->protected_->channels; i++) {
  98213. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  98214. free(encoder->private_->verify.input_fifo.data[i]);
  98215. encoder->private_->verify.input_fifo.data[i] = 0;
  98216. }
  98217. }
  98218. }
  98219. FLAC__bitwriter_free(encoder->private_->frame);
  98220. }
  98221. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  98222. {
  98223. FLAC__bool ok;
  98224. unsigned i, channel;
  98225. FLAC__ASSERT(new_blocksize > 0);
  98226. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  98227. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  98228. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  98229. if(new_blocksize <= encoder->private_->input_capacity)
  98230. return true;
  98231. ok = true;
  98232. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  98233. * requires that the input arrays (in our case the integer signals)
  98234. * have a buffer of up to 3 zeroes in front (at negative indices) for
  98235. * alignment purposes; we use 4 in front to keep the data well-aligned.
  98236. */
  98237. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  98238. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  98239. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  98240. encoder->private_->integer_signal[i] += 4;
  98241. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98242. #if 0 /* @@@ currently unused */
  98243. if(encoder->protected_->max_lpc_order > 0)
  98244. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  98245. #endif
  98246. #endif
  98247. }
  98248. for(i = 0; ok && i < 2; i++) {
  98249. 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]);
  98250. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  98251. encoder->private_->integer_signal_mid_side[i] += 4;
  98252. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98253. #if 0 /* @@@ currently unused */
  98254. if(encoder->protected_->max_lpc_order > 0)
  98255. 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]);
  98256. #endif
  98257. #endif
  98258. }
  98259. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98260. if(ok && encoder->protected_->max_lpc_order > 0) {
  98261. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  98262. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  98263. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  98264. }
  98265. #endif
  98266. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  98267. for(i = 0; ok && i < 2; i++) {
  98268. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  98269. }
  98270. }
  98271. for(channel = 0; ok && channel < 2; channel++) {
  98272. for(i = 0; ok && i < 2; i++) {
  98273. 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]);
  98274. }
  98275. }
  98276. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  98277. /*@@@ 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) */
  98278. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  98279. if(encoder->protected_->do_escape_coding)
  98280. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  98281. /* now adjust the windows if the blocksize has changed */
  98282. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98283. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  98284. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  98285. switch(encoder->protected_->apodizations[i].type) {
  98286. case FLAC__APODIZATION_BARTLETT:
  98287. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  98288. break;
  98289. case FLAC__APODIZATION_BARTLETT_HANN:
  98290. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  98291. break;
  98292. case FLAC__APODIZATION_BLACKMAN:
  98293. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  98294. break;
  98295. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  98296. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  98297. break;
  98298. case FLAC__APODIZATION_CONNES:
  98299. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  98300. break;
  98301. case FLAC__APODIZATION_FLATTOP:
  98302. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  98303. break;
  98304. case FLAC__APODIZATION_GAUSS:
  98305. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  98306. break;
  98307. case FLAC__APODIZATION_HAMMING:
  98308. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  98309. break;
  98310. case FLAC__APODIZATION_HANN:
  98311. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  98312. break;
  98313. case FLAC__APODIZATION_KAISER_BESSEL:
  98314. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  98315. break;
  98316. case FLAC__APODIZATION_NUTTALL:
  98317. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  98318. break;
  98319. case FLAC__APODIZATION_RECTANGLE:
  98320. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  98321. break;
  98322. case FLAC__APODIZATION_TRIANGLE:
  98323. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  98324. break;
  98325. case FLAC__APODIZATION_TUKEY:
  98326. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  98327. break;
  98328. case FLAC__APODIZATION_WELCH:
  98329. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  98330. break;
  98331. default:
  98332. FLAC__ASSERT(0);
  98333. /* double protection */
  98334. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  98335. break;
  98336. }
  98337. }
  98338. }
  98339. #endif
  98340. if(ok)
  98341. encoder->private_->input_capacity = new_blocksize;
  98342. else
  98343. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98344. return ok;
  98345. }
  98346. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  98347. {
  98348. const FLAC__byte *buffer;
  98349. size_t bytes;
  98350. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  98351. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  98352. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98353. return false;
  98354. }
  98355. if(encoder->protected_->verify) {
  98356. encoder->private_->verify.output.data = buffer;
  98357. encoder->private_->verify.output.bytes = bytes;
  98358. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  98359. encoder->private_->verify.needs_magic_hack = true;
  98360. }
  98361. else {
  98362. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  98363. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  98364. FLAC__bitwriter_clear(encoder->private_->frame);
  98365. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  98366. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  98367. return false;
  98368. }
  98369. }
  98370. }
  98371. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  98372. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  98373. FLAC__bitwriter_clear(encoder->private_->frame);
  98374. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98375. return false;
  98376. }
  98377. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  98378. FLAC__bitwriter_clear(encoder->private_->frame);
  98379. if(samples > 0) {
  98380. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  98381. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  98382. }
  98383. return true;
  98384. }
  98385. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  98386. {
  98387. FLAC__StreamEncoderWriteStatus status;
  98388. FLAC__uint64 output_position = 0;
  98389. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  98390. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  98391. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98392. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  98393. }
  98394. /*
  98395. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  98396. */
  98397. if(samples == 0) {
  98398. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  98399. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  98400. encoder->protected_->streaminfo_offset = output_position;
  98401. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  98402. encoder->protected_->seektable_offset = output_position;
  98403. }
  98404. /*
  98405. * Mark the current seek point if hit (if audio_offset == 0 that
  98406. * means we're still writing metadata and haven't hit the first
  98407. * frame yet)
  98408. */
  98409. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  98410. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  98411. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  98412. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  98413. FLAC__uint64 test_sample;
  98414. unsigned i;
  98415. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  98416. test_sample = encoder->private_->seek_table->points[i].sample_number;
  98417. if(test_sample > frame_last_sample) {
  98418. break;
  98419. }
  98420. else if(test_sample >= frame_first_sample) {
  98421. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  98422. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  98423. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  98424. encoder->private_->first_seekpoint_to_check++;
  98425. /* DO NOT: "break;" and here's why:
  98426. * The seektable template may contain more than one target
  98427. * sample for any given frame; we will keep looping, generating
  98428. * duplicate seekpoints for them, and we'll clean it up later,
  98429. * just before writing the seektable back to the metadata.
  98430. */
  98431. }
  98432. else {
  98433. encoder->private_->first_seekpoint_to_check++;
  98434. }
  98435. }
  98436. }
  98437. #if FLAC__HAS_OGG
  98438. if(encoder->private_->is_ogg) {
  98439. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  98440. &encoder->protected_->ogg_encoder_aspect,
  98441. buffer,
  98442. bytes,
  98443. samples,
  98444. encoder->private_->current_frame_number,
  98445. is_last_block,
  98446. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  98447. encoder,
  98448. encoder->private_->client_data
  98449. );
  98450. }
  98451. else
  98452. #endif
  98453. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  98454. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  98455. encoder->private_->bytes_written += bytes;
  98456. encoder->private_->samples_written += samples;
  98457. /* we keep a high watermark on the number of frames written because
  98458. * when the encoder goes back to write metadata, 'current_frame'
  98459. * will drop back to 0.
  98460. */
  98461. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  98462. }
  98463. else
  98464. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98465. return status;
  98466. }
  98467. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  98468. void update_metadata_(const FLAC__StreamEncoder *encoder)
  98469. {
  98470. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  98471. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  98472. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  98473. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  98474. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  98475. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  98476. FLAC__StreamEncoderSeekStatus seek_status;
  98477. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  98478. /* All this is based on intimate knowledge of the stream header
  98479. * layout, but a change to the header format that would break this
  98480. * would also break all streams encoded in the previous format.
  98481. */
  98482. /*
  98483. * Write MD5 signature
  98484. */
  98485. {
  98486. const unsigned md5_offset =
  98487. FLAC__STREAM_METADATA_HEADER_LENGTH +
  98488. (
  98489. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  98490. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  98491. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  98492. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  98493. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  98494. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  98495. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  98496. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  98497. ) / 8;
  98498. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  98499. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  98500. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98501. return;
  98502. }
  98503. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  98504. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98505. return;
  98506. }
  98507. }
  98508. /*
  98509. * Write total samples
  98510. */
  98511. {
  98512. const unsigned total_samples_byte_offset =
  98513. FLAC__STREAM_METADATA_HEADER_LENGTH +
  98514. (
  98515. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  98516. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  98517. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  98518. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  98519. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  98520. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  98521. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  98522. - 4
  98523. ) / 8;
  98524. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  98525. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  98526. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  98527. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  98528. b[4] = (FLAC__byte)(samples & 0xFF);
  98529. 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) {
  98530. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  98531. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98532. return;
  98533. }
  98534. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  98535. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98536. return;
  98537. }
  98538. }
  98539. /*
  98540. * Write min/max framesize
  98541. */
  98542. {
  98543. const unsigned min_framesize_offset =
  98544. FLAC__STREAM_METADATA_HEADER_LENGTH +
  98545. (
  98546. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  98547. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  98548. ) / 8;
  98549. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  98550. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  98551. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  98552. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  98553. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  98554. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  98555. 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) {
  98556. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  98557. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98558. return;
  98559. }
  98560. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  98561. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98562. return;
  98563. }
  98564. }
  98565. /*
  98566. * Write seektable
  98567. */
  98568. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  98569. unsigned i;
  98570. FLAC__format_seektable_sort(encoder->private_->seek_table);
  98571. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  98572. 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) {
  98573. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  98574. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98575. return;
  98576. }
  98577. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  98578. FLAC__uint64 xx;
  98579. unsigned x;
  98580. xx = encoder->private_->seek_table->points[i].sample_number;
  98581. b[7] = (FLAC__byte)xx; xx >>= 8;
  98582. b[6] = (FLAC__byte)xx; xx >>= 8;
  98583. b[5] = (FLAC__byte)xx; xx >>= 8;
  98584. b[4] = (FLAC__byte)xx; xx >>= 8;
  98585. b[3] = (FLAC__byte)xx; xx >>= 8;
  98586. b[2] = (FLAC__byte)xx; xx >>= 8;
  98587. b[1] = (FLAC__byte)xx; xx >>= 8;
  98588. b[0] = (FLAC__byte)xx; xx >>= 8;
  98589. xx = encoder->private_->seek_table->points[i].stream_offset;
  98590. b[15] = (FLAC__byte)xx; xx >>= 8;
  98591. b[14] = (FLAC__byte)xx; xx >>= 8;
  98592. b[13] = (FLAC__byte)xx; xx >>= 8;
  98593. b[12] = (FLAC__byte)xx; xx >>= 8;
  98594. b[11] = (FLAC__byte)xx; xx >>= 8;
  98595. b[10] = (FLAC__byte)xx; xx >>= 8;
  98596. b[9] = (FLAC__byte)xx; xx >>= 8;
  98597. b[8] = (FLAC__byte)xx; xx >>= 8;
  98598. x = encoder->private_->seek_table->points[i].frame_samples;
  98599. b[17] = (FLAC__byte)x; x >>= 8;
  98600. b[16] = (FLAC__byte)x; x >>= 8;
  98601. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  98602. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98603. return;
  98604. }
  98605. }
  98606. }
  98607. }
  98608. #if FLAC__HAS_OGG
  98609. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  98610. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  98611. {
  98612. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  98613. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  98614. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  98615. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  98616. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  98617. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  98618. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  98619. FLAC__STREAM_SYNC_LENGTH
  98620. ;
  98621. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  98622. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  98623. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  98624. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  98625. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  98626. ogg_page page;
  98627. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  98628. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  98629. /* Pre-check that client supports seeking, since we don't want the
  98630. * ogg_helper code to ever have to deal with this condition.
  98631. */
  98632. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  98633. return;
  98634. /* All this is based on intimate knowledge of the stream header
  98635. * layout, but a change to the header format that would break this
  98636. * would also break all streams encoded in the previous format.
  98637. */
  98638. /**
  98639. ** Write STREAMINFO stats
  98640. **/
  98641. simple_ogg_page__init(&page);
  98642. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  98643. simple_ogg_page__clear(&page);
  98644. return; /* state already set */
  98645. }
  98646. /*
  98647. * Write MD5 signature
  98648. */
  98649. {
  98650. const unsigned md5_offset =
  98651. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  98652. FLAC__STREAM_METADATA_HEADER_LENGTH +
  98653. (
  98654. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  98655. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  98656. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  98657. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  98658. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  98659. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  98660. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  98661. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  98662. ) / 8;
  98663. if(md5_offset + 16 > (unsigned)page.body_len) {
  98664. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98665. simple_ogg_page__clear(&page);
  98666. return;
  98667. }
  98668. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  98669. }
  98670. /*
  98671. * Write total samples
  98672. */
  98673. {
  98674. const unsigned total_samples_byte_offset =
  98675. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  98676. FLAC__STREAM_METADATA_HEADER_LENGTH +
  98677. (
  98678. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  98679. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  98680. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  98681. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  98682. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  98683. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  98684. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  98685. - 4
  98686. ) / 8;
  98687. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  98688. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98689. simple_ogg_page__clear(&page);
  98690. return;
  98691. }
  98692. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  98693. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  98694. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  98695. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  98696. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  98697. b[4] = (FLAC__byte)(samples & 0xFF);
  98698. memcpy(page.body + total_samples_byte_offset, b, 5);
  98699. }
  98700. /*
  98701. * Write min/max framesize
  98702. */
  98703. {
  98704. const unsigned min_framesize_offset =
  98705. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  98706. FLAC__STREAM_METADATA_HEADER_LENGTH +
  98707. (
  98708. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  98709. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  98710. ) / 8;
  98711. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  98712. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98713. simple_ogg_page__clear(&page);
  98714. return;
  98715. }
  98716. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  98717. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  98718. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  98719. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  98720. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  98721. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  98722. memcpy(page.body + min_framesize_offset, b, 6);
  98723. }
  98724. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  98725. simple_ogg_page__clear(&page);
  98726. return; /* state already set */
  98727. }
  98728. simple_ogg_page__clear(&page);
  98729. /*
  98730. * Write seektable
  98731. */
  98732. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  98733. unsigned i;
  98734. FLAC__byte *p;
  98735. FLAC__format_seektable_sort(encoder->private_->seek_table);
  98736. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  98737. simple_ogg_page__init(&page);
  98738. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  98739. simple_ogg_page__clear(&page);
  98740. return; /* state already set */
  98741. }
  98742. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  98743. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98744. simple_ogg_page__clear(&page);
  98745. return;
  98746. }
  98747. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  98748. FLAC__uint64 xx;
  98749. unsigned x;
  98750. xx = encoder->private_->seek_table->points[i].sample_number;
  98751. b[7] = (FLAC__byte)xx; xx >>= 8;
  98752. b[6] = (FLAC__byte)xx; xx >>= 8;
  98753. b[5] = (FLAC__byte)xx; xx >>= 8;
  98754. b[4] = (FLAC__byte)xx; xx >>= 8;
  98755. b[3] = (FLAC__byte)xx; xx >>= 8;
  98756. b[2] = (FLAC__byte)xx; xx >>= 8;
  98757. b[1] = (FLAC__byte)xx; xx >>= 8;
  98758. b[0] = (FLAC__byte)xx; xx >>= 8;
  98759. xx = encoder->private_->seek_table->points[i].stream_offset;
  98760. b[15] = (FLAC__byte)xx; xx >>= 8;
  98761. b[14] = (FLAC__byte)xx; xx >>= 8;
  98762. b[13] = (FLAC__byte)xx; xx >>= 8;
  98763. b[12] = (FLAC__byte)xx; xx >>= 8;
  98764. b[11] = (FLAC__byte)xx; xx >>= 8;
  98765. b[10] = (FLAC__byte)xx; xx >>= 8;
  98766. b[9] = (FLAC__byte)xx; xx >>= 8;
  98767. b[8] = (FLAC__byte)xx; xx >>= 8;
  98768. x = encoder->private_->seek_table->points[i].frame_samples;
  98769. b[17] = (FLAC__byte)x; x >>= 8;
  98770. b[16] = (FLAC__byte)x; x >>= 8;
  98771. memcpy(p, b, 18);
  98772. }
  98773. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  98774. simple_ogg_page__clear(&page);
  98775. return; /* state already set */
  98776. }
  98777. simple_ogg_page__clear(&page);
  98778. }
  98779. }
  98780. #endif
  98781. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  98782. {
  98783. FLAC__uint16 crc;
  98784. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  98785. /*
  98786. * Accumulate raw signal to the MD5 signature
  98787. */
  98788. 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)) {
  98789. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98790. return false;
  98791. }
  98792. /*
  98793. * Process the frame header and subframes into the frame bitbuffer
  98794. */
  98795. if(!process_subframes_(encoder, is_fractional_block)) {
  98796. /* the above function sets the state for us in case of an error */
  98797. return false;
  98798. }
  98799. /*
  98800. * Zero-pad the frame to a byte_boundary
  98801. */
  98802. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  98803. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98804. return false;
  98805. }
  98806. /*
  98807. * CRC-16 the whole thing
  98808. */
  98809. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  98810. if(
  98811. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  98812. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  98813. ) {
  98814. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98815. return false;
  98816. }
  98817. /*
  98818. * Write it
  98819. */
  98820. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  98821. /* the above function sets the state for us in case of an error */
  98822. return false;
  98823. }
  98824. /*
  98825. * Get ready for the next frame
  98826. */
  98827. encoder->private_->current_sample_number = 0;
  98828. encoder->private_->current_frame_number++;
  98829. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  98830. return true;
  98831. }
  98832. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  98833. {
  98834. FLAC__FrameHeader frame_header;
  98835. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  98836. FLAC__bool do_independent, do_mid_side;
  98837. /*
  98838. * Calculate the min,max Rice partition orders
  98839. */
  98840. if(is_fractional_block) {
  98841. max_partition_order = 0;
  98842. }
  98843. else {
  98844. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  98845. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  98846. }
  98847. min_partition_order = min(min_partition_order, max_partition_order);
  98848. /*
  98849. * Setup the frame
  98850. */
  98851. frame_header.blocksize = encoder->protected_->blocksize;
  98852. frame_header.sample_rate = encoder->protected_->sample_rate;
  98853. frame_header.channels = encoder->protected_->channels;
  98854. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  98855. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  98856. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  98857. frame_header.number.frame_number = encoder->private_->current_frame_number;
  98858. /*
  98859. * Figure out what channel assignments to try
  98860. */
  98861. if(encoder->protected_->do_mid_side_stereo) {
  98862. if(encoder->protected_->loose_mid_side_stereo) {
  98863. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  98864. do_independent = true;
  98865. do_mid_side = true;
  98866. }
  98867. else {
  98868. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  98869. do_mid_side = !do_independent;
  98870. }
  98871. }
  98872. else {
  98873. do_independent = true;
  98874. do_mid_side = true;
  98875. }
  98876. }
  98877. else {
  98878. do_independent = true;
  98879. do_mid_side = false;
  98880. }
  98881. FLAC__ASSERT(do_independent || do_mid_side);
  98882. /*
  98883. * Check for wasted bits; set effective bps for each subframe
  98884. */
  98885. if(do_independent) {
  98886. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  98887. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  98888. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  98889. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  98890. }
  98891. }
  98892. if(do_mid_side) {
  98893. FLAC__ASSERT(encoder->protected_->channels == 2);
  98894. for(channel = 0; channel < 2; channel++) {
  98895. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  98896. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  98897. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  98898. }
  98899. }
  98900. /*
  98901. * First do a normal encoding pass of each independent channel
  98902. */
  98903. if(do_independent) {
  98904. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  98905. if(!
  98906. process_subframe_(
  98907. encoder,
  98908. min_partition_order,
  98909. max_partition_order,
  98910. &frame_header,
  98911. encoder->private_->subframe_bps[channel],
  98912. encoder->private_->integer_signal[channel],
  98913. encoder->private_->subframe_workspace_ptr[channel],
  98914. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  98915. encoder->private_->residual_workspace[channel],
  98916. encoder->private_->best_subframe+channel,
  98917. encoder->private_->best_subframe_bits+channel
  98918. )
  98919. )
  98920. return false;
  98921. }
  98922. }
  98923. /*
  98924. * Now do mid and side channels if requested
  98925. */
  98926. if(do_mid_side) {
  98927. FLAC__ASSERT(encoder->protected_->channels == 2);
  98928. for(channel = 0; channel < 2; channel++) {
  98929. if(!
  98930. process_subframe_(
  98931. encoder,
  98932. min_partition_order,
  98933. max_partition_order,
  98934. &frame_header,
  98935. encoder->private_->subframe_bps_mid_side[channel],
  98936. encoder->private_->integer_signal_mid_side[channel],
  98937. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  98938. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  98939. encoder->private_->residual_workspace_mid_side[channel],
  98940. encoder->private_->best_subframe_mid_side+channel,
  98941. encoder->private_->best_subframe_bits_mid_side+channel
  98942. )
  98943. )
  98944. return false;
  98945. }
  98946. }
  98947. /*
  98948. * Compose the frame bitbuffer
  98949. */
  98950. if(do_mid_side) {
  98951. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  98952. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  98953. FLAC__ChannelAssignment channel_assignment;
  98954. FLAC__ASSERT(encoder->protected_->channels == 2);
  98955. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  98956. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  98957. }
  98958. else {
  98959. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  98960. unsigned min_bits;
  98961. int ca;
  98962. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  98963. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  98964. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  98965. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  98966. FLAC__ASSERT(do_independent && do_mid_side);
  98967. /* We have to figure out which channel assignent results in the smallest frame */
  98968. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  98969. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  98970. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  98971. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  98972. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  98973. min_bits = bits[channel_assignment];
  98974. for(ca = 1; ca <= 3; ca++) {
  98975. if(bits[ca] < min_bits) {
  98976. min_bits = bits[ca];
  98977. channel_assignment = (FLAC__ChannelAssignment)ca;
  98978. }
  98979. }
  98980. }
  98981. frame_header.channel_assignment = channel_assignment;
  98982. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  98983. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98984. return false;
  98985. }
  98986. switch(channel_assignment) {
  98987. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  98988. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  98989. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  98990. break;
  98991. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  98992. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  98993. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  98994. break;
  98995. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  98996. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  98997. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  98998. break;
  98999. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  99000. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  99001. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  99002. break;
  99003. default:
  99004. FLAC__ASSERT(0);
  99005. }
  99006. switch(channel_assignment) {
  99007. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  99008. left_bps = encoder->private_->subframe_bps [0];
  99009. right_bps = encoder->private_->subframe_bps [1];
  99010. break;
  99011. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  99012. left_bps = encoder->private_->subframe_bps [0];
  99013. right_bps = encoder->private_->subframe_bps_mid_side[1];
  99014. break;
  99015. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  99016. left_bps = encoder->private_->subframe_bps_mid_side[1];
  99017. right_bps = encoder->private_->subframe_bps [1];
  99018. break;
  99019. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  99020. left_bps = encoder->private_->subframe_bps_mid_side[0];
  99021. right_bps = encoder->private_->subframe_bps_mid_side[1];
  99022. break;
  99023. default:
  99024. FLAC__ASSERT(0);
  99025. }
  99026. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  99027. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  99028. return false;
  99029. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  99030. return false;
  99031. }
  99032. else {
  99033. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  99034. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99035. return false;
  99036. }
  99037. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  99038. 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)) {
  99039. /* the above function sets the state for us in case of an error */
  99040. return false;
  99041. }
  99042. }
  99043. }
  99044. if(encoder->protected_->loose_mid_side_stereo) {
  99045. encoder->private_->loose_mid_side_stereo_frame_count++;
  99046. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  99047. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  99048. }
  99049. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  99050. return true;
  99051. }
  99052. FLAC__bool process_subframe_(
  99053. FLAC__StreamEncoder *encoder,
  99054. unsigned min_partition_order,
  99055. unsigned max_partition_order,
  99056. const FLAC__FrameHeader *frame_header,
  99057. unsigned subframe_bps,
  99058. const FLAC__int32 integer_signal[],
  99059. FLAC__Subframe *subframe[2],
  99060. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  99061. FLAC__int32 *residual[2],
  99062. unsigned *best_subframe,
  99063. unsigned *best_bits
  99064. )
  99065. {
  99066. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99067. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  99068. #else
  99069. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  99070. #endif
  99071. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99072. FLAC__double lpc_residual_bits_per_sample;
  99073. 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 */
  99074. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  99075. unsigned min_lpc_order, max_lpc_order, lpc_order;
  99076. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  99077. #endif
  99078. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  99079. unsigned rice_parameter;
  99080. unsigned _candidate_bits, _best_bits;
  99081. unsigned _best_subframe;
  99082. /* only use RICE2 partitions if stream bps > 16 */
  99083. 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;
  99084. FLAC__ASSERT(frame_header->blocksize > 0);
  99085. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  99086. _best_subframe = 0;
  99087. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  99088. _best_bits = UINT_MAX;
  99089. else
  99090. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  99091. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  99092. unsigned signal_is_constant = false;
  99093. 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);
  99094. /* check for constant subframe */
  99095. if(
  99096. !encoder->private_->disable_constant_subframes &&
  99097. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99098. fixed_residual_bits_per_sample[1] == 0.0
  99099. #else
  99100. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  99101. #endif
  99102. ) {
  99103. /* the above means it's possible all samples are the same value; now double-check it: */
  99104. unsigned i;
  99105. signal_is_constant = true;
  99106. for(i = 1; i < frame_header->blocksize; i++) {
  99107. if(integer_signal[0] != integer_signal[i]) {
  99108. signal_is_constant = false;
  99109. break;
  99110. }
  99111. }
  99112. }
  99113. if(signal_is_constant) {
  99114. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  99115. if(_candidate_bits < _best_bits) {
  99116. _best_subframe = !_best_subframe;
  99117. _best_bits = _candidate_bits;
  99118. }
  99119. }
  99120. else {
  99121. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  99122. /* encode fixed */
  99123. if(encoder->protected_->do_exhaustive_model_search) {
  99124. min_fixed_order = 0;
  99125. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  99126. }
  99127. else {
  99128. min_fixed_order = max_fixed_order = guess_fixed_order;
  99129. }
  99130. if(max_fixed_order >= frame_header->blocksize)
  99131. max_fixed_order = frame_header->blocksize - 1;
  99132. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  99133. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99134. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  99135. continue; /* don't even try */
  99136. 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 */
  99137. #else
  99138. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  99139. continue; /* don't even try */
  99140. 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 */
  99141. #endif
  99142. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  99143. if(rice_parameter >= rice_parameter_limit) {
  99144. #ifdef DEBUG_VERBOSE
  99145. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  99146. #endif
  99147. rice_parameter = rice_parameter_limit - 1;
  99148. }
  99149. _candidate_bits =
  99150. evaluate_fixed_subframe_(
  99151. encoder,
  99152. integer_signal,
  99153. residual[!_best_subframe],
  99154. encoder->private_->abs_residual_partition_sums,
  99155. encoder->private_->raw_bits_per_partition,
  99156. frame_header->blocksize,
  99157. subframe_bps,
  99158. fixed_order,
  99159. rice_parameter,
  99160. rice_parameter_limit,
  99161. min_partition_order,
  99162. max_partition_order,
  99163. encoder->protected_->do_escape_coding,
  99164. encoder->protected_->rice_parameter_search_dist,
  99165. subframe[!_best_subframe],
  99166. partitioned_rice_contents[!_best_subframe]
  99167. );
  99168. if(_candidate_bits < _best_bits) {
  99169. _best_subframe = !_best_subframe;
  99170. _best_bits = _candidate_bits;
  99171. }
  99172. }
  99173. }
  99174. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99175. /* encode lpc */
  99176. if(encoder->protected_->max_lpc_order > 0) {
  99177. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  99178. max_lpc_order = frame_header->blocksize-1;
  99179. else
  99180. max_lpc_order = encoder->protected_->max_lpc_order;
  99181. if(max_lpc_order > 0) {
  99182. unsigned a;
  99183. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  99184. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  99185. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  99186. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  99187. if(autoc[0] != 0.0) {
  99188. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  99189. if(encoder->protected_->do_exhaustive_model_search) {
  99190. min_lpc_order = 1;
  99191. }
  99192. else {
  99193. const unsigned guess_lpc_order =
  99194. FLAC__lpc_compute_best_order(
  99195. lpc_error,
  99196. max_lpc_order,
  99197. frame_header->blocksize,
  99198. subframe_bps + (
  99199. encoder->protected_->do_qlp_coeff_prec_search?
  99200. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  99201. encoder->protected_->qlp_coeff_precision
  99202. )
  99203. );
  99204. min_lpc_order = max_lpc_order = guess_lpc_order;
  99205. }
  99206. if(max_lpc_order >= frame_header->blocksize)
  99207. max_lpc_order = frame_header->blocksize - 1;
  99208. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  99209. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  99210. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  99211. continue; /* don't even try */
  99212. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  99213. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  99214. if(rice_parameter >= rice_parameter_limit) {
  99215. #ifdef DEBUG_VERBOSE
  99216. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  99217. #endif
  99218. rice_parameter = rice_parameter_limit - 1;
  99219. }
  99220. if(encoder->protected_->do_qlp_coeff_prec_search) {
  99221. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  99222. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  99223. if(subframe_bps <= 17) {
  99224. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  99225. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  99226. }
  99227. else
  99228. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  99229. }
  99230. else {
  99231. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  99232. }
  99233. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  99234. _candidate_bits =
  99235. evaluate_lpc_subframe_(
  99236. encoder,
  99237. integer_signal,
  99238. residual[!_best_subframe],
  99239. encoder->private_->abs_residual_partition_sums,
  99240. encoder->private_->raw_bits_per_partition,
  99241. encoder->private_->lp_coeff[lpc_order-1],
  99242. frame_header->blocksize,
  99243. subframe_bps,
  99244. lpc_order,
  99245. qlp_coeff_precision,
  99246. rice_parameter,
  99247. rice_parameter_limit,
  99248. min_partition_order,
  99249. max_partition_order,
  99250. encoder->protected_->do_escape_coding,
  99251. encoder->protected_->rice_parameter_search_dist,
  99252. subframe[!_best_subframe],
  99253. partitioned_rice_contents[!_best_subframe]
  99254. );
  99255. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  99256. if(_candidate_bits < _best_bits) {
  99257. _best_subframe = !_best_subframe;
  99258. _best_bits = _candidate_bits;
  99259. }
  99260. }
  99261. }
  99262. }
  99263. }
  99264. }
  99265. }
  99266. }
  99267. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  99268. }
  99269. }
  99270. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  99271. if(_best_bits == UINT_MAX) {
  99272. FLAC__ASSERT(_best_subframe == 0);
  99273. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  99274. }
  99275. *best_subframe = _best_subframe;
  99276. *best_bits = _best_bits;
  99277. return true;
  99278. }
  99279. FLAC__bool add_subframe_(
  99280. FLAC__StreamEncoder *encoder,
  99281. unsigned blocksize,
  99282. unsigned subframe_bps,
  99283. const FLAC__Subframe *subframe,
  99284. FLAC__BitWriter *frame
  99285. )
  99286. {
  99287. switch(subframe->type) {
  99288. case FLAC__SUBFRAME_TYPE_CONSTANT:
  99289. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  99290. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99291. return false;
  99292. }
  99293. break;
  99294. case FLAC__SUBFRAME_TYPE_FIXED:
  99295. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  99296. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99297. return false;
  99298. }
  99299. break;
  99300. case FLAC__SUBFRAME_TYPE_LPC:
  99301. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  99302. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99303. return false;
  99304. }
  99305. break;
  99306. case FLAC__SUBFRAME_TYPE_VERBATIM:
  99307. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  99308. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99309. return false;
  99310. }
  99311. break;
  99312. default:
  99313. FLAC__ASSERT(0);
  99314. }
  99315. return true;
  99316. }
  99317. #define SPOTCHECK_ESTIMATE 0
  99318. #if SPOTCHECK_ESTIMATE
  99319. static void spotcheck_subframe_estimate_(
  99320. FLAC__StreamEncoder *encoder,
  99321. unsigned blocksize,
  99322. unsigned subframe_bps,
  99323. const FLAC__Subframe *subframe,
  99324. unsigned estimate
  99325. )
  99326. {
  99327. FLAC__bool ret;
  99328. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  99329. if(frame == 0) {
  99330. fprintf(stderr, "EST: can't allocate frame\n");
  99331. return;
  99332. }
  99333. if(!FLAC__bitwriter_init(frame)) {
  99334. fprintf(stderr, "EST: can't init frame\n");
  99335. return;
  99336. }
  99337. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  99338. FLAC__ASSERT(ret);
  99339. {
  99340. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  99341. if(estimate != actual)
  99342. 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);
  99343. }
  99344. FLAC__bitwriter_delete(frame);
  99345. }
  99346. #endif
  99347. unsigned evaluate_constant_subframe_(
  99348. FLAC__StreamEncoder *encoder,
  99349. const FLAC__int32 signal,
  99350. unsigned blocksize,
  99351. unsigned subframe_bps,
  99352. FLAC__Subframe *subframe
  99353. )
  99354. {
  99355. unsigned estimate;
  99356. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  99357. subframe->data.constant.value = signal;
  99358. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  99359. #if SPOTCHECK_ESTIMATE
  99360. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  99361. #else
  99362. (void)encoder, (void)blocksize;
  99363. #endif
  99364. return estimate;
  99365. }
  99366. unsigned evaluate_fixed_subframe_(
  99367. FLAC__StreamEncoder *encoder,
  99368. const FLAC__int32 signal[],
  99369. FLAC__int32 residual[],
  99370. FLAC__uint64 abs_residual_partition_sums[],
  99371. unsigned raw_bits_per_partition[],
  99372. unsigned blocksize,
  99373. unsigned subframe_bps,
  99374. unsigned order,
  99375. unsigned rice_parameter,
  99376. unsigned rice_parameter_limit,
  99377. unsigned min_partition_order,
  99378. unsigned max_partition_order,
  99379. FLAC__bool do_escape_coding,
  99380. unsigned rice_parameter_search_dist,
  99381. FLAC__Subframe *subframe,
  99382. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  99383. )
  99384. {
  99385. unsigned i, residual_bits, estimate;
  99386. const unsigned residual_samples = blocksize - order;
  99387. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  99388. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  99389. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  99390. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  99391. subframe->data.fixed.residual = residual;
  99392. residual_bits =
  99393. find_best_partition_order_(
  99394. encoder->private_,
  99395. residual,
  99396. abs_residual_partition_sums,
  99397. raw_bits_per_partition,
  99398. residual_samples,
  99399. order,
  99400. rice_parameter,
  99401. rice_parameter_limit,
  99402. min_partition_order,
  99403. max_partition_order,
  99404. subframe_bps,
  99405. do_escape_coding,
  99406. rice_parameter_search_dist,
  99407. &subframe->data.fixed.entropy_coding_method
  99408. );
  99409. subframe->data.fixed.order = order;
  99410. for(i = 0; i < order; i++)
  99411. subframe->data.fixed.warmup[i] = signal[i];
  99412. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  99413. #if SPOTCHECK_ESTIMATE
  99414. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  99415. #endif
  99416. return estimate;
  99417. }
  99418. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99419. unsigned evaluate_lpc_subframe_(
  99420. FLAC__StreamEncoder *encoder,
  99421. const FLAC__int32 signal[],
  99422. FLAC__int32 residual[],
  99423. FLAC__uint64 abs_residual_partition_sums[],
  99424. unsigned raw_bits_per_partition[],
  99425. const FLAC__real lp_coeff[],
  99426. unsigned blocksize,
  99427. unsigned subframe_bps,
  99428. unsigned order,
  99429. unsigned qlp_coeff_precision,
  99430. unsigned rice_parameter,
  99431. unsigned rice_parameter_limit,
  99432. unsigned min_partition_order,
  99433. unsigned max_partition_order,
  99434. FLAC__bool do_escape_coding,
  99435. unsigned rice_parameter_search_dist,
  99436. FLAC__Subframe *subframe,
  99437. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  99438. )
  99439. {
  99440. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  99441. unsigned i, residual_bits, estimate;
  99442. int quantization, ret;
  99443. const unsigned residual_samples = blocksize - order;
  99444. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  99445. if(subframe_bps <= 16) {
  99446. FLAC__ASSERT(order > 0);
  99447. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  99448. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  99449. }
  99450. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  99451. if(ret != 0)
  99452. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  99453. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  99454. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  99455. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  99456. else
  99457. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  99458. else
  99459. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  99460. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  99461. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  99462. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  99463. subframe->data.lpc.residual = residual;
  99464. residual_bits =
  99465. find_best_partition_order_(
  99466. encoder->private_,
  99467. residual,
  99468. abs_residual_partition_sums,
  99469. raw_bits_per_partition,
  99470. residual_samples,
  99471. order,
  99472. rice_parameter,
  99473. rice_parameter_limit,
  99474. min_partition_order,
  99475. max_partition_order,
  99476. subframe_bps,
  99477. do_escape_coding,
  99478. rice_parameter_search_dist,
  99479. &subframe->data.lpc.entropy_coding_method
  99480. );
  99481. subframe->data.lpc.order = order;
  99482. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  99483. subframe->data.lpc.quantization_level = quantization;
  99484. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  99485. for(i = 0; i < order; i++)
  99486. subframe->data.lpc.warmup[i] = signal[i];
  99487. 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;
  99488. #if SPOTCHECK_ESTIMATE
  99489. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  99490. #endif
  99491. return estimate;
  99492. }
  99493. #endif
  99494. unsigned evaluate_verbatim_subframe_(
  99495. FLAC__StreamEncoder *encoder,
  99496. const FLAC__int32 signal[],
  99497. unsigned blocksize,
  99498. unsigned subframe_bps,
  99499. FLAC__Subframe *subframe
  99500. )
  99501. {
  99502. unsigned estimate;
  99503. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  99504. subframe->data.verbatim.data = signal;
  99505. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  99506. #if SPOTCHECK_ESTIMATE
  99507. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  99508. #else
  99509. (void)encoder;
  99510. #endif
  99511. return estimate;
  99512. }
  99513. unsigned find_best_partition_order_(
  99514. FLAC__StreamEncoderPrivate *private_,
  99515. const FLAC__int32 residual[],
  99516. FLAC__uint64 abs_residual_partition_sums[],
  99517. unsigned raw_bits_per_partition[],
  99518. unsigned residual_samples,
  99519. unsigned predictor_order,
  99520. unsigned rice_parameter,
  99521. unsigned rice_parameter_limit,
  99522. unsigned min_partition_order,
  99523. unsigned max_partition_order,
  99524. unsigned bps,
  99525. FLAC__bool do_escape_coding,
  99526. unsigned rice_parameter_search_dist,
  99527. FLAC__EntropyCodingMethod *best_ecm
  99528. )
  99529. {
  99530. unsigned residual_bits, best_residual_bits = 0;
  99531. unsigned best_parameters_index = 0;
  99532. unsigned best_partition_order = 0;
  99533. const unsigned blocksize = residual_samples + predictor_order;
  99534. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  99535. min_partition_order = min(min_partition_order, max_partition_order);
  99536. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  99537. if(do_escape_coding)
  99538. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  99539. {
  99540. int partition_order;
  99541. unsigned sum;
  99542. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  99543. if(!
  99544. set_partitioned_rice_(
  99545. #ifdef EXACT_RICE_BITS_CALCULATION
  99546. residual,
  99547. #endif
  99548. abs_residual_partition_sums+sum,
  99549. raw_bits_per_partition+sum,
  99550. residual_samples,
  99551. predictor_order,
  99552. rice_parameter,
  99553. rice_parameter_limit,
  99554. rice_parameter_search_dist,
  99555. (unsigned)partition_order,
  99556. do_escape_coding,
  99557. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  99558. &residual_bits
  99559. )
  99560. )
  99561. {
  99562. FLAC__ASSERT(best_residual_bits != 0);
  99563. break;
  99564. }
  99565. sum += 1u << partition_order;
  99566. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  99567. best_residual_bits = residual_bits;
  99568. best_parameters_index = !best_parameters_index;
  99569. best_partition_order = partition_order;
  99570. }
  99571. }
  99572. }
  99573. best_ecm->data.partitioned_rice.order = best_partition_order;
  99574. {
  99575. /*
  99576. * We are allowed to de-const the pointer based on our special
  99577. * knowledge; it is const to the outside world.
  99578. */
  99579. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  99580. unsigned partition;
  99581. /* save best parameters and raw_bits */
  99582. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  99583. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  99584. if(do_escape_coding)
  99585. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  99586. /*
  99587. * Now need to check if the type should be changed to
  99588. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  99589. * size of the rice parameters.
  99590. */
  99591. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  99592. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  99593. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  99594. break;
  99595. }
  99596. }
  99597. }
  99598. return best_residual_bits;
  99599. }
  99600. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  99601. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  99602. const FLAC__int32 residual[],
  99603. FLAC__uint64 abs_residual_partition_sums[],
  99604. unsigned blocksize,
  99605. unsigned predictor_order,
  99606. unsigned min_partition_order,
  99607. unsigned max_partition_order
  99608. );
  99609. #endif
  99610. void precompute_partition_info_sums_(
  99611. const FLAC__int32 residual[],
  99612. FLAC__uint64 abs_residual_partition_sums[],
  99613. unsigned residual_samples,
  99614. unsigned predictor_order,
  99615. unsigned min_partition_order,
  99616. unsigned max_partition_order,
  99617. unsigned bps
  99618. )
  99619. {
  99620. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  99621. unsigned partitions = 1u << max_partition_order;
  99622. FLAC__ASSERT(default_partition_samples > predictor_order);
  99623. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  99624. /* slightly pessimistic but still catches all common cases */
  99625. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  99626. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  99627. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  99628. return;
  99629. }
  99630. #endif
  99631. /* first do max_partition_order */
  99632. {
  99633. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  99634. /* slightly pessimistic but still catches all common cases */
  99635. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  99636. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  99637. FLAC__uint32 abs_residual_partition_sum;
  99638. for(partition = residual_sample = 0; partition < partitions; partition++) {
  99639. end += default_partition_samples;
  99640. abs_residual_partition_sum = 0;
  99641. for( ; residual_sample < end; residual_sample++)
  99642. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  99643. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  99644. }
  99645. }
  99646. else { /* have to pessimistically use 64 bits for accumulator */
  99647. FLAC__uint64 abs_residual_partition_sum;
  99648. for(partition = residual_sample = 0; partition < partitions; partition++) {
  99649. end += default_partition_samples;
  99650. abs_residual_partition_sum = 0;
  99651. for( ; residual_sample < end; residual_sample++)
  99652. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  99653. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  99654. }
  99655. }
  99656. }
  99657. /* now merge partitions for lower orders */
  99658. {
  99659. unsigned from_partition = 0, to_partition = partitions;
  99660. int partition_order;
  99661. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  99662. unsigned i;
  99663. partitions >>= 1;
  99664. for(i = 0; i < partitions; i++) {
  99665. abs_residual_partition_sums[to_partition++] =
  99666. abs_residual_partition_sums[from_partition ] +
  99667. abs_residual_partition_sums[from_partition+1];
  99668. from_partition += 2;
  99669. }
  99670. }
  99671. }
  99672. }
  99673. void precompute_partition_info_escapes_(
  99674. const FLAC__int32 residual[],
  99675. unsigned raw_bits_per_partition[],
  99676. unsigned residual_samples,
  99677. unsigned predictor_order,
  99678. unsigned min_partition_order,
  99679. unsigned max_partition_order
  99680. )
  99681. {
  99682. int partition_order;
  99683. unsigned from_partition, to_partition = 0;
  99684. const unsigned blocksize = residual_samples + predictor_order;
  99685. /* first do max_partition_order */
  99686. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  99687. FLAC__int32 r;
  99688. FLAC__uint32 rmax;
  99689. unsigned partition, partition_sample, partition_samples, residual_sample;
  99690. const unsigned partitions = 1u << partition_order;
  99691. const unsigned default_partition_samples = blocksize >> partition_order;
  99692. FLAC__ASSERT(default_partition_samples > predictor_order);
  99693. for(partition = residual_sample = 0; partition < partitions; partition++) {
  99694. partition_samples = default_partition_samples;
  99695. if(partition == 0)
  99696. partition_samples -= predictor_order;
  99697. rmax = 0;
  99698. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  99699. r = residual[residual_sample++];
  99700. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  99701. if(r < 0)
  99702. rmax |= ~r;
  99703. else
  99704. rmax |= r;
  99705. }
  99706. /* now we know all residual values are in the range [-rmax-1,rmax] */
  99707. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  99708. }
  99709. to_partition = partitions;
  99710. break; /*@@@ yuck, should remove the 'for' loop instead */
  99711. }
  99712. /* now merge partitions for lower orders */
  99713. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  99714. unsigned m;
  99715. unsigned i;
  99716. const unsigned partitions = 1u << partition_order;
  99717. for(i = 0; i < partitions; i++) {
  99718. m = raw_bits_per_partition[from_partition];
  99719. from_partition++;
  99720. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  99721. from_partition++;
  99722. to_partition++;
  99723. }
  99724. }
  99725. }
  99726. #ifdef EXACT_RICE_BITS_CALCULATION
  99727. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  99728. const unsigned rice_parameter,
  99729. const unsigned partition_samples,
  99730. const FLAC__int32 *residual
  99731. )
  99732. {
  99733. unsigned i, partition_bits =
  99734. 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 */
  99735. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  99736. ;
  99737. for(i = 0; i < partition_samples; i++)
  99738. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  99739. return partition_bits;
  99740. }
  99741. #else
  99742. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  99743. const unsigned rice_parameter,
  99744. const unsigned partition_samples,
  99745. const FLAC__uint64 abs_residual_partition_sum
  99746. )
  99747. {
  99748. return
  99749. 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 */
  99750. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  99751. (
  99752. rice_parameter?
  99753. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  99754. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  99755. )
  99756. - (partition_samples >> 1)
  99757. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  99758. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  99759. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  99760. * So the subtraction term tries to guess how many extra bits were contributed.
  99761. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  99762. */
  99763. ;
  99764. }
  99765. #endif
  99766. FLAC__bool set_partitioned_rice_(
  99767. #ifdef EXACT_RICE_BITS_CALCULATION
  99768. const FLAC__int32 residual[],
  99769. #endif
  99770. const FLAC__uint64 abs_residual_partition_sums[],
  99771. const unsigned raw_bits_per_partition[],
  99772. const unsigned residual_samples,
  99773. const unsigned predictor_order,
  99774. const unsigned suggested_rice_parameter,
  99775. const unsigned rice_parameter_limit,
  99776. const unsigned rice_parameter_search_dist,
  99777. const unsigned partition_order,
  99778. const FLAC__bool search_for_escapes,
  99779. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  99780. unsigned *bits
  99781. )
  99782. {
  99783. unsigned rice_parameter, partition_bits;
  99784. unsigned best_partition_bits, best_rice_parameter = 0;
  99785. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  99786. unsigned *parameters, *raw_bits;
  99787. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99788. unsigned min_rice_parameter, max_rice_parameter;
  99789. #else
  99790. (void)rice_parameter_search_dist;
  99791. #endif
  99792. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  99793. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  99794. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  99795. parameters = partitioned_rice_contents->parameters;
  99796. raw_bits = partitioned_rice_contents->raw_bits;
  99797. if(partition_order == 0) {
  99798. best_partition_bits = (unsigned)(-1);
  99799. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99800. if(rice_parameter_search_dist) {
  99801. if(suggested_rice_parameter < rice_parameter_search_dist)
  99802. min_rice_parameter = 0;
  99803. else
  99804. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  99805. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  99806. if(max_rice_parameter >= rice_parameter_limit) {
  99807. #ifdef DEBUG_VERBOSE
  99808. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  99809. #endif
  99810. max_rice_parameter = rice_parameter_limit - 1;
  99811. }
  99812. }
  99813. else
  99814. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  99815. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  99816. #else
  99817. rice_parameter = suggested_rice_parameter;
  99818. #endif
  99819. #ifdef EXACT_RICE_BITS_CALCULATION
  99820. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  99821. #else
  99822. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  99823. #endif
  99824. if(partition_bits < best_partition_bits) {
  99825. best_rice_parameter = rice_parameter;
  99826. best_partition_bits = partition_bits;
  99827. }
  99828. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99829. }
  99830. #endif
  99831. if(search_for_escapes) {
  99832. 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;
  99833. if(partition_bits <= best_partition_bits) {
  99834. raw_bits[0] = raw_bits_per_partition[0];
  99835. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  99836. best_partition_bits = partition_bits;
  99837. }
  99838. else
  99839. raw_bits[0] = 0;
  99840. }
  99841. parameters[0] = best_rice_parameter;
  99842. bits_ += best_partition_bits;
  99843. }
  99844. else {
  99845. unsigned partition, residual_sample;
  99846. unsigned partition_samples;
  99847. FLAC__uint64 mean, k;
  99848. const unsigned partitions = 1u << partition_order;
  99849. for(partition = residual_sample = 0; partition < partitions; partition++) {
  99850. partition_samples = (residual_samples+predictor_order) >> partition_order;
  99851. if(partition == 0) {
  99852. if(partition_samples <= predictor_order)
  99853. return false;
  99854. else
  99855. partition_samples -= predictor_order;
  99856. }
  99857. mean = abs_residual_partition_sums[partition];
  99858. /* we are basically calculating the size in bits of the
  99859. * average residual magnitude in the partition:
  99860. * rice_parameter = floor(log2(mean/partition_samples))
  99861. * 'mean' is not a good name for the variable, it is
  99862. * actually the sum of magnitudes of all residual values
  99863. * in the partition, so the actual mean is
  99864. * mean/partition_samples
  99865. */
  99866. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  99867. ;
  99868. if(rice_parameter >= rice_parameter_limit) {
  99869. #ifdef DEBUG_VERBOSE
  99870. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  99871. #endif
  99872. rice_parameter = rice_parameter_limit - 1;
  99873. }
  99874. best_partition_bits = (unsigned)(-1);
  99875. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99876. if(rice_parameter_search_dist) {
  99877. if(rice_parameter < rice_parameter_search_dist)
  99878. min_rice_parameter = 0;
  99879. else
  99880. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  99881. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  99882. if(max_rice_parameter >= rice_parameter_limit) {
  99883. #ifdef DEBUG_VERBOSE
  99884. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  99885. #endif
  99886. max_rice_parameter = rice_parameter_limit - 1;
  99887. }
  99888. }
  99889. else
  99890. min_rice_parameter = max_rice_parameter = rice_parameter;
  99891. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  99892. #endif
  99893. #ifdef EXACT_RICE_BITS_CALCULATION
  99894. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  99895. #else
  99896. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  99897. #endif
  99898. if(partition_bits < best_partition_bits) {
  99899. best_rice_parameter = rice_parameter;
  99900. best_partition_bits = partition_bits;
  99901. }
  99902. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99903. }
  99904. #endif
  99905. if(search_for_escapes) {
  99906. 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;
  99907. if(partition_bits <= best_partition_bits) {
  99908. raw_bits[partition] = raw_bits_per_partition[partition];
  99909. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  99910. best_partition_bits = partition_bits;
  99911. }
  99912. else
  99913. raw_bits[partition] = 0;
  99914. }
  99915. parameters[partition] = best_rice_parameter;
  99916. bits_ += best_partition_bits;
  99917. residual_sample += partition_samples;
  99918. }
  99919. }
  99920. *bits = bits_;
  99921. return true;
  99922. }
  99923. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  99924. {
  99925. unsigned i, shift;
  99926. FLAC__int32 x = 0;
  99927. for(i = 0; i < samples && !(x&1); i++)
  99928. x |= signal[i];
  99929. if(x == 0) {
  99930. shift = 0;
  99931. }
  99932. else {
  99933. for(shift = 0; !(x&1); shift++)
  99934. x >>= 1;
  99935. }
  99936. if(shift > 0) {
  99937. for(i = 0; i < samples; i++)
  99938. signal[i] >>= shift;
  99939. }
  99940. return shift;
  99941. }
  99942. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  99943. {
  99944. unsigned channel;
  99945. for(channel = 0; channel < channels; channel++)
  99946. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  99947. fifo->tail += wide_samples;
  99948. FLAC__ASSERT(fifo->tail <= fifo->size);
  99949. }
  99950. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  99951. {
  99952. unsigned channel;
  99953. unsigned sample, wide_sample;
  99954. unsigned tail = fifo->tail;
  99955. sample = input_offset * channels;
  99956. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  99957. for(channel = 0; channel < channels; channel++)
  99958. fifo->data[channel][tail] = input[sample++];
  99959. tail++;
  99960. }
  99961. fifo->tail = tail;
  99962. FLAC__ASSERT(fifo->tail <= fifo->size);
  99963. }
  99964. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  99965. {
  99966. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  99967. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  99968. (void)decoder;
  99969. if(encoder->private_->verify.needs_magic_hack) {
  99970. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  99971. *bytes = FLAC__STREAM_SYNC_LENGTH;
  99972. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  99973. encoder->private_->verify.needs_magic_hack = false;
  99974. }
  99975. else {
  99976. if(encoded_bytes == 0) {
  99977. /*
  99978. * If we get here, a FIFO underflow has occurred,
  99979. * which means there is a bug somewhere.
  99980. */
  99981. FLAC__ASSERT(0);
  99982. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  99983. }
  99984. else if(encoded_bytes < *bytes)
  99985. *bytes = encoded_bytes;
  99986. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  99987. encoder->private_->verify.output.data += *bytes;
  99988. encoder->private_->verify.output.bytes -= *bytes;
  99989. }
  99990. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  99991. }
  99992. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  99993. {
  99994. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  99995. unsigned channel;
  99996. const unsigned channels = frame->header.channels;
  99997. const unsigned blocksize = frame->header.blocksize;
  99998. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  99999. (void)decoder;
  100000. for(channel = 0; channel < channels; channel++) {
  100001. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  100002. unsigned i, sample = 0;
  100003. FLAC__int32 expect = 0, got = 0;
  100004. for(i = 0; i < blocksize; i++) {
  100005. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  100006. sample = i;
  100007. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  100008. got = (FLAC__int32)buffer[channel][i];
  100009. break;
  100010. }
  100011. }
  100012. FLAC__ASSERT(i < blocksize);
  100013. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100014. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  100015. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  100016. encoder->private_->verify.error_stats.channel = channel;
  100017. encoder->private_->verify.error_stats.sample = sample;
  100018. encoder->private_->verify.error_stats.expected = expect;
  100019. encoder->private_->verify.error_stats.got = got;
  100020. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  100021. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  100022. }
  100023. }
  100024. /* dequeue the frame from the fifo */
  100025. encoder->private_->verify.input_fifo.tail -= blocksize;
  100026. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  100027. for(channel = 0; channel < channels; channel++)
  100028. 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]));
  100029. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  100030. }
  100031. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  100032. {
  100033. (void)decoder, (void)metadata, (void)client_data;
  100034. }
  100035. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  100036. {
  100037. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  100038. (void)decoder, (void)status;
  100039. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  100040. }
  100041. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  100042. {
  100043. (void)client_data;
  100044. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  100045. if (*bytes == 0) {
  100046. if (feof(encoder->private_->file))
  100047. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  100048. else if (ferror(encoder->private_->file))
  100049. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  100050. }
  100051. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  100052. }
  100053. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  100054. {
  100055. (void)client_data;
  100056. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  100057. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  100058. else
  100059. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  100060. }
  100061. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  100062. {
  100063. off_t offset;
  100064. (void)client_data;
  100065. offset = ftello(encoder->private_->file);
  100066. if(offset < 0) {
  100067. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  100068. }
  100069. else {
  100070. *absolute_byte_offset = (FLAC__uint64)offset;
  100071. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  100072. }
  100073. }
  100074. #ifdef FLAC__VALGRIND_TESTING
  100075. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  100076. {
  100077. size_t ret = fwrite(ptr, size, nmemb, stream);
  100078. if(!ferror(stream))
  100079. fflush(stream);
  100080. return ret;
  100081. }
  100082. #else
  100083. #define local__fwrite fwrite
  100084. #endif
  100085. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  100086. {
  100087. (void)client_data, (void)current_frame;
  100088. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  100089. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  100090. #if FLAC__HAS_OGG
  100091. /* We would like to be able to use 'samples > 0' in the
  100092. * clause here but currently because of the nature of our
  100093. * Ogg writing implementation, 'samples' is always 0 (see
  100094. * ogg_encoder_aspect.c). The downside is extra progress
  100095. * callbacks.
  100096. */
  100097. encoder->private_->is_ogg? true :
  100098. #endif
  100099. samples > 0
  100100. );
  100101. if(call_it) {
  100102. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  100103. * because at this point in the callback chain, the stats
  100104. * have not been updated. Only after we return and control
  100105. * gets back to write_frame_() are the stats updated
  100106. */
  100107. 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);
  100108. }
  100109. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  100110. }
  100111. else
  100112. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  100113. }
  100114. /*
  100115. * This will forcibly set stdout to binary mode (for OSes that require it)
  100116. */
  100117. FILE *get_binary_stdout_(void)
  100118. {
  100119. /* if something breaks here it is probably due to the presence or
  100120. * absence of an underscore before the identifiers 'setmode',
  100121. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100122. */
  100123. #if defined _MSC_VER || defined __MINGW32__
  100124. _setmode(_fileno(stdout), _O_BINARY);
  100125. #elif defined __CYGWIN__
  100126. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100127. setmode(_fileno(stdout), _O_BINARY);
  100128. #elif defined __EMX__
  100129. setmode(fileno(stdout), O_BINARY);
  100130. #endif
  100131. return stdout;
  100132. }
  100133. #endif
  100134. /********* End of inlined file: stream_encoder.c *********/
  100135. /********* Start of inlined file: stream_encoder_framing.c *********/
  100136. /********* Start of inlined file: juce_FlacHeader.h *********/
  100137. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  100138. // tasks..
  100139. #define VERSION "1.2.1"
  100140. #define FLAC__NO_DLL 1
  100141. #ifdef _MSC_VER
  100142. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  100143. #endif
  100144. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  100145. #define FLAC__SYS_DARWIN 1
  100146. #endif
  100147. /********* End of inlined file: juce_FlacHeader.h *********/
  100148. #if JUCE_USE_FLAC
  100149. #if HAVE_CONFIG_H
  100150. # include <config.h>
  100151. #endif
  100152. #include <stdio.h>
  100153. #include <string.h> /* for strlen() */
  100154. #ifdef max
  100155. #undef max
  100156. #endif
  100157. #define max(x,y) ((x)>(y)?(x):(y))
  100158. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  100159. 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);
  100160. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  100161. {
  100162. unsigned i, j;
  100163. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  100164. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100165. return false;
  100166. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  100167. return false;
  100168. /*
  100169. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  100170. */
  100171. i = metadata->length;
  100172. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  100173. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  100174. i -= metadata->data.vorbis_comment.vendor_string.length;
  100175. i += vendor_string_length;
  100176. }
  100177. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  100178. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  100179. return false;
  100180. switch(metadata->type) {
  100181. case FLAC__METADATA_TYPE_STREAMINFO:
  100182. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  100183. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  100184. return false;
  100185. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  100186. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100187. return false;
  100188. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  100189. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100190. return false;
  100191. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  100192. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100193. return false;
  100194. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  100195. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100196. return false;
  100197. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  100198. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  100199. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100200. return false;
  100201. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  100202. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  100203. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100204. return false;
  100205. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  100206. return false;
  100207. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  100208. return false;
  100209. break;
  100210. case FLAC__METADATA_TYPE_PADDING:
  100211. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  100212. return false;
  100213. break;
  100214. case FLAC__METADATA_TYPE_APPLICATION:
  100215. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  100216. return false;
  100217. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  100218. return false;
  100219. break;
  100220. case FLAC__METADATA_TYPE_SEEKTABLE:
  100221. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  100222. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100223. return false;
  100224. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100225. return false;
  100226. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100227. return false;
  100228. }
  100229. break;
  100230. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100231. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  100232. return false;
  100233. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  100234. return false;
  100235. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  100236. return false;
  100237. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  100238. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  100239. return false;
  100240. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  100241. return false;
  100242. }
  100243. break;
  100244. case FLAC__METADATA_TYPE_CUESHEET:
  100245. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100246. 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))
  100247. return false;
  100248. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100249. return false;
  100250. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100251. return false;
  100252. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100253. return false;
  100254. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100255. return false;
  100256. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  100257. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  100258. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100259. return false;
  100260. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100261. return false;
  100262. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100263. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100264. return false;
  100265. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100266. return false;
  100267. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100268. return false;
  100269. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100270. return false;
  100271. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100272. return false;
  100273. for(j = 0; j < track->num_indices; j++) {
  100274. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  100275. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100276. return false;
  100277. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100278. return false;
  100279. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100280. return false;
  100281. }
  100282. }
  100283. break;
  100284. case FLAC__METADATA_TYPE_PICTURE:
  100285. {
  100286. size_t len;
  100287. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100288. return false;
  100289. len = strlen(metadata->data.picture.mime_type);
  100290. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100291. return false;
  100292. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  100293. return false;
  100294. len = strlen((const char *)metadata->data.picture.description);
  100295. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100296. return false;
  100297. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  100298. return false;
  100299. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100300. return false;
  100301. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100302. return false;
  100303. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100304. return false;
  100305. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100306. return false;
  100307. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100308. return false;
  100309. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  100310. return false;
  100311. }
  100312. break;
  100313. default:
  100314. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  100315. return false;
  100316. break;
  100317. }
  100318. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  100319. return true;
  100320. }
  100321. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  100322. {
  100323. unsigned u, blocksize_hint, sample_rate_hint;
  100324. FLAC__byte crc;
  100325. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  100326. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  100327. return false;
  100328. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  100329. return false;
  100330. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  100331. return false;
  100332. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  100333. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  100334. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  100335. blocksize_hint = 0;
  100336. switch(header->blocksize) {
  100337. case 192: u = 1; break;
  100338. case 576: u = 2; break;
  100339. case 1152: u = 3; break;
  100340. case 2304: u = 4; break;
  100341. case 4608: u = 5; break;
  100342. case 256: u = 8; break;
  100343. case 512: u = 9; break;
  100344. case 1024: u = 10; break;
  100345. case 2048: u = 11; break;
  100346. case 4096: u = 12; break;
  100347. case 8192: u = 13; break;
  100348. case 16384: u = 14; break;
  100349. case 32768: u = 15; break;
  100350. default:
  100351. if(header->blocksize <= 0x100)
  100352. blocksize_hint = u = 6;
  100353. else
  100354. blocksize_hint = u = 7;
  100355. break;
  100356. }
  100357. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  100358. return false;
  100359. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  100360. sample_rate_hint = 0;
  100361. switch(header->sample_rate) {
  100362. case 88200: u = 1; break;
  100363. case 176400: u = 2; break;
  100364. case 192000: u = 3; break;
  100365. case 8000: u = 4; break;
  100366. case 16000: u = 5; break;
  100367. case 22050: u = 6; break;
  100368. case 24000: u = 7; break;
  100369. case 32000: u = 8; break;
  100370. case 44100: u = 9; break;
  100371. case 48000: u = 10; break;
  100372. case 96000: u = 11; break;
  100373. default:
  100374. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  100375. sample_rate_hint = u = 12;
  100376. else if(header->sample_rate % 10 == 0)
  100377. sample_rate_hint = u = 14;
  100378. else if(header->sample_rate <= 0xffff)
  100379. sample_rate_hint = u = 13;
  100380. else
  100381. u = 0;
  100382. break;
  100383. }
  100384. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  100385. return false;
  100386. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  100387. switch(header->channel_assignment) {
  100388. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100389. u = header->channels - 1;
  100390. break;
  100391. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100392. FLAC__ASSERT(header->channels == 2);
  100393. u = 8;
  100394. break;
  100395. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100396. FLAC__ASSERT(header->channels == 2);
  100397. u = 9;
  100398. break;
  100399. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100400. FLAC__ASSERT(header->channels == 2);
  100401. u = 10;
  100402. break;
  100403. default:
  100404. FLAC__ASSERT(0);
  100405. }
  100406. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  100407. return false;
  100408. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  100409. switch(header->bits_per_sample) {
  100410. case 8 : u = 1; break;
  100411. case 12: u = 2; break;
  100412. case 16: u = 4; break;
  100413. case 20: u = 5; break;
  100414. case 24: u = 6; break;
  100415. default: u = 0; break;
  100416. }
  100417. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  100418. return false;
  100419. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  100420. return false;
  100421. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  100422. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  100423. return false;
  100424. }
  100425. else {
  100426. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  100427. return false;
  100428. }
  100429. if(blocksize_hint)
  100430. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  100431. return false;
  100432. switch(sample_rate_hint) {
  100433. case 12:
  100434. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  100435. return false;
  100436. break;
  100437. case 13:
  100438. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  100439. return false;
  100440. break;
  100441. case 14:
  100442. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  100443. return false;
  100444. break;
  100445. }
  100446. /* write the CRC */
  100447. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  100448. return false;
  100449. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  100450. return false;
  100451. return true;
  100452. }
  100453. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  100454. {
  100455. FLAC__bool ok;
  100456. ok =
  100457. 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) &&
  100458. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  100459. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  100460. ;
  100461. return ok;
  100462. }
  100463. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  100464. {
  100465. unsigned i;
  100466. 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))
  100467. return false;
  100468. if(wasted_bits)
  100469. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  100470. return false;
  100471. for(i = 0; i < subframe->order; i++)
  100472. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  100473. return false;
  100474. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  100475. return false;
  100476. switch(subframe->entropy_coding_method.type) {
  100477. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100478. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100479. if(!add_residual_partitioned_rice_(
  100480. bw,
  100481. subframe->residual,
  100482. residual_samples,
  100483. subframe->order,
  100484. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  100485. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  100486. subframe->entropy_coding_method.data.partitioned_rice.order,
  100487. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  100488. ))
  100489. return false;
  100490. break;
  100491. default:
  100492. FLAC__ASSERT(0);
  100493. }
  100494. return true;
  100495. }
  100496. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  100497. {
  100498. unsigned i;
  100499. 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))
  100500. return false;
  100501. if(wasted_bits)
  100502. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  100503. return false;
  100504. for(i = 0; i < subframe->order; i++)
  100505. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  100506. return false;
  100507. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  100508. return false;
  100509. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  100510. return false;
  100511. for(i = 0; i < subframe->order; i++)
  100512. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  100513. return false;
  100514. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  100515. return false;
  100516. switch(subframe->entropy_coding_method.type) {
  100517. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100518. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100519. if(!add_residual_partitioned_rice_(
  100520. bw,
  100521. subframe->residual,
  100522. residual_samples,
  100523. subframe->order,
  100524. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  100525. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  100526. subframe->entropy_coding_method.data.partitioned_rice.order,
  100527. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  100528. ))
  100529. return false;
  100530. break;
  100531. default:
  100532. FLAC__ASSERT(0);
  100533. }
  100534. return true;
  100535. }
  100536. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  100537. {
  100538. unsigned i;
  100539. const FLAC__int32 *signal = subframe->data;
  100540. 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))
  100541. return false;
  100542. if(wasted_bits)
  100543. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  100544. return false;
  100545. for(i = 0; i < samples; i++)
  100546. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  100547. return false;
  100548. return true;
  100549. }
  100550. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  100551. {
  100552. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100553. return false;
  100554. switch(method->type) {
  100555. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100556. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100557. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100558. return false;
  100559. break;
  100560. default:
  100561. FLAC__ASSERT(0);
  100562. }
  100563. return true;
  100564. }
  100565. 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)
  100566. {
  100567. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  100568. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  100569. if(partition_order == 0) {
  100570. unsigned i;
  100571. if(raw_bits[0] == 0) {
  100572. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  100573. return false;
  100574. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  100575. return false;
  100576. }
  100577. else {
  100578. FLAC__ASSERT(rice_parameters[0] == 0);
  100579. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  100580. return false;
  100581. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  100582. return false;
  100583. for(i = 0; i < residual_samples; i++) {
  100584. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  100585. return false;
  100586. }
  100587. }
  100588. return true;
  100589. }
  100590. else {
  100591. unsigned i, j, k = 0, k_last = 0;
  100592. unsigned partition_samples;
  100593. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  100594. for(i = 0; i < (1u<<partition_order); i++) {
  100595. partition_samples = default_partition_samples;
  100596. if(i == 0)
  100597. partition_samples -= predictor_order;
  100598. k += partition_samples;
  100599. if(raw_bits[i] == 0) {
  100600. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  100601. return false;
  100602. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  100603. return false;
  100604. }
  100605. else {
  100606. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  100607. return false;
  100608. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  100609. return false;
  100610. for(j = k_last; j < k; j++) {
  100611. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  100612. return false;
  100613. }
  100614. }
  100615. k_last = k;
  100616. }
  100617. return true;
  100618. }
  100619. }
  100620. #endif
  100621. /********* End of inlined file: stream_encoder_framing.c *********/
  100622. /********* Start of inlined file: window_flac.c *********/
  100623. /********* Start of inlined file: juce_FlacHeader.h *********/
  100624. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  100625. // tasks..
  100626. #define VERSION "1.2.1"
  100627. #define FLAC__NO_DLL 1
  100628. #ifdef _MSC_VER
  100629. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  100630. #endif
  100631. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  100632. #define FLAC__SYS_DARWIN 1
  100633. #endif
  100634. /********* End of inlined file: juce_FlacHeader.h *********/
  100635. #if JUCE_USE_FLAC
  100636. #if HAVE_CONFIG_H
  100637. # include <config.h>
  100638. #endif
  100639. #include <math.h>
  100640. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100641. #ifndef M_PI
  100642. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  100643. #define M_PI 3.14159265358979323846
  100644. #endif
  100645. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  100646. {
  100647. const FLAC__int32 N = L - 1;
  100648. FLAC__int32 n;
  100649. if (L & 1) {
  100650. for (n = 0; n <= N/2; n++)
  100651. window[n] = 2.0f * n / (float)N;
  100652. for (; n <= N; n++)
  100653. window[n] = 2.0f - 2.0f * n / (float)N;
  100654. }
  100655. else {
  100656. for (n = 0; n <= L/2-1; n++)
  100657. window[n] = 2.0f * n / (float)N;
  100658. for (; n <= N; n++)
  100659. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  100660. }
  100661. }
  100662. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  100663. {
  100664. const FLAC__int32 N = L - 1;
  100665. FLAC__int32 n;
  100666. for (n = 0; n < L; n++)
  100667. 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)));
  100668. }
  100669. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  100670. {
  100671. const FLAC__int32 N = L - 1;
  100672. FLAC__int32 n;
  100673. for (n = 0; n < L; n++)
  100674. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  100675. }
  100676. /* 4-term -92dB side-lobe */
  100677. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  100678. {
  100679. const FLAC__int32 N = L - 1;
  100680. FLAC__int32 n;
  100681. for (n = 0; n <= N; n++)
  100682. 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));
  100683. }
  100684. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  100685. {
  100686. const FLAC__int32 N = L - 1;
  100687. const double N2 = (double)N / 2.;
  100688. FLAC__int32 n;
  100689. for (n = 0; n <= N; n++) {
  100690. double k = ((double)n - N2) / N2;
  100691. k = 1.0f - k * k;
  100692. window[n] = (FLAC__real)(k * k);
  100693. }
  100694. }
  100695. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  100696. {
  100697. const FLAC__int32 N = L - 1;
  100698. FLAC__int32 n;
  100699. for (n = 0; n < L; n++)
  100700. 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));
  100701. }
  100702. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  100703. {
  100704. const FLAC__int32 N = L - 1;
  100705. const double N2 = (double)N / 2.;
  100706. FLAC__int32 n;
  100707. for (n = 0; n <= N; n++) {
  100708. const double k = ((double)n - N2) / (stddev * N2);
  100709. window[n] = (FLAC__real)exp(-0.5f * k * k);
  100710. }
  100711. }
  100712. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  100713. {
  100714. const FLAC__int32 N = L - 1;
  100715. FLAC__int32 n;
  100716. for (n = 0; n < L; n++)
  100717. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  100718. }
  100719. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  100720. {
  100721. const FLAC__int32 N = L - 1;
  100722. FLAC__int32 n;
  100723. for (n = 0; n < L; n++)
  100724. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  100725. }
  100726. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  100727. {
  100728. const FLAC__int32 N = L - 1;
  100729. FLAC__int32 n;
  100730. for (n = 0; n < L; n++)
  100731. 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));
  100732. }
  100733. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  100734. {
  100735. const FLAC__int32 N = L - 1;
  100736. FLAC__int32 n;
  100737. for (n = 0; n < L; n++)
  100738. 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));
  100739. }
  100740. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  100741. {
  100742. FLAC__int32 n;
  100743. for (n = 0; n < L; n++)
  100744. window[n] = 1.0f;
  100745. }
  100746. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  100747. {
  100748. FLAC__int32 n;
  100749. if (L & 1) {
  100750. for (n = 1; n <= L+1/2; n++)
  100751. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  100752. for (; n <= L; n++)
  100753. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  100754. }
  100755. else {
  100756. for (n = 1; n <= L/2; n++)
  100757. window[n-1] = 2.0f * n / (float)L;
  100758. for (; n <= L; n++)
  100759. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  100760. }
  100761. }
  100762. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  100763. {
  100764. if (p <= 0.0)
  100765. FLAC__window_rectangle(window, L);
  100766. else if (p >= 1.0)
  100767. FLAC__window_hann(window, L);
  100768. else {
  100769. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  100770. FLAC__int32 n;
  100771. /* start with rectangle... */
  100772. FLAC__window_rectangle(window, L);
  100773. /* ...replace ends with hann */
  100774. if (Np > 0) {
  100775. for (n = 0; n <= Np; n++) {
  100776. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  100777. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  100778. }
  100779. }
  100780. }
  100781. }
  100782. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  100783. {
  100784. const FLAC__int32 N = L - 1;
  100785. const double N2 = (double)N / 2.;
  100786. FLAC__int32 n;
  100787. for (n = 0; n <= N; n++) {
  100788. const double k = ((double)n - N2) / N2;
  100789. window[n] = (FLAC__real)(1.0f - k * k);
  100790. }
  100791. }
  100792. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  100793. #endif
  100794. /********* End of inlined file: window_flac.c *********/
  100795. }
  100796. #ifdef _MSC_VER
  100797. #pragma warning (pop)
  100798. #endif
  100799. BEGIN_JUCE_NAMESPACE
  100800. using namespace FlacNamespace;
  100801. #define flacFormatName TRANS("FLAC file")
  100802. static const tchar* const flacExtensions[] = { T(".flac"), 0 };
  100803. class FlacReader : public AudioFormatReader
  100804. {
  100805. FLAC__StreamDecoder* decoder;
  100806. AudioSampleBuffer reservoir;
  100807. int reservoirStart, samplesInReservoir;
  100808. bool ok, scanningForLength;
  100809. public:
  100810. FlacReader (InputStream* const in)
  100811. : AudioFormatReader (in, flacFormatName),
  100812. reservoir (2, 0),
  100813. reservoirStart (0),
  100814. samplesInReservoir (0),
  100815. scanningForLength (false)
  100816. {
  100817. using namespace FlacNamespace;
  100818. lengthInSamples = 0;
  100819. decoder = FLAC__stream_decoder_new();
  100820. ok = FLAC__stream_decoder_init_stream (decoder,
  100821. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  100822. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  100823. (void*) this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  100824. if (ok)
  100825. {
  100826. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  100827. if (lengthInSamples == 0 && sampleRate > 0)
  100828. {
  100829. // the length hasn't been stored in the metadata, so we'll need to
  100830. // work it out the length the hard way, by scanning the whole file..
  100831. scanningForLength = true;
  100832. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  100833. scanningForLength = false;
  100834. const int64 tempLength = lengthInSamples;
  100835. FLAC__stream_decoder_reset (decoder);
  100836. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  100837. lengthInSamples = tempLength;
  100838. }
  100839. }
  100840. }
  100841. ~FlacReader()
  100842. {
  100843. FLAC__stream_decoder_delete (decoder);
  100844. }
  100845. void useMetadata (const FLAC__StreamMetadata_StreamInfo& info)
  100846. {
  100847. sampleRate = info.sample_rate;
  100848. bitsPerSample = info.bits_per_sample;
  100849. lengthInSamples = (unsigned int) info.total_samples;
  100850. numChannels = info.channels;
  100851. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  100852. }
  100853. // returns the number of samples read
  100854. bool read (int** destSamples,
  100855. int64 startSampleInFile,
  100856. int numSamples)
  100857. {
  100858. using namespace FlacNamespace;
  100859. if (! ok)
  100860. return false;
  100861. int offset = 0;
  100862. if (startSampleInFile < 0)
  100863. {
  100864. const int num = (int) jmin ((int64) numSamples, -startSampleInFile);
  100865. int n = 0;
  100866. while (destSamples[n] != 0)
  100867. {
  100868. zeromem (destSamples[n], sizeof (int) * num);
  100869. ++n;
  100870. }
  100871. offset += num;
  100872. startSampleInFile += num;
  100873. numSamples -= num;
  100874. }
  100875. while (numSamples > 0)
  100876. {
  100877. if (startSampleInFile >= reservoirStart
  100878. && startSampleInFile < reservoirStart + samplesInReservoir)
  100879. {
  100880. const int num = (int) jmin ((int64) numSamples,
  100881. reservoirStart + samplesInReservoir - startSampleInFile);
  100882. jassert (num > 0);
  100883. int n = 0;
  100884. while (destSamples[n] != 0)
  100885. {
  100886. memcpy (destSamples[n] + offset,
  100887. reservoir.getSampleData (n, (int) (startSampleInFile - reservoirStart)),
  100888. sizeof (int) * num);
  100889. ++n;
  100890. }
  100891. offset += num;
  100892. startSampleInFile += num;
  100893. numSamples -= num;
  100894. }
  100895. else
  100896. {
  100897. if (startSampleInFile < reservoirStart
  100898. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  100899. {
  100900. if (startSampleInFile >= (int) lengthInSamples)
  100901. {
  100902. samplesInReservoir = 0;
  100903. break;
  100904. }
  100905. // had some problems with flac crashing if the read pos is aligned more
  100906. // accurately than this. Probably fixed in newer versions of the library, though.
  100907. reservoirStart = (int) (startSampleInFile & ~511);
  100908. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  100909. }
  100910. else
  100911. {
  100912. reservoirStart += samplesInReservoir;
  100913. }
  100914. samplesInReservoir = 0;
  100915. FLAC__stream_decoder_process_single (decoder);
  100916. if (samplesInReservoir == 0)
  100917. break;
  100918. }
  100919. }
  100920. if (numSamples > 0)
  100921. {
  100922. int n = 0;
  100923. while (destSamples[n] != 0)
  100924. {
  100925. zeromem (destSamples[n] + offset, sizeof (int) * numSamples);
  100926. ++n;
  100927. }
  100928. }
  100929. return true;
  100930. }
  100931. void useSamples (const FLAC__int32* const buffer[], int numSamples)
  100932. {
  100933. if (scanningForLength)
  100934. {
  100935. lengthInSamples += numSamples;
  100936. }
  100937. else
  100938. {
  100939. if (numSamples > reservoir.getNumSamples())
  100940. reservoir.setSize (numChannels, numSamples, false, false, true);
  100941. const int bitsToShift = 32 - bitsPerSample;
  100942. for (int i = 0; i < (int) numChannels; ++i)
  100943. {
  100944. const FLAC__int32* src = buffer[i];
  100945. int n = i;
  100946. while (src == 0 && n > 0)
  100947. src = buffer [--n];
  100948. if (src != 0)
  100949. {
  100950. int* dest = (int*) reservoir.getSampleData(i);
  100951. for (int j = 0; j < numSamples; ++j)
  100952. dest[j] = src[j] << bitsToShift;
  100953. }
  100954. }
  100955. samplesInReservoir = numSamples;
  100956. }
  100957. }
  100958. static FLAC__StreamDecoderReadStatus readCallback_ (const FLAC__StreamDecoder*, FLAC__byte buffer[], size_t* bytes, void* client_data)
  100959. {
  100960. *bytes = (unsigned int) ((const FlacReader*) client_data)->input->read (buffer, (int) *bytes);
  100961. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100962. }
  100963. static FLAC__StreamDecoderSeekStatus seekCallback_ (const FLAC__StreamDecoder*, FLAC__uint64 absolute_byte_offset, void* client_data)
  100964. {
  100965. ((const FlacReader*) client_data)->input->setPosition ((int) absolute_byte_offset);
  100966. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  100967. }
  100968. static FLAC__StreamDecoderTellStatus tellCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* absolute_byte_offset, void* client_data)
  100969. {
  100970. *absolute_byte_offset = ((const FlacReader*) client_data)->input->getPosition();
  100971. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  100972. }
  100973. static FLAC__StreamDecoderLengthStatus lengthCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* stream_length, void* client_data)
  100974. {
  100975. *stream_length = ((const FlacReader*) client_data)->input->getTotalLength();
  100976. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  100977. }
  100978. static FLAC__bool eofCallback_ (const FLAC__StreamDecoder*, void* client_data)
  100979. {
  100980. return ((const FlacReader*) client_data)->input->isExhausted();
  100981. }
  100982. static FLAC__StreamDecoderWriteStatus writeCallback_ (const FLAC__StreamDecoder*,
  100983. const FLAC__Frame* frame,
  100984. const FLAC__int32* const buffer[],
  100985. void* client_data)
  100986. {
  100987. ((FlacReader*) client_data)->useSamples (buffer, frame->header.blocksize);
  100988. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  100989. }
  100990. static void metadataCallback_ (const FLAC__StreamDecoder*,
  100991. const FLAC__StreamMetadata* metadata,
  100992. void* client_data)
  100993. {
  100994. ((FlacReader*) client_data)->useMetadata (metadata->data.stream_info);
  100995. }
  100996. static void errorCallback_ (const FLAC__StreamDecoder*, FLAC__StreamDecoderErrorStatus, void*)
  100997. {
  100998. }
  100999. juce_UseDebuggingNewOperator
  101000. };
  101001. class FlacWriter : public AudioFormatWriter
  101002. {
  101003. FLAC__StreamEncoder* encoder;
  101004. MemoryBlock temp;
  101005. public:
  101006. bool ok;
  101007. FlacWriter (OutputStream* const out,
  101008. const double sampleRate,
  101009. const int numChannels,
  101010. const int bitsPerSample_)
  101011. : AudioFormatWriter (out, flacFormatName,
  101012. sampleRate,
  101013. numChannels,
  101014. bitsPerSample_)
  101015. {
  101016. using namespace FlacNamespace;
  101017. encoder = FLAC__stream_encoder_new();
  101018. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  101019. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  101020. FLAC__stream_encoder_set_channels (encoder, numChannels);
  101021. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin (24, bitsPerSample));
  101022. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  101023. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  101024. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  101025. ok = FLAC__stream_encoder_init_stream (encoder,
  101026. encodeWriteCallback, encodeSeekCallback,
  101027. encodeTellCallback, encodeMetadataCallback,
  101028. (void*) this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  101029. }
  101030. ~FlacWriter()
  101031. {
  101032. if (ok)
  101033. {
  101034. FLAC__stream_encoder_finish (encoder);
  101035. output->flush();
  101036. }
  101037. else
  101038. {
  101039. output = 0; // to stop the base class deleting this, as it needs to be returned
  101040. // to the caller of createWriter()
  101041. }
  101042. FLAC__stream_encoder_delete (encoder);
  101043. }
  101044. bool write (const int** samplesToWrite, int numSamples)
  101045. {
  101046. if (! ok)
  101047. return false;
  101048. int* buf[3];
  101049. const int bitsToShift = 32 - bitsPerSample;
  101050. if (bitsToShift > 0)
  101051. {
  101052. const int numChannels = (samplesToWrite[1] == 0) ? 1 : 2;
  101053. temp.setSize (sizeof (int) * numSamples * numChannels);
  101054. buf[0] = (int*) temp.getData();
  101055. buf[1] = buf[0] + numSamples;
  101056. buf[2] = 0;
  101057. for (int i = numChannels; --i >= 0;)
  101058. {
  101059. if (samplesToWrite[i] != 0)
  101060. {
  101061. for (int j = 0; j < numSamples; ++j)
  101062. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  101063. }
  101064. }
  101065. samplesToWrite = (const int**) buf;
  101066. }
  101067. return FLAC__stream_encoder_process (encoder,
  101068. (const FLAC__int32**) samplesToWrite,
  101069. numSamples) != 0;
  101070. }
  101071. bool writeData (const void* const data, const int size) const
  101072. {
  101073. return output->write (data, size);
  101074. }
  101075. static void packUint32 (FLAC__uint32 val, FLAC__byte* b, const int bytes)
  101076. {
  101077. b += bytes;
  101078. for (int i = 0; i < bytes; ++i)
  101079. {
  101080. *(--b) = (FLAC__byte) (val & 0xff);
  101081. val >>= 8;
  101082. }
  101083. }
  101084. void writeMetaData (const FLAC__StreamMetadata* metadata)
  101085. {
  101086. using namespace FlacNamespace;
  101087. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  101088. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  101089. const unsigned int channelsMinus1 = info.channels - 1;
  101090. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  101091. packUint32 (info.min_blocksize, buffer, 2);
  101092. packUint32 (info.max_blocksize, buffer + 2, 2);
  101093. packUint32 (info.min_framesize, buffer + 4, 3);
  101094. packUint32 (info.max_framesize, buffer + 7, 3);
  101095. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  101096. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  101097. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  101098. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  101099. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  101100. memcpy (buffer + 18, info.md5sum, 16);
  101101. const bool ok = output->setPosition (4);
  101102. (void) ok;
  101103. // if this fails, you've given it an output stream that can't seek! It needs
  101104. // to be able to seek back to write the header
  101105. jassert (ok);
  101106. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  101107. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  101108. }
  101109. static FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FLAC__StreamEncoder*,
  101110. const FLAC__byte buffer[],
  101111. size_t bytes,
  101112. unsigned int /*samples*/,
  101113. unsigned int /*current_frame*/,
  101114. void* client_data)
  101115. {
  101116. using namespace FlacNamespace;
  101117. return ((FlacWriter*) client_data)->writeData (buffer, (int) bytes)
  101118. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  101119. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  101120. }
  101121. static FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FLAC__StreamEncoder*, FLAC__uint64, void*)
  101122. {
  101123. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  101124. }
  101125. static FLAC__StreamEncoderTellStatus encodeTellCallback (const FLAC__StreamEncoder*, FLAC__uint64*, void*)
  101126. {
  101127. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  101128. }
  101129. static void encodeMetadataCallback (const FLAC__StreamEncoder*,
  101130. const FLAC__StreamMetadata* metadata,
  101131. void* client_data)
  101132. {
  101133. ((FlacWriter*) client_data)->writeMetaData (metadata);
  101134. }
  101135. juce_UseDebuggingNewOperator
  101136. };
  101137. FlacAudioFormat::FlacAudioFormat()
  101138. : AudioFormat (flacFormatName, (const tchar**) flacExtensions)
  101139. {
  101140. }
  101141. FlacAudioFormat::~FlacAudioFormat()
  101142. {
  101143. }
  101144. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  101145. {
  101146. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  101147. return Array <int> (rates);
  101148. }
  101149. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  101150. {
  101151. const int depths[] = { 16, 24, 0 };
  101152. return Array <int> (depths);
  101153. }
  101154. bool FlacAudioFormat::canDoStereo()
  101155. {
  101156. return true;
  101157. }
  101158. bool FlacAudioFormat::canDoMono()
  101159. {
  101160. return true;
  101161. }
  101162. bool FlacAudioFormat::isCompressed()
  101163. {
  101164. return true;
  101165. }
  101166. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  101167. const bool deleteStreamIfOpeningFails)
  101168. {
  101169. FlacReader* r = new FlacReader (in);
  101170. if (r->sampleRate == 0)
  101171. {
  101172. if (! deleteStreamIfOpeningFails)
  101173. r->input = 0;
  101174. deleteAndZero (r);
  101175. }
  101176. return r;
  101177. }
  101178. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  101179. double sampleRate,
  101180. unsigned int numberOfChannels,
  101181. int bitsPerSample,
  101182. const StringPairArray& /*metadataValues*/,
  101183. int /*qualityOptionIndex*/)
  101184. {
  101185. if (getPossibleBitDepths().contains (bitsPerSample))
  101186. {
  101187. FlacWriter* w = new FlacWriter (out,
  101188. sampleRate,
  101189. numberOfChannels,
  101190. bitsPerSample);
  101191. if (! w->ok)
  101192. deleteAndZero (w);
  101193. return w;
  101194. }
  101195. return 0;
  101196. }
  101197. END_JUCE_NAMESPACE
  101198. #endif
  101199. /********* End of inlined file: juce_FlacAudioFormat.cpp *********/
  101200. /********* Start of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  101201. #if JUCE_USE_OGGVORBIS
  101202. #if JUCE_MAC
  101203. #define __MACOSX__ 1
  101204. #endif
  101205. namespace OggVorbisNamespace
  101206. {
  101207. /********* Start of inlined file: vorbisenc.h *********/
  101208. #ifndef _OV_ENC_H_
  101209. #define _OV_ENC_H_
  101210. #ifdef __cplusplus
  101211. extern "C"
  101212. {
  101213. #endif /* __cplusplus */
  101214. /********* Start of inlined file: codec.h *********/
  101215. #ifndef _vorbis_codec_h_
  101216. #define _vorbis_codec_h_
  101217. #ifdef __cplusplus
  101218. extern "C"
  101219. {
  101220. #endif /* __cplusplus */
  101221. /********* Start of inlined file: ogg.h *********/
  101222. #ifndef _OGG_H
  101223. #define _OGG_H
  101224. #ifdef __cplusplus
  101225. extern "C" {
  101226. #endif
  101227. /********* Start of inlined file: os_types.h *********/
  101228. #ifndef _OS_TYPES_H
  101229. #define _OS_TYPES_H
  101230. /* make it easy on the folks that want to compile the libs with a
  101231. different malloc than stdlib */
  101232. #define _ogg_malloc malloc
  101233. #define _ogg_calloc calloc
  101234. #define _ogg_realloc realloc
  101235. #define _ogg_free free
  101236. #if defined(_WIN32)
  101237. # if defined(__CYGWIN__)
  101238. # include <_G_config.h>
  101239. typedef _G_int64_t ogg_int64_t;
  101240. typedef _G_int32_t ogg_int32_t;
  101241. typedef _G_uint32_t ogg_uint32_t;
  101242. typedef _G_int16_t ogg_int16_t;
  101243. typedef _G_uint16_t ogg_uint16_t;
  101244. # elif defined(__MINGW32__)
  101245. typedef short ogg_int16_t;
  101246. typedef unsigned short ogg_uint16_t;
  101247. typedef int ogg_int32_t;
  101248. typedef unsigned int ogg_uint32_t;
  101249. typedef long long ogg_int64_t;
  101250. typedef unsigned long long ogg_uint64_t;
  101251. # elif defined(__MWERKS__)
  101252. typedef long long ogg_int64_t;
  101253. typedef int ogg_int32_t;
  101254. typedef unsigned int ogg_uint32_t;
  101255. typedef short ogg_int16_t;
  101256. typedef unsigned short ogg_uint16_t;
  101257. # else
  101258. /* MSVC/Borland */
  101259. typedef __int64 ogg_int64_t;
  101260. typedef __int32 ogg_int32_t;
  101261. typedef unsigned __int32 ogg_uint32_t;
  101262. typedef __int16 ogg_int16_t;
  101263. typedef unsigned __int16 ogg_uint16_t;
  101264. # endif
  101265. #elif defined(__MACOS__)
  101266. # include <sys/types.h>
  101267. typedef SInt16 ogg_int16_t;
  101268. typedef UInt16 ogg_uint16_t;
  101269. typedef SInt32 ogg_int32_t;
  101270. typedef UInt32 ogg_uint32_t;
  101271. typedef SInt64 ogg_int64_t;
  101272. #elif defined(__MACOSX__) /* MacOS X Framework build */
  101273. # include <sys/types.h>
  101274. typedef int16_t ogg_int16_t;
  101275. typedef u_int16_t ogg_uint16_t;
  101276. typedef int32_t ogg_int32_t;
  101277. typedef u_int32_t ogg_uint32_t;
  101278. typedef int64_t ogg_int64_t;
  101279. #elif defined(__BEOS__)
  101280. /* Be */
  101281. # include <inttypes.h>
  101282. typedef int16_t ogg_int16_t;
  101283. typedef u_int16_t ogg_uint16_t;
  101284. typedef int32_t ogg_int32_t;
  101285. typedef u_int32_t ogg_uint32_t;
  101286. typedef int64_t ogg_int64_t;
  101287. #elif defined (__EMX__)
  101288. /* OS/2 GCC */
  101289. typedef short ogg_int16_t;
  101290. typedef unsigned short ogg_uint16_t;
  101291. typedef int ogg_int32_t;
  101292. typedef unsigned int ogg_uint32_t;
  101293. typedef long long ogg_int64_t;
  101294. #elif defined (DJGPP)
  101295. /* DJGPP */
  101296. typedef short ogg_int16_t;
  101297. typedef int ogg_int32_t;
  101298. typedef unsigned int ogg_uint32_t;
  101299. typedef long long ogg_int64_t;
  101300. #elif defined(R5900)
  101301. /* PS2 EE */
  101302. typedef long ogg_int64_t;
  101303. typedef int ogg_int32_t;
  101304. typedef unsigned ogg_uint32_t;
  101305. typedef short ogg_int16_t;
  101306. #elif defined(__SYMBIAN32__)
  101307. /* Symbian GCC */
  101308. typedef signed short ogg_int16_t;
  101309. typedef unsigned short ogg_uint16_t;
  101310. typedef signed int ogg_int32_t;
  101311. typedef unsigned int ogg_uint32_t;
  101312. typedef long long int ogg_int64_t;
  101313. #else
  101314. # include <sys/types.h>
  101315. /********* Start of inlined file: config_types.h *********/
  101316. #ifndef __CONFIG_TYPES_H__
  101317. #define __CONFIG_TYPES_H__
  101318. typedef int16_t ogg_int16_t;
  101319. typedef unsigned short ogg_uint16_t;
  101320. typedef int32_t ogg_int32_t;
  101321. typedef unsigned int ogg_uint32_t;
  101322. typedef int64_t ogg_int64_t;
  101323. #endif
  101324. /********* End of inlined file: config_types.h *********/
  101325. #endif
  101326. #endif /* _OS_TYPES_H */
  101327. /********* End of inlined file: os_types.h *********/
  101328. typedef struct {
  101329. long endbyte;
  101330. int endbit;
  101331. unsigned char *buffer;
  101332. unsigned char *ptr;
  101333. long storage;
  101334. } oggpack_buffer;
  101335. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  101336. typedef struct {
  101337. unsigned char *header;
  101338. long header_len;
  101339. unsigned char *body;
  101340. long body_len;
  101341. } ogg_page;
  101342. ogg_uint32_t bitreverse(ogg_uint32_t x){
  101343. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  101344. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  101345. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  101346. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  101347. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  101348. }
  101349. /* ogg_stream_state contains the current encode/decode state of a logical
  101350. Ogg bitstream **********************************************************/
  101351. typedef struct {
  101352. unsigned char *body_data; /* bytes from packet bodies */
  101353. long body_storage; /* storage elements allocated */
  101354. long body_fill; /* elements stored; fill mark */
  101355. long body_returned; /* elements of fill returned */
  101356. int *lacing_vals; /* The values that will go to the segment table */
  101357. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  101358. this way, but it is simple coupled to the
  101359. lacing fifo */
  101360. long lacing_storage;
  101361. long lacing_fill;
  101362. long lacing_packet;
  101363. long lacing_returned;
  101364. unsigned char header[282]; /* working space for header encode */
  101365. int header_fill;
  101366. int e_o_s; /* set when we have buffered the last packet in the
  101367. logical bitstream */
  101368. int b_o_s; /* set after we've written the initial page
  101369. of a logical bitstream */
  101370. long serialno;
  101371. long pageno;
  101372. ogg_int64_t packetno; /* sequence number for decode; the framing
  101373. knows where there's a hole in the data,
  101374. but we need coupling so that the codec
  101375. (which is in a seperate abstraction
  101376. layer) also knows about the gap */
  101377. ogg_int64_t granulepos;
  101378. } ogg_stream_state;
  101379. /* ogg_packet is used to encapsulate the data and metadata belonging
  101380. to a single raw Ogg/Vorbis packet *************************************/
  101381. typedef struct {
  101382. unsigned char *packet;
  101383. long bytes;
  101384. long b_o_s;
  101385. long e_o_s;
  101386. ogg_int64_t granulepos;
  101387. ogg_int64_t packetno; /* sequence number for decode; the framing
  101388. knows where there's a hole in the data,
  101389. but we need coupling so that the codec
  101390. (which is in a seperate abstraction
  101391. layer) also knows about the gap */
  101392. } ogg_packet;
  101393. typedef struct {
  101394. unsigned char *data;
  101395. int storage;
  101396. int fill;
  101397. int returned;
  101398. int unsynced;
  101399. int headerbytes;
  101400. int bodybytes;
  101401. } ogg_sync_state;
  101402. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  101403. extern void oggpack_writeinit(oggpack_buffer *b);
  101404. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  101405. extern void oggpack_writealign(oggpack_buffer *b);
  101406. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  101407. extern void oggpack_reset(oggpack_buffer *b);
  101408. extern void oggpack_writeclear(oggpack_buffer *b);
  101409. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  101410. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  101411. extern long oggpack_look(oggpack_buffer *b,int bits);
  101412. extern long oggpack_look1(oggpack_buffer *b);
  101413. extern void oggpack_adv(oggpack_buffer *b,int bits);
  101414. extern void oggpack_adv1(oggpack_buffer *b);
  101415. extern long oggpack_read(oggpack_buffer *b,int bits);
  101416. extern long oggpack_read1(oggpack_buffer *b);
  101417. extern long oggpack_bytes(oggpack_buffer *b);
  101418. extern long oggpack_bits(oggpack_buffer *b);
  101419. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  101420. extern void oggpackB_writeinit(oggpack_buffer *b);
  101421. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  101422. extern void oggpackB_writealign(oggpack_buffer *b);
  101423. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  101424. extern void oggpackB_reset(oggpack_buffer *b);
  101425. extern void oggpackB_writeclear(oggpack_buffer *b);
  101426. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  101427. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  101428. extern long oggpackB_look(oggpack_buffer *b,int bits);
  101429. extern long oggpackB_look1(oggpack_buffer *b);
  101430. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  101431. extern void oggpackB_adv1(oggpack_buffer *b);
  101432. extern long oggpackB_read(oggpack_buffer *b,int bits);
  101433. extern long oggpackB_read1(oggpack_buffer *b);
  101434. extern long oggpackB_bytes(oggpack_buffer *b);
  101435. extern long oggpackB_bits(oggpack_buffer *b);
  101436. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  101437. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  101438. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  101439. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  101440. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  101441. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  101442. extern int ogg_sync_init(ogg_sync_state *oy);
  101443. extern int ogg_sync_clear(ogg_sync_state *oy);
  101444. extern int ogg_sync_reset(ogg_sync_state *oy);
  101445. extern int ogg_sync_destroy(ogg_sync_state *oy);
  101446. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  101447. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  101448. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  101449. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  101450. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  101451. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  101452. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  101453. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  101454. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  101455. extern int ogg_stream_clear(ogg_stream_state *os);
  101456. extern int ogg_stream_reset(ogg_stream_state *os);
  101457. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  101458. extern int ogg_stream_destroy(ogg_stream_state *os);
  101459. extern int ogg_stream_eos(ogg_stream_state *os);
  101460. extern void ogg_page_checksum_set(ogg_page *og);
  101461. extern int ogg_page_version(ogg_page *og);
  101462. extern int ogg_page_continued(ogg_page *og);
  101463. extern int ogg_page_bos(ogg_page *og);
  101464. extern int ogg_page_eos(ogg_page *og);
  101465. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  101466. extern int ogg_page_serialno(ogg_page *og);
  101467. extern long ogg_page_pageno(ogg_page *og);
  101468. extern int ogg_page_packets(ogg_page *og);
  101469. extern void ogg_packet_clear(ogg_packet *op);
  101470. #ifdef __cplusplus
  101471. }
  101472. #endif
  101473. #endif /* _OGG_H */
  101474. /********* End of inlined file: ogg.h *********/
  101475. typedef struct vorbis_info{
  101476. int version;
  101477. int channels;
  101478. long rate;
  101479. /* The below bitrate declarations are *hints*.
  101480. Combinations of the three values carry the following implications:
  101481. all three set to the same value:
  101482. implies a fixed rate bitstream
  101483. only nominal set:
  101484. implies a VBR stream that averages the nominal bitrate. No hard
  101485. upper/lower limit
  101486. upper and or lower set:
  101487. implies a VBR bitstream that obeys the bitrate limits. nominal
  101488. may also be set to give a nominal rate.
  101489. none set:
  101490. the coder does not care to speculate.
  101491. */
  101492. long bitrate_upper;
  101493. long bitrate_nominal;
  101494. long bitrate_lower;
  101495. long bitrate_window;
  101496. void *codec_setup;
  101497. } vorbis_info;
  101498. /* vorbis_dsp_state buffers the current vorbis audio
  101499. analysis/synthesis state. The DSP state belongs to a specific
  101500. logical bitstream ****************************************************/
  101501. typedef struct vorbis_dsp_state{
  101502. int analysisp;
  101503. vorbis_info *vi;
  101504. float **pcm;
  101505. float **pcmret;
  101506. int pcm_storage;
  101507. int pcm_current;
  101508. int pcm_returned;
  101509. int preextrapolate;
  101510. int eofflag;
  101511. long lW;
  101512. long W;
  101513. long nW;
  101514. long centerW;
  101515. ogg_int64_t granulepos;
  101516. ogg_int64_t sequence;
  101517. ogg_int64_t glue_bits;
  101518. ogg_int64_t time_bits;
  101519. ogg_int64_t floor_bits;
  101520. ogg_int64_t res_bits;
  101521. void *backend_state;
  101522. } vorbis_dsp_state;
  101523. typedef struct vorbis_block{
  101524. /* necessary stream state for linking to the framing abstraction */
  101525. float **pcm; /* this is a pointer into local storage */
  101526. oggpack_buffer opb;
  101527. long lW;
  101528. long W;
  101529. long nW;
  101530. int pcmend;
  101531. int mode;
  101532. int eofflag;
  101533. ogg_int64_t granulepos;
  101534. ogg_int64_t sequence;
  101535. vorbis_dsp_state *vd; /* For read-only access of configuration */
  101536. /* local storage to avoid remallocing; it's up to the mapping to
  101537. structure it */
  101538. void *localstore;
  101539. long localtop;
  101540. long localalloc;
  101541. long totaluse;
  101542. struct alloc_chain *reap;
  101543. /* bitmetrics for the frame */
  101544. long glue_bits;
  101545. long time_bits;
  101546. long floor_bits;
  101547. long res_bits;
  101548. void *internal;
  101549. } vorbis_block;
  101550. /* vorbis_block is a single block of data to be processed as part of
  101551. the analysis/synthesis stream; it belongs to a specific logical
  101552. bitstream, but is independant from other vorbis_blocks belonging to
  101553. that logical bitstream. *************************************************/
  101554. struct alloc_chain{
  101555. void *ptr;
  101556. struct alloc_chain *next;
  101557. };
  101558. /* vorbis_info contains all the setup information specific to the
  101559. specific compression/decompression mode in progress (eg,
  101560. psychoacoustic settings, channel setup, options, codebook
  101561. etc). vorbis_info and substructures are in backends.h.
  101562. *********************************************************************/
  101563. /* the comments are not part of vorbis_info so that vorbis_info can be
  101564. static storage */
  101565. typedef struct vorbis_comment{
  101566. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  101567. whatever vendor is set to in encode */
  101568. char **user_comments;
  101569. int *comment_lengths;
  101570. int comments;
  101571. char *vendor;
  101572. } vorbis_comment;
  101573. /* libvorbis encodes in two abstraction layers; first we perform DSP
  101574. and produce a packet (see docs/analysis.txt). The packet is then
  101575. coded into a framed OggSquish bitstream by the second layer (see
  101576. docs/framing.txt). Decode is the reverse process; we sync/frame
  101577. the bitstream and extract individual packets, then decode the
  101578. packet back into PCM audio.
  101579. The extra framing/packetizing is used in streaming formats, such as
  101580. files. Over the net (such as with UDP), the framing and
  101581. packetization aren't necessary as they're provided by the transport
  101582. and the streaming layer is not used */
  101583. /* Vorbis PRIMITIVES: general ***************************************/
  101584. extern void vorbis_info_init(vorbis_info *vi);
  101585. extern void vorbis_info_clear(vorbis_info *vi);
  101586. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  101587. extern void vorbis_comment_init(vorbis_comment *vc);
  101588. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  101589. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  101590. char *tag, char *contents);
  101591. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  101592. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  101593. extern void vorbis_comment_clear(vorbis_comment *vc);
  101594. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  101595. extern int vorbis_block_clear(vorbis_block *vb);
  101596. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  101597. extern double vorbis_granule_time(vorbis_dsp_state *v,
  101598. ogg_int64_t granulepos);
  101599. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  101600. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  101601. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  101602. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  101603. vorbis_comment *vc,
  101604. ogg_packet *op,
  101605. ogg_packet *op_comm,
  101606. ogg_packet *op_code);
  101607. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  101608. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  101609. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  101610. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  101611. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  101612. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  101613. ogg_packet *op);
  101614. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  101615. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  101616. ogg_packet *op);
  101617. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  101618. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  101619. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  101620. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  101621. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  101622. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  101623. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  101624. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  101625. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  101626. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  101627. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  101628. /* Vorbis ERRORS and return codes ***********************************/
  101629. #define OV_FALSE -1
  101630. #define OV_EOF -2
  101631. #define OV_HOLE -3
  101632. #define OV_EREAD -128
  101633. #define OV_EFAULT -129
  101634. #define OV_EIMPL -130
  101635. #define OV_EINVAL -131
  101636. #define OV_ENOTVORBIS -132
  101637. #define OV_EBADHEADER -133
  101638. #define OV_EVERSION -134
  101639. #define OV_ENOTAUDIO -135
  101640. #define OV_EBADPACKET -136
  101641. #define OV_EBADLINK -137
  101642. #define OV_ENOSEEK -138
  101643. #ifdef __cplusplus
  101644. }
  101645. #endif /* __cplusplus */
  101646. #endif
  101647. /********* End of inlined file: codec.h *********/
  101648. extern int vorbis_encode_init(vorbis_info *vi,
  101649. long channels,
  101650. long rate,
  101651. long max_bitrate,
  101652. long nominal_bitrate,
  101653. long min_bitrate);
  101654. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  101655. long channels,
  101656. long rate,
  101657. long max_bitrate,
  101658. long nominal_bitrate,
  101659. long min_bitrate);
  101660. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  101661. long channels,
  101662. long rate,
  101663. float quality /* quality level from 0. (lo) to 1. (hi) */
  101664. );
  101665. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  101666. long channels,
  101667. long rate,
  101668. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  101669. );
  101670. extern int vorbis_encode_setup_init(vorbis_info *vi);
  101671. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  101672. /* deprecated rate management supported only for compatability */
  101673. #define OV_ECTL_RATEMANAGE_GET 0x10
  101674. #define OV_ECTL_RATEMANAGE_SET 0x11
  101675. #define OV_ECTL_RATEMANAGE_AVG 0x12
  101676. #define OV_ECTL_RATEMANAGE_HARD 0x13
  101677. struct ovectl_ratemanage_arg {
  101678. int management_active;
  101679. long bitrate_hard_min;
  101680. long bitrate_hard_max;
  101681. double bitrate_hard_window;
  101682. long bitrate_av_lo;
  101683. long bitrate_av_hi;
  101684. double bitrate_av_window;
  101685. double bitrate_av_window_center;
  101686. };
  101687. /* new rate setup */
  101688. #define OV_ECTL_RATEMANAGE2_GET 0x14
  101689. #define OV_ECTL_RATEMANAGE2_SET 0x15
  101690. struct ovectl_ratemanage2_arg {
  101691. int management_active;
  101692. long bitrate_limit_min_kbps;
  101693. long bitrate_limit_max_kbps;
  101694. long bitrate_limit_reservoir_bits;
  101695. double bitrate_limit_reservoir_bias;
  101696. long bitrate_average_kbps;
  101697. double bitrate_average_damping;
  101698. };
  101699. #define OV_ECTL_LOWPASS_GET 0x20
  101700. #define OV_ECTL_LOWPASS_SET 0x21
  101701. #define OV_ECTL_IBLOCK_GET 0x30
  101702. #define OV_ECTL_IBLOCK_SET 0x31
  101703. #ifdef __cplusplus
  101704. }
  101705. #endif /* __cplusplus */
  101706. #endif
  101707. /********* End of inlined file: vorbisenc.h *********/
  101708. /********* Start of inlined file: vorbisfile.h *********/
  101709. #ifndef _OV_FILE_H_
  101710. #define _OV_FILE_H_
  101711. #ifdef __cplusplus
  101712. extern "C"
  101713. {
  101714. #endif /* __cplusplus */
  101715. #include <stdio.h>
  101716. /* The function prototypes for the callbacks are basically the same as for
  101717. * the stdio functions fread, fseek, fclose, ftell.
  101718. * The one difference is that the FILE * arguments have been replaced with
  101719. * a void * - this is to be used as a pointer to whatever internal data these
  101720. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  101721. *
  101722. * If you use other functions, check the docs for these functions and return
  101723. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  101724. * unseekable
  101725. */
  101726. typedef struct {
  101727. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  101728. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  101729. int (*close_func) (void *datasource);
  101730. long (*tell_func) (void *datasource);
  101731. } ov_callbacks;
  101732. #define NOTOPEN 0
  101733. #define PARTOPEN 1
  101734. #define OPENED 2
  101735. #define STREAMSET 3
  101736. #define INITSET 4
  101737. typedef struct OggVorbis_File {
  101738. void *datasource; /* Pointer to a FILE *, etc. */
  101739. int seekable;
  101740. ogg_int64_t offset;
  101741. ogg_int64_t end;
  101742. ogg_sync_state oy;
  101743. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  101744. stream appears */
  101745. int links;
  101746. ogg_int64_t *offsets;
  101747. ogg_int64_t *dataoffsets;
  101748. long *serialnos;
  101749. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  101750. compatability; x2 size, stores both
  101751. beginning and end values */
  101752. vorbis_info *vi;
  101753. vorbis_comment *vc;
  101754. /* Decoding working state local storage */
  101755. ogg_int64_t pcm_offset;
  101756. int ready_state;
  101757. long current_serialno;
  101758. int current_link;
  101759. double bittrack;
  101760. double samptrack;
  101761. ogg_stream_state os; /* take physical pages, weld into a logical
  101762. stream of packets */
  101763. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  101764. vorbis_block vb; /* local working space for packet->PCM decode */
  101765. ov_callbacks callbacks;
  101766. } OggVorbis_File;
  101767. extern int ov_clear(OggVorbis_File *vf);
  101768. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  101769. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  101770. char *initial, long ibytes, ov_callbacks callbacks);
  101771. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  101772. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  101773. char *initial, long ibytes, ov_callbacks callbacks);
  101774. extern int ov_test_open(OggVorbis_File *vf);
  101775. extern long ov_bitrate(OggVorbis_File *vf,int i);
  101776. extern long ov_bitrate_instant(OggVorbis_File *vf);
  101777. extern long ov_streams(OggVorbis_File *vf);
  101778. extern long ov_seekable(OggVorbis_File *vf);
  101779. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  101780. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  101781. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  101782. extern double ov_time_total(OggVorbis_File *vf,int i);
  101783. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  101784. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  101785. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  101786. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  101787. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  101788. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  101789. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  101790. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  101791. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  101792. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  101793. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  101794. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  101795. extern double ov_time_tell(OggVorbis_File *vf);
  101796. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  101797. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  101798. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  101799. int *bitstream);
  101800. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  101801. int bigendianp,int word,int sgned,int *bitstream);
  101802. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  101803. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  101804. extern int ov_halfrate_p(OggVorbis_File *vf);
  101805. #ifdef __cplusplus
  101806. }
  101807. #endif /* __cplusplus */
  101808. #endif
  101809. /********* End of inlined file: vorbisfile.h *********/
  101810. /********* Start of inlined file: bitwise.c *********/
  101811. /* We're 'LSb' endian; if we write a word but read individual bits,
  101812. then we'll read the lsb first */
  101813. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  101814. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  101815. // tasks..
  101816. #ifdef _MSC_VER
  101817. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  101818. #endif
  101819. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  101820. #if JUCE_USE_OGGVORBIS
  101821. #include <string.h>
  101822. #include <stdlib.h>
  101823. #define BUFFER_INCREMENT 256
  101824. static const unsigned long mask[]=
  101825. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  101826. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  101827. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  101828. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  101829. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  101830. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  101831. 0x3fffffff,0x7fffffff,0xffffffff };
  101832. static const unsigned int mask8B[]=
  101833. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  101834. void oggpack_writeinit(oggpack_buffer *b){
  101835. memset(b,0,sizeof(*b));
  101836. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  101837. b->buffer[0]='\0';
  101838. b->storage=BUFFER_INCREMENT;
  101839. }
  101840. void oggpackB_writeinit(oggpack_buffer *b){
  101841. oggpack_writeinit(b);
  101842. }
  101843. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  101844. long bytes=bits>>3;
  101845. bits-=bytes*8;
  101846. b->ptr=b->buffer+bytes;
  101847. b->endbit=bits;
  101848. b->endbyte=bytes;
  101849. *b->ptr&=mask[bits];
  101850. }
  101851. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  101852. long bytes=bits>>3;
  101853. bits-=bytes*8;
  101854. b->ptr=b->buffer+bytes;
  101855. b->endbit=bits;
  101856. b->endbyte=bytes;
  101857. *b->ptr&=mask8B[bits];
  101858. }
  101859. /* Takes only up to 32 bits. */
  101860. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  101861. if(b->endbyte+4>=b->storage){
  101862. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  101863. b->storage+=BUFFER_INCREMENT;
  101864. b->ptr=b->buffer+b->endbyte;
  101865. }
  101866. value&=mask[bits];
  101867. bits+=b->endbit;
  101868. b->ptr[0]|=value<<b->endbit;
  101869. if(bits>=8){
  101870. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  101871. if(bits>=16){
  101872. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  101873. if(bits>=24){
  101874. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  101875. if(bits>=32){
  101876. if(b->endbit)
  101877. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  101878. else
  101879. b->ptr[4]=0;
  101880. }
  101881. }
  101882. }
  101883. }
  101884. b->endbyte+=bits/8;
  101885. b->ptr+=bits/8;
  101886. b->endbit=bits&7;
  101887. }
  101888. /* Takes only up to 32 bits. */
  101889. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  101890. if(b->endbyte+4>=b->storage){
  101891. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  101892. b->storage+=BUFFER_INCREMENT;
  101893. b->ptr=b->buffer+b->endbyte;
  101894. }
  101895. value=(value&mask[bits])<<(32-bits);
  101896. bits+=b->endbit;
  101897. b->ptr[0]|=value>>(24+b->endbit);
  101898. if(bits>=8){
  101899. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  101900. if(bits>=16){
  101901. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  101902. if(bits>=24){
  101903. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  101904. if(bits>=32){
  101905. if(b->endbit)
  101906. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  101907. else
  101908. b->ptr[4]=0;
  101909. }
  101910. }
  101911. }
  101912. }
  101913. b->endbyte+=bits/8;
  101914. b->ptr+=bits/8;
  101915. b->endbit=bits&7;
  101916. }
  101917. void oggpack_writealign(oggpack_buffer *b){
  101918. int bits=8-b->endbit;
  101919. if(bits<8)
  101920. oggpack_write(b,0,bits);
  101921. }
  101922. void oggpackB_writealign(oggpack_buffer *b){
  101923. int bits=8-b->endbit;
  101924. if(bits<8)
  101925. oggpackB_write(b,0,bits);
  101926. }
  101927. static void oggpack_writecopy_helper(oggpack_buffer *b,
  101928. void *source,
  101929. long bits,
  101930. void (*w)(oggpack_buffer *,
  101931. unsigned long,
  101932. int),
  101933. int msb){
  101934. unsigned char *ptr=(unsigned char *)source;
  101935. long bytes=bits/8;
  101936. bits-=bytes*8;
  101937. if(b->endbit){
  101938. int i;
  101939. /* unaligned copy. Do it the hard way. */
  101940. for(i=0;i<bytes;i++)
  101941. w(b,(unsigned long)(ptr[i]),8);
  101942. }else{
  101943. /* aligned block copy */
  101944. if(b->endbyte+bytes+1>=b->storage){
  101945. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  101946. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  101947. b->ptr=b->buffer+b->endbyte;
  101948. }
  101949. memmove(b->ptr,source,bytes);
  101950. b->ptr+=bytes;
  101951. b->endbyte+=bytes;
  101952. *b->ptr=0;
  101953. }
  101954. if(bits){
  101955. if(msb)
  101956. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  101957. else
  101958. w(b,(unsigned long)(ptr[bytes]),bits);
  101959. }
  101960. }
  101961. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  101962. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  101963. }
  101964. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  101965. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  101966. }
  101967. void oggpack_reset(oggpack_buffer *b){
  101968. b->ptr=b->buffer;
  101969. b->buffer[0]=0;
  101970. b->endbit=b->endbyte=0;
  101971. }
  101972. void oggpackB_reset(oggpack_buffer *b){
  101973. oggpack_reset(b);
  101974. }
  101975. void oggpack_writeclear(oggpack_buffer *b){
  101976. _ogg_free(b->buffer);
  101977. memset(b,0,sizeof(*b));
  101978. }
  101979. void oggpackB_writeclear(oggpack_buffer *b){
  101980. oggpack_writeclear(b);
  101981. }
  101982. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  101983. memset(b,0,sizeof(*b));
  101984. b->buffer=b->ptr=buf;
  101985. b->storage=bytes;
  101986. }
  101987. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  101988. oggpack_readinit(b,buf,bytes);
  101989. }
  101990. /* Read in bits without advancing the bitptr; bits <= 32 */
  101991. long oggpack_look(oggpack_buffer *b,int bits){
  101992. unsigned long ret;
  101993. unsigned long m=mask[bits];
  101994. bits+=b->endbit;
  101995. if(b->endbyte+4>=b->storage){
  101996. /* not the main path */
  101997. if(b->endbyte*8+bits>b->storage*8)return(-1);
  101998. }
  101999. ret=b->ptr[0]>>b->endbit;
  102000. if(bits>8){
  102001. ret|=b->ptr[1]<<(8-b->endbit);
  102002. if(bits>16){
  102003. ret|=b->ptr[2]<<(16-b->endbit);
  102004. if(bits>24){
  102005. ret|=b->ptr[3]<<(24-b->endbit);
  102006. if(bits>32 && b->endbit)
  102007. ret|=b->ptr[4]<<(32-b->endbit);
  102008. }
  102009. }
  102010. }
  102011. return(m&ret);
  102012. }
  102013. /* Read in bits without advancing the bitptr; bits <= 32 */
  102014. long oggpackB_look(oggpack_buffer *b,int bits){
  102015. unsigned long ret;
  102016. int m=32-bits;
  102017. bits+=b->endbit;
  102018. if(b->endbyte+4>=b->storage){
  102019. /* not the main path */
  102020. if(b->endbyte*8+bits>b->storage*8)return(-1);
  102021. }
  102022. ret=b->ptr[0]<<(24+b->endbit);
  102023. if(bits>8){
  102024. ret|=b->ptr[1]<<(16+b->endbit);
  102025. if(bits>16){
  102026. ret|=b->ptr[2]<<(8+b->endbit);
  102027. if(bits>24){
  102028. ret|=b->ptr[3]<<(b->endbit);
  102029. if(bits>32 && b->endbit)
  102030. ret|=b->ptr[4]>>(8-b->endbit);
  102031. }
  102032. }
  102033. }
  102034. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  102035. }
  102036. long oggpack_look1(oggpack_buffer *b){
  102037. if(b->endbyte>=b->storage)return(-1);
  102038. return((b->ptr[0]>>b->endbit)&1);
  102039. }
  102040. long oggpackB_look1(oggpack_buffer *b){
  102041. if(b->endbyte>=b->storage)return(-1);
  102042. return((b->ptr[0]>>(7-b->endbit))&1);
  102043. }
  102044. void oggpack_adv(oggpack_buffer *b,int bits){
  102045. bits+=b->endbit;
  102046. b->ptr+=bits/8;
  102047. b->endbyte+=bits/8;
  102048. b->endbit=bits&7;
  102049. }
  102050. void oggpackB_adv(oggpack_buffer *b,int bits){
  102051. oggpack_adv(b,bits);
  102052. }
  102053. void oggpack_adv1(oggpack_buffer *b){
  102054. if(++(b->endbit)>7){
  102055. b->endbit=0;
  102056. b->ptr++;
  102057. b->endbyte++;
  102058. }
  102059. }
  102060. void oggpackB_adv1(oggpack_buffer *b){
  102061. oggpack_adv1(b);
  102062. }
  102063. /* bits <= 32 */
  102064. long oggpack_read(oggpack_buffer *b,int bits){
  102065. long ret;
  102066. unsigned long m=mask[bits];
  102067. bits+=b->endbit;
  102068. if(b->endbyte+4>=b->storage){
  102069. /* not the main path */
  102070. ret=-1L;
  102071. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  102072. }
  102073. ret=b->ptr[0]>>b->endbit;
  102074. if(bits>8){
  102075. ret|=b->ptr[1]<<(8-b->endbit);
  102076. if(bits>16){
  102077. ret|=b->ptr[2]<<(16-b->endbit);
  102078. if(bits>24){
  102079. ret|=b->ptr[3]<<(24-b->endbit);
  102080. if(bits>32 && b->endbit){
  102081. ret|=b->ptr[4]<<(32-b->endbit);
  102082. }
  102083. }
  102084. }
  102085. }
  102086. ret&=m;
  102087. overflow:
  102088. b->ptr+=bits/8;
  102089. b->endbyte+=bits/8;
  102090. b->endbit=bits&7;
  102091. return(ret);
  102092. }
  102093. /* bits <= 32 */
  102094. long oggpackB_read(oggpack_buffer *b,int bits){
  102095. long ret;
  102096. long m=32-bits;
  102097. bits+=b->endbit;
  102098. if(b->endbyte+4>=b->storage){
  102099. /* not the main path */
  102100. ret=-1L;
  102101. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  102102. }
  102103. ret=b->ptr[0]<<(24+b->endbit);
  102104. if(bits>8){
  102105. ret|=b->ptr[1]<<(16+b->endbit);
  102106. if(bits>16){
  102107. ret|=b->ptr[2]<<(8+b->endbit);
  102108. if(bits>24){
  102109. ret|=b->ptr[3]<<(b->endbit);
  102110. if(bits>32 && b->endbit)
  102111. ret|=b->ptr[4]>>(8-b->endbit);
  102112. }
  102113. }
  102114. }
  102115. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  102116. overflow:
  102117. b->ptr+=bits/8;
  102118. b->endbyte+=bits/8;
  102119. b->endbit=bits&7;
  102120. return(ret);
  102121. }
  102122. long oggpack_read1(oggpack_buffer *b){
  102123. long ret;
  102124. if(b->endbyte>=b->storage){
  102125. /* not the main path */
  102126. ret=-1L;
  102127. goto overflow;
  102128. }
  102129. ret=(b->ptr[0]>>b->endbit)&1;
  102130. overflow:
  102131. b->endbit++;
  102132. if(b->endbit>7){
  102133. b->endbit=0;
  102134. b->ptr++;
  102135. b->endbyte++;
  102136. }
  102137. return(ret);
  102138. }
  102139. long oggpackB_read1(oggpack_buffer *b){
  102140. long ret;
  102141. if(b->endbyte>=b->storage){
  102142. /* not the main path */
  102143. ret=-1L;
  102144. goto overflow;
  102145. }
  102146. ret=(b->ptr[0]>>(7-b->endbit))&1;
  102147. overflow:
  102148. b->endbit++;
  102149. if(b->endbit>7){
  102150. b->endbit=0;
  102151. b->ptr++;
  102152. b->endbyte++;
  102153. }
  102154. return(ret);
  102155. }
  102156. long oggpack_bytes(oggpack_buffer *b){
  102157. return(b->endbyte+(b->endbit+7)/8);
  102158. }
  102159. long oggpack_bits(oggpack_buffer *b){
  102160. return(b->endbyte*8+b->endbit);
  102161. }
  102162. long oggpackB_bytes(oggpack_buffer *b){
  102163. return oggpack_bytes(b);
  102164. }
  102165. long oggpackB_bits(oggpack_buffer *b){
  102166. return oggpack_bits(b);
  102167. }
  102168. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  102169. return(b->buffer);
  102170. }
  102171. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  102172. return oggpack_get_buffer(b);
  102173. }
  102174. /* Self test of the bitwise routines; everything else is based on
  102175. them, so they damned well better be solid. */
  102176. #ifdef _V_SELFTEST
  102177. #include <stdio.h>
  102178. static int ilog(unsigned int v){
  102179. int ret=0;
  102180. while(v){
  102181. ret++;
  102182. v>>=1;
  102183. }
  102184. return(ret);
  102185. }
  102186. oggpack_buffer o;
  102187. oggpack_buffer r;
  102188. void report(char *in){
  102189. fprintf(stderr,"%s",in);
  102190. exit(1);
  102191. }
  102192. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  102193. long bytes,i;
  102194. unsigned char *buffer;
  102195. oggpack_reset(&o);
  102196. for(i=0;i<vals;i++)
  102197. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  102198. buffer=oggpack_get_buffer(&o);
  102199. bytes=oggpack_bytes(&o);
  102200. if(bytes!=compsize)report("wrong number of bytes!\n");
  102201. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  102202. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  102203. report("wrote incorrect value!\n");
  102204. }
  102205. oggpack_readinit(&r,buffer,bytes);
  102206. for(i=0;i<vals;i++){
  102207. int tbit=bits?bits:ilog(b[i]);
  102208. if(oggpack_look(&r,tbit)==-1)
  102209. report("out of data!\n");
  102210. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  102211. report("looked at incorrect value!\n");
  102212. if(tbit==1)
  102213. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  102214. report("looked at single bit incorrect value!\n");
  102215. if(tbit==1){
  102216. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  102217. report("read incorrect single bit value!\n");
  102218. }else{
  102219. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  102220. report("read incorrect value!\n");
  102221. }
  102222. }
  102223. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  102224. }
  102225. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  102226. long bytes,i;
  102227. unsigned char *buffer;
  102228. oggpackB_reset(&o);
  102229. for(i=0;i<vals;i++)
  102230. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  102231. buffer=oggpackB_get_buffer(&o);
  102232. bytes=oggpackB_bytes(&o);
  102233. if(bytes!=compsize)report("wrong number of bytes!\n");
  102234. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  102235. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  102236. report("wrote incorrect value!\n");
  102237. }
  102238. oggpackB_readinit(&r,buffer,bytes);
  102239. for(i=0;i<vals;i++){
  102240. int tbit=bits?bits:ilog(b[i]);
  102241. if(oggpackB_look(&r,tbit)==-1)
  102242. report("out of data!\n");
  102243. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  102244. report("looked at incorrect value!\n");
  102245. if(tbit==1)
  102246. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  102247. report("looked at single bit incorrect value!\n");
  102248. if(tbit==1){
  102249. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  102250. report("read incorrect single bit value!\n");
  102251. }else{
  102252. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  102253. report("read incorrect value!\n");
  102254. }
  102255. }
  102256. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  102257. }
  102258. int main(void){
  102259. unsigned char *buffer;
  102260. long bytes,i;
  102261. static unsigned long testbuffer1[]=
  102262. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  102263. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  102264. int test1size=43;
  102265. static unsigned long testbuffer2[]=
  102266. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  102267. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  102268. 85525151,0,12321,1,349528352};
  102269. int test2size=21;
  102270. static unsigned long testbuffer3[]=
  102271. {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,
  102272. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  102273. int test3size=56;
  102274. static unsigned long large[]=
  102275. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  102276. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  102277. 85525151,0,12321,1,2146528352};
  102278. int onesize=33;
  102279. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  102280. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  102281. 223,4};
  102282. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  102283. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  102284. 245,251,128};
  102285. int twosize=6;
  102286. static int two[6]={61,255,255,251,231,29};
  102287. static int twoB[6]={247,63,255,253,249,120};
  102288. int threesize=54;
  102289. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  102290. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  102291. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  102292. 100,52,4,14,18,86,77,1};
  102293. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  102294. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  102295. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  102296. 200,20,254,4,58,106,176,144,0};
  102297. int foursize=38;
  102298. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  102299. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  102300. 28,2,133,0,1};
  102301. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  102302. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  102303. 129,10,4,32};
  102304. int fivesize=45;
  102305. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  102306. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  102307. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  102308. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  102309. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  102310. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  102311. int sixsize=7;
  102312. static int six[7]={17,177,170,242,169,19,148};
  102313. static int sixB[7]={136,141,85,79,149,200,41};
  102314. /* Test read/write together */
  102315. /* Later we test against pregenerated bitstreams */
  102316. oggpack_writeinit(&o);
  102317. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  102318. cliptest(testbuffer1,test1size,0,one,onesize);
  102319. fprintf(stderr,"ok.");
  102320. fprintf(stderr,"\nNull bit call (LSb): ");
  102321. cliptest(testbuffer3,test3size,0,two,twosize);
  102322. fprintf(stderr,"ok.");
  102323. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  102324. cliptest(testbuffer2,test2size,0,three,threesize);
  102325. fprintf(stderr,"ok.");
  102326. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  102327. oggpack_reset(&o);
  102328. for(i=0;i<test2size;i++)
  102329. oggpack_write(&o,large[i],32);
  102330. buffer=oggpack_get_buffer(&o);
  102331. bytes=oggpack_bytes(&o);
  102332. oggpack_readinit(&r,buffer,bytes);
  102333. for(i=0;i<test2size;i++){
  102334. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  102335. if(oggpack_look(&r,32)!=large[i]){
  102336. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  102337. oggpack_look(&r,32),large[i]);
  102338. report("read incorrect value!\n");
  102339. }
  102340. oggpack_adv(&r,32);
  102341. }
  102342. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  102343. fprintf(stderr,"ok.");
  102344. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  102345. cliptest(testbuffer1,test1size,7,four,foursize);
  102346. fprintf(stderr,"ok.");
  102347. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  102348. cliptest(testbuffer2,test2size,17,five,fivesize);
  102349. fprintf(stderr,"ok.");
  102350. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  102351. cliptest(testbuffer3,test3size,1,six,sixsize);
  102352. fprintf(stderr,"ok.");
  102353. fprintf(stderr,"\nTesting read past end (LSb): ");
  102354. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  102355. for(i=0;i<64;i++){
  102356. if(oggpack_read(&r,1)!=0){
  102357. fprintf(stderr,"failed; got -1 prematurely.\n");
  102358. exit(1);
  102359. }
  102360. }
  102361. if(oggpack_look(&r,1)!=-1 ||
  102362. oggpack_read(&r,1)!=-1){
  102363. fprintf(stderr,"failed; read past end without -1.\n");
  102364. exit(1);
  102365. }
  102366. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  102367. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  102368. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  102369. exit(1);
  102370. }
  102371. if(oggpack_look(&r,18)!=0 ||
  102372. oggpack_look(&r,18)!=0){
  102373. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  102374. exit(1);
  102375. }
  102376. if(oggpack_look(&r,19)!=-1 ||
  102377. oggpack_look(&r,19)!=-1){
  102378. fprintf(stderr,"failed; read past end without -1.\n");
  102379. exit(1);
  102380. }
  102381. if(oggpack_look(&r,32)!=-1 ||
  102382. oggpack_look(&r,32)!=-1){
  102383. fprintf(stderr,"failed; read past end without -1.\n");
  102384. exit(1);
  102385. }
  102386. oggpack_writeclear(&o);
  102387. fprintf(stderr,"ok.\n");
  102388. /********** lazy, cut-n-paste retest with MSb packing ***********/
  102389. /* Test read/write together */
  102390. /* Later we test against pregenerated bitstreams */
  102391. oggpackB_writeinit(&o);
  102392. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  102393. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  102394. fprintf(stderr,"ok.");
  102395. fprintf(stderr,"\nNull bit call (MSb): ");
  102396. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  102397. fprintf(stderr,"ok.");
  102398. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  102399. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  102400. fprintf(stderr,"ok.");
  102401. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  102402. oggpackB_reset(&o);
  102403. for(i=0;i<test2size;i++)
  102404. oggpackB_write(&o,large[i],32);
  102405. buffer=oggpackB_get_buffer(&o);
  102406. bytes=oggpackB_bytes(&o);
  102407. oggpackB_readinit(&r,buffer,bytes);
  102408. for(i=0;i<test2size;i++){
  102409. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  102410. if(oggpackB_look(&r,32)!=large[i]){
  102411. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  102412. oggpackB_look(&r,32),large[i]);
  102413. report("read incorrect value!\n");
  102414. }
  102415. oggpackB_adv(&r,32);
  102416. }
  102417. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  102418. fprintf(stderr,"ok.");
  102419. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  102420. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  102421. fprintf(stderr,"ok.");
  102422. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  102423. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  102424. fprintf(stderr,"ok.");
  102425. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  102426. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  102427. fprintf(stderr,"ok.");
  102428. fprintf(stderr,"\nTesting read past end (MSb): ");
  102429. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  102430. for(i=0;i<64;i++){
  102431. if(oggpackB_read(&r,1)!=0){
  102432. fprintf(stderr,"failed; got -1 prematurely.\n");
  102433. exit(1);
  102434. }
  102435. }
  102436. if(oggpackB_look(&r,1)!=-1 ||
  102437. oggpackB_read(&r,1)!=-1){
  102438. fprintf(stderr,"failed; read past end without -1.\n");
  102439. exit(1);
  102440. }
  102441. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  102442. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  102443. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  102444. exit(1);
  102445. }
  102446. if(oggpackB_look(&r,18)!=0 ||
  102447. oggpackB_look(&r,18)!=0){
  102448. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  102449. exit(1);
  102450. }
  102451. if(oggpackB_look(&r,19)!=-1 ||
  102452. oggpackB_look(&r,19)!=-1){
  102453. fprintf(stderr,"failed; read past end without -1.\n");
  102454. exit(1);
  102455. }
  102456. if(oggpackB_look(&r,32)!=-1 ||
  102457. oggpackB_look(&r,32)!=-1){
  102458. fprintf(stderr,"failed; read past end without -1.\n");
  102459. exit(1);
  102460. }
  102461. oggpackB_writeclear(&o);
  102462. fprintf(stderr,"ok.\n\n");
  102463. return(0);
  102464. }
  102465. #endif /* _V_SELFTEST */
  102466. #undef BUFFER_INCREMENT
  102467. #endif
  102468. /********* End of inlined file: bitwise.c *********/
  102469. /********* Start of inlined file: framing.c *********/
  102470. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  102471. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  102472. // tasks..
  102473. #ifdef _MSC_VER
  102474. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  102475. #endif
  102476. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  102477. #if JUCE_USE_OGGVORBIS
  102478. #include <stdlib.h>
  102479. #include <string.h>
  102480. /* A complete description of Ogg framing exists in docs/framing.html */
  102481. int ogg_page_version(ogg_page *og){
  102482. return((int)(og->header[4]));
  102483. }
  102484. int ogg_page_continued(ogg_page *og){
  102485. return((int)(og->header[5]&0x01));
  102486. }
  102487. int ogg_page_bos(ogg_page *og){
  102488. return((int)(og->header[5]&0x02));
  102489. }
  102490. int ogg_page_eos(ogg_page *og){
  102491. return((int)(og->header[5]&0x04));
  102492. }
  102493. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  102494. unsigned char *page=og->header;
  102495. ogg_int64_t granulepos=page[13]&(0xff);
  102496. granulepos= (granulepos<<8)|(page[12]&0xff);
  102497. granulepos= (granulepos<<8)|(page[11]&0xff);
  102498. granulepos= (granulepos<<8)|(page[10]&0xff);
  102499. granulepos= (granulepos<<8)|(page[9]&0xff);
  102500. granulepos= (granulepos<<8)|(page[8]&0xff);
  102501. granulepos= (granulepos<<8)|(page[7]&0xff);
  102502. granulepos= (granulepos<<8)|(page[6]&0xff);
  102503. return(granulepos);
  102504. }
  102505. int ogg_page_serialno(ogg_page *og){
  102506. return(og->header[14] |
  102507. (og->header[15]<<8) |
  102508. (og->header[16]<<16) |
  102509. (og->header[17]<<24));
  102510. }
  102511. long ogg_page_pageno(ogg_page *og){
  102512. return(og->header[18] |
  102513. (og->header[19]<<8) |
  102514. (og->header[20]<<16) |
  102515. (og->header[21]<<24));
  102516. }
  102517. /* returns the number of packets that are completed on this page (if
  102518. the leading packet is begun on a previous page, but ends on this
  102519. page, it's counted */
  102520. /* NOTE:
  102521. If a page consists of a packet begun on a previous page, and a new
  102522. packet begun (but not completed) on this page, the return will be:
  102523. ogg_page_packets(page) ==1,
  102524. ogg_page_continued(page) !=0
  102525. If a page happens to be a single packet that was begun on a
  102526. previous page, and spans to the next page (in the case of a three or
  102527. more page packet), the return will be:
  102528. ogg_page_packets(page) ==0,
  102529. ogg_page_continued(page) !=0
  102530. */
  102531. int ogg_page_packets(ogg_page *og){
  102532. int i,n=og->header[26],count=0;
  102533. for(i=0;i<n;i++)
  102534. if(og->header[27+i]<255)count++;
  102535. return(count);
  102536. }
  102537. #if 0
  102538. /* helper to initialize lookup for direct-table CRC (illustrative; we
  102539. use the static init below) */
  102540. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  102541. int i;
  102542. unsigned long r;
  102543. r = index << 24;
  102544. for (i=0; i<8; i++)
  102545. if (r & 0x80000000UL)
  102546. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  102547. polynomial, although we use an
  102548. unreflected alg and an init/final
  102549. of 0, not 0xffffffff */
  102550. else
  102551. r<<=1;
  102552. return (r & 0xffffffffUL);
  102553. }
  102554. #endif
  102555. static const ogg_uint32_t crc_lookup[256]={
  102556. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  102557. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  102558. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  102559. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  102560. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  102561. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  102562. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  102563. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  102564. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  102565. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  102566. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  102567. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  102568. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  102569. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  102570. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  102571. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  102572. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  102573. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  102574. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  102575. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  102576. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  102577. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  102578. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  102579. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  102580. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  102581. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  102582. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  102583. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  102584. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  102585. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  102586. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  102587. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  102588. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  102589. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  102590. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  102591. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  102592. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  102593. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  102594. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  102595. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  102596. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  102597. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  102598. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  102599. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  102600. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  102601. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  102602. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  102603. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  102604. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  102605. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  102606. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  102607. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  102608. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  102609. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  102610. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  102611. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  102612. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  102613. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  102614. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  102615. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  102616. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  102617. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  102618. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  102619. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  102620. /* init the encode/decode logical stream state */
  102621. int ogg_stream_init(ogg_stream_state *os,int serialno){
  102622. if(os){
  102623. memset(os,0,sizeof(*os));
  102624. os->body_storage=16*1024;
  102625. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  102626. os->lacing_storage=1024;
  102627. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  102628. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  102629. os->serialno=serialno;
  102630. return(0);
  102631. }
  102632. return(-1);
  102633. }
  102634. /* _clear does not free os, only the non-flat storage within */
  102635. int ogg_stream_clear(ogg_stream_state *os){
  102636. if(os){
  102637. if(os->body_data)_ogg_free(os->body_data);
  102638. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  102639. if(os->granule_vals)_ogg_free(os->granule_vals);
  102640. memset(os,0,sizeof(*os));
  102641. }
  102642. return(0);
  102643. }
  102644. int ogg_stream_destroy(ogg_stream_state *os){
  102645. if(os){
  102646. ogg_stream_clear(os);
  102647. _ogg_free(os);
  102648. }
  102649. return(0);
  102650. }
  102651. /* Helpers for ogg_stream_encode; this keeps the structure and
  102652. what's happening fairly clear */
  102653. static void _os_body_expand(ogg_stream_state *os,int needed){
  102654. if(os->body_storage<=os->body_fill+needed){
  102655. os->body_storage+=(needed+1024);
  102656. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  102657. }
  102658. }
  102659. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  102660. if(os->lacing_storage<=os->lacing_fill+needed){
  102661. os->lacing_storage+=(needed+32);
  102662. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  102663. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  102664. }
  102665. }
  102666. /* checksum the page */
  102667. /* Direct table CRC; note that this will be faster in the future if we
  102668. perform the checksum silmultaneously with other copies */
  102669. void ogg_page_checksum_set(ogg_page *og){
  102670. if(og){
  102671. ogg_uint32_t crc_reg=0;
  102672. int i;
  102673. /* safety; needed for API behavior, but not framing code */
  102674. og->header[22]=0;
  102675. og->header[23]=0;
  102676. og->header[24]=0;
  102677. og->header[25]=0;
  102678. for(i=0;i<og->header_len;i++)
  102679. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  102680. for(i=0;i<og->body_len;i++)
  102681. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  102682. og->header[22]=(unsigned char)(crc_reg&0xff);
  102683. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  102684. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  102685. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  102686. }
  102687. }
  102688. /* submit data to the internal buffer of the framing engine */
  102689. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  102690. int lacing_vals=op->bytes/255+1,i;
  102691. if(os->body_returned){
  102692. /* advance packet data according to the body_returned pointer. We
  102693. had to keep it around to return a pointer into the buffer last
  102694. call */
  102695. os->body_fill-=os->body_returned;
  102696. if(os->body_fill)
  102697. memmove(os->body_data,os->body_data+os->body_returned,
  102698. os->body_fill);
  102699. os->body_returned=0;
  102700. }
  102701. /* make sure we have the buffer storage */
  102702. _os_body_expand(os,op->bytes);
  102703. _os_lacing_expand(os,lacing_vals);
  102704. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  102705. the liability of overly clean abstraction for the time being. It
  102706. will actually be fairly easy to eliminate the extra copy in the
  102707. future */
  102708. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  102709. os->body_fill+=op->bytes;
  102710. /* Store lacing vals for this packet */
  102711. for(i=0;i<lacing_vals-1;i++){
  102712. os->lacing_vals[os->lacing_fill+i]=255;
  102713. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  102714. }
  102715. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  102716. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  102717. /* flag the first segment as the beginning of the packet */
  102718. os->lacing_vals[os->lacing_fill]|= 0x100;
  102719. os->lacing_fill+=lacing_vals;
  102720. /* for the sake of completeness */
  102721. os->packetno++;
  102722. if(op->e_o_s)os->e_o_s=1;
  102723. return(0);
  102724. }
  102725. /* This will flush remaining packets into a page (returning nonzero),
  102726. even if there is not enough data to trigger a flush normally
  102727. (undersized page). If there are no packets or partial packets to
  102728. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  102729. try to flush a normal sized page like ogg_stream_pageout; a call to
  102730. ogg_stream_flush does not guarantee that all packets have flushed.
  102731. Only a return value of 0 from ogg_stream_flush indicates all packet
  102732. data is flushed into pages.
  102733. since ogg_stream_flush will flush the last page in a stream even if
  102734. it's undersized, you almost certainly want to use ogg_stream_pageout
  102735. (and *not* ogg_stream_flush) unless you specifically need to flush
  102736. an page regardless of size in the middle of a stream. */
  102737. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  102738. int i;
  102739. int vals=0;
  102740. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  102741. int bytes=0;
  102742. long acc=0;
  102743. ogg_int64_t granule_pos=-1;
  102744. if(maxvals==0)return(0);
  102745. /* construct a page */
  102746. /* decide how many segments to include */
  102747. /* If this is the initial header case, the first page must only include
  102748. the initial header packet */
  102749. if(os->b_o_s==0){ /* 'initial header page' case */
  102750. granule_pos=0;
  102751. for(vals=0;vals<maxvals;vals++){
  102752. if((os->lacing_vals[vals]&0x0ff)<255){
  102753. vals++;
  102754. break;
  102755. }
  102756. }
  102757. }else{
  102758. for(vals=0;vals<maxvals;vals++){
  102759. if(acc>4096)break;
  102760. acc+=os->lacing_vals[vals]&0x0ff;
  102761. if((os->lacing_vals[vals]&0xff)<255)
  102762. granule_pos=os->granule_vals[vals];
  102763. }
  102764. }
  102765. /* construct the header in temp storage */
  102766. memcpy(os->header,"OggS",4);
  102767. /* stream structure version */
  102768. os->header[4]=0x00;
  102769. /* continued packet flag? */
  102770. os->header[5]=0x00;
  102771. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  102772. /* first page flag? */
  102773. if(os->b_o_s==0)os->header[5]|=0x02;
  102774. /* last page flag? */
  102775. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  102776. os->b_o_s=1;
  102777. /* 64 bits of PCM position */
  102778. for(i=6;i<14;i++){
  102779. os->header[i]=(unsigned char)(granule_pos&0xff);
  102780. granule_pos>>=8;
  102781. }
  102782. /* 32 bits of stream serial number */
  102783. {
  102784. long serialno=os->serialno;
  102785. for(i=14;i<18;i++){
  102786. os->header[i]=(unsigned char)(serialno&0xff);
  102787. serialno>>=8;
  102788. }
  102789. }
  102790. /* 32 bits of page counter (we have both counter and page header
  102791. because this val can roll over) */
  102792. if(os->pageno==-1)os->pageno=0; /* because someone called
  102793. stream_reset; this would be a
  102794. strange thing to do in an
  102795. encode stream, but it has
  102796. plausible uses */
  102797. {
  102798. long pageno=os->pageno++;
  102799. for(i=18;i<22;i++){
  102800. os->header[i]=(unsigned char)(pageno&0xff);
  102801. pageno>>=8;
  102802. }
  102803. }
  102804. /* zero for computation; filled in later */
  102805. os->header[22]=0;
  102806. os->header[23]=0;
  102807. os->header[24]=0;
  102808. os->header[25]=0;
  102809. /* segment table */
  102810. os->header[26]=(unsigned char)(vals&0xff);
  102811. for(i=0;i<vals;i++)
  102812. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  102813. /* set pointers in the ogg_page struct */
  102814. og->header=os->header;
  102815. og->header_len=os->header_fill=vals+27;
  102816. og->body=os->body_data+os->body_returned;
  102817. og->body_len=bytes;
  102818. /* advance the lacing data and set the body_returned pointer */
  102819. os->lacing_fill-=vals;
  102820. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  102821. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  102822. os->body_returned+=bytes;
  102823. /* calculate the checksum */
  102824. ogg_page_checksum_set(og);
  102825. /* done */
  102826. return(1);
  102827. }
  102828. /* This constructs pages from buffered packet segments. The pointers
  102829. returned are to static buffers; do not free. The returned buffers are
  102830. good only until the next call (using the same ogg_stream_state) */
  102831. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  102832. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  102833. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  102834. os->lacing_fill>=255 || /* 'segment table full' case */
  102835. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  102836. return(ogg_stream_flush(os,og));
  102837. }
  102838. /* not enough data to construct a page and not end of stream */
  102839. return(0);
  102840. }
  102841. int ogg_stream_eos(ogg_stream_state *os){
  102842. return os->e_o_s;
  102843. }
  102844. /* DECODING PRIMITIVES: packet streaming layer **********************/
  102845. /* This has two layers to place more of the multi-serialno and paging
  102846. control in the application's hands. First, we expose a data buffer
  102847. using ogg_sync_buffer(). The app either copies into the
  102848. buffer, or passes it directly to read(), etc. We then call
  102849. ogg_sync_wrote() to tell how many bytes we just added.
  102850. Pages are returned (pointers into the buffer in ogg_sync_state)
  102851. by ogg_sync_pageout(). The page is then submitted to
  102852. ogg_stream_pagein() along with the appropriate
  102853. ogg_stream_state* (ie, matching serialno). We then get raw
  102854. packets out calling ogg_stream_packetout() with a
  102855. ogg_stream_state. */
  102856. /* initialize the struct to a known state */
  102857. int ogg_sync_init(ogg_sync_state *oy){
  102858. if(oy){
  102859. memset(oy,0,sizeof(*oy));
  102860. }
  102861. return(0);
  102862. }
  102863. /* clear non-flat storage within */
  102864. int ogg_sync_clear(ogg_sync_state *oy){
  102865. if(oy){
  102866. if(oy->data)_ogg_free(oy->data);
  102867. ogg_sync_init(oy);
  102868. }
  102869. return(0);
  102870. }
  102871. int ogg_sync_destroy(ogg_sync_state *oy){
  102872. if(oy){
  102873. ogg_sync_clear(oy);
  102874. _ogg_free(oy);
  102875. }
  102876. return(0);
  102877. }
  102878. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  102879. /* first, clear out any space that has been previously returned */
  102880. if(oy->returned){
  102881. oy->fill-=oy->returned;
  102882. if(oy->fill>0)
  102883. memmove(oy->data,oy->data+oy->returned,oy->fill);
  102884. oy->returned=0;
  102885. }
  102886. if(size>oy->storage-oy->fill){
  102887. /* We need to extend the internal buffer */
  102888. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  102889. if(oy->data)
  102890. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  102891. else
  102892. oy->data=(unsigned char*) _ogg_malloc(newsize);
  102893. oy->storage=newsize;
  102894. }
  102895. /* expose a segment at least as large as requested at the fill mark */
  102896. return((char *)oy->data+oy->fill);
  102897. }
  102898. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  102899. if(oy->fill+bytes>oy->storage)return(-1);
  102900. oy->fill+=bytes;
  102901. return(0);
  102902. }
  102903. /* sync the stream. This is meant to be useful for finding page
  102904. boundaries.
  102905. return values for this:
  102906. -n) skipped n bytes
  102907. 0) page not ready; more data (no bytes skipped)
  102908. n) page synced at current location; page length n bytes
  102909. */
  102910. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  102911. unsigned char *page=oy->data+oy->returned;
  102912. unsigned char *next;
  102913. long bytes=oy->fill-oy->returned;
  102914. if(oy->headerbytes==0){
  102915. int headerbytes,i;
  102916. if(bytes<27)return(0); /* not enough for a header */
  102917. /* verify capture pattern */
  102918. if(memcmp(page,"OggS",4))goto sync_fail;
  102919. headerbytes=page[26]+27;
  102920. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  102921. /* count up body length in the segment table */
  102922. for(i=0;i<page[26];i++)
  102923. oy->bodybytes+=page[27+i];
  102924. oy->headerbytes=headerbytes;
  102925. }
  102926. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  102927. /* The whole test page is buffered. Verify the checksum */
  102928. {
  102929. /* Grab the checksum bytes, set the header field to zero */
  102930. char chksum[4];
  102931. ogg_page log;
  102932. memcpy(chksum,page+22,4);
  102933. memset(page+22,0,4);
  102934. /* set up a temp page struct and recompute the checksum */
  102935. log.header=page;
  102936. log.header_len=oy->headerbytes;
  102937. log.body=page+oy->headerbytes;
  102938. log.body_len=oy->bodybytes;
  102939. ogg_page_checksum_set(&log);
  102940. /* Compare */
  102941. if(memcmp(chksum,page+22,4)){
  102942. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  102943. at all) */
  102944. /* replace the computed checksum with the one actually read in */
  102945. memcpy(page+22,chksum,4);
  102946. /* Bad checksum. Lose sync */
  102947. goto sync_fail;
  102948. }
  102949. }
  102950. /* yes, have a whole page all ready to go */
  102951. {
  102952. unsigned char *page=oy->data+oy->returned;
  102953. long bytes;
  102954. if(og){
  102955. og->header=page;
  102956. og->header_len=oy->headerbytes;
  102957. og->body=page+oy->headerbytes;
  102958. og->body_len=oy->bodybytes;
  102959. }
  102960. oy->unsynced=0;
  102961. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  102962. oy->headerbytes=0;
  102963. oy->bodybytes=0;
  102964. return(bytes);
  102965. }
  102966. sync_fail:
  102967. oy->headerbytes=0;
  102968. oy->bodybytes=0;
  102969. /* search for possible capture */
  102970. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  102971. if(!next)
  102972. next=oy->data+oy->fill;
  102973. oy->returned=next-oy->data;
  102974. return(-(next-page));
  102975. }
  102976. /* sync the stream and get a page. Keep trying until we find a page.
  102977. Supress 'sync errors' after reporting the first.
  102978. return values:
  102979. -1) recapture (hole in data)
  102980. 0) need more data
  102981. 1) page returned
  102982. Returns pointers into buffered data; invalidated by next call to
  102983. _stream, _clear, _init, or _buffer */
  102984. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  102985. /* all we need to do is verify a page at the head of the stream
  102986. buffer. If it doesn't verify, we look for the next potential
  102987. frame */
  102988. for(;;){
  102989. long ret=ogg_sync_pageseek(oy,og);
  102990. if(ret>0){
  102991. /* have a page */
  102992. return(1);
  102993. }
  102994. if(ret==0){
  102995. /* need more data */
  102996. return(0);
  102997. }
  102998. /* head did not start a synced page... skipped some bytes */
  102999. if(!oy->unsynced){
  103000. oy->unsynced=1;
  103001. return(-1);
  103002. }
  103003. /* loop. keep looking */
  103004. }
  103005. }
  103006. /* add the incoming page to the stream state; we decompose the page
  103007. into packet segments here as well. */
  103008. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  103009. unsigned char *header=og->header;
  103010. unsigned char *body=og->body;
  103011. long bodysize=og->body_len;
  103012. int segptr=0;
  103013. int version=ogg_page_version(og);
  103014. int continued=ogg_page_continued(og);
  103015. int bos=ogg_page_bos(og);
  103016. int eos=ogg_page_eos(og);
  103017. ogg_int64_t granulepos=ogg_page_granulepos(og);
  103018. int serialno=ogg_page_serialno(og);
  103019. long pageno=ogg_page_pageno(og);
  103020. int segments=header[26];
  103021. /* clean up 'returned data' */
  103022. {
  103023. long lr=os->lacing_returned;
  103024. long br=os->body_returned;
  103025. /* body data */
  103026. if(br){
  103027. os->body_fill-=br;
  103028. if(os->body_fill)
  103029. memmove(os->body_data,os->body_data+br,os->body_fill);
  103030. os->body_returned=0;
  103031. }
  103032. if(lr){
  103033. /* segment table */
  103034. if(os->lacing_fill-lr){
  103035. memmove(os->lacing_vals,os->lacing_vals+lr,
  103036. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  103037. memmove(os->granule_vals,os->granule_vals+lr,
  103038. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  103039. }
  103040. os->lacing_fill-=lr;
  103041. os->lacing_packet-=lr;
  103042. os->lacing_returned=0;
  103043. }
  103044. }
  103045. /* check the serial number */
  103046. if(serialno!=os->serialno)return(-1);
  103047. if(version>0)return(-1);
  103048. _os_lacing_expand(os,segments+1);
  103049. /* are we in sequence? */
  103050. if(pageno!=os->pageno){
  103051. int i;
  103052. /* unroll previous partial packet (if any) */
  103053. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  103054. os->body_fill-=os->lacing_vals[i]&0xff;
  103055. os->lacing_fill=os->lacing_packet;
  103056. /* make a note of dropped data in segment table */
  103057. if(os->pageno!=-1){
  103058. os->lacing_vals[os->lacing_fill++]=0x400;
  103059. os->lacing_packet++;
  103060. }
  103061. }
  103062. /* are we a 'continued packet' page? If so, we may need to skip
  103063. some segments */
  103064. if(continued){
  103065. if(os->lacing_fill<1 ||
  103066. os->lacing_vals[os->lacing_fill-1]==0x400){
  103067. bos=0;
  103068. for(;segptr<segments;segptr++){
  103069. int val=header[27+segptr];
  103070. body+=val;
  103071. bodysize-=val;
  103072. if(val<255){
  103073. segptr++;
  103074. break;
  103075. }
  103076. }
  103077. }
  103078. }
  103079. if(bodysize){
  103080. _os_body_expand(os,bodysize);
  103081. memcpy(os->body_data+os->body_fill,body,bodysize);
  103082. os->body_fill+=bodysize;
  103083. }
  103084. {
  103085. int saved=-1;
  103086. while(segptr<segments){
  103087. int val=header[27+segptr];
  103088. os->lacing_vals[os->lacing_fill]=val;
  103089. os->granule_vals[os->lacing_fill]=-1;
  103090. if(bos){
  103091. os->lacing_vals[os->lacing_fill]|=0x100;
  103092. bos=0;
  103093. }
  103094. if(val<255)saved=os->lacing_fill;
  103095. os->lacing_fill++;
  103096. segptr++;
  103097. if(val<255)os->lacing_packet=os->lacing_fill;
  103098. }
  103099. /* set the granulepos on the last granuleval of the last full packet */
  103100. if(saved!=-1){
  103101. os->granule_vals[saved]=granulepos;
  103102. }
  103103. }
  103104. if(eos){
  103105. os->e_o_s=1;
  103106. if(os->lacing_fill>0)
  103107. os->lacing_vals[os->lacing_fill-1]|=0x200;
  103108. }
  103109. os->pageno=pageno+1;
  103110. return(0);
  103111. }
  103112. /* clear things to an initial state. Good to call, eg, before seeking */
  103113. int ogg_sync_reset(ogg_sync_state *oy){
  103114. oy->fill=0;
  103115. oy->returned=0;
  103116. oy->unsynced=0;
  103117. oy->headerbytes=0;
  103118. oy->bodybytes=0;
  103119. return(0);
  103120. }
  103121. int ogg_stream_reset(ogg_stream_state *os){
  103122. os->body_fill=0;
  103123. os->body_returned=0;
  103124. os->lacing_fill=0;
  103125. os->lacing_packet=0;
  103126. os->lacing_returned=0;
  103127. os->header_fill=0;
  103128. os->e_o_s=0;
  103129. os->b_o_s=0;
  103130. os->pageno=-1;
  103131. os->packetno=0;
  103132. os->granulepos=0;
  103133. return(0);
  103134. }
  103135. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  103136. ogg_stream_reset(os);
  103137. os->serialno=serialno;
  103138. return(0);
  103139. }
  103140. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  103141. /* The last part of decode. We have the stream broken into packet
  103142. segments. Now we need to group them into packets (or return the
  103143. out of sync markers) */
  103144. int ptr=os->lacing_returned;
  103145. if(os->lacing_packet<=ptr)return(0);
  103146. if(os->lacing_vals[ptr]&0x400){
  103147. /* we need to tell the codec there's a gap; it might need to
  103148. handle previous packet dependencies. */
  103149. os->lacing_returned++;
  103150. os->packetno++;
  103151. return(-1);
  103152. }
  103153. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  103154. to ask if there's a whole packet
  103155. waiting */
  103156. /* Gather the whole packet. We'll have no holes or a partial packet */
  103157. {
  103158. int size=os->lacing_vals[ptr]&0xff;
  103159. int bytes=size;
  103160. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  103161. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  103162. while(size==255){
  103163. int val=os->lacing_vals[++ptr];
  103164. size=val&0xff;
  103165. if(val&0x200)eos=0x200;
  103166. bytes+=size;
  103167. }
  103168. if(op){
  103169. op->e_o_s=eos;
  103170. op->b_o_s=bos;
  103171. op->packet=os->body_data+os->body_returned;
  103172. op->packetno=os->packetno;
  103173. op->granulepos=os->granule_vals[ptr];
  103174. op->bytes=bytes;
  103175. }
  103176. if(adv){
  103177. os->body_returned+=bytes;
  103178. os->lacing_returned=ptr+1;
  103179. os->packetno++;
  103180. }
  103181. }
  103182. return(1);
  103183. }
  103184. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  103185. return _packetout(os,op,1);
  103186. }
  103187. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  103188. return _packetout(os,op,0);
  103189. }
  103190. void ogg_packet_clear(ogg_packet *op) {
  103191. _ogg_free(op->packet);
  103192. memset(op, 0, sizeof(*op));
  103193. }
  103194. #ifdef _V_SELFTEST
  103195. #include <stdio.h>
  103196. ogg_stream_state os_en, os_de;
  103197. ogg_sync_state oy;
  103198. void checkpacket(ogg_packet *op,int len, int no, int pos){
  103199. long j;
  103200. static int sequence=0;
  103201. static int lastno=0;
  103202. if(op->bytes!=len){
  103203. fprintf(stderr,"incorrect packet length!\n");
  103204. exit(1);
  103205. }
  103206. if(op->granulepos!=pos){
  103207. fprintf(stderr,"incorrect packet position!\n");
  103208. exit(1);
  103209. }
  103210. /* packet number just follows sequence/gap; adjust the input number
  103211. for that */
  103212. if(no==0){
  103213. sequence=0;
  103214. }else{
  103215. sequence++;
  103216. if(no>lastno+1)
  103217. sequence++;
  103218. }
  103219. lastno=no;
  103220. if(op->packetno!=sequence){
  103221. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  103222. (long)(op->packetno),sequence);
  103223. exit(1);
  103224. }
  103225. /* Test data */
  103226. for(j=0;j<op->bytes;j++)
  103227. if(op->packet[j]!=((j+no)&0xff)){
  103228. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  103229. j,op->packet[j],(j+no)&0xff);
  103230. exit(1);
  103231. }
  103232. }
  103233. void check_page(unsigned char *data,const int *header,ogg_page *og){
  103234. long j;
  103235. /* Test data */
  103236. for(j=0;j<og->body_len;j++)
  103237. if(og->body[j]!=data[j]){
  103238. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  103239. j,data[j],og->body[j]);
  103240. exit(1);
  103241. }
  103242. /* Test header */
  103243. for(j=0;j<og->header_len;j++){
  103244. if(og->header[j]!=header[j]){
  103245. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  103246. for(j=0;j<header[26]+27;j++)
  103247. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  103248. fprintf(stderr,"\n");
  103249. exit(1);
  103250. }
  103251. }
  103252. if(og->header_len!=header[26]+27){
  103253. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  103254. og->header_len,header[26]+27);
  103255. exit(1);
  103256. }
  103257. }
  103258. void print_header(ogg_page *og){
  103259. int j;
  103260. fprintf(stderr,"\nHEADER:\n");
  103261. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  103262. og->header[0],og->header[1],og->header[2],og->header[3],
  103263. (int)og->header[4],(int)og->header[5]);
  103264. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  103265. (og->header[9]<<24)|(og->header[8]<<16)|
  103266. (og->header[7]<<8)|og->header[6],
  103267. (og->header[17]<<24)|(og->header[16]<<16)|
  103268. (og->header[15]<<8)|og->header[14],
  103269. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  103270. (og->header[19]<<8)|og->header[18]);
  103271. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  103272. (int)og->header[22],(int)og->header[23],
  103273. (int)og->header[24],(int)og->header[25],
  103274. (int)og->header[26]);
  103275. for(j=27;j<og->header_len;j++)
  103276. fprintf(stderr,"%d ",(int)og->header[j]);
  103277. fprintf(stderr,")\n\n");
  103278. }
  103279. void copy_page(ogg_page *og){
  103280. unsigned char *temp=_ogg_malloc(og->header_len);
  103281. memcpy(temp,og->header,og->header_len);
  103282. og->header=temp;
  103283. temp=_ogg_malloc(og->body_len);
  103284. memcpy(temp,og->body,og->body_len);
  103285. og->body=temp;
  103286. }
  103287. void free_page(ogg_page *og){
  103288. _ogg_free (og->header);
  103289. _ogg_free (og->body);
  103290. }
  103291. void error(void){
  103292. fprintf(stderr,"error!\n");
  103293. exit(1);
  103294. }
  103295. /* 17 only */
  103296. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  103297. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103298. 0x01,0x02,0x03,0x04,0,0,0,0,
  103299. 0x15,0xed,0xec,0x91,
  103300. 1,
  103301. 17};
  103302. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  103303. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103304. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103305. 0x01,0x02,0x03,0x04,0,0,0,0,
  103306. 0x59,0x10,0x6c,0x2c,
  103307. 1,
  103308. 17};
  103309. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  103310. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  103311. 0x01,0x02,0x03,0x04,1,0,0,0,
  103312. 0x89,0x33,0x85,0xce,
  103313. 13,
  103314. 254,255,0,255,1,255,245,255,255,0,
  103315. 255,255,90};
  103316. /* nil packets; beginning,middle,end */
  103317. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103318. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103319. 0x01,0x02,0x03,0x04,0,0,0,0,
  103320. 0xff,0x7b,0x23,0x17,
  103321. 1,
  103322. 0};
  103323. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  103324. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  103325. 0x01,0x02,0x03,0x04,1,0,0,0,
  103326. 0x5c,0x3f,0x66,0xcb,
  103327. 17,
  103328. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  103329. 255,255,90,0};
  103330. /* large initial packet */
  103331. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103332. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103333. 0x01,0x02,0x03,0x04,0,0,0,0,
  103334. 0x01,0x27,0x31,0xaa,
  103335. 18,
  103336. 255,255,255,255,255,255,255,255,
  103337. 255,255,255,255,255,255,255,255,255,10};
  103338. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  103339. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  103340. 0x01,0x02,0x03,0x04,1,0,0,0,
  103341. 0x7f,0x4e,0x8a,0xd2,
  103342. 4,
  103343. 255,4,255,0};
  103344. /* continuing packet test */
  103345. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103346. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103347. 0x01,0x02,0x03,0x04,0,0,0,0,
  103348. 0xff,0x7b,0x23,0x17,
  103349. 1,
  103350. 0};
  103351. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  103352. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  103353. 0x01,0x02,0x03,0x04,1,0,0,0,
  103354. 0x54,0x05,0x51,0xc8,
  103355. 17,
  103356. 255,255,255,255,255,255,255,255,
  103357. 255,255,255,255,255,255,255,255,255};
  103358. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  103359. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  103360. 0x01,0x02,0x03,0x04,2,0,0,0,
  103361. 0xc8,0xc3,0xcb,0xed,
  103362. 5,
  103363. 10,255,4,255,0};
  103364. /* page with the 255 segment limit */
  103365. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103366. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103367. 0x01,0x02,0x03,0x04,0,0,0,0,
  103368. 0xff,0x7b,0x23,0x17,
  103369. 1,
  103370. 0};
  103371. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  103372. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  103373. 0x01,0x02,0x03,0x04,1,0,0,0,
  103374. 0xed,0x2a,0x2e,0xa7,
  103375. 255,
  103376. 10,10,10,10,10,10,10,10,
  103377. 10,10,10,10,10,10,10,10,
  103378. 10,10,10,10,10,10,10,10,
  103379. 10,10,10,10,10,10,10,10,
  103380. 10,10,10,10,10,10,10,10,
  103381. 10,10,10,10,10,10,10,10,
  103382. 10,10,10,10,10,10,10,10,
  103383. 10,10,10,10,10,10,10,10,
  103384. 10,10,10,10,10,10,10,10,
  103385. 10,10,10,10,10,10,10,10,
  103386. 10,10,10,10,10,10,10,10,
  103387. 10,10,10,10,10,10,10,10,
  103388. 10,10,10,10,10,10,10,10,
  103389. 10,10,10,10,10,10,10,10,
  103390. 10,10,10,10,10,10,10,10,
  103391. 10,10,10,10,10,10,10,10,
  103392. 10,10,10,10,10,10,10,10,
  103393. 10,10,10,10,10,10,10,10,
  103394. 10,10,10,10,10,10,10,10,
  103395. 10,10,10,10,10,10,10,10,
  103396. 10,10,10,10,10,10,10,10,
  103397. 10,10,10,10,10,10,10,10,
  103398. 10,10,10,10,10,10,10,10,
  103399. 10,10,10,10,10,10,10,10,
  103400. 10,10,10,10,10,10,10,10,
  103401. 10,10,10,10,10,10,10,10,
  103402. 10,10,10,10,10,10,10,10,
  103403. 10,10,10,10,10,10,10,10,
  103404. 10,10,10,10,10,10,10,10,
  103405. 10,10,10,10,10,10,10,10,
  103406. 10,10,10,10,10,10,10,10,
  103407. 10,10,10,10,10,10,10};
  103408. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  103409. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  103410. 0x01,0x02,0x03,0x04,2,0,0,0,
  103411. 0x6c,0x3b,0x82,0x3d,
  103412. 1,
  103413. 50};
  103414. /* packet that overspans over an entire page */
  103415. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103416. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103417. 0x01,0x02,0x03,0x04,0,0,0,0,
  103418. 0xff,0x7b,0x23,0x17,
  103419. 1,
  103420. 0};
  103421. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  103422. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  103423. 0x01,0x02,0x03,0x04,1,0,0,0,
  103424. 0x3c,0xd9,0x4d,0x3f,
  103425. 17,
  103426. 100,255,255,255,255,255,255,255,255,
  103427. 255,255,255,255,255,255,255,255};
  103428. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  103429. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  103430. 0x01,0x02,0x03,0x04,2,0,0,0,
  103431. 0x01,0xd2,0xe5,0xe5,
  103432. 17,
  103433. 255,255,255,255,255,255,255,255,
  103434. 255,255,255,255,255,255,255,255,255};
  103435. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  103436. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  103437. 0x01,0x02,0x03,0x04,3,0,0,0,
  103438. 0xef,0xdd,0x88,0xde,
  103439. 7,
  103440. 255,255,75,255,4,255,0};
  103441. /* packet that overspans over an entire page */
  103442. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103443. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103444. 0x01,0x02,0x03,0x04,0,0,0,0,
  103445. 0xff,0x7b,0x23,0x17,
  103446. 1,
  103447. 0};
  103448. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  103449. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  103450. 0x01,0x02,0x03,0x04,1,0,0,0,
  103451. 0x3c,0xd9,0x4d,0x3f,
  103452. 17,
  103453. 100,255,255,255,255,255,255,255,255,
  103454. 255,255,255,255,255,255,255,255};
  103455. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  103456. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  103457. 0x01,0x02,0x03,0x04,2,0,0,0,
  103458. 0xd4,0xe0,0x60,0xe5,
  103459. 1,0};
  103460. void test_pack(const int *pl, const int **headers, int byteskip,
  103461. int pageskip, int packetskip){
  103462. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  103463. long inptr=0;
  103464. long outptr=0;
  103465. long deptr=0;
  103466. long depacket=0;
  103467. long granule_pos=7,pageno=0;
  103468. int i,j,packets,pageout=pageskip;
  103469. int eosflag=0;
  103470. int bosflag=0;
  103471. int byteskipcount=0;
  103472. ogg_stream_reset(&os_en);
  103473. ogg_stream_reset(&os_de);
  103474. ogg_sync_reset(&oy);
  103475. for(packets=0;packets<packetskip;packets++)
  103476. depacket+=pl[packets];
  103477. for(packets=0;;packets++)if(pl[packets]==-1)break;
  103478. for(i=0;i<packets;i++){
  103479. /* construct a test packet */
  103480. ogg_packet op;
  103481. int len=pl[i];
  103482. op.packet=data+inptr;
  103483. op.bytes=len;
  103484. op.e_o_s=(pl[i+1]<0?1:0);
  103485. op.granulepos=granule_pos;
  103486. granule_pos+=1024;
  103487. for(j=0;j<len;j++)data[inptr++]=i+j;
  103488. /* submit the test packet */
  103489. ogg_stream_packetin(&os_en,&op);
  103490. /* retrieve any finished pages */
  103491. {
  103492. ogg_page og;
  103493. while(ogg_stream_pageout(&os_en,&og)){
  103494. /* We have a page. Check it carefully */
  103495. fprintf(stderr,"%ld, ",pageno);
  103496. if(headers[pageno]==NULL){
  103497. fprintf(stderr,"coded too many pages!\n");
  103498. exit(1);
  103499. }
  103500. check_page(data+outptr,headers[pageno],&og);
  103501. outptr+=og.body_len;
  103502. pageno++;
  103503. if(pageskip){
  103504. bosflag=1;
  103505. pageskip--;
  103506. deptr+=og.body_len;
  103507. }
  103508. /* have a complete page; submit it to sync/decode */
  103509. {
  103510. ogg_page og_de;
  103511. ogg_packet op_de,op_de2;
  103512. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  103513. char *next=buf;
  103514. byteskipcount+=og.header_len;
  103515. if(byteskipcount>byteskip){
  103516. memcpy(next,og.header,byteskipcount-byteskip);
  103517. next+=byteskipcount-byteskip;
  103518. byteskipcount=byteskip;
  103519. }
  103520. byteskipcount+=og.body_len;
  103521. if(byteskipcount>byteskip){
  103522. memcpy(next,og.body,byteskipcount-byteskip);
  103523. next+=byteskipcount-byteskip;
  103524. byteskipcount=byteskip;
  103525. }
  103526. ogg_sync_wrote(&oy,next-buf);
  103527. while(1){
  103528. int ret=ogg_sync_pageout(&oy,&og_de);
  103529. if(ret==0)break;
  103530. if(ret<0)continue;
  103531. /* got a page. Happy happy. Verify that it's good. */
  103532. fprintf(stderr,"(%ld), ",pageout);
  103533. check_page(data+deptr,headers[pageout],&og_de);
  103534. deptr+=og_de.body_len;
  103535. pageout++;
  103536. /* submit it to deconstitution */
  103537. ogg_stream_pagein(&os_de,&og_de);
  103538. /* packets out? */
  103539. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  103540. ogg_stream_packetpeek(&os_de,NULL);
  103541. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  103542. /* verify peek and out match */
  103543. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  103544. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  103545. depacket);
  103546. exit(1);
  103547. }
  103548. /* verify the packet! */
  103549. /* check data */
  103550. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  103551. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  103552. depacket);
  103553. exit(1);
  103554. }
  103555. /* check bos flag */
  103556. if(bosflag==0 && op_de.b_o_s==0){
  103557. fprintf(stderr,"b_o_s flag not set on packet!\n");
  103558. exit(1);
  103559. }
  103560. if(bosflag && op_de.b_o_s){
  103561. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  103562. exit(1);
  103563. }
  103564. bosflag=1;
  103565. depacket+=op_de.bytes;
  103566. /* check eos flag */
  103567. if(eosflag){
  103568. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  103569. exit(1);
  103570. }
  103571. if(op_de.e_o_s)eosflag=1;
  103572. /* check granulepos flag */
  103573. if(op_de.granulepos!=-1){
  103574. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  103575. }
  103576. }
  103577. }
  103578. }
  103579. }
  103580. }
  103581. }
  103582. _ogg_free(data);
  103583. if(headers[pageno]!=NULL){
  103584. fprintf(stderr,"did not write last page!\n");
  103585. exit(1);
  103586. }
  103587. if(headers[pageout]!=NULL){
  103588. fprintf(stderr,"did not decode last page!\n");
  103589. exit(1);
  103590. }
  103591. if(inptr!=outptr){
  103592. fprintf(stderr,"encoded page data incomplete!\n");
  103593. exit(1);
  103594. }
  103595. if(inptr!=deptr){
  103596. fprintf(stderr,"decoded page data incomplete!\n");
  103597. exit(1);
  103598. }
  103599. if(inptr!=depacket){
  103600. fprintf(stderr,"decoded packet data incomplete!\n");
  103601. exit(1);
  103602. }
  103603. if(!eosflag){
  103604. fprintf(stderr,"Never got a packet with EOS set!\n");
  103605. exit(1);
  103606. }
  103607. fprintf(stderr,"ok.\n");
  103608. }
  103609. int main(void){
  103610. ogg_stream_init(&os_en,0x04030201);
  103611. ogg_stream_init(&os_de,0x04030201);
  103612. ogg_sync_init(&oy);
  103613. /* Exercise each code path in the framing code. Also verify that
  103614. the checksums are working. */
  103615. {
  103616. /* 17 only */
  103617. const int packets[]={17, -1};
  103618. const int *headret[]={head1_0,NULL};
  103619. fprintf(stderr,"testing single page encoding... ");
  103620. test_pack(packets,headret,0,0,0);
  103621. }
  103622. {
  103623. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  103624. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  103625. const int *headret[]={head1_1,head2_1,NULL};
  103626. fprintf(stderr,"testing basic page encoding... ");
  103627. test_pack(packets,headret,0,0,0);
  103628. }
  103629. {
  103630. /* nil packets; beginning,middle,end */
  103631. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  103632. const int *headret[]={head1_2,head2_2,NULL};
  103633. fprintf(stderr,"testing basic nil packets... ");
  103634. test_pack(packets,headret,0,0,0);
  103635. }
  103636. {
  103637. /* large initial packet */
  103638. const int packets[]={4345,259,255,-1};
  103639. const int *headret[]={head1_3,head2_3,NULL};
  103640. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  103641. test_pack(packets,headret,0,0,0);
  103642. }
  103643. {
  103644. /* continuing packet test */
  103645. const int packets[]={0,4345,259,255,-1};
  103646. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  103647. fprintf(stderr,"testing single packet page span... ");
  103648. test_pack(packets,headret,0,0,0);
  103649. }
  103650. /* page with the 255 segment limit */
  103651. {
  103652. const int packets[]={0,10,10,10,10,10,10,10,10,
  103653. 10,10,10,10,10,10,10,10,
  103654. 10,10,10,10,10,10,10,10,
  103655. 10,10,10,10,10,10,10,10,
  103656. 10,10,10,10,10,10,10,10,
  103657. 10,10,10,10,10,10,10,10,
  103658. 10,10,10,10,10,10,10,10,
  103659. 10,10,10,10,10,10,10,10,
  103660. 10,10,10,10,10,10,10,10,
  103661. 10,10,10,10,10,10,10,10,
  103662. 10,10,10,10,10,10,10,10,
  103663. 10,10,10,10,10,10,10,10,
  103664. 10,10,10,10,10,10,10,10,
  103665. 10,10,10,10,10,10,10,10,
  103666. 10,10,10,10,10,10,10,10,
  103667. 10,10,10,10,10,10,10,10,
  103668. 10,10,10,10,10,10,10,10,
  103669. 10,10,10,10,10,10,10,10,
  103670. 10,10,10,10,10,10,10,10,
  103671. 10,10,10,10,10,10,10,10,
  103672. 10,10,10,10,10,10,10,10,
  103673. 10,10,10,10,10,10,10,10,
  103674. 10,10,10,10,10,10,10,10,
  103675. 10,10,10,10,10,10,10,10,
  103676. 10,10,10,10,10,10,10,10,
  103677. 10,10,10,10,10,10,10,10,
  103678. 10,10,10,10,10,10,10,10,
  103679. 10,10,10,10,10,10,10,10,
  103680. 10,10,10,10,10,10,10,10,
  103681. 10,10,10,10,10,10,10,10,
  103682. 10,10,10,10,10,10,10,10,
  103683. 10,10,10,10,10,10,10,50,-1};
  103684. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  103685. fprintf(stderr,"testing max packet segments... ");
  103686. test_pack(packets,headret,0,0,0);
  103687. }
  103688. {
  103689. /* packet that overspans over an entire page */
  103690. const int packets[]={0,100,9000,259,255,-1};
  103691. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  103692. fprintf(stderr,"testing very large packets... ");
  103693. test_pack(packets,headret,0,0,0);
  103694. }
  103695. {
  103696. /* test for the libogg 1.1.1 resync in large continuation bug
  103697. found by Josh Coalson) */
  103698. const int packets[]={0,100,9000,259,255,-1};
  103699. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  103700. fprintf(stderr,"testing continuation resync in very large packets... ");
  103701. test_pack(packets,headret,100,2,3);
  103702. }
  103703. {
  103704. /* term only page. why not? */
  103705. const int packets[]={0,100,4080,-1};
  103706. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  103707. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  103708. test_pack(packets,headret,0,0,0);
  103709. }
  103710. {
  103711. /* build a bunch of pages for testing */
  103712. unsigned char *data=_ogg_malloc(1024*1024);
  103713. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  103714. int inptr=0,i,j;
  103715. ogg_page og[5];
  103716. ogg_stream_reset(&os_en);
  103717. for(i=0;pl[i]!=-1;i++){
  103718. ogg_packet op;
  103719. int len=pl[i];
  103720. op.packet=data+inptr;
  103721. op.bytes=len;
  103722. op.e_o_s=(pl[i+1]<0?1:0);
  103723. op.granulepos=(i+1)*1000;
  103724. for(j=0;j<len;j++)data[inptr++]=i+j;
  103725. ogg_stream_packetin(&os_en,&op);
  103726. }
  103727. _ogg_free(data);
  103728. /* retrieve finished pages */
  103729. for(i=0;i<5;i++){
  103730. if(ogg_stream_pageout(&os_en,&og[i])==0){
  103731. fprintf(stderr,"Too few pages output building sync tests!\n");
  103732. exit(1);
  103733. }
  103734. copy_page(&og[i]);
  103735. }
  103736. /* Test lost pages on pagein/packetout: no rollback */
  103737. {
  103738. ogg_page temp;
  103739. ogg_packet test;
  103740. fprintf(stderr,"Testing loss of pages... ");
  103741. ogg_sync_reset(&oy);
  103742. ogg_stream_reset(&os_de);
  103743. for(i=0;i<5;i++){
  103744. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  103745. og[i].header_len);
  103746. ogg_sync_wrote(&oy,og[i].header_len);
  103747. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  103748. ogg_sync_wrote(&oy,og[i].body_len);
  103749. }
  103750. ogg_sync_pageout(&oy,&temp);
  103751. ogg_stream_pagein(&os_de,&temp);
  103752. ogg_sync_pageout(&oy,&temp);
  103753. ogg_stream_pagein(&os_de,&temp);
  103754. ogg_sync_pageout(&oy,&temp);
  103755. /* skip */
  103756. ogg_sync_pageout(&oy,&temp);
  103757. ogg_stream_pagein(&os_de,&temp);
  103758. /* do we get the expected results/packets? */
  103759. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103760. checkpacket(&test,0,0,0);
  103761. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103762. checkpacket(&test,100,1,-1);
  103763. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103764. checkpacket(&test,4079,2,3000);
  103765. if(ogg_stream_packetout(&os_de,&test)!=-1){
  103766. fprintf(stderr,"Error: loss of page did not return error\n");
  103767. exit(1);
  103768. }
  103769. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103770. checkpacket(&test,76,5,-1);
  103771. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103772. checkpacket(&test,34,6,-1);
  103773. fprintf(stderr,"ok.\n");
  103774. }
  103775. /* Test lost pages on pagein/packetout: rollback with continuation */
  103776. {
  103777. ogg_page temp;
  103778. ogg_packet test;
  103779. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  103780. ogg_sync_reset(&oy);
  103781. ogg_stream_reset(&os_de);
  103782. for(i=0;i<5;i++){
  103783. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  103784. og[i].header_len);
  103785. ogg_sync_wrote(&oy,og[i].header_len);
  103786. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  103787. ogg_sync_wrote(&oy,og[i].body_len);
  103788. }
  103789. ogg_sync_pageout(&oy,&temp);
  103790. ogg_stream_pagein(&os_de,&temp);
  103791. ogg_sync_pageout(&oy,&temp);
  103792. ogg_stream_pagein(&os_de,&temp);
  103793. ogg_sync_pageout(&oy,&temp);
  103794. ogg_stream_pagein(&os_de,&temp);
  103795. ogg_sync_pageout(&oy,&temp);
  103796. /* skip */
  103797. ogg_sync_pageout(&oy,&temp);
  103798. ogg_stream_pagein(&os_de,&temp);
  103799. /* do we get the expected results/packets? */
  103800. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103801. checkpacket(&test,0,0,0);
  103802. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103803. checkpacket(&test,100,1,-1);
  103804. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103805. checkpacket(&test,4079,2,3000);
  103806. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103807. checkpacket(&test,2956,3,4000);
  103808. if(ogg_stream_packetout(&os_de,&test)!=-1){
  103809. fprintf(stderr,"Error: loss of page did not return error\n");
  103810. exit(1);
  103811. }
  103812. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103813. checkpacket(&test,300,13,14000);
  103814. fprintf(stderr,"ok.\n");
  103815. }
  103816. /* the rest only test sync */
  103817. {
  103818. ogg_page og_de;
  103819. /* Test fractional page inputs: incomplete capture */
  103820. fprintf(stderr,"Testing sync on partial inputs... ");
  103821. ogg_sync_reset(&oy);
  103822. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103823. 3);
  103824. ogg_sync_wrote(&oy,3);
  103825. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103826. /* Test fractional page inputs: incomplete fixed header */
  103827. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  103828. 20);
  103829. ogg_sync_wrote(&oy,20);
  103830. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103831. /* Test fractional page inputs: incomplete header */
  103832. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  103833. 5);
  103834. ogg_sync_wrote(&oy,5);
  103835. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103836. /* Test fractional page inputs: incomplete body */
  103837. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  103838. og[1].header_len-28);
  103839. ogg_sync_wrote(&oy,og[1].header_len-28);
  103840. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103841. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  103842. ogg_sync_wrote(&oy,1000);
  103843. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103844. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  103845. og[1].body_len-1000);
  103846. ogg_sync_wrote(&oy,og[1].body_len-1000);
  103847. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103848. fprintf(stderr,"ok.\n");
  103849. }
  103850. /* Test fractional page inputs: page + incomplete capture */
  103851. {
  103852. ogg_page og_de;
  103853. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  103854. ogg_sync_reset(&oy);
  103855. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103856. og[1].header_len);
  103857. ogg_sync_wrote(&oy,og[1].header_len);
  103858. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103859. og[1].body_len);
  103860. ogg_sync_wrote(&oy,og[1].body_len);
  103861. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103862. 20);
  103863. ogg_sync_wrote(&oy,20);
  103864. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103865. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103866. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  103867. og[1].header_len-20);
  103868. ogg_sync_wrote(&oy,og[1].header_len-20);
  103869. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103870. og[1].body_len);
  103871. ogg_sync_wrote(&oy,og[1].body_len);
  103872. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103873. fprintf(stderr,"ok.\n");
  103874. }
  103875. /* Test recapture: garbage + page */
  103876. {
  103877. ogg_page og_de;
  103878. fprintf(stderr,"Testing search for capture... ");
  103879. ogg_sync_reset(&oy);
  103880. /* 'garbage' */
  103881. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103882. og[1].body_len);
  103883. ogg_sync_wrote(&oy,og[1].body_len);
  103884. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103885. og[1].header_len);
  103886. ogg_sync_wrote(&oy,og[1].header_len);
  103887. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103888. og[1].body_len);
  103889. ogg_sync_wrote(&oy,og[1].body_len);
  103890. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  103891. 20);
  103892. ogg_sync_wrote(&oy,20);
  103893. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103894. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103895. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103896. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  103897. og[2].header_len-20);
  103898. ogg_sync_wrote(&oy,og[2].header_len-20);
  103899. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  103900. og[2].body_len);
  103901. ogg_sync_wrote(&oy,og[2].body_len);
  103902. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103903. fprintf(stderr,"ok.\n");
  103904. }
  103905. /* Test recapture: page + garbage + page */
  103906. {
  103907. ogg_page og_de;
  103908. fprintf(stderr,"Testing recapture... ");
  103909. ogg_sync_reset(&oy);
  103910. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103911. og[1].header_len);
  103912. ogg_sync_wrote(&oy,og[1].header_len);
  103913. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103914. og[1].body_len);
  103915. ogg_sync_wrote(&oy,og[1].body_len);
  103916. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  103917. og[2].header_len);
  103918. ogg_sync_wrote(&oy,og[2].header_len);
  103919. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  103920. og[2].header_len);
  103921. ogg_sync_wrote(&oy,og[2].header_len);
  103922. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103923. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  103924. og[2].body_len-5);
  103925. ogg_sync_wrote(&oy,og[2].body_len-5);
  103926. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  103927. og[3].header_len);
  103928. ogg_sync_wrote(&oy,og[3].header_len);
  103929. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  103930. og[3].body_len);
  103931. ogg_sync_wrote(&oy,og[3].body_len);
  103932. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103933. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103934. fprintf(stderr,"ok.\n");
  103935. }
  103936. /* Free page data that was previously copied */
  103937. {
  103938. for(i=0;i<5;i++){
  103939. free_page(&og[i]);
  103940. }
  103941. }
  103942. }
  103943. return(0);
  103944. }
  103945. #endif
  103946. #endif
  103947. /********* End of inlined file: framing.c *********/
  103948. /********* Start of inlined file: analysis.c *********/
  103949. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  103950. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  103951. // tasks..
  103952. #ifdef _MSC_VER
  103953. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  103954. #endif
  103955. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  103956. #if JUCE_USE_OGGVORBIS
  103957. #include <stdio.h>
  103958. #include <string.h>
  103959. #include <math.h>
  103960. /********* Start of inlined file: codec_internal.h *********/
  103961. #ifndef _V_CODECI_H_
  103962. #define _V_CODECI_H_
  103963. /********* Start of inlined file: envelope.h *********/
  103964. #ifndef _V_ENVELOPE_
  103965. #define _V_ENVELOPE_
  103966. /********* Start of inlined file: mdct.h *********/
  103967. #ifndef _OGG_mdct_H_
  103968. #define _OGG_mdct_H_
  103969. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  103970. #ifdef MDCT_INTEGERIZED
  103971. #define DATA_TYPE int
  103972. #define REG_TYPE register int
  103973. #define TRIGBITS 14
  103974. #define cPI3_8 6270
  103975. #define cPI2_8 11585
  103976. #define cPI1_8 15137
  103977. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  103978. #define MULT_NORM(x) ((x)>>TRIGBITS)
  103979. #define HALVE(x) ((x)>>1)
  103980. #else
  103981. #define DATA_TYPE float
  103982. #define REG_TYPE float
  103983. #define cPI3_8 .38268343236508977175F
  103984. #define cPI2_8 .70710678118654752441F
  103985. #define cPI1_8 .92387953251128675613F
  103986. #define FLOAT_CONV(x) (x)
  103987. #define MULT_NORM(x) (x)
  103988. #define HALVE(x) ((x)*.5f)
  103989. #endif
  103990. typedef struct {
  103991. int n;
  103992. int log2n;
  103993. DATA_TYPE *trig;
  103994. int *bitrev;
  103995. DATA_TYPE scale;
  103996. } mdct_lookup;
  103997. extern void mdct_init(mdct_lookup *lookup,int n);
  103998. extern void mdct_clear(mdct_lookup *l);
  103999. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  104000. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  104001. #endif
  104002. /********* End of inlined file: mdct.h *********/
  104003. #define VE_PRE 16
  104004. #define VE_WIN 4
  104005. #define VE_POST 2
  104006. #define VE_AMP (VE_PRE+VE_POST-1)
  104007. #define VE_BANDS 7
  104008. #define VE_NEARDC 15
  104009. #define VE_MINSTRETCH 2 /* a bit less than short block */
  104010. #define VE_MAXSTRETCH 12 /* one-third full block */
  104011. typedef struct {
  104012. float ampbuf[VE_AMP];
  104013. int ampptr;
  104014. float nearDC[VE_NEARDC];
  104015. float nearDC_acc;
  104016. float nearDC_partialacc;
  104017. int nearptr;
  104018. } envelope_filter_state;
  104019. typedef struct {
  104020. int begin;
  104021. int end;
  104022. float *window;
  104023. float total;
  104024. } envelope_band;
  104025. typedef struct {
  104026. int ch;
  104027. int winlength;
  104028. int searchstep;
  104029. float minenergy;
  104030. mdct_lookup mdct;
  104031. float *mdct_win;
  104032. envelope_band band[VE_BANDS];
  104033. envelope_filter_state *filter;
  104034. int stretch;
  104035. int *mark;
  104036. long storage;
  104037. long current;
  104038. long curmark;
  104039. long cursor;
  104040. } envelope_lookup;
  104041. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  104042. extern void _ve_envelope_clear(envelope_lookup *e);
  104043. extern long _ve_envelope_search(vorbis_dsp_state *v);
  104044. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  104045. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  104046. #endif
  104047. /********* End of inlined file: envelope.h *********/
  104048. /********* Start of inlined file: codebook.h *********/
  104049. #ifndef _V_CODEBOOK_H_
  104050. #define _V_CODEBOOK_H_
  104051. /* This structure encapsulates huffman and VQ style encoding books; it
  104052. doesn't do anything specific to either.
  104053. valuelist/quantlist are nonNULL (and q_* significant) only if
  104054. there's entry->value mapping to be done.
  104055. If encode-side mapping must be done (and thus the entry needs to be
  104056. hunted), the auxiliary encode pointer will point to a decision
  104057. tree. This is true of both VQ and huffman, but is mostly useful
  104058. with VQ.
  104059. */
  104060. typedef struct static_codebook{
  104061. long dim; /* codebook dimensions (elements per vector) */
  104062. long entries; /* codebook entries */
  104063. long *lengthlist; /* codeword lengths in bits */
  104064. /* mapping ***************************************************************/
  104065. int maptype; /* 0=none
  104066. 1=implicitly populated values from map column
  104067. 2=listed arbitrary values */
  104068. /* The below does a linear, single monotonic sequence mapping. */
  104069. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  104070. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  104071. int q_quant; /* bits: 0 < quant <= 16 */
  104072. int q_sequencep; /* bitflag */
  104073. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  104074. map == 2: list of dim*entries quantized entry vals
  104075. */
  104076. /* encode helpers ********************************************************/
  104077. struct encode_aux_nearestmatch *nearest_tree;
  104078. struct encode_aux_threshmatch *thresh_tree;
  104079. struct encode_aux_pigeonhole *pigeon_tree;
  104080. int allocedp;
  104081. } static_codebook;
  104082. /* this structures an arbitrary trained book to quickly find the
  104083. nearest cell match */
  104084. typedef struct encode_aux_nearestmatch{
  104085. /* pre-calculated partitioning tree */
  104086. long *ptr0;
  104087. long *ptr1;
  104088. long *p; /* decision points (each is an entry) */
  104089. long *q; /* decision points (each is an entry) */
  104090. long aux; /* number of tree entries */
  104091. long alloc;
  104092. } encode_aux_nearestmatch;
  104093. /* assumes a maptype of 1; encode side only, so that's OK */
  104094. typedef struct encode_aux_threshmatch{
  104095. float *quantthresh;
  104096. long *quantmap;
  104097. int quantvals;
  104098. int threshvals;
  104099. } encode_aux_threshmatch;
  104100. typedef struct encode_aux_pigeonhole{
  104101. float min;
  104102. float del;
  104103. int mapentries;
  104104. int quantvals;
  104105. long *pigeonmap;
  104106. long fittotal;
  104107. long *fitlist;
  104108. long *fitmap;
  104109. long *fitlength;
  104110. } encode_aux_pigeonhole;
  104111. typedef struct codebook{
  104112. long dim; /* codebook dimensions (elements per vector) */
  104113. long entries; /* codebook entries */
  104114. long used_entries; /* populated codebook entries */
  104115. const static_codebook *c;
  104116. /* for encode, the below are entry-ordered, fully populated */
  104117. /* for decode, the below are ordered by bitreversed codeword and only
  104118. used entries are populated */
  104119. float *valuelist; /* list of dim*entries actual entry values */
  104120. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  104121. int *dec_index; /* only used if sparseness collapsed */
  104122. char *dec_codelengths;
  104123. ogg_uint32_t *dec_firsttable;
  104124. int dec_firsttablen;
  104125. int dec_maxlength;
  104126. } codebook;
  104127. extern void vorbis_staticbook_clear(static_codebook *b);
  104128. extern void vorbis_staticbook_destroy(static_codebook *b);
  104129. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  104130. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  104131. extern void vorbis_book_clear(codebook *b);
  104132. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  104133. extern float *_book_logdist(const static_codebook *b,float *vals);
  104134. extern float _float32_unpack(long val);
  104135. extern long _float32_pack(float val);
  104136. extern int _best(codebook *book, float *a, int step);
  104137. extern int _ilog(unsigned int v);
  104138. extern long _book_maptype1_quantvals(const static_codebook *b);
  104139. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  104140. extern long vorbis_book_codeword(codebook *book,int entry);
  104141. extern long vorbis_book_codelen(codebook *book,int entry);
  104142. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  104143. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  104144. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  104145. extern int vorbis_book_errorv(codebook *book, float *a);
  104146. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  104147. oggpack_buffer *b);
  104148. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  104149. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  104150. oggpack_buffer *b,int n);
  104151. extern long vorbis_book_decodev_set(codebook *book, float *a,
  104152. oggpack_buffer *b,int n);
  104153. extern long vorbis_book_decodev_add(codebook *book, float *a,
  104154. oggpack_buffer *b,int n);
  104155. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  104156. long off,int ch,
  104157. oggpack_buffer *b,int n);
  104158. #endif
  104159. /********* End of inlined file: codebook.h *********/
  104160. #define BLOCKTYPE_IMPULSE 0
  104161. #define BLOCKTYPE_PADDING 1
  104162. #define BLOCKTYPE_TRANSITION 0
  104163. #define BLOCKTYPE_LONG 1
  104164. #define PACKETBLOBS 15
  104165. typedef struct vorbis_block_internal{
  104166. float **pcmdelay; /* this is a pointer into local storage */
  104167. float ampmax;
  104168. int blocktype;
  104169. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  104170. blob [PACKETBLOBS/2] points to
  104171. the oggpack_buffer in the
  104172. main vorbis_block */
  104173. } vorbis_block_internal;
  104174. typedef void vorbis_look_floor;
  104175. typedef void vorbis_look_residue;
  104176. typedef void vorbis_look_transform;
  104177. /* mode ************************************************************/
  104178. typedef struct {
  104179. int blockflag;
  104180. int windowtype;
  104181. int transformtype;
  104182. int mapping;
  104183. } vorbis_info_mode;
  104184. typedef void vorbis_info_floor;
  104185. typedef void vorbis_info_residue;
  104186. typedef void vorbis_info_mapping;
  104187. /********* Start of inlined file: psy.h *********/
  104188. #ifndef _V_PSY_H_
  104189. #define _V_PSY_H_
  104190. /********* Start of inlined file: smallft.h *********/
  104191. #ifndef _V_SMFT_H_
  104192. #define _V_SMFT_H_
  104193. typedef struct {
  104194. int n;
  104195. float *trigcache;
  104196. int *splitcache;
  104197. } drft_lookup;
  104198. extern void drft_forward(drft_lookup *l,float *data);
  104199. extern void drft_backward(drft_lookup *l,float *data);
  104200. extern void drft_init(drft_lookup *l,int n);
  104201. extern void drft_clear(drft_lookup *l);
  104202. #endif
  104203. /********* End of inlined file: smallft.h *********/
  104204. /********* Start of inlined file: backends.h *********/
  104205. /* this is exposed up here because we need it for static modes.
  104206. Lookups for each backend aren't exposed because there's no reason
  104207. to do so */
  104208. #ifndef _vorbis_backend_h_
  104209. #define _vorbis_backend_h_
  104210. /* this would all be simpler/shorter with templates, but.... */
  104211. /* Floor backend generic *****************************************/
  104212. typedef struct{
  104213. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  104214. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  104215. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  104216. void (*free_info) (vorbis_info_floor *);
  104217. void (*free_look) (vorbis_look_floor *);
  104218. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  104219. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  104220. void *buffer,float *);
  104221. } vorbis_func_floor;
  104222. typedef struct{
  104223. int order;
  104224. long rate;
  104225. long barkmap;
  104226. int ampbits;
  104227. int ampdB;
  104228. int numbooks; /* <= 16 */
  104229. int books[16];
  104230. float lessthan; /* encode-only config setting hacks for libvorbis */
  104231. float greaterthan; /* encode-only config setting hacks for libvorbis */
  104232. } vorbis_info_floor0;
  104233. #define VIF_POSIT 63
  104234. #define VIF_CLASS 16
  104235. #define VIF_PARTS 31
  104236. typedef struct{
  104237. int partitions; /* 0 to 31 */
  104238. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  104239. int class_dim[VIF_CLASS]; /* 1 to 8 */
  104240. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  104241. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  104242. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  104243. int mult; /* 1 2 3 or 4 */
  104244. int postlist[VIF_POSIT+2]; /* first two implicit */
  104245. /* encode side analysis parameters */
  104246. float maxover;
  104247. float maxunder;
  104248. float maxerr;
  104249. float twofitweight;
  104250. float twofitatten;
  104251. int n;
  104252. } vorbis_info_floor1;
  104253. /* Residue backend generic *****************************************/
  104254. typedef struct{
  104255. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  104256. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  104257. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  104258. vorbis_info_residue *);
  104259. void (*free_info) (vorbis_info_residue *);
  104260. void (*free_look) (vorbis_look_residue *);
  104261. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  104262. float **,int *,int);
  104263. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  104264. vorbis_look_residue *,
  104265. float **,float **,int *,int,long **);
  104266. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  104267. float **,int *,int);
  104268. } vorbis_func_residue;
  104269. typedef struct vorbis_info_residue0{
  104270. /* block-partitioned VQ coded straight residue */
  104271. long begin;
  104272. long end;
  104273. /* first stage (lossless partitioning) */
  104274. int grouping; /* group n vectors per partition */
  104275. int partitions; /* possible codebooks for a partition */
  104276. int groupbook; /* huffbook for partitioning */
  104277. int secondstages[64]; /* expanded out to pointers in lookup */
  104278. int booklist[256]; /* list of second stage books */
  104279. float classmetric1[64];
  104280. float classmetric2[64];
  104281. } vorbis_info_residue0;
  104282. /* Mapping backend generic *****************************************/
  104283. typedef struct{
  104284. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  104285. oggpack_buffer *);
  104286. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  104287. void (*free_info) (vorbis_info_mapping *);
  104288. int (*forward) (struct vorbis_block *vb);
  104289. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  104290. } vorbis_func_mapping;
  104291. typedef struct vorbis_info_mapping0{
  104292. int submaps; /* <= 16 */
  104293. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  104294. int floorsubmap[16]; /* [mux] submap to floors */
  104295. int residuesubmap[16]; /* [mux] submap to residue */
  104296. int coupling_steps;
  104297. int coupling_mag[256];
  104298. int coupling_ang[256];
  104299. } vorbis_info_mapping0;
  104300. #endif
  104301. /********* End of inlined file: backends.h *********/
  104302. #ifndef EHMER_MAX
  104303. #define EHMER_MAX 56
  104304. #endif
  104305. /* psychoacoustic setup ********************************************/
  104306. #define P_BANDS 17 /* 62Hz to 16kHz */
  104307. #define P_LEVELS 8 /* 30dB to 100dB */
  104308. #define P_LEVEL_0 30. /* 30 dB */
  104309. #define P_NOISECURVES 3
  104310. #define NOISE_COMPAND_LEVELS 40
  104311. typedef struct vorbis_info_psy{
  104312. int blockflag;
  104313. float ath_adjatt;
  104314. float ath_maxatt;
  104315. float tone_masteratt[P_NOISECURVES];
  104316. float tone_centerboost;
  104317. float tone_decay;
  104318. float tone_abs_limit;
  104319. float toneatt[P_BANDS];
  104320. int noisemaskp;
  104321. float noisemaxsupp;
  104322. float noisewindowlo;
  104323. float noisewindowhi;
  104324. int noisewindowlomin;
  104325. int noisewindowhimin;
  104326. int noisewindowfixed;
  104327. float noiseoff[P_NOISECURVES][P_BANDS];
  104328. float noisecompand[NOISE_COMPAND_LEVELS];
  104329. float max_curve_dB;
  104330. int normal_channel_p;
  104331. int normal_point_p;
  104332. int normal_start;
  104333. int normal_partition;
  104334. double normal_thresh;
  104335. } vorbis_info_psy;
  104336. typedef struct{
  104337. int eighth_octave_lines;
  104338. /* for block long/short tuning; encode only */
  104339. float preecho_thresh[VE_BANDS];
  104340. float postecho_thresh[VE_BANDS];
  104341. float stretch_penalty;
  104342. float preecho_minenergy;
  104343. float ampmax_att_per_sec;
  104344. /* channel coupling config */
  104345. int coupling_pkHz[PACKETBLOBS];
  104346. int coupling_pointlimit[2][PACKETBLOBS];
  104347. int coupling_prepointamp[PACKETBLOBS];
  104348. int coupling_postpointamp[PACKETBLOBS];
  104349. int sliding_lowpass[2][PACKETBLOBS];
  104350. } vorbis_info_psy_global;
  104351. typedef struct {
  104352. float ampmax;
  104353. int channels;
  104354. vorbis_info_psy_global *gi;
  104355. int coupling_pointlimit[2][P_NOISECURVES];
  104356. } vorbis_look_psy_global;
  104357. typedef struct {
  104358. int n;
  104359. struct vorbis_info_psy *vi;
  104360. float ***tonecurves;
  104361. float **noiseoffset;
  104362. float *ath;
  104363. long *octave; /* in n.ocshift format */
  104364. long *bark;
  104365. long firstoc;
  104366. long shiftoc;
  104367. int eighth_octave_lines; /* power of two, please */
  104368. int total_octave_lines;
  104369. long rate; /* cache it */
  104370. float m_val; /* Masking compensation value */
  104371. } vorbis_look_psy;
  104372. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  104373. vorbis_info_psy_global *gi,int n,long rate);
  104374. extern void _vp_psy_clear(vorbis_look_psy *p);
  104375. extern void *_vi_psy_dup(void *source);
  104376. extern void _vi_psy_free(vorbis_info_psy *i);
  104377. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  104378. extern void _vp_remove_floor(vorbis_look_psy *p,
  104379. float *mdct,
  104380. int *icodedflr,
  104381. float *residue,
  104382. int sliding_lowpass);
  104383. extern void _vp_noisemask(vorbis_look_psy *p,
  104384. float *logmdct,
  104385. float *logmask);
  104386. extern void _vp_tonemask(vorbis_look_psy *p,
  104387. float *logfft,
  104388. float *logmask,
  104389. float global_specmax,
  104390. float local_specmax);
  104391. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  104392. float *noise,
  104393. float *tone,
  104394. int offset_select,
  104395. float *logmask,
  104396. float *mdct,
  104397. float *logmdct);
  104398. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  104399. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  104400. vorbis_info_psy_global *g,
  104401. vorbis_look_psy *p,
  104402. vorbis_info_mapping0 *vi,
  104403. float **mdct);
  104404. extern void _vp_couple(int blobno,
  104405. vorbis_info_psy_global *g,
  104406. vorbis_look_psy *p,
  104407. vorbis_info_mapping0 *vi,
  104408. float **res,
  104409. float **mag_memo,
  104410. int **mag_sort,
  104411. int **ifloor,
  104412. int *nonzero,
  104413. int sliding_lowpass);
  104414. extern void _vp_noise_normalize(vorbis_look_psy *p,
  104415. float *in,float *out,int *sortedindex);
  104416. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  104417. float *magnitudes,int *sortedindex);
  104418. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  104419. vorbis_look_psy *p,
  104420. vorbis_info_mapping0 *vi,
  104421. float **mags);
  104422. extern void hf_reduction(vorbis_info_psy_global *g,
  104423. vorbis_look_psy *p,
  104424. vorbis_info_mapping0 *vi,
  104425. float **mdct);
  104426. #endif
  104427. /********* End of inlined file: psy.h *********/
  104428. /********* Start of inlined file: bitrate.h *********/
  104429. #ifndef _V_BITRATE_H_
  104430. #define _V_BITRATE_H_
  104431. /********* Start of inlined file: os.h *********/
  104432. #ifndef _OS_H
  104433. #define _OS_H
  104434. /********************************************************************
  104435. * *
  104436. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  104437. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  104438. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  104439. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  104440. * *
  104441. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  104442. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  104443. * *
  104444. ********************************************************************
  104445. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  104446. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  104447. ********************************************************************/
  104448. #ifdef HAVE_CONFIG_H
  104449. #include "config.h"
  104450. #endif
  104451. #include <math.h>
  104452. /********* Start of inlined file: misc.h *********/
  104453. #ifndef _V_RANDOM_H_
  104454. #define _V_RANDOM_H_
  104455. extern int analysis_noisy;
  104456. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  104457. extern void _vorbis_block_ripcord(vorbis_block *vb);
  104458. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  104459. ogg_int64_t off);
  104460. #ifdef DEBUG_MALLOC
  104461. #define _VDBG_GRAPHFILE "malloc.m"
  104462. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  104463. extern void _VDBG_free(void *ptr,char *file,long line);
  104464. #ifndef MISC_C
  104465. #undef _ogg_malloc
  104466. #undef _ogg_calloc
  104467. #undef _ogg_realloc
  104468. #undef _ogg_free
  104469. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  104470. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  104471. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  104472. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  104473. #endif
  104474. #endif
  104475. #endif
  104476. /********* End of inlined file: misc.h *********/
  104477. #ifndef _V_IFDEFJAIL_H_
  104478. # define _V_IFDEFJAIL_H_
  104479. # ifdef __GNUC__
  104480. # define STIN static __inline__
  104481. # elif _WIN32
  104482. # define STIN static __inline
  104483. # else
  104484. # define STIN static
  104485. # endif
  104486. #ifdef DJGPP
  104487. # define rint(x) (floor((x)+0.5f))
  104488. #endif
  104489. #ifndef M_PI
  104490. # define M_PI (3.1415926536f)
  104491. #endif
  104492. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  104493. # include <malloc.h>
  104494. # define rint(x) (floor((x)+0.5f))
  104495. # define NO_FLOAT_MATH_LIB
  104496. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  104497. #endif
  104498. #if defined(__SYMBIAN32__) && defined(__WINS__)
  104499. void *_alloca(size_t size);
  104500. # define alloca _alloca
  104501. #endif
  104502. #ifndef FAST_HYPOT
  104503. # define FAST_HYPOT hypot
  104504. #endif
  104505. #endif
  104506. #ifdef HAVE_ALLOCA_H
  104507. # include <alloca.h>
  104508. #endif
  104509. #ifdef USE_MEMORY_H
  104510. # include <memory.h>
  104511. #endif
  104512. #ifndef min
  104513. # define min(x,y) ((x)>(y)?(y):(x))
  104514. #endif
  104515. #ifndef max
  104516. # define max(x,y) ((x)<(y)?(y):(x))
  104517. #endif
  104518. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  104519. # define VORBIS_FPU_CONTROL
  104520. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  104521. Because of encapsulation constraints (GCC can't see inside the asm
  104522. block and so we end up doing stupid things like a store/load that
  104523. is collectively a noop), we do it this way */
  104524. /* we must set up the fpu before this works!! */
  104525. typedef ogg_int16_t vorbis_fpu_control;
  104526. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  104527. ogg_int16_t ret;
  104528. ogg_int16_t temp;
  104529. __asm__ __volatile__("fnstcw %0\n\t"
  104530. "movw %0,%%dx\n\t"
  104531. "orw $62463,%%dx\n\t"
  104532. "movw %%dx,%1\n\t"
  104533. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  104534. *fpu=ret;
  104535. }
  104536. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  104537. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  104538. }
  104539. /* assumes the FPU is in round mode! */
  104540. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  104541. we get extra fst/fld to
  104542. truncate precision */
  104543. int i;
  104544. __asm__("fistl %0": "=m"(i) : "t"(f));
  104545. return(i);
  104546. }
  104547. #endif
  104548. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  104549. # define VORBIS_FPU_CONTROL
  104550. typedef ogg_int16_t vorbis_fpu_control;
  104551. static __inline int vorbis_ftoi(double f){
  104552. int i;
  104553. __asm{
  104554. fld f
  104555. fistp i
  104556. }
  104557. return i;
  104558. }
  104559. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  104560. }
  104561. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  104562. }
  104563. #endif
  104564. #ifndef VORBIS_FPU_CONTROL
  104565. typedef int vorbis_fpu_control;
  104566. static int vorbis_ftoi(double f){
  104567. return (int)(f+.5);
  104568. }
  104569. /* We don't have special code for this compiler/arch, so do it the slow way */
  104570. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  104571. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  104572. #endif
  104573. #endif /* _OS_H */
  104574. /********* End of inlined file: os.h *********/
  104575. /* encode side bitrate tracking */
  104576. typedef struct bitrate_manager_state {
  104577. int managed;
  104578. long avg_reservoir;
  104579. long minmax_reservoir;
  104580. long avg_bitsper;
  104581. long min_bitsper;
  104582. long max_bitsper;
  104583. long short_per_long;
  104584. double avgfloat;
  104585. vorbis_block *vb;
  104586. int choice;
  104587. } bitrate_manager_state;
  104588. typedef struct bitrate_manager_info{
  104589. long avg_rate;
  104590. long min_rate;
  104591. long max_rate;
  104592. long reservoir_bits;
  104593. double reservoir_bias;
  104594. double slew_damp;
  104595. } bitrate_manager_info;
  104596. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  104597. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  104598. extern int vorbis_bitrate_managed(vorbis_block *vb);
  104599. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  104600. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  104601. #endif
  104602. /********* End of inlined file: bitrate.h *********/
  104603. static int ilog(unsigned int v){
  104604. int ret=0;
  104605. while(v){
  104606. ret++;
  104607. v>>=1;
  104608. }
  104609. return(ret);
  104610. }
  104611. static int ilog2(unsigned int v){
  104612. int ret=0;
  104613. if(v)--v;
  104614. while(v){
  104615. ret++;
  104616. v>>=1;
  104617. }
  104618. return(ret);
  104619. }
  104620. typedef struct private_state {
  104621. /* local lookup storage */
  104622. envelope_lookup *ve; /* envelope lookup */
  104623. int window[2];
  104624. vorbis_look_transform **transform[2]; /* block, type */
  104625. drft_lookup fft_look[2];
  104626. int modebits;
  104627. vorbis_look_floor **flr;
  104628. vorbis_look_residue **residue;
  104629. vorbis_look_psy *psy;
  104630. vorbis_look_psy_global *psy_g_look;
  104631. /* local storage, only used on the encoding side. This way the
  104632. application does not need to worry about freeing some packets'
  104633. memory and not others'; packet storage is always tracked.
  104634. Cleared next call to a _dsp_ function */
  104635. unsigned char *header;
  104636. unsigned char *header1;
  104637. unsigned char *header2;
  104638. bitrate_manager_state bms;
  104639. ogg_int64_t sample_count;
  104640. } private_state;
  104641. /* codec_setup_info contains all the setup information specific to the
  104642. specific compression/decompression mode in progress (eg,
  104643. psychoacoustic settings, channel setup, options, codebook
  104644. etc).
  104645. *********************************************************************/
  104646. /********* Start of inlined file: highlevel.h *********/
  104647. typedef struct highlevel_byblocktype {
  104648. double tone_mask_setting;
  104649. double tone_peaklimit_setting;
  104650. double noise_bias_setting;
  104651. double noise_compand_setting;
  104652. } highlevel_byblocktype;
  104653. typedef struct highlevel_encode_setup {
  104654. void *setup;
  104655. int set_in_stone;
  104656. double base_setting;
  104657. double long_setting;
  104658. double short_setting;
  104659. double impulse_noisetune;
  104660. int managed;
  104661. long bitrate_min;
  104662. long bitrate_av;
  104663. double bitrate_av_damp;
  104664. long bitrate_max;
  104665. long bitrate_reservoir;
  104666. double bitrate_reservoir_bias;
  104667. int impulse_block_p;
  104668. int noise_normalize_p;
  104669. double stereo_point_setting;
  104670. double lowpass_kHz;
  104671. double ath_floating_dB;
  104672. double ath_absolute_dB;
  104673. double amplitude_track_dBpersec;
  104674. double trigger_setting;
  104675. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  104676. } highlevel_encode_setup;
  104677. /********* End of inlined file: highlevel.h *********/
  104678. typedef struct codec_setup_info {
  104679. /* Vorbis supports only short and long blocks, but allows the
  104680. encoder to choose the sizes */
  104681. long blocksizes[2];
  104682. /* modes are the primary means of supporting on-the-fly different
  104683. blocksizes, different channel mappings (LR or M/A),
  104684. different residue backends, etc. Each mode consists of a
  104685. blocksize flag and a mapping (along with the mapping setup */
  104686. int modes;
  104687. int maps;
  104688. int floors;
  104689. int residues;
  104690. int books;
  104691. int psys; /* encode only */
  104692. vorbis_info_mode *mode_param[64];
  104693. int map_type[64];
  104694. vorbis_info_mapping *map_param[64];
  104695. int floor_type[64];
  104696. vorbis_info_floor *floor_param[64];
  104697. int residue_type[64];
  104698. vorbis_info_residue *residue_param[64];
  104699. static_codebook *book_param[256];
  104700. codebook *fullbooks;
  104701. vorbis_info_psy *psy_param[4]; /* encode only */
  104702. vorbis_info_psy_global psy_g_param;
  104703. bitrate_manager_info bi;
  104704. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  104705. highly redundant structure, but
  104706. improves clarity of program flow. */
  104707. int halfrate_flag; /* painless downsample for decode */
  104708. } codec_setup_info;
  104709. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  104710. extern void _vp_global_free(vorbis_look_psy_global *look);
  104711. #endif
  104712. /********* End of inlined file: codec_internal.h *********/
  104713. /********* Start of inlined file: registry.h *********/
  104714. #ifndef _V_REG_H_
  104715. #define _V_REG_H_
  104716. #define VI_TRANSFORMB 1
  104717. #define VI_WINDOWB 1
  104718. #define VI_TIMEB 1
  104719. #define VI_FLOORB 2
  104720. #define VI_RESB 3
  104721. #define VI_MAPB 1
  104722. extern vorbis_func_floor *_floor_P[];
  104723. extern vorbis_func_residue *_residue_P[];
  104724. extern vorbis_func_mapping *_mapping_P[];
  104725. #endif
  104726. /********* End of inlined file: registry.h *********/
  104727. /********* Start of inlined file: scales.h *********/
  104728. #ifndef _V_SCALES_H_
  104729. #define _V_SCALES_H_
  104730. #include <math.h>
  104731. /* 20log10(x) */
  104732. #define VORBIS_IEEE_FLOAT32 1
  104733. #ifdef VORBIS_IEEE_FLOAT32
  104734. static float unitnorm(float x){
  104735. union {
  104736. ogg_uint32_t i;
  104737. float f;
  104738. } ix;
  104739. ix.f = x;
  104740. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  104741. return ix.f;
  104742. }
  104743. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  104744. static float todB(const float *x){
  104745. union {
  104746. ogg_uint32_t i;
  104747. float f;
  104748. } ix;
  104749. ix.f = *x;
  104750. ix.i = ix.i&0x7fffffff;
  104751. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  104752. }
  104753. #define todB_nn(x) todB(x)
  104754. #else
  104755. static float unitnorm(float x){
  104756. if(x<0)return(-1.f);
  104757. return(1.f);
  104758. }
  104759. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  104760. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  104761. #endif
  104762. #define fromdB(x) (exp((x)*.11512925f))
  104763. /* The bark scale equations are approximations, since the original
  104764. table was somewhat hand rolled. The below are chosen to have the
  104765. best possible fit to the rolled tables, thus their somewhat odd
  104766. appearance (these are more accurate and over a longer range than
  104767. the oft-quoted bark equations found in the texts I have). The
  104768. approximations are valid from 0 - 30kHz (nyquist) or so.
  104769. all f in Hz, z in Bark */
  104770. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  104771. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  104772. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  104773. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  104774. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  104775. 0.0 */
  104776. #define toOC(n) (log(n)*1.442695f-5.965784f)
  104777. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  104778. #endif
  104779. /********* End of inlined file: scales.h *********/
  104780. int analysis_noisy=1;
  104781. /* decides between modes, dispatches to the appropriate mapping. */
  104782. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  104783. int ret,i;
  104784. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  104785. vb->glue_bits=0;
  104786. vb->time_bits=0;
  104787. vb->floor_bits=0;
  104788. vb->res_bits=0;
  104789. /* first things first. Make sure encode is ready */
  104790. for(i=0;i<PACKETBLOBS;i++)
  104791. oggpack_reset(vbi->packetblob[i]);
  104792. /* we only have one mapping type (0), and we let the mapping code
  104793. itself figure out what soft mode to use. This allows easier
  104794. bitrate management */
  104795. if((ret=_mapping_P[0]->forward(vb)))
  104796. return(ret);
  104797. if(op){
  104798. if(vorbis_bitrate_managed(vb))
  104799. /* The app is using a bitmanaged mode... but not using the
  104800. bitrate management interface. */
  104801. return(OV_EINVAL);
  104802. op->packet=oggpack_get_buffer(&vb->opb);
  104803. op->bytes=oggpack_bytes(&vb->opb);
  104804. op->b_o_s=0;
  104805. op->e_o_s=vb->eofflag;
  104806. op->granulepos=vb->granulepos;
  104807. op->packetno=vb->sequence; /* for sake of completeness */
  104808. }
  104809. return(0);
  104810. }
  104811. /* there was no great place to put this.... */
  104812. void _analysis_output_always(char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  104813. int j;
  104814. FILE *of;
  104815. char buffer[80];
  104816. /* if(i==5870){*/
  104817. sprintf(buffer,"%s_%d.m",base,i);
  104818. of=fopen(buffer,"w");
  104819. if(!of)perror("failed to open data dump file");
  104820. for(j=0;j<n;j++){
  104821. if(bark){
  104822. float b=toBARK((4000.f*j/n)+.25);
  104823. fprintf(of,"%f ",b);
  104824. }else
  104825. if(off!=0)
  104826. fprintf(of,"%f ",(double)(j+off)/8000.);
  104827. else
  104828. fprintf(of,"%f ",(double)j);
  104829. if(dB){
  104830. float val;
  104831. if(v[j]==0.)
  104832. val=-140.;
  104833. else
  104834. val=todB(v+j);
  104835. fprintf(of,"%f\n",val);
  104836. }else{
  104837. fprintf(of,"%f\n",v[j]);
  104838. }
  104839. }
  104840. fclose(of);
  104841. /* } */
  104842. }
  104843. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  104844. ogg_int64_t off){
  104845. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  104846. }
  104847. #endif
  104848. /********* End of inlined file: analysis.c *********/
  104849. /********* Start of inlined file: bitrate.c *********/
  104850. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  104851. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  104852. // tasks..
  104853. #ifdef _MSC_VER
  104854. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  104855. #endif
  104856. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  104857. #if JUCE_USE_OGGVORBIS
  104858. #include <stdlib.h>
  104859. #include <string.h>
  104860. #include <math.h>
  104861. /* compute bitrate tracking setup */
  104862. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  104863. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  104864. bitrate_manager_info *bi=&ci->bi;
  104865. memset(bm,0,sizeof(*bm));
  104866. if(bi && (bi->reservoir_bits>0)){
  104867. long ratesamples=vi->rate;
  104868. int halfsamples=ci->blocksizes[0]>>1;
  104869. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  104870. bm->managed=1;
  104871. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  104872. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  104873. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  104874. bm->avgfloat=PACKETBLOBS/2;
  104875. /* not a necessary fix, but one that leads to a more balanced
  104876. typical initialization */
  104877. {
  104878. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  104879. bm->minmax_reservoir=desired_fill;
  104880. bm->avg_reservoir=desired_fill;
  104881. }
  104882. }
  104883. }
  104884. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  104885. memset(bm,0,sizeof(*bm));
  104886. return;
  104887. }
  104888. int vorbis_bitrate_managed(vorbis_block *vb){
  104889. vorbis_dsp_state *vd=vb->vd;
  104890. private_state *b=(private_state*)vd->backend_state;
  104891. bitrate_manager_state *bm=&b->bms;
  104892. if(bm && bm->managed)return(1);
  104893. return(0);
  104894. }
  104895. /* finish taking in the block we just processed */
  104896. int vorbis_bitrate_addblock(vorbis_block *vb){
  104897. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  104898. vorbis_dsp_state *vd=vb->vd;
  104899. private_state *b=(private_state*)vd->backend_state;
  104900. bitrate_manager_state *bm=&b->bms;
  104901. vorbis_info *vi=vd->vi;
  104902. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  104903. bitrate_manager_info *bi=&ci->bi;
  104904. int choice=rint(bm->avgfloat);
  104905. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104906. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  104907. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  104908. int samples=ci->blocksizes[vb->W]>>1;
  104909. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  104910. if(!bm->managed){
  104911. /* not a bitrate managed stream, but for API simplicity, we'll
  104912. buffer the packet to keep the code path clean */
  104913. if(bm->vb)return(-1); /* one has been submitted without
  104914. being claimed */
  104915. bm->vb=vb;
  104916. return(0);
  104917. }
  104918. bm->vb=vb;
  104919. /* look ahead for avg floater */
  104920. if(bm->avg_bitsper>0){
  104921. double slew=0.;
  104922. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  104923. double slewlimit= 15./bi->slew_damp;
  104924. /* choosing a new floater:
  104925. if we're over target, we slew down
  104926. if we're under target, we slew up
  104927. choose slew as follows: look through packetblobs of this frame
  104928. and set slew as the first in the appropriate direction that
  104929. gives us the slew we want. This may mean no slew if delta is
  104930. already favorable.
  104931. Then limit slew to slew max */
  104932. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  104933. while(choice>0 && this_bits>avg_target_bits &&
  104934. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  104935. choice--;
  104936. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104937. }
  104938. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  104939. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  104940. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  104941. choice++;
  104942. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104943. }
  104944. }
  104945. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  104946. if(slew<-slewlimit)slew=-slewlimit;
  104947. if(slew>slewlimit)slew=slewlimit;
  104948. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  104949. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104950. }
  104951. /* enforce min(if used) on the current floater (if used) */
  104952. if(bm->min_bitsper>0){
  104953. /* do we need to force the bitrate up? */
  104954. if(this_bits<min_target_bits){
  104955. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  104956. choice++;
  104957. if(choice>=PACKETBLOBS)break;
  104958. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104959. }
  104960. }
  104961. }
  104962. /* enforce max (if used) on the current floater (if used) */
  104963. if(bm->max_bitsper>0){
  104964. /* do we need to force the bitrate down? */
  104965. if(this_bits>max_target_bits){
  104966. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  104967. choice--;
  104968. if(choice<0)break;
  104969. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104970. }
  104971. }
  104972. }
  104973. /* Choice of packetblobs now made based on floater, and min/max
  104974. requirements. Now boundary check extreme choices */
  104975. if(choice<0){
  104976. /* choosing a smaller packetblob is insufficient to trim bitrate.
  104977. frame will need to be truncated */
  104978. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  104979. bm->choice=choice=0;
  104980. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  104981. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  104982. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104983. }
  104984. }else{
  104985. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  104986. if(choice>=PACKETBLOBS)
  104987. choice=PACKETBLOBS-1;
  104988. bm->choice=choice;
  104989. /* prop up bitrate according to demand. pad this frame out with zeroes */
  104990. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  104991. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  104992. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104993. }
  104994. /* now we have the final packet and the final packet size. Update statistics */
  104995. /* min and max reservoir */
  104996. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  104997. if(max_target_bits>0 && this_bits>max_target_bits){
  104998. bm->minmax_reservoir+=(this_bits-max_target_bits);
  104999. }else if(min_target_bits>0 && this_bits<min_target_bits){
  105000. bm->minmax_reservoir+=(this_bits-min_target_bits);
  105001. }else{
  105002. /* inbetween; we want to take reservoir toward but not past desired_fill */
  105003. if(bm->minmax_reservoir>desired_fill){
  105004. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  105005. bm->minmax_reservoir+=(this_bits-max_target_bits);
  105006. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  105007. }else{
  105008. bm->minmax_reservoir=desired_fill;
  105009. }
  105010. }else{
  105011. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  105012. bm->minmax_reservoir+=(this_bits-min_target_bits);
  105013. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  105014. }else{
  105015. bm->minmax_reservoir=desired_fill;
  105016. }
  105017. }
  105018. }
  105019. }
  105020. /* avg reservoir */
  105021. if(bm->avg_bitsper>0){
  105022. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  105023. bm->avg_reservoir+=this_bits-avg_target_bits;
  105024. }
  105025. return(0);
  105026. }
  105027. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  105028. private_state *b=(private_state*)vd->backend_state;
  105029. bitrate_manager_state *bm=&b->bms;
  105030. vorbis_block *vb=bm->vb;
  105031. int choice=PACKETBLOBS/2;
  105032. if(!vb)return 0;
  105033. if(op){
  105034. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  105035. if(vorbis_bitrate_managed(vb))
  105036. choice=bm->choice;
  105037. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  105038. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  105039. op->b_o_s=0;
  105040. op->e_o_s=vb->eofflag;
  105041. op->granulepos=vb->granulepos;
  105042. op->packetno=vb->sequence; /* for sake of completeness */
  105043. }
  105044. bm->vb=0;
  105045. return(1);
  105046. }
  105047. #endif
  105048. /********* End of inlined file: bitrate.c *********/
  105049. /********* Start of inlined file: block.c *********/
  105050. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105051. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105052. // tasks..
  105053. #ifdef _MSC_VER
  105054. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105055. #endif
  105056. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105057. #if JUCE_USE_OGGVORBIS
  105058. #include <stdio.h>
  105059. #include <stdlib.h>
  105060. #include <string.h>
  105061. /********* Start of inlined file: window.h *********/
  105062. #ifndef _V_WINDOW_
  105063. #define _V_WINDOW_
  105064. extern float *_vorbis_window_get(int n);
  105065. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  105066. int lW,int W,int nW);
  105067. #endif
  105068. /********* End of inlined file: window.h *********/
  105069. /********* Start of inlined file: lpc.h *********/
  105070. #ifndef _V_LPC_H_
  105071. #define _V_LPC_H_
  105072. /* simple linear scale LPC code */
  105073. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  105074. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  105075. float *data,long n);
  105076. #endif
  105077. /********* End of inlined file: lpc.h *********/
  105078. /* pcm accumulator examples (not exhaustive):
  105079. <-------------- lW ---------------->
  105080. <--------------- W ---------------->
  105081. : .....|..... _______________ |
  105082. : .''' | '''_--- | |\ |
  105083. :.....''' |_____--- '''......| | \_______|
  105084. :.................|__________________|_______|__|______|
  105085. |<------ Sl ------>| > Sr < |endW
  105086. |beginSl |endSl | |endSr
  105087. |beginW |endlW |beginSr
  105088. |< lW >|
  105089. <--------------- W ---------------->
  105090. | | .. ______________ |
  105091. | | ' `/ | ---_ |
  105092. |___.'___/`. | ---_____|
  105093. |_______|__|_______|_________________|
  105094. | >|Sl|< |<------ Sr ----->|endW
  105095. | | |endSl |beginSr |endSr
  105096. |beginW | |endlW
  105097. mult[0] |beginSl mult[n]
  105098. <-------------- lW ----------------->
  105099. |<--W-->|
  105100. : .............. ___ | |
  105101. : .''' |`/ \ | |
  105102. :.....''' |/`....\|...|
  105103. :.........................|___|___|___|
  105104. |Sl |Sr |endW
  105105. | | |endSr
  105106. | |beginSr
  105107. | |endSl
  105108. |beginSl
  105109. |beginW
  105110. */
  105111. /* block abstraction setup *********************************************/
  105112. #ifndef WORD_ALIGN
  105113. #define WORD_ALIGN 8
  105114. #endif
  105115. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  105116. int i;
  105117. memset(vb,0,sizeof(*vb));
  105118. vb->vd=v;
  105119. vb->localalloc=0;
  105120. vb->localstore=NULL;
  105121. if(v->analysisp){
  105122. vorbis_block_internal *vbi=(vorbis_block_internal*)
  105123. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  105124. vbi->ampmax=-9999;
  105125. for(i=0;i<PACKETBLOBS;i++){
  105126. if(i==PACKETBLOBS/2){
  105127. vbi->packetblob[i]=&vb->opb;
  105128. }else{
  105129. vbi->packetblob[i]=
  105130. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  105131. }
  105132. oggpack_writeinit(vbi->packetblob[i]);
  105133. }
  105134. }
  105135. return(0);
  105136. }
  105137. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  105138. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  105139. if(bytes+vb->localtop>vb->localalloc){
  105140. /* can't just _ogg_realloc... there are outstanding pointers */
  105141. if(vb->localstore){
  105142. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  105143. vb->totaluse+=vb->localtop;
  105144. link->next=vb->reap;
  105145. link->ptr=vb->localstore;
  105146. vb->reap=link;
  105147. }
  105148. /* highly conservative */
  105149. vb->localalloc=bytes;
  105150. vb->localstore=_ogg_malloc(vb->localalloc);
  105151. vb->localtop=0;
  105152. }
  105153. {
  105154. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  105155. vb->localtop+=bytes;
  105156. return ret;
  105157. }
  105158. }
  105159. /* reap the chain, pull the ripcord */
  105160. void _vorbis_block_ripcord(vorbis_block *vb){
  105161. /* reap the chain */
  105162. struct alloc_chain *reap=vb->reap;
  105163. while(reap){
  105164. struct alloc_chain *next=reap->next;
  105165. _ogg_free(reap->ptr);
  105166. memset(reap,0,sizeof(*reap));
  105167. _ogg_free(reap);
  105168. reap=next;
  105169. }
  105170. /* consolidate storage */
  105171. if(vb->totaluse){
  105172. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  105173. vb->localalloc+=vb->totaluse;
  105174. vb->totaluse=0;
  105175. }
  105176. /* pull the ripcord */
  105177. vb->localtop=0;
  105178. vb->reap=NULL;
  105179. }
  105180. int vorbis_block_clear(vorbis_block *vb){
  105181. int i;
  105182. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  105183. _vorbis_block_ripcord(vb);
  105184. if(vb->localstore)_ogg_free(vb->localstore);
  105185. if(vbi){
  105186. for(i=0;i<PACKETBLOBS;i++){
  105187. oggpack_writeclear(vbi->packetblob[i]);
  105188. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  105189. }
  105190. _ogg_free(vbi);
  105191. }
  105192. memset(vb,0,sizeof(*vb));
  105193. return(0);
  105194. }
  105195. /* Analysis side code, but directly related to blocking. Thus it's
  105196. here and not in analysis.c (which is for analysis transforms only).
  105197. The init is here because some of it is shared */
  105198. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  105199. int i;
  105200. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  105201. private_state *b=NULL;
  105202. int hs;
  105203. if(ci==NULL) return 1;
  105204. hs=ci->halfrate_flag;
  105205. memset(v,0,sizeof(*v));
  105206. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  105207. v->vi=vi;
  105208. b->modebits=ilog2(ci->modes);
  105209. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  105210. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  105211. /* MDCT is tranform 0 */
  105212. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  105213. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  105214. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  105215. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  105216. /* Vorbis I uses only window type 0 */
  105217. b->window[0]=ilog2(ci->blocksizes[0])-6;
  105218. b->window[1]=ilog2(ci->blocksizes[1])-6;
  105219. if(encp){ /* encode/decode differ here */
  105220. /* analysis always needs an fft */
  105221. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  105222. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  105223. /* finish the codebooks */
  105224. if(!ci->fullbooks){
  105225. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  105226. for(i=0;i<ci->books;i++)
  105227. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  105228. }
  105229. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  105230. for(i=0;i<ci->psys;i++){
  105231. _vp_psy_init(b->psy+i,
  105232. ci->psy_param[i],
  105233. &ci->psy_g_param,
  105234. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  105235. vi->rate);
  105236. }
  105237. v->analysisp=1;
  105238. }else{
  105239. /* finish the codebooks */
  105240. if(!ci->fullbooks){
  105241. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  105242. for(i=0;i<ci->books;i++){
  105243. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  105244. /* decode codebooks are now standalone after init */
  105245. vorbis_staticbook_destroy(ci->book_param[i]);
  105246. ci->book_param[i]=NULL;
  105247. }
  105248. }
  105249. }
  105250. /* initialize the storage vectors. blocksize[1] is small for encode,
  105251. but the correct size for decode */
  105252. v->pcm_storage=ci->blocksizes[1];
  105253. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  105254. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  105255. {
  105256. int i;
  105257. for(i=0;i<vi->channels;i++)
  105258. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  105259. }
  105260. /* all 1 (large block) or 0 (small block) */
  105261. /* explicitly set for the sake of clarity */
  105262. v->lW=0; /* previous window size */
  105263. v->W=0; /* current window size */
  105264. /* all vector indexes */
  105265. v->centerW=ci->blocksizes[1]/2;
  105266. v->pcm_current=v->centerW;
  105267. /* initialize all the backend lookups */
  105268. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  105269. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  105270. for(i=0;i<ci->floors;i++)
  105271. b->flr[i]=_floor_P[ci->floor_type[i]]->
  105272. look(v,ci->floor_param[i]);
  105273. for(i=0;i<ci->residues;i++)
  105274. b->residue[i]=_residue_P[ci->residue_type[i]]->
  105275. look(v,ci->residue_param[i]);
  105276. return 0;
  105277. }
  105278. /* arbitrary settings and spec-mandated numbers get filled in here */
  105279. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  105280. private_state *b=NULL;
  105281. if(_vds_shared_init(v,vi,1))return 1;
  105282. b=(private_state*)v->backend_state;
  105283. b->psy_g_look=_vp_global_look(vi);
  105284. /* Initialize the envelope state storage */
  105285. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  105286. _ve_envelope_init(b->ve,vi);
  105287. vorbis_bitrate_init(vi,&b->bms);
  105288. /* compressed audio packets start after the headers
  105289. with sequence number 3 */
  105290. v->sequence=3;
  105291. return(0);
  105292. }
  105293. void vorbis_dsp_clear(vorbis_dsp_state *v){
  105294. int i;
  105295. if(v){
  105296. vorbis_info *vi=v->vi;
  105297. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  105298. private_state *b=(private_state*)v->backend_state;
  105299. if(b){
  105300. if(b->ve){
  105301. _ve_envelope_clear(b->ve);
  105302. _ogg_free(b->ve);
  105303. }
  105304. if(b->transform[0]){
  105305. mdct_clear((mdct_lookup*) b->transform[0][0]);
  105306. _ogg_free(b->transform[0][0]);
  105307. _ogg_free(b->transform[0]);
  105308. }
  105309. if(b->transform[1]){
  105310. mdct_clear((mdct_lookup*) b->transform[1][0]);
  105311. _ogg_free(b->transform[1][0]);
  105312. _ogg_free(b->transform[1]);
  105313. }
  105314. if(b->flr){
  105315. for(i=0;i<ci->floors;i++)
  105316. _floor_P[ci->floor_type[i]]->
  105317. free_look(b->flr[i]);
  105318. _ogg_free(b->flr);
  105319. }
  105320. if(b->residue){
  105321. for(i=0;i<ci->residues;i++)
  105322. _residue_P[ci->residue_type[i]]->
  105323. free_look(b->residue[i]);
  105324. _ogg_free(b->residue);
  105325. }
  105326. if(b->psy){
  105327. for(i=0;i<ci->psys;i++)
  105328. _vp_psy_clear(b->psy+i);
  105329. _ogg_free(b->psy);
  105330. }
  105331. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  105332. vorbis_bitrate_clear(&b->bms);
  105333. drft_clear(&b->fft_look[0]);
  105334. drft_clear(&b->fft_look[1]);
  105335. }
  105336. if(v->pcm){
  105337. for(i=0;i<vi->channels;i++)
  105338. if(v->pcm[i])_ogg_free(v->pcm[i]);
  105339. _ogg_free(v->pcm);
  105340. if(v->pcmret)_ogg_free(v->pcmret);
  105341. }
  105342. if(b){
  105343. /* free header, header1, header2 */
  105344. if(b->header)_ogg_free(b->header);
  105345. if(b->header1)_ogg_free(b->header1);
  105346. if(b->header2)_ogg_free(b->header2);
  105347. _ogg_free(b);
  105348. }
  105349. memset(v,0,sizeof(*v));
  105350. }
  105351. }
  105352. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  105353. int i;
  105354. vorbis_info *vi=v->vi;
  105355. private_state *b=(private_state*)v->backend_state;
  105356. /* free header, header1, header2 */
  105357. if(b->header)_ogg_free(b->header);b->header=NULL;
  105358. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  105359. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  105360. /* Do we have enough storage space for the requested buffer? If not,
  105361. expand the PCM (and envelope) storage */
  105362. if(v->pcm_current+vals>=v->pcm_storage){
  105363. v->pcm_storage=v->pcm_current+vals*2;
  105364. for(i=0;i<vi->channels;i++){
  105365. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  105366. }
  105367. }
  105368. for(i=0;i<vi->channels;i++)
  105369. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  105370. return(v->pcmret);
  105371. }
  105372. static void _preextrapolate_helper(vorbis_dsp_state *v){
  105373. int i;
  105374. int order=32;
  105375. float *lpc=(float*)alloca(order*sizeof(*lpc));
  105376. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  105377. long j;
  105378. v->preextrapolate=1;
  105379. if(v->pcm_current-v->centerW>order*2){ /* safety */
  105380. for(i=0;i<v->vi->channels;i++){
  105381. /* need to run the extrapolation in reverse! */
  105382. for(j=0;j<v->pcm_current;j++)
  105383. work[j]=v->pcm[i][v->pcm_current-j-1];
  105384. /* prime as above */
  105385. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  105386. /* run the predictor filter */
  105387. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  105388. order,
  105389. work+v->pcm_current-v->centerW,
  105390. v->centerW);
  105391. for(j=0;j<v->pcm_current;j++)
  105392. v->pcm[i][v->pcm_current-j-1]=work[j];
  105393. }
  105394. }
  105395. }
  105396. /* call with val<=0 to set eof */
  105397. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  105398. vorbis_info *vi=v->vi;
  105399. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  105400. if(vals<=0){
  105401. int order=32;
  105402. int i;
  105403. float *lpc=(float*) alloca(order*sizeof(*lpc));
  105404. /* if it wasn't done earlier (very short sample) */
  105405. if(!v->preextrapolate)
  105406. _preextrapolate_helper(v);
  105407. /* We're encoding the end of the stream. Just make sure we have
  105408. [at least] a few full blocks of zeroes at the end. */
  105409. /* actually, we don't want zeroes; that could drop a large
  105410. amplitude off a cliff, creating spread spectrum noise that will
  105411. suck to encode. Extrapolate for the sake of cleanliness. */
  105412. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  105413. v->eofflag=v->pcm_current;
  105414. v->pcm_current+=ci->blocksizes[1]*3;
  105415. for(i=0;i<vi->channels;i++){
  105416. if(v->eofflag>order*2){
  105417. /* extrapolate with LPC to fill in */
  105418. long n;
  105419. /* make a predictor filter */
  105420. n=v->eofflag;
  105421. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  105422. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  105423. /* run the predictor filter */
  105424. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  105425. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  105426. }else{
  105427. /* not enough data to extrapolate (unlikely to happen due to
  105428. guarding the overlap, but bulletproof in case that
  105429. assumtion goes away). zeroes will do. */
  105430. memset(v->pcm[i]+v->eofflag,0,
  105431. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  105432. }
  105433. }
  105434. }else{
  105435. if(v->pcm_current+vals>v->pcm_storage)
  105436. return(OV_EINVAL);
  105437. v->pcm_current+=vals;
  105438. /* we may want to reverse extrapolate the beginning of a stream
  105439. too... in case we're beginning on a cliff! */
  105440. /* clumsy, but simple. It only runs once, so simple is good. */
  105441. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  105442. _preextrapolate_helper(v);
  105443. }
  105444. return(0);
  105445. }
  105446. /* do the deltas, envelope shaping, pre-echo and determine the size of
  105447. the next block on which to continue analysis */
  105448. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  105449. int i;
  105450. vorbis_info *vi=v->vi;
  105451. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  105452. private_state *b=(private_state*)v->backend_state;
  105453. vorbis_look_psy_global *g=b->psy_g_look;
  105454. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  105455. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  105456. /* check to see if we're started... */
  105457. if(!v->preextrapolate)return(0);
  105458. /* check to see if we're done... */
  105459. if(v->eofflag==-1)return(0);
  105460. /* By our invariant, we have lW, W and centerW set. Search for
  105461. the next boundary so we can determine nW (the next window size)
  105462. which lets us compute the shape of the current block's window */
  105463. /* we do an envelope search even on a single blocksize; we may still
  105464. be throwing more bits at impulses, and envelope search handles
  105465. marking impulses too. */
  105466. {
  105467. long bp=_ve_envelope_search(v);
  105468. if(bp==-1){
  105469. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  105470. full long block */
  105471. v->nW=0;
  105472. }else{
  105473. if(ci->blocksizes[0]==ci->blocksizes[1])
  105474. v->nW=0;
  105475. else
  105476. v->nW=bp;
  105477. }
  105478. }
  105479. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  105480. {
  105481. /* center of next block + next block maximum right side. */
  105482. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  105483. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  105484. although this check is
  105485. less strict that the
  105486. _ve_envelope_search,
  105487. the search is not run
  105488. if we only use one
  105489. block size */
  105490. }
  105491. /* fill in the block. Note that for a short window, lW and nW are *short*
  105492. regardless of actual settings in the stream */
  105493. _vorbis_block_ripcord(vb);
  105494. vb->lW=v->lW;
  105495. vb->W=v->W;
  105496. vb->nW=v->nW;
  105497. if(v->W){
  105498. if(!v->lW || !v->nW){
  105499. vbi->blocktype=BLOCKTYPE_TRANSITION;
  105500. /*fprintf(stderr,"-");*/
  105501. }else{
  105502. vbi->blocktype=BLOCKTYPE_LONG;
  105503. /*fprintf(stderr,"_");*/
  105504. }
  105505. }else{
  105506. if(_ve_envelope_mark(v)){
  105507. vbi->blocktype=BLOCKTYPE_IMPULSE;
  105508. /*fprintf(stderr,"|");*/
  105509. }else{
  105510. vbi->blocktype=BLOCKTYPE_PADDING;
  105511. /*fprintf(stderr,".");*/
  105512. }
  105513. }
  105514. vb->vd=v;
  105515. vb->sequence=v->sequence++;
  105516. vb->granulepos=v->granulepos;
  105517. vb->pcmend=ci->blocksizes[v->W];
  105518. /* copy the vectors; this uses the local storage in vb */
  105519. /* this tracks 'strongest peak' for later psychoacoustics */
  105520. /* moved to the global psy state; clean this mess up */
  105521. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  105522. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  105523. vbi->ampmax=g->ampmax;
  105524. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  105525. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  105526. for(i=0;i<vi->channels;i++){
  105527. vbi->pcmdelay[i]=
  105528. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  105529. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  105530. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  105531. /* before we added the delay
  105532. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  105533. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  105534. */
  105535. }
  105536. /* handle eof detection: eof==0 means that we've not yet received EOF
  105537. eof>0 marks the last 'real' sample in pcm[]
  105538. eof<0 'no more to do'; doesn't get here */
  105539. if(v->eofflag){
  105540. if(v->centerW>=v->eofflag){
  105541. v->eofflag=-1;
  105542. vb->eofflag=1;
  105543. return(1);
  105544. }
  105545. }
  105546. /* advance storage vectors and clean up */
  105547. {
  105548. int new_centerNext=ci->blocksizes[1]/2;
  105549. int movementW=centerNext-new_centerNext;
  105550. if(movementW>0){
  105551. _ve_envelope_shift(b->ve,movementW);
  105552. v->pcm_current-=movementW;
  105553. for(i=0;i<vi->channels;i++)
  105554. memmove(v->pcm[i],v->pcm[i]+movementW,
  105555. v->pcm_current*sizeof(*v->pcm[i]));
  105556. v->lW=v->W;
  105557. v->W=v->nW;
  105558. v->centerW=new_centerNext;
  105559. if(v->eofflag){
  105560. v->eofflag-=movementW;
  105561. if(v->eofflag<=0)v->eofflag=-1;
  105562. /* do not add padding to end of stream! */
  105563. if(v->centerW>=v->eofflag){
  105564. v->granulepos+=movementW-(v->centerW-v->eofflag);
  105565. }else{
  105566. v->granulepos+=movementW;
  105567. }
  105568. }else{
  105569. v->granulepos+=movementW;
  105570. }
  105571. }
  105572. }
  105573. /* done */
  105574. return(1);
  105575. }
  105576. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  105577. vorbis_info *vi=v->vi;
  105578. codec_setup_info *ci;
  105579. int hs;
  105580. if(!v->backend_state)return -1;
  105581. if(!vi)return -1;
  105582. ci=(codec_setup_info*) vi->codec_setup;
  105583. if(!ci)return -1;
  105584. hs=ci->halfrate_flag;
  105585. v->centerW=ci->blocksizes[1]>>(hs+1);
  105586. v->pcm_current=v->centerW>>hs;
  105587. v->pcm_returned=-1;
  105588. v->granulepos=-1;
  105589. v->sequence=-1;
  105590. v->eofflag=0;
  105591. ((private_state *)(v->backend_state))->sample_count=-1;
  105592. return(0);
  105593. }
  105594. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  105595. if(_vds_shared_init(v,vi,0)) return 1;
  105596. vorbis_synthesis_restart(v);
  105597. return 0;
  105598. }
  105599. /* Unlike in analysis, the window is only partially applied for each
  105600. block. The time domain envelope is not yet handled at the point of
  105601. calling (as it relies on the previous block). */
  105602. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  105603. vorbis_info *vi=v->vi;
  105604. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  105605. private_state *b=(private_state*)v->backend_state;
  105606. int hs=ci->halfrate_flag;
  105607. int i,j;
  105608. if(!vb)return(OV_EINVAL);
  105609. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  105610. v->lW=v->W;
  105611. v->W=vb->W;
  105612. v->nW=-1;
  105613. if((v->sequence==-1)||
  105614. (v->sequence+1 != vb->sequence)){
  105615. v->granulepos=-1; /* out of sequence; lose count */
  105616. b->sample_count=-1;
  105617. }
  105618. v->sequence=vb->sequence;
  105619. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  105620. was called on block */
  105621. int n=ci->blocksizes[v->W]>>(hs+1);
  105622. int n0=ci->blocksizes[0]>>(hs+1);
  105623. int n1=ci->blocksizes[1]>>(hs+1);
  105624. int thisCenter;
  105625. int prevCenter;
  105626. v->glue_bits+=vb->glue_bits;
  105627. v->time_bits+=vb->time_bits;
  105628. v->floor_bits+=vb->floor_bits;
  105629. v->res_bits+=vb->res_bits;
  105630. if(v->centerW){
  105631. thisCenter=n1;
  105632. prevCenter=0;
  105633. }else{
  105634. thisCenter=0;
  105635. prevCenter=n1;
  105636. }
  105637. /* v->pcm is now used like a two-stage double buffer. We don't want
  105638. to have to constantly shift *or* adjust memory usage. Don't
  105639. accept a new block until the old is shifted out */
  105640. for(j=0;j<vi->channels;j++){
  105641. /* the overlap/add section */
  105642. if(v->lW){
  105643. if(v->W){
  105644. /* large/large */
  105645. float *w=_vorbis_window_get(b->window[1]-hs);
  105646. float *pcm=v->pcm[j]+prevCenter;
  105647. float *p=vb->pcm[j];
  105648. for(i=0;i<n1;i++)
  105649. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  105650. }else{
  105651. /* large/small */
  105652. float *w=_vorbis_window_get(b->window[0]-hs);
  105653. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  105654. float *p=vb->pcm[j];
  105655. for(i=0;i<n0;i++)
  105656. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  105657. }
  105658. }else{
  105659. if(v->W){
  105660. /* small/large */
  105661. float *w=_vorbis_window_get(b->window[0]-hs);
  105662. float *pcm=v->pcm[j]+prevCenter;
  105663. float *p=vb->pcm[j]+n1/2-n0/2;
  105664. for(i=0;i<n0;i++)
  105665. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  105666. for(;i<n1/2+n0/2;i++)
  105667. pcm[i]=p[i];
  105668. }else{
  105669. /* small/small */
  105670. float *w=_vorbis_window_get(b->window[0]-hs);
  105671. float *pcm=v->pcm[j]+prevCenter;
  105672. float *p=vb->pcm[j];
  105673. for(i=0;i<n0;i++)
  105674. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  105675. }
  105676. }
  105677. /* the copy section */
  105678. {
  105679. float *pcm=v->pcm[j]+thisCenter;
  105680. float *p=vb->pcm[j]+n;
  105681. for(i=0;i<n;i++)
  105682. pcm[i]=p[i];
  105683. }
  105684. }
  105685. if(v->centerW)
  105686. v->centerW=0;
  105687. else
  105688. v->centerW=n1;
  105689. /* deal with initial packet state; we do this using the explicit
  105690. pcm_returned==-1 flag otherwise we're sensitive to first block
  105691. being short or long */
  105692. if(v->pcm_returned==-1){
  105693. v->pcm_returned=thisCenter;
  105694. v->pcm_current=thisCenter;
  105695. }else{
  105696. v->pcm_returned=prevCenter;
  105697. v->pcm_current=prevCenter+
  105698. ((ci->blocksizes[v->lW]/4+
  105699. ci->blocksizes[v->W]/4)>>hs);
  105700. }
  105701. }
  105702. /* track the frame number... This is for convenience, but also
  105703. making sure our last packet doesn't end with added padding. If
  105704. the last packet is partial, the number of samples we'll have to
  105705. return will be past the vb->granulepos.
  105706. This is not foolproof! It will be confused if we begin
  105707. decoding at the last page after a seek or hole. In that case,
  105708. we don't have a starting point to judge where the last frame
  105709. is. For this reason, vorbisfile will always try to make sure
  105710. it reads the last two marked pages in proper sequence */
  105711. if(b->sample_count==-1){
  105712. b->sample_count=0;
  105713. }else{
  105714. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  105715. }
  105716. if(v->granulepos==-1){
  105717. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  105718. v->granulepos=vb->granulepos;
  105719. /* is this a short page? */
  105720. if(b->sample_count>v->granulepos){
  105721. /* corner case; if this is both the first and last audio page,
  105722. then spec says the end is cut, not beginning */
  105723. if(vb->eofflag){
  105724. /* trim the end */
  105725. /* no preceeding granulepos; assume we started at zero (we'd
  105726. have to in a short single-page stream) */
  105727. /* granulepos could be -1 due to a seek, but that would result
  105728. in a long count, not short count */
  105729. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  105730. }else{
  105731. /* trim the beginning */
  105732. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  105733. if(v->pcm_returned>v->pcm_current)
  105734. v->pcm_returned=v->pcm_current;
  105735. }
  105736. }
  105737. }
  105738. }else{
  105739. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  105740. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  105741. if(v->granulepos>vb->granulepos){
  105742. long extra=v->granulepos-vb->granulepos;
  105743. if(extra)
  105744. if(vb->eofflag){
  105745. /* partial last frame. Strip the extra samples off */
  105746. v->pcm_current-=extra>>hs;
  105747. } /* else {Shouldn't happen *unless* the bitstream is out of
  105748. spec. Either way, believe the bitstream } */
  105749. } /* else {Shouldn't happen *unless* the bitstream is out of
  105750. spec. Either way, believe the bitstream } */
  105751. v->granulepos=vb->granulepos;
  105752. }
  105753. }
  105754. /* Update, cleanup */
  105755. if(vb->eofflag)v->eofflag=1;
  105756. return(0);
  105757. }
  105758. /* pcm==NULL indicates we just want the pending samples, no more */
  105759. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  105760. vorbis_info *vi=v->vi;
  105761. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  105762. if(pcm){
  105763. int i;
  105764. for(i=0;i<vi->channels;i++)
  105765. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  105766. *pcm=v->pcmret;
  105767. }
  105768. return(v->pcm_current-v->pcm_returned);
  105769. }
  105770. return(0);
  105771. }
  105772. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  105773. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  105774. v->pcm_returned+=n;
  105775. return(0);
  105776. }
  105777. /* intended for use with a specific vorbisfile feature; we want access
  105778. to the [usually synthetic/postextrapolated] buffer and lapping at
  105779. the end of a decode cycle, specifically, a half-short-block worth.
  105780. This funtion works like pcmout above, except it will also expose
  105781. this implicit buffer data not normally decoded. */
  105782. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  105783. vorbis_info *vi=v->vi;
  105784. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  105785. int hs=ci->halfrate_flag;
  105786. int n=ci->blocksizes[v->W]>>(hs+1);
  105787. int n0=ci->blocksizes[0]>>(hs+1);
  105788. int n1=ci->blocksizes[1]>>(hs+1);
  105789. int i,j;
  105790. if(v->pcm_returned<0)return 0;
  105791. /* our returned data ends at pcm_returned; because the synthesis pcm
  105792. buffer is a two-fragment ring, that means our data block may be
  105793. fragmented by buffering, wrapping or a short block not filling
  105794. out a buffer. To simplify things, we unfragment if it's at all
  105795. possibly needed. Otherwise, we'd need to call lapout more than
  105796. once as well as hold additional dsp state. Opt for
  105797. simplicity. */
  105798. /* centerW was advanced by blockin; it would be the center of the
  105799. *next* block */
  105800. if(v->centerW==n1){
  105801. /* the data buffer wraps; swap the halves */
  105802. /* slow, sure, small */
  105803. for(j=0;j<vi->channels;j++){
  105804. float *p=v->pcm[j];
  105805. for(i=0;i<n1;i++){
  105806. float temp=p[i];
  105807. p[i]=p[i+n1];
  105808. p[i+n1]=temp;
  105809. }
  105810. }
  105811. v->pcm_current-=n1;
  105812. v->pcm_returned-=n1;
  105813. v->centerW=0;
  105814. }
  105815. /* solidify buffer into contiguous space */
  105816. if((v->lW^v->W)==1){
  105817. /* long/short or short/long */
  105818. for(j=0;j<vi->channels;j++){
  105819. float *s=v->pcm[j];
  105820. float *d=v->pcm[j]+(n1-n0)/2;
  105821. for(i=(n1+n0)/2-1;i>=0;--i)
  105822. d[i]=s[i];
  105823. }
  105824. v->pcm_returned+=(n1-n0)/2;
  105825. v->pcm_current+=(n1-n0)/2;
  105826. }else{
  105827. if(v->lW==0){
  105828. /* short/short */
  105829. for(j=0;j<vi->channels;j++){
  105830. float *s=v->pcm[j];
  105831. float *d=v->pcm[j]+n1-n0;
  105832. for(i=n0-1;i>=0;--i)
  105833. d[i]=s[i];
  105834. }
  105835. v->pcm_returned+=n1-n0;
  105836. v->pcm_current+=n1-n0;
  105837. }
  105838. }
  105839. if(pcm){
  105840. int i;
  105841. for(i=0;i<vi->channels;i++)
  105842. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  105843. *pcm=v->pcmret;
  105844. }
  105845. return(n1+n-v->pcm_returned);
  105846. }
  105847. float *vorbis_window(vorbis_dsp_state *v,int W){
  105848. vorbis_info *vi=v->vi;
  105849. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  105850. int hs=ci->halfrate_flag;
  105851. private_state *b=(private_state*)v->backend_state;
  105852. if(b->window[W]-1<0)return NULL;
  105853. return _vorbis_window_get(b->window[W]-hs);
  105854. }
  105855. #endif
  105856. /********* End of inlined file: block.c *********/
  105857. /********* Start of inlined file: codebook.c *********/
  105858. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105859. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105860. // tasks..
  105861. #ifdef _MSC_VER
  105862. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105863. #endif
  105864. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105865. #if JUCE_USE_OGGVORBIS
  105866. #include <stdlib.h>
  105867. #include <string.h>
  105868. #include <math.h>
  105869. /* packs the given codebook into the bitstream **************************/
  105870. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  105871. long i,j;
  105872. int ordered=0;
  105873. /* first the basic parameters */
  105874. oggpack_write(opb,0x564342,24);
  105875. oggpack_write(opb,c->dim,16);
  105876. oggpack_write(opb,c->entries,24);
  105877. /* pack the codewords. There are two packings; length ordered and
  105878. length random. Decide between the two now. */
  105879. for(i=1;i<c->entries;i++)
  105880. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  105881. if(i==c->entries)ordered=1;
  105882. if(ordered){
  105883. /* length ordered. We only need to say how many codewords of
  105884. each length. The actual codewords are generated
  105885. deterministically */
  105886. long count=0;
  105887. oggpack_write(opb,1,1); /* ordered */
  105888. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  105889. for(i=1;i<c->entries;i++){
  105890. long thisx=c->lengthlist[i];
  105891. long last=c->lengthlist[i-1];
  105892. if(thisx>last){
  105893. for(j=last;j<thisx;j++){
  105894. oggpack_write(opb,i-count,_ilog(c->entries-count));
  105895. count=i;
  105896. }
  105897. }
  105898. }
  105899. oggpack_write(opb,i-count,_ilog(c->entries-count));
  105900. }else{
  105901. /* length random. Again, we don't code the codeword itself, just
  105902. the length. This time, though, we have to encode each length */
  105903. oggpack_write(opb,0,1); /* unordered */
  105904. /* algortihmic mapping has use for 'unused entries', which we tag
  105905. here. The algorithmic mapping happens as usual, but the unused
  105906. entry has no codeword. */
  105907. for(i=0;i<c->entries;i++)
  105908. if(c->lengthlist[i]==0)break;
  105909. if(i==c->entries){
  105910. oggpack_write(opb,0,1); /* no unused entries */
  105911. for(i=0;i<c->entries;i++)
  105912. oggpack_write(opb,c->lengthlist[i]-1,5);
  105913. }else{
  105914. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  105915. for(i=0;i<c->entries;i++){
  105916. if(c->lengthlist[i]==0){
  105917. oggpack_write(opb,0,1);
  105918. }else{
  105919. oggpack_write(opb,1,1);
  105920. oggpack_write(opb,c->lengthlist[i]-1,5);
  105921. }
  105922. }
  105923. }
  105924. }
  105925. /* is the entry number the desired return value, or do we have a
  105926. mapping? If we have a mapping, what type? */
  105927. oggpack_write(opb,c->maptype,4);
  105928. switch(c->maptype){
  105929. case 0:
  105930. /* no mapping */
  105931. break;
  105932. case 1:case 2:
  105933. /* implicitly populated value mapping */
  105934. /* explicitly populated value mapping */
  105935. if(!c->quantlist){
  105936. /* no quantlist? error */
  105937. return(-1);
  105938. }
  105939. /* values that define the dequantization */
  105940. oggpack_write(opb,c->q_min,32);
  105941. oggpack_write(opb,c->q_delta,32);
  105942. oggpack_write(opb,c->q_quant-1,4);
  105943. oggpack_write(opb,c->q_sequencep,1);
  105944. {
  105945. int quantvals;
  105946. switch(c->maptype){
  105947. case 1:
  105948. /* a single column of (c->entries/c->dim) quantized values for
  105949. building a full value list algorithmically (square lattice) */
  105950. quantvals=_book_maptype1_quantvals(c);
  105951. break;
  105952. case 2:
  105953. /* every value (c->entries*c->dim total) specified explicitly */
  105954. quantvals=c->entries*c->dim;
  105955. break;
  105956. default: /* NOT_REACHABLE */
  105957. quantvals=-1;
  105958. }
  105959. /* quantized values */
  105960. for(i=0;i<quantvals;i++)
  105961. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  105962. }
  105963. break;
  105964. default:
  105965. /* error case; we don't have any other map types now */
  105966. return(-1);
  105967. }
  105968. return(0);
  105969. }
  105970. /* unpacks a codebook from the packet buffer into the codebook struct,
  105971. readies the codebook auxiliary structures for decode *************/
  105972. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  105973. long i,j;
  105974. memset(s,0,sizeof(*s));
  105975. s->allocedp=1;
  105976. /* make sure alignment is correct */
  105977. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  105978. /* first the basic parameters */
  105979. s->dim=oggpack_read(opb,16);
  105980. s->entries=oggpack_read(opb,24);
  105981. if(s->entries==-1)goto _eofout;
  105982. /* codeword ordering.... length ordered or unordered? */
  105983. switch((int)oggpack_read(opb,1)){
  105984. case 0:
  105985. /* unordered */
  105986. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  105987. /* allocated but unused entries? */
  105988. if(oggpack_read(opb,1)){
  105989. /* yes, unused entries */
  105990. for(i=0;i<s->entries;i++){
  105991. if(oggpack_read(opb,1)){
  105992. long num=oggpack_read(opb,5);
  105993. if(num==-1)goto _eofout;
  105994. s->lengthlist[i]=num+1;
  105995. }else
  105996. s->lengthlist[i]=0;
  105997. }
  105998. }else{
  105999. /* all entries used; no tagging */
  106000. for(i=0;i<s->entries;i++){
  106001. long num=oggpack_read(opb,5);
  106002. if(num==-1)goto _eofout;
  106003. s->lengthlist[i]=num+1;
  106004. }
  106005. }
  106006. break;
  106007. case 1:
  106008. /* ordered */
  106009. {
  106010. long length=oggpack_read(opb,5)+1;
  106011. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  106012. for(i=0;i<s->entries;){
  106013. long num=oggpack_read(opb,_ilog(s->entries-i));
  106014. if(num==-1)goto _eofout;
  106015. for(j=0;j<num && i<s->entries;j++,i++)
  106016. s->lengthlist[i]=length;
  106017. length++;
  106018. }
  106019. }
  106020. break;
  106021. default:
  106022. /* EOF */
  106023. return(-1);
  106024. }
  106025. /* Do we have a mapping to unpack? */
  106026. switch((s->maptype=oggpack_read(opb,4))){
  106027. case 0:
  106028. /* no mapping */
  106029. break;
  106030. case 1: case 2:
  106031. /* implicitly populated value mapping */
  106032. /* explicitly populated value mapping */
  106033. s->q_min=oggpack_read(opb,32);
  106034. s->q_delta=oggpack_read(opb,32);
  106035. s->q_quant=oggpack_read(opb,4)+1;
  106036. s->q_sequencep=oggpack_read(opb,1);
  106037. {
  106038. int quantvals=0;
  106039. switch(s->maptype){
  106040. case 1:
  106041. quantvals=_book_maptype1_quantvals(s);
  106042. break;
  106043. case 2:
  106044. quantvals=s->entries*s->dim;
  106045. break;
  106046. }
  106047. /* quantized values */
  106048. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  106049. for(i=0;i<quantvals;i++)
  106050. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  106051. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  106052. }
  106053. break;
  106054. default:
  106055. goto _errout;
  106056. }
  106057. /* all set */
  106058. return(0);
  106059. _errout:
  106060. _eofout:
  106061. vorbis_staticbook_clear(s);
  106062. return(-1);
  106063. }
  106064. /* returns the number of bits ************************************************/
  106065. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  106066. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  106067. return(book->c->lengthlist[a]);
  106068. }
  106069. /* One the encode side, our vector writers are each designed for a
  106070. specific purpose, and the encoder is not flexible without modification:
  106071. The LSP vector coder uses a single stage nearest-match with no
  106072. interleave, so no step and no error return. This is specced by floor0
  106073. and doesn't change.
  106074. Residue0 encoding interleaves, uses multiple stages, and each stage
  106075. peels of a specific amount of resolution from a lattice (thus we want
  106076. to match by threshold, not nearest match). Residue doesn't *have* to
  106077. be encoded that way, but to change it, one will need to add more
  106078. infrastructure on the encode side (decode side is specced and simpler) */
  106079. /* floor0 LSP (single stage, non interleaved, nearest match) */
  106080. /* returns entry number and *modifies a* to the quantization value *****/
  106081. int vorbis_book_errorv(codebook *book,float *a){
  106082. int dim=book->dim,k;
  106083. int best=_best(book,a,1);
  106084. for(k=0;k<dim;k++)
  106085. a[k]=(book->valuelist+best*dim)[k];
  106086. return(best);
  106087. }
  106088. /* returns the number of bits and *modifies a* to the quantization value *****/
  106089. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  106090. int k,dim=book->dim;
  106091. for(k=0;k<dim;k++)
  106092. a[k]=(book->valuelist+best*dim)[k];
  106093. return(vorbis_book_encode(book,best,b));
  106094. }
  106095. /* the 'eliminate the decode tree' optimization actually requires the
  106096. codewords to be MSb first, not LSb. This is an annoying inelegancy
  106097. (and one of the first places where carefully thought out design
  106098. turned out to be wrong; Vorbis II and future Ogg codecs should go
  106099. to an MSb bitpacker), but not actually the huge hit it appears to
  106100. be. The first-stage decode table catches most words so that
  106101. bitreverse is not in the main execution path. */
  106102. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  106103. int read=book->dec_maxlength;
  106104. long lo,hi;
  106105. long lok = oggpack_look(b,book->dec_firsttablen);
  106106. if (lok >= 0) {
  106107. long entry = book->dec_firsttable[lok];
  106108. if(entry&0x80000000UL){
  106109. lo=(entry>>15)&0x7fff;
  106110. hi=book->used_entries-(entry&0x7fff);
  106111. }else{
  106112. oggpack_adv(b, book->dec_codelengths[entry-1]);
  106113. return(entry-1);
  106114. }
  106115. }else{
  106116. lo=0;
  106117. hi=book->used_entries;
  106118. }
  106119. lok = oggpack_look(b, read);
  106120. while(lok<0 && read>1)
  106121. lok = oggpack_look(b, --read);
  106122. if(lok<0)return -1;
  106123. /* bisect search for the codeword in the ordered list */
  106124. {
  106125. ogg_uint32_t testword=bitreverse((ogg_uint32_t)lok);
  106126. while(hi-lo>1){
  106127. long p=(hi-lo)>>1;
  106128. long test=book->codelist[lo+p]>testword;
  106129. lo+=p&(test-1);
  106130. hi-=p&(-test);
  106131. }
  106132. if(book->dec_codelengths[lo]<=read){
  106133. oggpack_adv(b, book->dec_codelengths[lo]);
  106134. return(lo);
  106135. }
  106136. }
  106137. oggpack_adv(b, read);
  106138. return(-1);
  106139. }
  106140. /* Decode side is specced and easier, because we don't need to find
  106141. matches using different criteria; we simply read and map. There are
  106142. two things we need to do 'depending':
  106143. We may need to support interleave. We don't really, but it's
  106144. convenient to do it here rather than rebuild the vector later.
  106145. Cascades may be additive or multiplicitive; this is not inherent in
  106146. the codebook, but set in the code using the codebook. Like
  106147. interleaving, it's easiest to do it here.
  106148. addmul==0 -> declarative (set the value)
  106149. addmul==1 -> additive
  106150. addmul==2 -> multiplicitive */
  106151. /* returns the [original, not compacted] entry number or -1 on eof *********/
  106152. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  106153. long packed_entry=decode_packed_entry_number(book,b);
  106154. if(packed_entry>=0)
  106155. return(book->dec_index[packed_entry]);
  106156. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  106157. return(packed_entry);
  106158. }
  106159. /* returns 0 on OK or -1 on eof *************************************/
  106160. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  106161. int step=n/book->dim;
  106162. long *entry = (long*)alloca(sizeof(*entry)*step);
  106163. float **t = (float**)alloca(sizeof(*t)*step);
  106164. int i,j,o;
  106165. for (i = 0; i < step; i++) {
  106166. entry[i]=decode_packed_entry_number(book,b);
  106167. if(entry[i]==-1)return(-1);
  106168. t[i] = book->valuelist+entry[i]*book->dim;
  106169. }
  106170. for(i=0,o=0;i<book->dim;i++,o+=step)
  106171. for (j=0;j<step;j++)
  106172. a[o+j]+=t[j][i];
  106173. return(0);
  106174. }
  106175. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  106176. int i,j,entry;
  106177. float *t;
  106178. if(book->dim>8){
  106179. for(i=0;i<n;){
  106180. entry = decode_packed_entry_number(book,b);
  106181. if(entry==-1)return(-1);
  106182. t = book->valuelist+entry*book->dim;
  106183. for (j=0;j<book->dim;)
  106184. a[i++]+=t[j++];
  106185. }
  106186. }else{
  106187. for(i=0;i<n;){
  106188. entry = decode_packed_entry_number(book,b);
  106189. if(entry==-1)return(-1);
  106190. t = book->valuelist+entry*book->dim;
  106191. j=0;
  106192. switch((int)book->dim){
  106193. case 8:
  106194. a[i++]+=t[j++];
  106195. case 7:
  106196. a[i++]+=t[j++];
  106197. case 6:
  106198. a[i++]+=t[j++];
  106199. case 5:
  106200. a[i++]+=t[j++];
  106201. case 4:
  106202. a[i++]+=t[j++];
  106203. case 3:
  106204. a[i++]+=t[j++];
  106205. case 2:
  106206. a[i++]+=t[j++];
  106207. case 1:
  106208. a[i++]+=t[j++];
  106209. case 0:
  106210. break;
  106211. }
  106212. }
  106213. }
  106214. return(0);
  106215. }
  106216. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  106217. int i,j,entry;
  106218. float *t;
  106219. for(i=0;i<n;){
  106220. entry = decode_packed_entry_number(book,b);
  106221. if(entry==-1)return(-1);
  106222. t = book->valuelist+entry*book->dim;
  106223. for (j=0;j<book->dim;)
  106224. a[i++]=t[j++];
  106225. }
  106226. return(0);
  106227. }
  106228. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  106229. oggpack_buffer *b,int n){
  106230. long i,j,entry;
  106231. int chptr=0;
  106232. for(i=offset/ch;i<(offset+n)/ch;){
  106233. entry = decode_packed_entry_number(book,b);
  106234. if(entry==-1)return(-1);
  106235. {
  106236. const float *t = book->valuelist+entry*book->dim;
  106237. for (j=0;j<book->dim;j++){
  106238. a[chptr++][i]+=t[j];
  106239. if(chptr==ch){
  106240. chptr=0;
  106241. i++;
  106242. }
  106243. }
  106244. }
  106245. }
  106246. return(0);
  106247. }
  106248. #ifdef _V_SELFTEST
  106249. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  106250. number of vectors through (keeping track of the quantized values),
  106251. and decode using the unpacked book. quantized version of in should
  106252. exactly equal out */
  106253. #include <stdio.h>
  106254. #include "vorbis/book/lsp20_0.vqh"
  106255. #include "vorbis/book/res0a_13.vqh"
  106256. #define TESTSIZE 40
  106257. float test1[TESTSIZE]={
  106258. 0.105939f,
  106259. 0.215373f,
  106260. 0.429117f,
  106261. 0.587974f,
  106262. 0.181173f,
  106263. 0.296583f,
  106264. 0.515707f,
  106265. 0.715261f,
  106266. 0.162327f,
  106267. 0.263834f,
  106268. 0.342876f,
  106269. 0.406025f,
  106270. 0.103571f,
  106271. 0.223561f,
  106272. 0.368513f,
  106273. 0.540313f,
  106274. 0.136672f,
  106275. 0.395882f,
  106276. 0.587183f,
  106277. 0.652476f,
  106278. 0.114338f,
  106279. 0.417300f,
  106280. 0.525486f,
  106281. 0.698679f,
  106282. 0.147492f,
  106283. 0.324481f,
  106284. 0.643089f,
  106285. 0.757582f,
  106286. 0.139556f,
  106287. 0.215795f,
  106288. 0.324559f,
  106289. 0.399387f,
  106290. 0.120236f,
  106291. 0.267420f,
  106292. 0.446940f,
  106293. 0.608760f,
  106294. 0.115587f,
  106295. 0.287234f,
  106296. 0.571081f,
  106297. 0.708603f,
  106298. };
  106299. float test3[TESTSIZE]={
  106300. 0,1,-2,3,4,-5,6,7,8,9,
  106301. 8,-2,7,-1,4,6,8,3,1,-9,
  106302. 10,11,12,13,14,15,26,17,18,19,
  106303. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  106304. static_codebook *testlist[]={&_vq_book_lsp20_0,
  106305. &_vq_book_res0a_13,NULL};
  106306. float *testvec[]={test1,test3};
  106307. int main(){
  106308. oggpack_buffer write;
  106309. oggpack_buffer read;
  106310. long ptr=0,i;
  106311. oggpack_writeinit(&write);
  106312. fprintf(stderr,"Testing codebook abstraction...:\n");
  106313. while(testlist[ptr]){
  106314. codebook c;
  106315. static_codebook s;
  106316. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  106317. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  106318. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  106319. memset(iv,0,sizeof(*iv)*TESTSIZE);
  106320. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  106321. /* pack the codebook, write the testvector */
  106322. oggpack_reset(&write);
  106323. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  106324. we can write */
  106325. vorbis_staticbook_pack(testlist[ptr],&write);
  106326. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  106327. for(i=0;i<TESTSIZE;i+=c.dim){
  106328. int best=_best(&c,qv+i,1);
  106329. vorbis_book_encodev(&c,best,qv+i,&write);
  106330. }
  106331. vorbis_book_clear(&c);
  106332. fprintf(stderr,"OK.\n");
  106333. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  106334. /* transfer the write data to a read buffer and unpack/read */
  106335. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  106336. if(vorbis_staticbook_unpack(&read,&s)){
  106337. fprintf(stderr,"Error unpacking codebook.\n");
  106338. exit(1);
  106339. }
  106340. if(vorbis_book_init_decode(&c,&s)){
  106341. fprintf(stderr,"Error initializing codebook.\n");
  106342. exit(1);
  106343. }
  106344. for(i=0;i<TESTSIZE;i+=c.dim)
  106345. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  106346. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  106347. exit(1);
  106348. }
  106349. for(i=0;i<TESTSIZE;i++)
  106350. if(fabs(qv[i]-iv[i])>.000001){
  106351. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  106352. iv[i],qv[i],i);
  106353. exit(1);
  106354. }
  106355. fprintf(stderr,"OK\n");
  106356. ptr++;
  106357. }
  106358. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  106359. exit(0);
  106360. }
  106361. #endif
  106362. #endif
  106363. /********* End of inlined file: codebook.c *********/
  106364. /********* Start of inlined file: envelope.c *********/
  106365. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106366. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106367. // tasks..
  106368. #ifdef _MSC_VER
  106369. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106370. #endif
  106371. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106372. #if JUCE_USE_OGGVORBIS
  106373. #include <stdlib.h>
  106374. #include <string.h>
  106375. #include <stdio.h>
  106376. #include <math.h>
  106377. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  106378. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106379. vorbis_info_psy_global *gi=&ci->psy_g_param;
  106380. int ch=vi->channels;
  106381. int i,j;
  106382. int n=e->winlength=128;
  106383. e->searchstep=64; /* not random */
  106384. e->minenergy=gi->preecho_minenergy;
  106385. e->ch=ch;
  106386. e->storage=128;
  106387. e->cursor=ci->blocksizes[1]/2;
  106388. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  106389. mdct_init(&e->mdct,n);
  106390. for(i=0;i<n;i++){
  106391. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  106392. e->mdct_win[i]*=e->mdct_win[i];
  106393. }
  106394. /* magic follows */
  106395. e->band[0].begin=2; e->band[0].end=4;
  106396. e->band[1].begin=4; e->band[1].end=5;
  106397. e->band[2].begin=6; e->band[2].end=6;
  106398. e->band[3].begin=9; e->band[3].end=8;
  106399. e->band[4].begin=13; e->band[4].end=8;
  106400. e->band[5].begin=17; e->band[5].end=8;
  106401. e->band[6].begin=22; e->band[6].end=8;
  106402. for(j=0;j<VE_BANDS;j++){
  106403. n=e->band[j].end;
  106404. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  106405. for(i=0;i<n;i++){
  106406. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  106407. e->band[j].total+=e->band[j].window[i];
  106408. }
  106409. e->band[j].total=1./e->band[j].total;
  106410. }
  106411. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  106412. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  106413. }
  106414. void _ve_envelope_clear(envelope_lookup *e){
  106415. int i;
  106416. mdct_clear(&e->mdct);
  106417. for(i=0;i<VE_BANDS;i++)
  106418. _ogg_free(e->band[i].window);
  106419. _ogg_free(e->mdct_win);
  106420. _ogg_free(e->filter);
  106421. _ogg_free(e->mark);
  106422. memset(e,0,sizeof(*e));
  106423. }
  106424. /* fairly straight threshhold-by-band based until we find something
  106425. that works better and isn't patented. */
  106426. static int _ve_amp(envelope_lookup *ve,
  106427. vorbis_info_psy_global *gi,
  106428. float *data,
  106429. envelope_band *bands,
  106430. envelope_filter_state *filters,
  106431. long pos){
  106432. long n=ve->winlength;
  106433. int ret=0;
  106434. long i,j;
  106435. float decay;
  106436. /* we want to have a 'minimum bar' for energy, else we're just
  106437. basing blocks on quantization noise that outweighs the signal
  106438. itself (for low power signals) */
  106439. float minV=ve->minenergy;
  106440. float *vec=(float*) alloca(n*sizeof(*vec));
  106441. /* stretch is used to gradually lengthen the number of windows
  106442. considered prevoius-to-potential-trigger */
  106443. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  106444. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  106445. if(penalty<0.f)penalty=0.f;
  106446. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  106447. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  106448. totalshift+pos*ve->searchstep);*/
  106449. /* window and transform */
  106450. for(i=0;i<n;i++)
  106451. vec[i]=data[i]*ve->mdct_win[i];
  106452. mdct_forward(&ve->mdct,vec,vec);
  106453. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  106454. /* near-DC spreading function; this has nothing to do with
  106455. psychoacoustics, just sidelobe leakage and window size */
  106456. {
  106457. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  106458. int ptr=filters->nearptr;
  106459. /* the accumulation is regularly refreshed from scratch to avoid
  106460. floating point creep */
  106461. if(ptr==0){
  106462. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  106463. filters->nearDC_partialacc=temp;
  106464. }else{
  106465. decay=filters->nearDC_acc+=temp;
  106466. filters->nearDC_partialacc+=temp;
  106467. }
  106468. filters->nearDC_acc-=filters->nearDC[ptr];
  106469. filters->nearDC[ptr]=temp;
  106470. decay*=(1./(VE_NEARDC+1));
  106471. filters->nearptr++;
  106472. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  106473. decay=todB(&decay)*.5-15.f;
  106474. }
  106475. /* perform spreading and limiting, also smooth the spectrum. yes,
  106476. the MDCT results in all real coefficients, but it still *behaves*
  106477. like real/imaginary pairs */
  106478. for(i=0;i<n/2;i+=2){
  106479. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  106480. val=todB(&val)*.5f;
  106481. if(val<decay)val=decay;
  106482. if(val<minV)val=minV;
  106483. vec[i>>1]=val;
  106484. decay-=8.;
  106485. }
  106486. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  106487. /* perform preecho/postecho triggering by band */
  106488. for(j=0;j<VE_BANDS;j++){
  106489. float acc=0.;
  106490. float valmax,valmin;
  106491. /* accumulate amplitude */
  106492. for(i=0;i<bands[j].end;i++)
  106493. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  106494. acc*=bands[j].total;
  106495. /* convert amplitude to delta */
  106496. {
  106497. int p,thisx=filters[j].ampptr;
  106498. float postmax,postmin,premax=-99999.f,premin=99999.f;
  106499. p=thisx;
  106500. p--;
  106501. if(p<0)p+=VE_AMP;
  106502. postmax=max(acc,filters[j].ampbuf[p]);
  106503. postmin=min(acc,filters[j].ampbuf[p]);
  106504. for(i=0;i<stretch;i++){
  106505. p--;
  106506. if(p<0)p+=VE_AMP;
  106507. premax=max(premax,filters[j].ampbuf[p]);
  106508. premin=min(premin,filters[j].ampbuf[p]);
  106509. }
  106510. valmin=postmin-premin;
  106511. valmax=postmax-premax;
  106512. /*filters[j].markers[pos]=valmax;*/
  106513. filters[j].ampbuf[thisx]=acc;
  106514. filters[j].ampptr++;
  106515. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  106516. }
  106517. /* look at min/max, decide trigger */
  106518. if(valmax>gi->preecho_thresh[j]+penalty){
  106519. ret|=1;
  106520. ret|=4;
  106521. }
  106522. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  106523. }
  106524. return(ret);
  106525. }
  106526. #if 0
  106527. static int seq=0;
  106528. static ogg_int64_t totalshift=-1024;
  106529. #endif
  106530. long _ve_envelope_search(vorbis_dsp_state *v){
  106531. vorbis_info *vi=v->vi;
  106532. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  106533. vorbis_info_psy_global *gi=&ci->psy_g_param;
  106534. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  106535. long i,j;
  106536. int first=ve->current/ve->searchstep;
  106537. int last=v->pcm_current/ve->searchstep-VE_WIN;
  106538. if(first<0)first=0;
  106539. /* make sure we have enough storage to match the PCM */
  106540. if(last+VE_WIN+VE_POST>ve->storage){
  106541. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  106542. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  106543. }
  106544. for(j=first;j<last;j++){
  106545. int ret=0;
  106546. ve->stretch++;
  106547. if(ve->stretch>VE_MAXSTRETCH*2)
  106548. ve->stretch=VE_MAXSTRETCH*2;
  106549. for(i=0;i<ve->ch;i++){
  106550. float *pcm=v->pcm[i]+ve->searchstep*(j);
  106551. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  106552. }
  106553. ve->mark[j+VE_POST]=0;
  106554. if(ret&1){
  106555. ve->mark[j]=1;
  106556. ve->mark[j+1]=1;
  106557. }
  106558. if(ret&2){
  106559. ve->mark[j]=1;
  106560. if(j>0)ve->mark[j-1]=1;
  106561. }
  106562. if(ret&4)ve->stretch=-1;
  106563. }
  106564. ve->current=last*ve->searchstep;
  106565. {
  106566. long centerW=v->centerW;
  106567. long testW=
  106568. centerW+
  106569. ci->blocksizes[v->W]/4+
  106570. ci->blocksizes[1]/2+
  106571. ci->blocksizes[0]/4;
  106572. j=ve->cursor;
  106573. while(j<ve->current-(ve->searchstep)){/* account for postecho
  106574. working back one window */
  106575. if(j>=testW)return(1);
  106576. ve->cursor=j;
  106577. if(ve->mark[j/ve->searchstep]){
  106578. if(j>centerW){
  106579. #if 0
  106580. if(j>ve->curmark){
  106581. float *marker=alloca(v->pcm_current*sizeof(*marker));
  106582. int l,m;
  106583. memset(marker,0,sizeof(*marker)*v->pcm_current);
  106584. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  106585. seq,
  106586. (totalshift+ve->cursor)/44100.,
  106587. (totalshift+j)/44100.);
  106588. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  106589. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  106590. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  106591. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  106592. for(m=0;m<VE_BANDS;m++){
  106593. char buf[80];
  106594. sprintf(buf,"delL%d",m);
  106595. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  106596. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  106597. }
  106598. for(m=0;m<VE_BANDS;m++){
  106599. char buf[80];
  106600. sprintf(buf,"delR%d",m);
  106601. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  106602. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  106603. }
  106604. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  106605. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  106606. seq++;
  106607. }
  106608. #endif
  106609. ve->curmark=j;
  106610. if(j>=testW)return(1);
  106611. return(0);
  106612. }
  106613. }
  106614. j+=ve->searchstep;
  106615. }
  106616. }
  106617. return(-1);
  106618. }
  106619. int _ve_envelope_mark(vorbis_dsp_state *v){
  106620. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  106621. vorbis_info *vi=v->vi;
  106622. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106623. long centerW=v->centerW;
  106624. long beginW=centerW-ci->blocksizes[v->W]/4;
  106625. long endW=centerW+ci->blocksizes[v->W]/4;
  106626. if(v->W){
  106627. beginW-=ci->blocksizes[v->lW]/4;
  106628. endW+=ci->blocksizes[v->nW]/4;
  106629. }else{
  106630. beginW-=ci->blocksizes[0]/4;
  106631. endW+=ci->blocksizes[0]/4;
  106632. }
  106633. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  106634. {
  106635. long first=beginW/ve->searchstep;
  106636. long last=endW/ve->searchstep;
  106637. long i;
  106638. for(i=first;i<last;i++)
  106639. if(ve->mark[i])return(1);
  106640. }
  106641. return(0);
  106642. }
  106643. void _ve_envelope_shift(envelope_lookup *e,long shift){
  106644. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  106645. ahead of ve->current */
  106646. int smallshift=shift/e->searchstep;
  106647. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  106648. #if 0
  106649. for(i=0;i<VE_BANDS*e->ch;i++)
  106650. memmove(e->filter[i].markers,
  106651. e->filter[i].markers+smallshift,
  106652. (1024-smallshift)*sizeof(*(*e->filter).markers));
  106653. totalshift+=shift;
  106654. #endif
  106655. e->current-=shift;
  106656. if(e->curmark>=0)
  106657. e->curmark-=shift;
  106658. e->cursor-=shift;
  106659. }
  106660. #endif
  106661. /********* End of inlined file: envelope.c *********/
  106662. /********* Start of inlined file: floor0.c *********/
  106663. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106664. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106665. // tasks..
  106666. #ifdef _MSC_VER
  106667. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106668. #endif
  106669. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106670. #if JUCE_USE_OGGVORBIS
  106671. #include <stdlib.h>
  106672. #include <string.h>
  106673. #include <math.h>
  106674. /********* Start of inlined file: lsp.h *********/
  106675. #ifndef _V_LSP_H_
  106676. #define _V_LSP_H_
  106677. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  106678. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  106679. float *lsp,int m,
  106680. float amp,float ampoffset);
  106681. #endif
  106682. /********* End of inlined file: lsp.h *********/
  106683. #include <stdio.h>
  106684. typedef struct {
  106685. int ln;
  106686. int m;
  106687. int **linearmap;
  106688. int n[2];
  106689. vorbis_info_floor0 *vi;
  106690. long bits;
  106691. long frames;
  106692. } vorbis_look_floor0;
  106693. /***********************************************/
  106694. static void floor0_free_info(vorbis_info_floor *i){
  106695. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  106696. if(info){
  106697. memset(info,0,sizeof(*info));
  106698. _ogg_free(info);
  106699. }
  106700. }
  106701. static void floor0_free_look(vorbis_look_floor *i){
  106702. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  106703. if(look){
  106704. if(look->linearmap){
  106705. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  106706. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  106707. _ogg_free(look->linearmap);
  106708. }
  106709. memset(look,0,sizeof(*look));
  106710. _ogg_free(look);
  106711. }
  106712. }
  106713. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  106714. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106715. int j;
  106716. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  106717. info->order=oggpack_read(opb,8);
  106718. info->rate=oggpack_read(opb,16);
  106719. info->barkmap=oggpack_read(opb,16);
  106720. info->ampbits=oggpack_read(opb,6);
  106721. info->ampdB=oggpack_read(opb,8);
  106722. info->numbooks=oggpack_read(opb,4)+1;
  106723. if(info->order<1)goto err_out;
  106724. if(info->rate<1)goto err_out;
  106725. if(info->barkmap<1)goto err_out;
  106726. if(info->numbooks<1)goto err_out;
  106727. for(j=0;j<info->numbooks;j++){
  106728. info->books[j]=oggpack_read(opb,8);
  106729. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  106730. }
  106731. return(info);
  106732. err_out:
  106733. floor0_free_info(info);
  106734. return(NULL);
  106735. }
  106736. /* initialize Bark scale and normalization lookups. We could do this
  106737. with static tables, but Vorbis allows a number of possible
  106738. combinations, so it's best to do it computationally.
  106739. The below is authoritative in terms of defining scale mapping.
  106740. Note that the scale depends on the sampling rate as well as the
  106741. linear block and mapping sizes */
  106742. static void floor0_map_lazy_init(vorbis_block *vb,
  106743. vorbis_info_floor *infoX,
  106744. vorbis_look_floor0 *look){
  106745. if(!look->linearmap[vb->W]){
  106746. vorbis_dsp_state *vd=vb->vd;
  106747. vorbis_info *vi=vd->vi;
  106748. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106749. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  106750. int W=vb->W;
  106751. int n=ci->blocksizes[W]/2,j;
  106752. /* we choose a scaling constant so that:
  106753. floor(bark(rate/2-1)*C)=mapped-1
  106754. floor(bark(rate/2)*C)=mapped */
  106755. float scale=look->ln/toBARK(info->rate/2.f);
  106756. /* the mapping from a linear scale to a smaller bark scale is
  106757. straightforward. We do *not* make sure that the linear mapping
  106758. does not skip bark-scale bins; the decoder simply skips them and
  106759. the encoder may do what it wishes in filling them. They're
  106760. necessary in some mapping combinations to keep the scale spacing
  106761. accurate */
  106762. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  106763. for(j=0;j<n;j++){
  106764. int val=floor( toBARK((info->rate/2.f)/n*j)
  106765. *scale); /* bark numbers represent band edges */
  106766. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  106767. look->linearmap[W][j]=val;
  106768. }
  106769. look->linearmap[W][j]=-1;
  106770. look->n[W]=n;
  106771. }
  106772. }
  106773. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  106774. vorbis_info_floor *i){
  106775. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  106776. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  106777. look->m=info->order;
  106778. look->ln=info->barkmap;
  106779. look->vi=info;
  106780. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  106781. return look;
  106782. }
  106783. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  106784. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  106785. vorbis_info_floor0 *info=look->vi;
  106786. int j,k;
  106787. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  106788. if(ampraw>0){ /* also handles the -1 out of data case */
  106789. long maxval=(1<<info->ampbits)-1;
  106790. float amp=(float)ampraw/maxval*info->ampdB;
  106791. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  106792. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  106793. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  106794. codebook *b=ci->fullbooks+info->books[booknum];
  106795. float last=0.f;
  106796. /* the additional b->dim is a guard against any possible stack
  106797. smash; b->dim is provably more than we can overflow the
  106798. vector */
  106799. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  106800. for(j=0;j<look->m;j+=b->dim)
  106801. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  106802. for(j=0;j<look->m;){
  106803. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  106804. last=lsp[j-1];
  106805. }
  106806. lsp[look->m]=amp;
  106807. return(lsp);
  106808. }
  106809. }
  106810. eop:
  106811. return(NULL);
  106812. }
  106813. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  106814. void *memo,float *out){
  106815. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  106816. vorbis_info_floor0 *info=look->vi;
  106817. floor0_map_lazy_init(vb,info,look);
  106818. if(memo){
  106819. float *lsp=(float *)memo;
  106820. float amp=lsp[look->m];
  106821. /* take the coefficients back to a spectral envelope curve */
  106822. vorbis_lsp_to_curve(out,
  106823. look->linearmap[vb->W],
  106824. look->n[vb->W],
  106825. look->ln,
  106826. lsp,look->m,amp,(float)info->ampdB);
  106827. return(1);
  106828. }
  106829. memset(out,0,sizeof(*out)*look->n[vb->W]);
  106830. return(0);
  106831. }
  106832. /* export hooks */
  106833. vorbis_func_floor floor0_exportbundle={
  106834. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  106835. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  106836. };
  106837. #endif
  106838. /********* End of inlined file: floor0.c *********/
  106839. /********* Start of inlined file: floor1.c *********/
  106840. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106841. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106842. // tasks..
  106843. #ifdef _MSC_VER
  106844. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106845. #endif
  106846. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106847. #if JUCE_USE_OGGVORBIS
  106848. #include <stdlib.h>
  106849. #include <string.h>
  106850. #include <math.h>
  106851. #include <stdio.h>
  106852. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  106853. typedef struct {
  106854. int sorted_index[VIF_POSIT+2];
  106855. int forward_index[VIF_POSIT+2];
  106856. int reverse_index[VIF_POSIT+2];
  106857. int hineighbor[VIF_POSIT];
  106858. int loneighbor[VIF_POSIT];
  106859. int posts;
  106860. int n;
  106861. int quant_q;
  106862. vorbis_info_floor1 *vi;
  106863. long phrasebits;
  106864. long postbits;
  106865. long frames;
  106866. } vorbis_look_floor1;
  106867. typedef struct lsfit_acc{
  106868. long x0;
  106869. long x1;
  106870. long xa;
  106871. long ya;
  106872. long x2a;
  106873. long y2a;
  106874. long xya;
  106875. long an;
  106876. } lsfit_acc;
  106877. /***********************************************/
  106878. static void floor1_free_info(vorbis_info_floor *i){
  106879. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  106880. if(info){
  106881. memset(info,0,sizeof(*info));
  106882. _ogg_free(info);
  106883. }
  106884. }
  106885. static void floor1_free_look(vorbis_look_floor *i){
  106886. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  106887. if(look){
  106888. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  106889. (float)look->phrasebits/look->frames,
  106890. (float)look->postbits/look->frames,
  106891. (float)(look->postbits+look->phrasebits)/look->frames);*/
  106892. memset(look,0,sizeof(*look));
  106893. _ogg_free(look);
  106894. }
  106895. }
  106896. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  106897. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  106898. int j,k;
  106899. int count=0;
  106900. int rangebits;
  106901. int maxposit=info->postlist[1];
  106902. int maxclass=-1;
  106903. /* save out partitions */
  106904. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  106905. for(j=0;j<info->partitions;j++){
  106906. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  106907. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  106908. }
  106909. /* save out partition classes */
  106910. for(j=0;j<maxclass+1;j++){
  106911. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  106912. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  106913. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  106914. for(k=0;k<(1<<info->class_subs[j]);k++)
  106915. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  106916. }
  106917. /* save out the post list */
  106918. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  106919. oggpack_write(opb,ilog2(maxposit),4);
  106920. rangebits=ilog2(maxposit);
  106921. for(j=0,k=0;j<info->partitions;j++){
  106922. count+=info->class_dim[info->partitionclass[j]];
  106923. for(;k<count;k++)
  106924. oggpack_write(opb,info->postlist[k+2],rangebits);
  106925. }
  106926. }
  106927. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  106928. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106929. int j,k,count=0,maxclass=-1,rangebits;
  106930. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  106931. /* read partitions */
  106932. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  106933. for(j=0;j<info->partitions;j++){
  106934. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  106935. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  106936. }
  106937. /* read partition classes */
  106938. for(j=0;j<maxclass+1;j++){
  106939. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  106940. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  106941. if(info->class_subs[j]<0)
  106942. goto err_out;
  106943. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  106944. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  106945. goto err_out;
  106946. for(k=0;k<(1<<info->class_subs[j]);k++){
  106947. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  106948. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  106949. goto err_out;
  106950. }
  106951. }
  106952. /* read the post list */
  106953. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  106954. rangebits=oggpack_read(opb,4);
  106955. for(j=0,k=0;j<info->partitions;j++){
  106956. count+=info->class_dim[info->partitionclass[j]];
  106957. for(;k<count;k++){
  106958. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  106959. if(t<0 || t>=(1<<rangebits))
  106960. goto err_out;
  106961. }
  106962. }
  106963. info->postlist[0]=0;
  106964. info->postlist[1]=1<<rangebits;
  106965. return(info);
  106966. err_out:
  106967. floor1_free_info(info);
  106968. return(NULL);
  106969. }
  106970. static int icomp(const void *a,const void *b){
  106971. return(**(int **)a-**(int **)b);
  106972. }
  106973. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  106974. vorbis_info_floor *in){
  106975. int *sortpointer[VIF_POSIT+2];
  106976. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  106977. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  106978. int i,j,n=0;
  106979. look->vi=info;
  106980. look->n=info->postlist[1];
  106981. /* we drop each position value in-between already decoded values,
  106982. and use linear interpolation to predict each new value past the
  106983. edges. The positions are read in the order of the position
  106984. list... we precompute the bounding positions in the lookup. Of
  106985. course, the neighbors can change (if a position is declined), but
  106986. this is an initial mapping */
  106987. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  106988. n+=2;
  106989. look->posts=n;
  106990. /* also store a sorted position index */
  106991. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  106992. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  106993. /* points from sort order back to range number */
  106994. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  106995. /* points from range order to sorted position */
  106996. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  106997. /* we actually need the post values too */
  106998. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  106999. /* quantize values to multiplier spec */
  107000. switch(info->mult){
  107001. case 1: /* 1024 -> 256 */
  107002. look->quant_q=256;
  107003. break;
  107004. case 2: /* 1024 -> 128 */
  107005. look->quant_q=128;
  107006. break;
  107007. case 3: /* 1024 -> 86 */
  107008. look->quant_q=86;
  107009. break;
  107010. case 4: /* 1024 -> 64 */
  107011. look->quant_q=64;
  107012. break;
  107013. }
  107014. /* discover our neighbors for decode where we don't use fit flags
  107015. (that would push the neighbors outward) */
  107016. for(i=0;i<n-2;i++){
  107017. int lo=0;
  107018. int hi=1;
  107019. int lx=0;
  107020. int hx=look->n;
  107021. int currentx=info->postlist[i+2];
  107022. for(j=0;j<i+2;j++){
  107023. int x=info->postlist[j];
  107024. if(x>lx && x<currentx){
  107025. lo=j;
  107026. lx=x;
  107027. }
  107028. if(x<hx && x>currentx){
  107029. hi=j;
  107030. hx=x;
  107031. }
  107032. }
  107033. look->loneighbor[i]=lo;
  107034. look->hineighbor[i]=hi;
  107035. }
  107036. return(look);
  107037. }
  107038. static int render_point(int x0,int x1,int y0,int y1,int x){
  107039. y0&=0x7fff; /* mask off flag */
  107040. y1&=0x7fff;
  107041. {
  107042. int dy=y1-y0;
  107043. int adx=x1-x0;
  107044. int ady=abs(dy);
  107045. int err=ady*(x-x0);
  107046. int off=err/adx;
  107047. if(dy<0)return(y0-off);
  107048. return(y0+off);
  107049. }
  107050. }
  107051. static int vorbis_dBquant(const float *x){
  107052. int i= *x*7.3142857f+1023.5f;
  107053. if(i>1023)return(1023);
  107054. if(i<0)return(0);
  107055. return i;
  107056. }
  107057. static float FLOOR1_fromdB_LOOKUP[256]={
  107058. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  107059. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  107060. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  107061. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  107062. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  107063. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  107064. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  107065. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  107066. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  107067. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  107068. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  107069. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  107070. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  107071. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  107072. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  107073. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  107074. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  107075. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  107076. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  107077. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  107078. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  107079. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  107080. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  107081. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  107082. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  107083. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  107084. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  107085. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  107086. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  107087. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  107088. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  107089. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  107090. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  107091. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  107092. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  107093. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  107094. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  107095. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  107096. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  107097. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  107098. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  107099. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  107100. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  107101. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  107102. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  107103. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  107104. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  107105. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  107106. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  107107. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  107108. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  107109. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  107110. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  107111. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  107112. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  107113. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  107114. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  107115. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  107116. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  107117. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  107118. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  107119. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  107120. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  107121. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  107122. };
  107123. static void render_line(int x0,int x1,int y0,int y1,float *d){
  107124. int dy=y1-y0;
  107125. int adx=x1-x0;
  107126. int ady=abs(dy);
  107127. int base=dy/adx;
  107128. int sy=(dy<0?base-1:base+1);
  107129. int x=x0;
  107130. int y=y0;
  107131. int err=0;
  107132. ady-=abs(base*adx);
  107133. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  107134. while(++x<x1){
  107135. err=err+ady;
  107136. if(err>=adx){
  107137. err-=adx;
  107138. y+=sy;
  107139. }else{
  107140. y+=base;
  107141. }
  107142. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  107143. }
  107144. }
  107145. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  107146. int dy=y1-y0;
  107147. int adx=x1-x0;
  107148. int ady=abs(dy);
  107149. int base=dy/adx;
  107150. int sy=(dy<0?base-1:base+1);
  107151. int x=x0;
  107152. int y=y0;
  107153. int err=0;
  107154. ady-=abs(base*adx);
  107155. d[x]=y;
  107156. while(++x<x1){
  107157. err=err+ady;
  107158. if(err>=adx){
  107159. err-=adx;
  107160. y+=sy;
  107161. }else{
  107162. y+=base;
  107163. }
  107164. d[x]=y;
  107165. }
  107166. }
  107167. /* the floor has already been filtered to only include relevant sections */
  107168. static int accumulate_fit(const float *flr,const float *mdct,
  107169. int x0, int x1,lsfit_acc *a,
  107170. int n,vorbis_info_floor1 *info){
  107171. long i;
  107172. 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;
  107173. memset(a,0,sizeof(*a));
  107174. a->x0=x0;
  107175. a->x1=x1;
  107176. if(x1>=n)x1=n-1;
  107177. for(i=x0;i<=x1;i++){
  107178. int quantized=vorbis_dBquant(flr+i);
  107179. if(quantized){
  107180. if(mdct[i]+info->twofitatten>=flr[i]){
  107181. xa += i;
  107182. ya += quantized;
  107183. x2a += i*i;
  107184. y2a += quantized*quantized;
  107185. xya += i*quantized;
  107186. na++;
  107187. }else{
  107188. xb += i;
  107189. yb += quantized;
  107190. x2b += i*i;
  107191. y2b += quantized*quantized;
  107192. xyb += i*quantized;
  107193. nb++;
  107194. }
  107195. }
  107196. }
  107197. xb+=xa;
  107198. yb+=ya;
  107199. x2b+=x2a;
  107200. y2b+=y2a;
  107201. xyb+=xya;
  107202. nb+=na;
  107203. /* weight toward the actually used frequencies if we meet the threshhold */
  107204. {
  107205. int weight=nb*info->twofitweight/(na+1);
  107206. a->xa=xa*weight+xb;
  107207. a->ya=ya*weight+yb;
  107208. a->x2a=x2a*weight+x2b;
  107209. a->y2a=y2a*weight+y2b;
  107210. a->xya=xya*weight+xyb;
  107211. a->an=na*weight+nb;
  107212. }
  107213. return(na);
  107214. }
  107215. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  107216. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  107217. long x0=a[0].x0;
  107218. long x1=a[fits-1].x1;
  107219. for(i=0;i<fits;i++){
  107220. x+=a[i].xa;
  107221. y+=a[i].ya;
  107222. x2+=a[i].x2a;
  107223. y2+=a[i].y2a;
  107224. xy+=a[i].xya;
  107225. an+=a[i].an;
  107226. }
  107227. if(*y0>=0){
  107228. x+= x0;
  107229. y+= *y0;
  107230. x2+= x0 * x0;
  107231. y2+= *y0 * *y0;
  107232. xy+= *y0 * x0;
  107233. an++;
  107234. }
  107235. if(*y1>=0){
  107236. x+= x1;
  107237. y+= *y1;
  107238. x2+= x1 * x1;
  107239. y2+= *y1 * *y1;
  107240. xy+= *y1 * x1;
  107241. an++;
  107242. }
  107243. if(an){
  107244. /* need 64 bit multiplies, which C doesn't give portably as int */
  107245. double fx=x;
  107246. double fy=y;
  107247. double fx2=x2;
  107248. double fxy=xy;
  107249. double denom=1./(an*fx2-fx*fx);
  107250. double a=(fy*fx2-fxy*fx)*denom;
  107251. double b=(an*fxy-fx*fy)*denom;
  107252. *y0=rint(a+b*x0);
  107253. *y1=rint(a+b*x1);
  107254. /* limit to our range! */
  107255. if(*y0>1023)*y0=1023;
  107256. if(*y1>1023)*y1=1023;
  107257. if(*y0<0)*y0=0;
  107258. if(*y1<0)*y1=0;
  107259. }else{
  107260. *y0=0;
  107261. *y1=0;
  107262. }
  107263. }
  107264. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  107265. long y=0;
  107266. int i;
  107267. for(i=0;i<fits && y==0;i++)
  107268. y+=a[i].ya;
  107269. *y0=*y1=y;
  107270. }*/
  107271. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  107272. const float *mdct,
  107273. vorbis_info_floor1 *info){
  107274. int dy=y1-y0;
  107275. int adx=x1-x0;
  107276. int ady=abs(dy);
  107277. int base=dy/adx;
  107278. int sy=(dy<0?base-1:base+1);
  107279. int x=x0;
  107280. int y=y0;
  107281. int err=0;
  107282. int val=vorbis_dBquant(mask+x);
  107283. int mse=0;
  107284. int n=0;
  107285. ady-=abs(base*adx);
  107286. mse=(y-val);
  107287. mse*=mse;
  107288. n++;
  107289. if(mdct[x]+info->twofitatten>=mask[x]){
  107290. if(y+info->maxover<val)return(1);
  107291. if(y-info->maxunder>val)return(1);
  107292. }
  107293. while(++x<x1){
  107294. err=err+ady;
  107295. if(err>=adx){
  107296. err-=adx;
  107297. y+=sy;
  107298. }else{
  107299. y+=base;
  107300. }
  107301. val=vorbis_dBquant(mask+x);
  107302. mse+=((y-val)*(y-val));
  107303. n++;
  107304. if(mdct[x]+info->twofitatten>=mask[x]){
  107305. if(val){
  107306. if(y+info->maxover<val)return(1);
  107307. if(y-info->maxunder>val)return(1);
  107308. }
  107309. }
  107310. }
  107311. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  107312. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  107313. if(mse/n>info->maxerr)return(1);
  107314. return(0);
  107315. }
  107316. static int post_Y(int *A,int *B,int pos){
  107317. if(A[pos]<0)
  107318. return B[pos];
  107319. if(B[pos]<0)
  107320. return A[pos];
  107321. return (A[pos]+B[pos])>>1;
  107322. }
  107323. int *floor1_fit(vorbis_block *vb,void *look_,
  107324. const float *logmdct, /* in */
  107325. const float *logmask){
  107326. long i,j;
  107327. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  107328. vorbis_info_floor1 *info=look->vi;
  107329. long n=look->n;
  107330. long posts=look->posts;
  107331. long nonzero=0;
  107332. lsfit_acc fits[VIF_POSIT+1];
  107333. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  107334. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  107335. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  107336. int hineighbor[VIF_POSIT+2];
  107337. int *output=NULL;
  107338. int memo[VIF_POSIT+2];
  107339. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  107340. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  107341. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  107342. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  107343. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  107344. /* quantize the relevant floor points and collect them into line fit
  107345. structures (one per minimal division) at the same time */
  107346. if(posts==0){
  107347. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  107348. }else{
  107349. for(i=0;i<posts-1;i++)
  107350. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  107351. look->sorted_index[i+1],fits+i,
  107352. n,info);
  107353. }
  107354. if(nonzero){
  107355. /* start by fitting the implicit base case.... */
  107356. int y0=-200;
  107357. int y1=-200;
  107358. fit_line(fits,posts-1,&y0,&y1);
  107359. fit_valueA[0]=y0;
  107360. fit_valueB[0]=y0;
  107361. fit_valueB[1]=y1;
  107362. fit_valueA[1]=y1;
  107363. /* Non degenerate case */
  107364. /* start progressive splitting. This is a greedy, non-optimal
  107365. algorithm, but simple and close enough to the best
  107366. answer. */
  107367. for(i=2;i<posts;i++){
  107368. int sortpos=look->reverse_index[i];
  107369. int ln=loneighbor[sortpos];
  107370. int hn=hineighbor[sortpos];
  107371. /* eliminate repeat searches of a particular range with a memo */
  107372. if(memo[ln]!=hn){
  107373. /* haven't performed this error search yet */
  107374. int lsortpos=look->reverse_index[ln];
  107375. int hsortpos=look->reverse_index[hn];
  107376. memo[ln]=hn;
  107377. {
  107378. /* A note: we want to bound/minimize *local*, not global, error */
  107379. int lx=info->postlist[ln];
  107380. int hx=info->postlist[hn];
  107381. int ly=post_Y(fit_valueA,fit_valueB,ln);
  107382. int hy=post_Y(fit_valueA,fit_valueB,hn);
  107383. if(ly==-1 || hy==-1){
  107384. exit(1);
  107385. }
  107386. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  107387. /* outside error bounds/begin search area. Split it. */
  107388. int ly0=-200;
  107389. int ly1=-200;
  107390. int hy0=-200;
  107391. int hy1=-200;
  107392. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  107393. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  107394. /* store new edge values */
  107395. fit_valueB[ln]=ly0;
  107396. if(ln==0)fit_valueA[ln]=ly0;
  107397. fit_valueA[i]=ly1;
  107398. fit_valueB[i]=hy0;
  107399. fit_valueA[hn]=hy1;
  107400. if(hn==1)fit_valueB[hn]=hy1;
  107401. if(ly1>=0 || hy0>=0){
  107402. /* store new neighbor values */
  107403. for(j=sortpos-1;j>=0;j--)
  107404. if(hineighbor[j]==hn)
  107405. hineighbor[j]=i;
  107406. else
  107407. break;
  107408. for(j=sortpos+1;j<posts;j++)
  107409. if(loneighbor[j]==ln)
  107410. loneighbor[j]=i;
  107411. else
  107412. break;
  107413. }
  107414. }else{
  107415. fit_valueA[i]=-200;
  107416. fit_valueB[i]=-200;
  107417. }
  107418. }
  107419. }
  107420. }
  107421. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  107422. output[0]=post_Y(fit_valueA,fit_valueB,0);
  107423. output[1]=post_Y(fit_valueA,fit_valueB,1);
  107424. /* fill in posts marked as not using a fit; we will zero
  107425. back out to 'unused' when encoding them so long as curve
  107426. interpolation doesn't force them into use */
  107427. for(i=2;i<posts;i++){
  107428. int ln=look->loneighbor[i-2];
  107429. int hn=look->hineighbor[i-2];
  107430. int x0=info->postlist[ln];
  107431. int x1=info->postlist[hn];
  107432. int y0=output[ln];
  107433. int y1=output[hn];
  107434. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  107435. int vx=post_Y(fit_valueA,fit_valueB,i);
  107436. if(vx>=0 && predicted!=vx){
  107437. output[i]=vx;
  107438. }else{
  107439. output[i]= predicted|0x8000;
  107440. }
  107441. }
  107442. }
  107443. return(output);
  107444. }
  107445. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  107446. int *A,int *B,
  107447. int del){
  107448. long i;
  107449. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  107450. long posts=look->posts;
  107451. int *output=NULL;
  107452. if(A && B){
  107453. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  107454. for(i=0;i<posts;i++){
  107455. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  107456. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  107457. }
  107458. }
  107459. return(output);
  107460. }
  107461. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  107462. void*look_,
  107463. int *post,int *ilogmask){
  107464. long i,j;
  107465. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  107466. vorbis_info_floor1 *info=look->vi;
  107467. long posts=look->posts;
  107468. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  107469. int out[VIF_POSIT+2];
  107470. static_codebook **sbooks=ci->book_param;
  107471. codebook *books=ci->fullbooks;
  107472. static long seq=0;
  107473. /* quantize values to multiplier spec */
  107474. if(post){
  107475. for(i=0;i<posts;i++){
  107476. int val=post[i]&0x7fff;
  107477. switch(info->mult){
  107478. case 1: /* 1024 -> 256 */
  107479. val>>=2;
  107480. break;
  107481. case 2: /* 1024 -> 128 */
  107482. val>>=3;
  107483. break;
  107484. case 3: /* 1024 -> 86 */
  107485. val/=12;
  107486. break;
  107487. case 4: /* 1024 -> 64 */
  107488. val>>=4;
  107489. break;
  107490. }
  107491. post[i]=val | (post[i]&0x8000);
  107492. }
  107493. out[0]=post[0];
  107494. out[1]=post[1];
  107495. /* find prediction values for each post and subtract them */
  107496. for(i=2;i<posts;i++){
  107497. int ln=look->loneighbor[i-2];
  107498. int hn=look->hineighbor[i-2];
  107499. int x0=info->postlist[ln];
  107500. int x1=info->postlist[hn];
  107501. int y0=post[ln];
  107502. int y1=post[hn];
  107503. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  107504. if((post[i]&0x8000) || (predicted==post[i])){
  107505. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  107506. in interpolation */
  107507. out[i]=0;
  107508. }else{
  107509. int headroom=(look->quant_q-predicted<predicted?
  107510. look->quant_q-predicted:predicted);
  107511. int val=post[i]-predicted;
  107512. /* at this point the 'deviation' value is in the range +/- max
  107513. range, but the real, unique range can always be mapped to
  107514. only [0-maxrange). So we want to wrap the deviation into
  107515. this limited range, but do it in the way that least screws
  107516. an essentially gaussian probability distribution. */
  107517. if(val<0)
  107518. if(val<-headroom)
  107519. val=headroom-val-1;
  107520. else
  107521. val=-1-(val<<1);
  107522. else
  107523. if(val>=headroom)
  107524. val= val+headroom;
  107525. else
  107526. val<<=1;
  107527. out[i]=val;
  107528. post[ln]&=0x7fff;
  107529. post[hn]&=0x7fff;
  107530. }
  107531. }
  107532. /* we have everything we need. pack it out */
  107533. /* mark nontrivial floor */
  107534. oggpack_write(opb,1,1);
  107535. /* beginning/end post */
  107536. look->frames++;
  107537. look->postbits+=ilog(look->quant_q-1)*2;
  107538. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  107539. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  107540. /* partition by partition */
  107541. for(i=0,j=2;i<info->partitions;i++){
  107542. int classx=info->partitionclass[i];
  107543. int cdim=info->class_dim[classx];
  107544. int csubbits=info->class_subs[classx];
  107545. int csub=1<<csubbits;
  107546. int bookas[8]={0,0,0,0,0,0,0,0};
  107547. int cval=0;
  107548. int cshift=0;
  107549. int k,l;
  107550. /* generate the partition's first stage cascade value */
  107551. if(csubbits){
  107552. int maxval[8];
  107553. for(k=0;k<csub;k++){
  107554. int booknum=info->class_subbook[classx][k];
  107555. if(booknum<0){
  107556. maxval[k]=1;
  107557. }else{
  107558. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  107559. }
  107560. }
  107561. for(k=0;k<cdim;k++){
  107562. for(l=0;l<csub;l++){
  107563. int val=out[j+k];
  107564. if(val<maxval[l]){
  107565. bookas[k]=l;
  107566. break;
  107567. }
  107568. }
  107569. cval|= bookas[k]<<cshift;
  107570. cshift+=csubbits;
  107571. }
  107572. /* write it */
  107573. look->phrasebits+=
  107574. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  107575. #ifdef TRAIN_FLOOR1
  107576. {
  107577. FILE *of;
  107578. char buffer[80];
  107579. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  107580. vb->pcmend/2,posts-2,class);
  107581. of=fopen(buffer,"a");
  107582. fprintf(of,"%d\n",cval);
  107583. fclose(of);
  107584. }
  107585. #endif
  107586. }
  107587. /* write post values */
  107588. for(k=0;k<cdim;k++){
  107589. int book=info->class_subbook[classx][bookas[k]];
  107590. if(book>=0){
  107591. /* hack to allow training with 'bad' books */
  107592. if(out[j+k]<(books+book)->entries)
  107593. look->postbits+=vorbis_book_encode(books+book,
  107594. out[j+k],opb);
  107595. /*else
  107596. fprintf(stderr,"+!");*/
  107597. #ifdef TRAIN_FLOOR1
  107598. {
  107599. FILE *of;
  107600. char buffer[80];
  107601. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  107602. vb->pcmend/2,posts-2,class,bookas[k]);
  107603. of=fopen(buffer,"a");
  107604. fprintf(of,"%d\n",out[j+k]);
  107605. fclose(of);
  107606. }
  107607. #endif
  107608. }
  107609. }
  107610. j+=cdim;
  107611. }
  107612. {
  107613. /* generate quantized floor equivalent to what we'd unpack in decode */
  107614. /* render the lines */
  107615. int hx=0;
  107616. int lx=0;
  107617. int ly=post[0]*info->mult;
  107618. for(j=1;j<look->posts;j++){
  107619. int current=look->forward_index[j];
  107620. int hy=post[current]&0x7fff;
  107621. if(hy==post[current]){
  107622. hy*=info->mult;
  107623. hx=info->postlist[current];
  107624. render_line0(lx,hx,ly,hy,ilogmask);
  107625. lx=hx;
  107626. ly=hy;
  107627. }
  107628. }
  107629. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  107630. seq++;
  107631. return(1);
  107632. }
  107633. }else{
  107634. oggpack_write(opb,0,1);
  107635. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  107636. seq++;
  107637. return(0);
  107638. }
  107639. }
  107640. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  107641. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  107642. vorbis_info_floor1 *info=look->vi;
  107643. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  107644. int i,j,k;
  107645. codebook *books=ci->fullbooks;
  107646. /* unpack wrapped/predicted values from stream */
  107647. if(oggpack_read(&vb->opb,1)==1){
  107648. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  107649. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  107650. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  107651. /* partition by partition */
  107652. for(i=0,j=2;i<info->partitions;i++){
  107653. int classx=info->partitionclass[i];
  107654. int cdim=info->class_dim[classx];
  107655. int csubbits=info->class_subs[classx];
  107656. int csub=1<<csubbits;
  107657. int cval=0;
  107658. /* decode the partition's first stage cascade value */
  107659. if(csubbits){
  107660. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  107661. if(cval==-1)goto eop;
  107662. }
  107663. for(k=0;k<cdim;k++){
  107664. int book=info->class_subbook[classx][cval&(csub-1)];
  107665. cval>>=csubbits;
  107666. if(book>=0){
  107667. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  107668. goto eop;
  107669. }else{
  107670. fit_value[j+k]=0;
  107671. }
  107672. }
  107673. j+=cdim;
  107674. }
  107675. /* unwrap positive values and reconsitute via linear interpolation */
  107676. for(i=2;i<look->posts;i++){
  107677. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  107678. info->postlist[look->hineighbor[i-2]],
  107679. fit_value[look->loneighbor[i-2]],
  107680. fit_value[look->hineighbor[i-2]],
  107681. info->postlist[i]);
  107682. int hiroom=look->quant_q-predicted;
  107683. int loroom=predicted;
  107684. int room=(hiroom<loroom?hiroom:loroom)<<1;
  107685. int val=fit_value[i];
  107686. if(val){
  107687. if(val>=room){
  107688. if(hiroom>loroom){
  107689. val = val-loroom;
  107690. }else{
  107691. val = -1-(val-hiroom);
  107692. }
  107693. }else{
  107694. if(val&1){
  107695. val= -((val+1)>>1);
  107696. }else{
  107697. val>>=1;
  107698. }
  107699. }
  107700. fit_value[i]=val+predicted;
  107701. fit_value[look->loneighbor[i-2]]&=0x7fff;
  107702. fit_value[look->hineighbor[i-2]]&=0x7fff;
  107703. }else{
  107704. fit_value[i]=predicted|0x8000;
  107705. }
  107706. }
  107707. return(fit_value);
  107708. }
  107709. eop:
  107710. return(NULL);
  107711. }
  107712. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  107713. float *out){
  107714. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  107715. vorbis_info_floor1 *info=look->vi;
  107716. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  107717. int n=ci->blocksizes[vb->W]/2;
  107718. int j;
  107719. if(memo){
  107720. /* render the lines */
  107721. int *fit_value=(int *)memo;
  107722. int hx=0;
  107723. int lx=0;
  107724. int ly=fit_value[0]*info->mult;
  107725. for(j=1;j<look->posts;j++){
  107726. int current=look->forward_index[j];
  107727. int hy=fit_value[current]&0x7fff;
  107728. if(hy==fit_value[current]){
  107729. hy*=info->mult;
  107730. hx=info->postlist[current];
  107731. render_line(lx,hx,ly,hy,out);
  107732. lx=hx;
  107733. ly=hy;
  107734. }
  107735. }
  107736. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  107737. return(1);
  107738. }
  107739. memset(out,0,sizeof(*out)*n);
  107740. return(0);
  107741. }
  107742. /* export hooks */
  107743. vorbis_func_floor floor1_exportbundle={
  107744. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  107745. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  107746. };
  107747. #endif
  107748. /********* End of inlined file: floor1.c *********/
  107749. /********* Start of inlined file: info.c *********/
  107750. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107751. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107752. // tasks..
  107753. #ifdef _MSC_VER
  107754. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107755. #endif
  107756. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107757. #if JUCE_USE_OGGVORBIS
  107758. /* general handling of the header and the vorbis_info structure (and
  107759. substructures) */
  107760. #include <stdlib.h>
  107761. #include <string.h>
  107762. #include <ctype.h>
  107763. static void _v_writestring(oggpack_buffer *o,char *s, int bytes){
  107764. while(bytes--){
  107765. oggpack_write(o,*s++,8);
  107766. }
  107767. }
  107768. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  107769. while(bytes--){
  107770. *buf++=oggpack_read(o,8);
  107771. }
  107772. }
  107773. void vorbis_comment_init(vorbis_comment *vc){
  107774. memset(vc,0,sizeof(*vc));
  107775. }
  107776. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  107777. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  107778. (vc->comments+2)*sizeof(*vc->user_comments));
  107779. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  107780. (vc->comments+2)*sizeof(*vc->comment_lengths));
  107781. vc->comment_lengths[vc->comments]=strlen(comment);
  107782. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  107783. strcpy(vc->user_comments[vc->comments], comment);
  107784. vc->comments++;
  107785. vc->user_comments[vc->comments]=NULL;
  107786. }
  107787. void vorbis_comment_add_tag(vorbis_comment *vc, char *tag, char *contents){
  107788. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  107789. strcpy(comment, tag);
  107790. strcat(comment, "=");
  107791. strcat(comment, contents);
  107792. vorbis_comment_add(vc, comment);
  107793. }
  107794. /* This is more or less the same as strncasecmp - but that doesn't exist
  107795. * everywhere, and this is a fairly trivial function, so we include it */
  107796. static int tagcompare(const char *s1, const char *s2, int n){
  107797. int c=0;
  107798. while(c < n){
  107799. if(toupper(s1[c]) != toupper(s2[c]))
  107800. return !0;
  107801. c++;
  107802. }
  107803. return 0;
  107804. }
  107805. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  107806. long i;
  107807. int found = 0;
  107808. int taglen = strlen(tag)+1; /* +1 for the = we append */
  107809. char *fulltag = (char*)alloca(taglen+ 1);
  107810. strcpy(fulltag, tag);
  107811. strcat(fulltag, "=");
  107812. for(i=0;i<vc->comments;i++){
  107813. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  107814. if(count == found)
  107815. /* We return a pointer to the data, not a copy */
  107816. return vc->user_comments[i] + taglen;
  107817. else
  107818. found++;
  107819. }
  107820. }
  107821. return NULL; /* didn't find anything */
  107822. }
  107823. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  107824. int i,count=0;
  107825. int taglen = strlen(tag)+1; /* +1 for the = we append */
  107826. char *fulltag = (char*)alloca(taglen+1);
  107827. strcpy(fulltag,tag);
  107828. strcat(fulltag, "=");
  107829. for(i=0;i<vc->comments;i++){
  107830. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  107831. count++;
  107832. }
  107833. return count;
  107834. }
  107835. void vorbis_comment_clear(vorbis_comment *vc){
  107836. if(vc){
  107837. long i;
  107838. for(i=0;i<vc->comments;i++)
  107839. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  107840. if(vc->user_comments)_ogg_free(vc->user_comments);
  107841. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  107842. if(vc->vendor)_ogg_free(vc->vendor);
  107843. }
  107844. memset(vc,0,sizeof(*vc));
  107845. }
  107846. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  107847. They may be equal, but short will never ge greater than long */
  107848. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  107849. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  107850. return ci ? ci->blocksizes[zo] : -1;
  107851. }
  107852. /* used by synthesis, which has a full, alloced vi */
  107853. void vorbis_info_init(vorbis_info *vi){
  107854. memset(vi,0,sizeof(*vi));
  107855. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  107856. }
  107857. void vorbis_info_clear(vorbis_info *vi){
  107858. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107859. int i;
  107860. if(ci){
  107861. for(i=0;i<ci->modes;i++)
  107862. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  107863. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  107864. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  107865. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  107866. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  107867. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  107868. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  107869. for(i=0;i<ci->books;i++){
  107870. if(ci->book_param[i]){
  107871. /* knows if the book was not alloced */
  107872. vorbis_staticbook_destroy(ci->book_param[i]);
  107873. }
  107874. if(ci->fullbooks)
  107875. vorbis_book_clear(ci->fullbooks+i);
  107876. }
  107877. if(ci->fullbooks)
  107878. _ogg_free(ci->fullbooks);
  107879. for(i=0;i<ci->psys;i++)
  107880. _vi_psy_free(ci->psy_param[i]);
  107881. _ogg_free(ci);
  107882. }
  107883. memset(vi,0,sizeof(*vi));
  107884. }
  107885. /* Header packing/unpacking ********************************************/
  107886. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  107887. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107888. if(!ci)return(OV_EFAULT);
  107889. vi->version=oggpack_read(opb,32);
  107890. if(vi->version!=0)return(OV_EVERSION);
  107891. vi->channels=oggpack_read(opb,8);
  107892. vi->rate=oggpack_read(opb,32);
  107893. vi->bitrate_upper=oggpack_read(opb,32);
  107894. vi->bitrate_nominal=oggpack_read(opb,32);
  107895. vi->bitrate_lower=oggpack_read(opb,32);
  107896. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  107897. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  107898. if(vi->rate<1)goto err_out;
  107899. if(vi->channels<1)goto err_out;
  107900. if(ci->blocksizes[0]<8)goto err_out;
  107901. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  107902. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  107903. return(0);
  107904. err_out:
  107905. vorbis_info_clear(vi);
  107906. return(OV_EBADHEADER);
  107907. }
  107908. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  107909. int i;
  107910. int vendorlen=oggpack_read(opb,32);
  107911. if(vendorlen<0)goto err_out;
  107912. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  107913. _v_readstring(opb,vc->vendor,vendorlen);
  107914. vc->comments=oggpack_read(opb,32);
  107915. if(vc->comments<0)goto err_out;
  107916. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  107917. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  107918. for(i=0;i<vc->comments;i++){
  107919. int len=oggpack_read(opb,32);
  107920. if(len<0)goto err_out;
  107921. vc->comment_lengths[i]=len;
  107922. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  107923. _v_readstring(opb,vc->user_comments[i],len);
  107924. }
  107925. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  107926. return(0);
  107927. err_out:
  107928. vorbis_comment_clear(vc);
  107929. return(OV_EBADHEADER);
  107930. }
  107931. /* all of the real encoding details are here. The modes, books,
  107932. everything */
  107933. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  107934. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107935. int i;
  107936. if(!ci)return(OV_EFAULT);
  107937. /* codebooks */
  107938. ci->books=oggpack_read(opb,8)+1;
  107939. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  107940. for(i=0;i<ci->books;i++){
  107941. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  107942. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  107943. }
  107944. /* time backend settings; hooks are unused */
  107945. {
  107946. int times=oggpack_read(opb,6)+1;
  107947. for(i=0;i<times;i++){
  107948. int test=oggpack_read(opb,16);
  107949. if(test<0 || test>=VI_TIMEB)goto err_out;
  107950. }
  107951. }
  107952. /* floor backend settings */
  107953. ci->floors=oggpack_read(opb,6)+1;
  107954. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  107955. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  107956. for(i=0;i<ci->floors;i++){
  107957. ci->floor_type[i]=oggpack_read(opb,16);
  107958. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  107959. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  107960. if(!ci->floor_param[i])goto err_out;
  107961. }
  107962. /* residue backend settings */
  107963. ci->residues=oggpack_read(opb,6)+1;
  107964. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  107965. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  107966. for(i=0;i<ci->residues;i++){
  107967. ci->residue_type[i]=oggpack_read(opb,16);
  107968. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  107969. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  107970. if(!ci->residue_param[i])goto err_out;
  107971. }
  107972. /* map backend settings */
  107973. ci->maps=oggpack_read(opb,6)+1;
  107974. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  107975. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  107976. for(i=0;i<ci->maps;i++){
  107977. ci->map_type[i]=oggpack_read(opb,16);
  107978. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  107979. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  107980. if(!ci->map_param[i])goto err_out;
  107981. }
  107982. /* mode settings */
  107983. ci->modes=oggpack_read(opb,6)+1;
  107984. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  107985. for(i=0;i<ci->modes;i++){
  107986. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  107987. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  107988. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  107989. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  107990. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  107991. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  107992. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  107993. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  107994. }
  107995. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  107996. return(0);
  107997. err_out:
  107998. vorbis_info_clear(vi);
  107999. return(OV_EBADHEADER);
  108000. }
  108001. /* The Vorbis header is in three packets; the initial small packet in
  108002. the first page that identifies basic parameters, a second packet
  108003. with bitstream comments and a third packet that holds the
  108004. codebook. */
  108005. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  108006. oggpack_buffer opb;
  108007. if(op){
  108008. oggpack_readinit(&opb,op->packet,op->bytes);
  108009. /* Which of the three types of header is this? */
  108010. /* Also verify header-ness, vorbis */
  108011. {
  108012. char buffer[6];
  108013. int packtype=oggpack_read(&opb,8);
  108014. memset(buffer,0,6);
  108015. _v_readstring(&opb,buffer,6);
  108016. if(memcmp(buffer,"vorbis",6)){
  108017. /* not a vorbis header */
  108018. return(OV_ENOTVORBIS);
  108019. }
  108020. switch(packtype){
  108021. case 0x01: /* least significant *bit* is read first */
  108022. if(!op->b_o_s){
  108023. /* Not the initial packet */
  108024. return(OV_EBADHEADER);
  108025. }
  108026. if(vi->rate!=0){
  108027. /* previously initialized info header */
  108028. return(OV_EBADHEADER);
  108029. }
  108030. return(_vorbis_unpack_info(vi,&opb));
  108031. case 0x03: /* least significant *bit* is read first */
  108032. if(vi->rate==0){
  108033. /* um... we didn't get the initial header */
  108034. return(OV_EBADHEADER);
  108035. }
  108036. return(_vorbis_unpack_comment(vc,&opb));
  108037. case 0x05: /* least significant *bit* is read first */
  108038. if(vi->rate==0 || vc->vendor==NULL){
  108039. /* um... we didn;t get the initial header or comments yet */
  108040. return(OV_EBADHEADER);
  108041. }
  108042. return(_vorbis_unpack_books(vi,&opb));
  108043. default:
  108044. /* Not a valid vorbis header type */
  108045. return(OV_EBADHEADER);
  108046. break;
  108047. }
  108048. }
  108049. }
  108050. return(OV_EBADHEADER);
  108051. }
  108052. /* pack side **********************************************************/
  108053. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  108054. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108055. if(!ci)return(OV_EFAULT);
  108056. /* preamble */
  108057. oggpack_write(opb,0x01,8);
  108058. _v_writestring(opb,"vorbis", 6);
  108059. /* basic information about the stream */
  108060. oggpack_write(opb,0x00,32);
  108061. oggpack_write(opb,vi->channels,8);
  108062. oggpack_write(opb,vi->rate,32);
  108063. oggpack_write(opb,vi->bitrate_upper,32);
  108064. oggpack_write(opb,vi->bitrate_nominal,32);
  108065. oggpack_write(opb,vi->bitrate_lower,32);
  108066. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  108067. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  108068. oggpack_write(opb,1,1);
  108069. return(0);
  108070. }
  108071. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  108072. char temp[]="Xiph.Org libVorbis I 20050304";
  108073. int bytes = strlen(temp);
  108074. /* preamble */
  108075. oggpack_write(opb,0x03,8);
  108076. _v_writestring(opb,"vorbis", 6);
  108077. /* vendor */
  108078. oggpack_write(opb,bytes,32);
  108079. _v_writestring(opb,temp, bytes);
  108080. /* comments */
  108081. oggpack_write(opb,vc->comments,32);
  108082. if(vc->comments){
  108083. int i;
  108084. for(i=0;i<vc->comments;i++){
  108085. if(vc->user_comments[i]){
  108086. oggpack_write(opb,vc->comment_lengths[i],32);
  108087. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  108088. }else{
  108089. oggpack_write(opb,0,32);
  108090. }
  108091. }
  108092. }
  108093. oggpack_write(opb,1,1);
  108094. return(0);
  108095. }
  108096. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  108097. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108098. int i;
  108099. if(!ci)return(OV_EFAULT);
  108100. oggpack_write(opb,0x05,8);
  108101. _v_writestring(opb,"vorbis", 6);
  108102. /* books */
  108103. oggpack_write(opb,ci->books-1,8);
  108104. for(i=0;i<ci->books;i++)
  108105. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  108106. /* times; hook placeholders */
  108107. oggpack_write(opb,0,6);
  108108. oggpack_write(opb,0,16);
  108109. /* floors */
  108110. oggpack_write(opb,ci->floors-1,6);
  108111. for(i=0;i<ci->floors;i++){
  108112. oggpack_write(opb,ci->floor_type[i],16);
  108113. if(_floor_P[ci->floor_type[i]]->pack)
  108114. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  108115. else
  108116. goto err_out;
  108117. }
  108118. /* residues */
  108119. oggpack_write(opb,ci->residues-1,6);
  108120. for(i=0;i<ci->residues;i++){
  108121. oggpack_write(opb,ci->residue_type[i],16);
  108122. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  108123. }
  108124. /* maps */
  108125. oggpack_write(opb,ci->maps-1,6);
  108126. for(i=0;i<ci->maps;i++){
  108127. oggpack_write(opb,ci->map_type[i],16);
  108128. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  108129. }
  108130. /* modes */
  108131. oggpack_write(opb,ci->modes-1,6);
  108132. for(i=0;i<ci->modes;i++){
  108133. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  108134. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  108135. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  108136. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  108137. }
  108138. oggpack_write(opb,1,1);
  108139. return(0);
  108140. err_out:
  108141. return(-1);
  108142. }
  108143. int vorbis_commentheader_out(vorbis_comment *vc,
  108144. ogg_packet *op){
  108145. oggpack_buffer opb;
  108146. oggpack_writeinit(&opb);
  108147. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  108148. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  108149. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  108150. op->bytes=oggpack_bytes(&opb);
  108151. op->b_o_s=0;
  108152. op->e_o_s=0;
  108153. op->granulepos=0;
  108154. op->packetno=1;
  108155. return 0;
  108156. }
  108157. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  108158. vorbis_comment *vc,
  108159. ogg_packet *op,
  108160. ogg_packet *op_comm,
  108161. ogg_packet *op_code){
  108162. int ret=OV_EIMPL;
  108163. vorbis_info *vi=v->vi;
  108164. oggpack_buffer opb;
  108165. private_state *b=(private_state*)v->backend_state;
  108166. if(!b){
  108167. ret=OV_EFAULT;
  108168. goto err_out;
  108169. }
  108170. /* first header packet **********************************************/
  108171. oggpack_writeinit(&opb);
  108172. if(_vorbis_pack_info(&opb,vi))goto err_out;
  108173. /* build the packet */
  108174. if(b->header)_ogg_free(b->header);
  108175. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  108176. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  108177. op->packet=b->header;
  108178. op->bytes=oggpack_bytes(&opb);
  108179. op->b_o_s=1;
  108180. op->e_o_s=0;
  108181. op->granulepos=0;
  108182. op->packetno=0;
  108183. /* second header packet (comments) **********************************/
  108184. oggpack_reset(&opb);
  108185. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  108186. if(b->header1)_ogg_free(b->header1);
  108187. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  108188. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  108189. op_comm->packet=b->header1;
  108190. op_comm->bytes=oggpack_bytes(&opb);
  108191. op_comm->b_o_s=0;
  108192. op_comm->e_o_s=0;
  108193. op_comm->granulepos=0;
  108194. op_comm->packetno=1;
  108195. /* third header packet (modes/codebooks) ****************************/
  108196. oggpack_reset(&opb);
  108197. if(_vorbis_pack_books(&opb,vi))goto err_out;
  108198. if(b->header2)_ogg_free(b->header2);
  108199. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  108200. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  108201. op_code->packet=b->header2;
  108202. op_code->bytes=oggpack_bytes(&opb);
  108203. op_code->b_o_s=0;
  108204. op_code->e_o_s=0;
  108205. op_code->granulepos=0;
  108206. op_code->packetno=2;
  108207. oggpack_writeclear(&opb);
  108208. return(0);
  108209. err_out:
  108210. oggpack_writeclear(&opb);
  108211. memset(op,0,sizeof(*op));
  108212. memset(op_comm,0,sizeof(*op_comm));
  108213. memset(op_code,0,sizeof(*op_code));
  108214. if(b->header)_ogg_free(b->header);
  108215. if(b->header1)_ogg_free(b->header1);
  108216. if(b->header2)_ogg_free(b->header2);
  108217. b->header=NULL;
  108218. b->header1=NULL;
  108219. b->header2=NULL;
  108220. return(ret);
  108221. }
  108222. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  108223. if(granulepos>=0)
  108224. return((double)granulepos/v->vi->rate);
  108225. return(-1);
  108226. }
  108227. #endif
  108228. /********* End of inlined file: info.c *********/
  108229. /********* Start of inlined file: lpc.c *********/
  108230. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  108231. are derived from code written by Jutta Degener and Carsten Bormann;
  108232. thus we include their copyright below. The entirety of this file
  108233. is freely redistributable on the condition that both of these
  108234. copyright notices are preserved without modification. */
  108235. /* Preserved Copyright: *********************************************/
  108236. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  108237. Technische Universita"t Berlin
  108238. Any use of this software is permitted provided that this notice is not
  108239. removed and that neither the authors nor the Technische Universita"t
  108240. Berlin are deemed to have made any representations as to the
  108241. suitability of this software for any purpose nor are held responsible
  108242. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  108243. THIS SOFTWARE.
  108244. As a matter of courtesy, the authors request to be informed about uses
  108245. this software has found, about bugs in this software, and about any
  108246. improvements that may be of general interest.
  108247. Berlin, 28.11.1994
  108248. Jutta Degener
  108249. Carsten Bormann
  108250. *********************************************************************/
  108251. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108252. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108253. // tasks..
  108254. #ifdef _MSC_VER
  108255. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108256. #endif
  108257. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108258. #if JUCE_USE_OGGVORBIS
  108259. #include <stdlib.h>
  108260. #include <string.h>
  108261. #include <math.h>
  108262. /* Autocorrelation LPC coeff generation algorithm invented by
  108263. N. Levinson in 1947, modified by J. Durbin in 1959. */
  108264. /* Input : n elements of time doamin data
  108265. Output: m lpc coefficients, excitation energy */
  108266. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  108267. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  108268. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  108269. double error;
  108270. int i,j;
  108271. /* autocorrelation, p+1 lag coefficients */
  108272. j=m+1;
  108273. while(j--){
  108274. double d=0; /* double needed for accumulator depth */
  108275. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  108276. aut[j]=d;
  108277. }
  108278. /* Generate lpc coefficients from autocorr values */
  108279. error=aut[0];
  108280. for(i=0;i<m;i++){
  108281. double r= -aut[i+1];
  108282. if(error==0){
  108283. memset(lpci,0,m*sizeof(*lpci));
  108284. return 0;
  108285. }
  108286. /* Sum up this iteration's reflection coefficient; note that in
  108287. Vorbis we don't save it. If anyone wants to recycle this code
  108288. and needs reflection coefficients, save the results of 'r' from
  108289. each iteration. */
  108290. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  108291. r/=error;
  108292. /* Update LPC coefficients and total error */
  108293. lpc[i]=r;
  108294. for(j=0;j<i/2;j++){
  108295. double tmp=lpc[j];
  108296. lpc[j]+=r*lpc[i-1-j];
  108297. lpc[i-1-j]+=r*tmp;
  108298. }
  108299. if(i%2)lpc[j]+=lpc[j]*r;
  108300. error*=1.f-r*r;
  108301. }
  108302. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  108303. /* we need the error value to know how big an impulse to hit the
  108304. filter with later */
  108305. return error;
  108306. }
  108307. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  108308. float *data,long n){
  108309. /* in: coeff[0...m-1] LPC coefficients
  108310. prime[0...m-1] initial values (allocated size of n+m-1)
  108311. out: data[0...n-1] data samples */
  108312. long i,j,o,p;
  108313. float y;
  108314. float *work=(float*)alloca(sizeof(*work)*(m+n));
  108315. if(!prime)
  108316. for(i=0;i<m;i++)
  108317. work[i]=0.f;
  108318. else
  108319. for(i=0;i<m;i++)
  108320. work[i]=prime[i];
  108321. for(i=0;i<n;i++){
  108322. y=0;
  108323. o=i;
  108324. p=m;
  108325. for(j=0;j<m;j++)
  108326. y-=work[o++]*coeff[--p];
  108327. data[i]=work[o]=y;
  108328. }
  108329. }
  108330. #endif
  108331. /********* End of inlined file: lpc.c *********/
  108332. /********* Start of inlined file: lsp.c *********/
  108333. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  108334. an iterative root polisher (CACM algorithm 283). It *is* possible
  108335. to confuse this algorithm into not converging; that should only
  108336. happen with absurdly closely spaced roots (very sharp peaks in the
  108337. LPC f response) which in turn should be impossible in our use of
  108338. the code. If this *does* happen anyway, it's a bug in the floor
  108339. finder; find the cause of the confusion (probably a single bin
  108340. spike or accidental near-float-limit resolution problems) and
  108341. correct it. */
  108342. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108343. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108344. // tasks..
  108345. #ifdef _MSC_VER
  108346. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108347. #endif
  108348. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108349. #if JUCE_USE_OGGVORBIS
  108350. #include <math.h>
  108351. #include <string.h>
  108352. #include <stdlib.h>
  108353. /********* Start of inlined file: lookup.h *********/
  108354. #ifndef _V_LOOKUP_H_
  108355. #ifdef FLOAT_LOOKUP
  108356. extern float vorbis_coslook(float a);
  108357. extern float vorbis_invsqlook(float a);
  108358. extern float vorbis_invsq2explook(int a);
  108359. extern float vorbis_fromdBlook(float a);
  108360. #endif
  108361. #ifdef INT_LOOKUP
  108362. extern long vorbis_invsqlook_i(long a,long e);
  108363. extern long vorbis_coslook_i(long a);
  108364. extern float vorbis_fromdBlook_i(long a);
  108365. #endif
  108366. #endif
  108367. /********* End of inlined file: lookup.h *********/
  108368. /* three possible LSP to f curve functions; the exact computation
  108369. (float), a lookup based float implementation, and an integer
  108370. implementation. The float lookup is likely the optimal choice on
  108371. any machine with an FPU. The integer implementation is *not* fixed
  108372. point (due to the need for a large dynamic range and thus a
  108373. seperately tracked exponent) and thus much more complex than the
  108374. relatively simple float implementations. It's mostly for future
  108375. work on a fully fixed point implementation for processors like the
  108376. ARM family. */
  108377. /* undefine both for the 'old' but more precise implementation */
  108378. #define FLOAT_LOOKUP
  108379. #undef INT_LOOKUP
  108380. #ifdef FLOAT_LOOKUP
  108381. /********* Start of inlined file: lookup.c *********/
  108382. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108383. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108384. // tasks..
  108385. #ifdef _MSC_VER
  108386. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108387. #endif
  108388. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108389. #if JUCE_USE_OGGVORBIS
  108390. #include <math.h>
  108391. /********* Start of inlined file: lookup.h *********/
  108392. #ifndef _V_LOOKUP_H_
  108393. #ifdef FLOAT_LOOKUP
  108394. extern float vorbis_coslook(float a);
  108395. extern float vorbis_invsqlook(float a);
  108396. extern float vorbis_invsq2explook(int a);
  108397. extern float vorbis_fromdBlook(float a);
  108398. #endif
  108399. #ifdef INT_LOOKUP
  108400. extern long vorbis_invsqlook_i(long a,long e);
  108401. extern long vorbis_coslook_i(long a);
  108402. extern float vorbis_fromdBlook_i(long a);
  108403. #endif
  108404. #endif
  108405. /********* End of inlined file: lookup.h *********/
  108406. /********* Start of inlined file: lookup_data.h *********/
  108407. #ifndef _V_LOOKUP_DATA_H_
  108408. #ifdef FLOAT_LOOKUP
  108409. #define COS_LOOKUP_SZ 128
  108410. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  108411. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  108412. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  108413. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  108414. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  108415. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  108416. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  108417. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  108418. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  108419. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  108420. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  108421. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  108422. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  108423. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  108424. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  108425. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  108426. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  108427. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  108428. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  108429. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  108430. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  108431. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  108432. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  108433. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  108434. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  108435. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  108436. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  108437. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  108438. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  108439. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  108440. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  108441. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  108442. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  108443. -1.0000000000000f,
  108444. };
  108445. #define INVSQ_LOOKUP_SZ 32
  108446. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  108447. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  108448. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  108449. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  108450. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  108451. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  108452. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  108453. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  108454. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  108455. 1.000000000000f,
  108456. };
  108457. #define INVSQ2EXP_LOOKUP_MIN (-32)
  108458. #define INVSQ2EXP_LOOKUP_MAX 32
  108459. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  108460. INVSQ2EXP_LOOKUP_MIN+1]={
  108461. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  108462. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  108463. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  108464. 1024.f, 724.0773439f, 512.f, 362.038672f,
  108465. 256.f, 181.019336f, 128.f, 90.50966799f,
  108466. 64.f, 45.254834f, 32.f, 22.627417f,
  108467. 16.f, 11.3137085f, 8.f, 5.656854249f,
  108468. 4.f, 2.828427125f, 2.f, 1.414213562f,
  108469. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  108470. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  108471. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  108472. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  108473. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  108474. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  108475. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  108476. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  108477. 1.525878906e-05f,
  108478. };
  108479. #endif
  108480. #define FROMdB_LOOKUP_SZ 35
  108481. #define FROMdB2_LOOKUP_SZ 32
  108482. #define FROMdB_SHIFT 5
  108483. #define FROMdB2_SHIFT 3
  108484. #define FROMdB2_MASK 31
  108485. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  108486. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  108487. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  108488. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  108489. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  108490. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  108491. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  108492. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  108493. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  108494. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  108495. };
  108496. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  108497. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  108498. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  108499. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  108500. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  108501. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  108502. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  108503. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  108504. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  108505. };
  108506. #ifdef INT_LOOKUP
  108507. #define INVSQ_LOOKUP_I_SHIFT 10
  108508. #define INVSQ_LOOKUP_I_MASK 1023
  108509. static long INVSQ_LOOKUP_I[64+1]={
  108510. 92682l, 91966l, 91267l, 90583l,
  108511. 89915l, 89261l, 88621l, 87995l,
  108512. 87381l, 86781l, 86192l, 85616l,
  108513. 85051l, 84497l, 83953l, 83420l,
  108514. 82897l, 82384l, 81880l, 81385l,
  108515. 80899l, 80422l, 79953l, 79492l,
  108516. 79039l, 78594l, 78156l, 77726l,
  108517. 77302l, 76885l, 76475l, 76072l,
  108518. 75674l, 75283l, 74898l, 74519l,
  108519. 74146l, 73778l, 73415l, 73058l,
  108520. 72706l, 72359l, 72016l, 71679l,
  108521. 71347l, 71019l, 70695l, 70376l,
  108522. 70061l, 69750l, 69444l, 69141l,
  108523. 68842l, 68548l, 68256l, 67969l,
  108524. 67685l, 67405l, 67128l, 66855l,
  108525. 66585l, 66318l, 66054l, 65794l,
  108526. 65536l,
  108527. };
  108528. #define COS_LOOKUP_I_SHIFT 9
  108529. #define COS_LOOKUP_I_MASK 511
  108530. #define COS_LOOKUP_I_SZ 128
  108531. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  108532. 16384l, 16379l, 16364l, 16340l,
  108533. 16305l, 16261l, 16207l, 16143l,
  108534. 16069l, 15986l, 15893l, 15791l,
  108535. 15679l, 15557l, 15426l, 15286l,
  108536. 15137l, 14978l, 14811l, 14635l,
  108537. 14449l, 14256l, 14053l, 13842l,
  108538. 13623l, 13395l, 13160l, 12916l,
  108539. 12665l, 12406l, 12140l, 11866l,
  108540. 11585l, 11297l, 11003l, 10702l,
  108541. 10394l, 10080l, 9760l, 9434l,
  108542. 9102l, 8765l, 8423l, 8076l,
  108543. 7723l, 7366l, 7005l, 6639l,
  108544. 6270l, 5897l, 5520l, 5139l,
  108545. 4756l, 4370l, 3981l, 3590l,
  108546. 3196l, 2801l, 2404l, 2006l,
  108547. 1606l, 1205l, 804l, 402l,
  108548. 0l, -401l, -803l, -1204l,
  108549. -1605l, -2005l, -2403l, -2800l,
  108550. -3195l, -3589l, -3980l, -4369l,
  108551. -4755l, -5138l, -5519l, -5896l,
  108552. -6269l, -6638l, -7004l, -7365l,
  108553. -7722l, -8075l, -8422l, -8764l,
  108554. -9101l, -9433l, -9759l, -10079l,
  108555. -10393l, -10701l, -11002l, -11296l,
  108556. -11584l, -11865l, -12139l, -12405l,
  108557. -12664l, -12915l, -13159l, -13394l,
  108558. -13622l, -13841l, -14052l, -14255l,
  108559. -14448l, -14634l, -14810l, -14977l,
  108560. -15136l, -15285l, -15425l, -15556l,
  108561. -15678l, -15790l, -15892l, -15985l,
  108562. -16068l, -16142l, -16206l, -16260l,
  108563. -16304l, -16339l, -16363l, -16378l,
  108564. -16383l,
  108565. };
  108566. #endif
  108567. #endif
  108568. /********* End of inlined file: lookup_data.h *********/
  108569. #ifdef FLOAT_LOOKUP
  108570. /* interpolated lookup based cos function, domain 0 to PI only */
  108571. float vorbis_coslook(float a){
  108572. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  108573. int i=vorbis_ftoi(d-.5);
  108574. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  108575. }
  108576. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  108577. float vorbis_invsqlook(float a){
  108578. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  108579. int i=vorbis_ftoi(d-.5f);
  108580. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  108581. }
  108582. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  108583. float vorbis_invsq2explook(int a){
  108584. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  108585. }
  108586. #include <stdio.h>
  108587. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  108588. float vorbis_fromdBlook(float a){
  108589. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  108590. return (i<0)?1.f:
  108591. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  108592. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  108593. }
  108594. #endif
  108595. #ifdef INT_LOOKUP
  108596. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  108597. 16.16 format
  108598. returns in m.8 format */
  108599. long vorbis_invsqlook_i(long a,long e){
  108600. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  108601. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  108602. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  108603. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  108604. d)>>16); /* result 1.16 */
  108605. e+=32;
  108606. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  108607. e=(e>>1)-8;
  108608. return(val>>e);
  108609. }
  108610. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  108611. /* a is in n.12 format */
  108612. float vorbis_fromdBlook_i(long a){
  108613. int i=(-a)>>(12-FROMdB2_SHIFT);
  108614. return (i<0)?1.f:
  108615. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  108616. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  108617. }
  108618. /* interpolated lookup based cos function, domain 0 to PI only */
  108619. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  108620. long vorbis_coslook_i(long a){
  108621. int i=a>>COS_LOOKUP_I_SHIFT;
  108622. int d=a&COS_LOOKUP_I_MASK;
  108623. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  108624. COS_LOOKUP_I_SHIFT);
  108625. }
  108626. #endif
  108627. #endif
  108628. /********* End of inlined file: lookup.c *********/
  108629. /* catch this in the build system; we #include for
  108630. compilers (like gcc) that can't inline across
  108631. modules */
  108632. /* side effect: changes *lsp to cosines of lsp */
  108633. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  108634. float amp,float ampoffset){
  108635. int i;
  108636. float wdel=M_PI/ln;
  108637. vorbis_fpu_control fpu;
  108638. (void) fpu; // to avoid an unused variable warning
  108639. vorbis_fpu_setround(&fpu);
  108640. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  108641. i=0;
  108642. while(i<n){
  108643. int k=map[i];
  108644. int qexp;
  108645. float p=.7071067812f;
  108646. float q=.7071067812f;
  108647. float w=vorbis_coslook(wdel*k);
  108648. float *ftmp=lsp;
  108649. int c=m>>1;
  108650. do{
  108651. q*=ftmp[0]-w;
  108652. p*=ftmp[1]-w;
  108653. ftmp+=2;
  108654. }while(--c);
  108655. if(m&1){
  108656. /* odd order filter; slightly assymetric */
  108657. /* the last coefficient */
  108658. q*=ftmp[0]-w;
  108659. q*=q;
  108660. p*=p*(1.f-w*w);
  108661. }else{
  108662. /* even order filter; still symmetric */
  108663. q*=q*(1.f+w);
  108664. p*=p*(1.f-w);
  108665. }
  108666. q=frexp(p+q,&qexp);
  108667. q=vorbis_fromdBlook(amp*
  108668. vorbis_invsqlook(q)*
  108669. vorbis_invsq2explook(qexp+m)-
  108670. ampoffset);
  108671. do{
  108672. curve[i++]*=q;
  108673. }while(map[i]==k);
  108674. }
  108675. vorbis_fpu_restore(fpu);
  108676. }
  108677. #else
  108678. #ifdef INT_LOOKUP
  108679. /********* Start of inlined file: lookup.c *********/
  108680. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108681. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108682. // tasks..
  108683. #ifdef _MSC_VER
  108684. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108685. #endif
  108686. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108687. #if JUCE_USE_OGGVORBIS
  108688. #include <math.h>
  108689. /********* Start of inlined file: lookup.h *********/
  108690. #ifndef _V_LOOKUP_H_
  108691. #ifdef FLOAT_LOOKUP
  108692. extern float vorbis_coslook(float a);
  108693. extern float vorbis_invsqlook(float a);
  108694. extern float vorbis_invsq2explook(int a);
  108695. extern float vorbis_fromdBlook(float a);
  108696. #endif
  108697. #ifdef INT_LOOKUP
  108698. extern long vorbis_invsqlook_i(long a,long e);
  108699. extern long vorbis_coslook_i(long a);
  108700. extern float vorbis_fromdBlook_i(long a);
  108701. #endif
  108702. #endif
  108703. /********* End of inlined file: lookup.h *********/
  108704. /********* Start of inlined file: lookup_data.h *********/
  108705. #ifndef _V_LOOKUP_DATA_H_
  108706. #ifdef FLOAT_LOOKUP
  108707. #define COS_LOOKUP_SZ 128
  108708. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  108709. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  108710. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  108711. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  108712. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  108713. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  108714. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  108715. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  108716. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  108717. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  108718. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  108719. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  108720. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  108721. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  108722. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  108723. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  108724. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  108725. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  108726. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  108727. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  108728. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  108729. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  108730. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  108731. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  108732. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  108733. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  108734. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  108735. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  108736. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  108737. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  108738. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  108739. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  108740. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  108741. -1.0000000000000f,
  108742. };
  108743. #define INVSQ_LOOKUP_SZ 32
  108744. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  108745. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  108746. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  108747. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  108748. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  108749. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  108750. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  108751. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  108752. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  108753. 1.000000000000f,
  108754. };
  108755. #define INVSQ2EXP_LOOKUP_MIN (-32)
  108756. #define INVSQ2EXP_LOOKUP_MAX 32
  108757. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  108758. INVSQ2EXP_LOOKUP_MIN+1]={
  108759. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  108760. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  108761. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  108762. 1024.f, 724.0773439f, 512.f, 362.038672f,
  108763. 256.f, 181.019336f, 128.f, 90.50966799f,
  108764. 64.f, 45.254834f, 32.f, 22.627417f,
  108765. 16.f, 11.3137085f, 8.f, 5.656854249f,
  108766. 4.f, 2.828427125f, 2.f, 1.414213562f,
  108767. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  108768. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  108769. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  108770. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  108771. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  108772. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  108773. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  108774. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  108775. 1.525878906e-05f,
  108776. };
  108777. #endif
  108778. #define FROMdB_LOOKUP_SZ 35
  108779. #define FROMdB2_LOOKUP_SZ 32
  108780. #define FROMdB_SHIFT 5
  108781. #define FROMdB2_SHIFT 3
  108782. #define FROMdB2_MASK 31
  108783. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  108784. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  108785. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  108786. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  108787. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  108788. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  108789. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  108790. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  108791. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  108792. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  108793. };
  108794. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  108795. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  108796. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  108797. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  108798. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  108799. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  108800. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  108801. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  108802. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  108803. };
  108804. #ifdef INT_LOOKUP
  108805. #define INVSQ_LOOKUP_I_SHIFT 10
  108806. #define INVSQ_LOOKUP_I_MASK 1023
  108807. static long INVSQ_LOOKUP_I[64+1]={
  108808. 92682l, 91966l, 91267l, 90583l,
  108809. 89915l, 89261l, 88621l, 87995l,
  108810. 87381l, 86781l, 86192l, 85616l,
  108811. 85051l, 84497l, 83953l, 83420l,
  108812. 82897l, 82384l, 81880l, 81385l,
  108813. 80899l, 80422l, 79953l, 79492l,
  108814. 79039l, 78594l, 78156l, 77726l,
  108815. 77302l, 76885l, 76475l, 76072l,
  108816. 75674l, 75283l, 74898l, 74519l,
  108817. 74146l, 73778l, 73415l, 73058l,
  108818. 72706l, 72359l, 72016l, 71679l,
  108819. 71347l, 71019l, 70695l, 70376l,
  108820. 70061l, 69750l, 69444l, 69141l,
  108821. 68842l, 68548l, 68256l, 67969l,
  108822. 67685l, 67405l, 67128l, 66855l,
  108823. 66585l, 66318l, 66054l, 65794l,
  108824. 65536l,
  108825. };
  108826. #define COS_LOOKUP_I_SHIFT 9
  108827. #define COS_LOOKUP_I_MASK 511
  108828. #define COS_LOOKUP_I_SZ 128
  108829. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  108830. 16384l, 16379l, 16364l, 16340l,
  108831. 16305l, 16261l, 16207l, 16143l,
  108832. 16069l, 15986l, 15893l, 15791l,
  108833. 15679l, 15557l, 15426l, 15286l,
  108834. 15137l, 14978l, 14811l, 14635l,
  108835. 14449l, 14256l, 14053l, 13842l,
  108836. 13623l, 13395l, 13160l, 12916l,
  108837. 12665l, 12406l, 12140l, 11866l,
  108838. 11585l, 11297l, 11003l, 10702l,
  108839. 10394l, 10080l, 9760l, 9434l,
  108840. 9102l, 8765l, 8423l, 8076l,
  108841. 7723l, 7366l, 7005l, 6639l,
  108842. 6270l, 5897l, 5520l, 5139l,
  108843. 4756l, 4370l, 3981l, 3590l,
  108844. 3196l, 2801l, 2404l, 2006l,
  108845. 1606l, 1205l, 804l, 402l,
  108846. 0l, -401l, -803l, -1204l,
  108847. -1605l, -2005l, -2403l, -2800l,
  108848. -3195l, -3589l, -3980l, -4369l,
  108849. -4755l, -5138l, -5519l, -5896l,
  108850. -6269l, -6638l, -7004l, -7365l,
  108851. -7722l, -8075l, -8422l, -8764l,
  108852. -9101l, -9433l, -9759l, -10079l,
  108853. -10393l, -10701l, -11002l, -11296l,
  108854. -11584l, -11865l, -12139l, -12405l,
  108855. -12664l, -12915l, -13159l, -13394l,
  108856. -13622l, -13841l, -14052l, -14255l,
  108857. -14448l, -14634l, -14810l, -14977l,
  108858. -15136l, -15285l, -15425l, -15556l,
  108859. -15678l, -15790l, -15892l, -15985l,
  108860. -16068l, -16142l, -16206l, -16260l,
  108861. -16304l, -16339l, -16363l, -16378l,
  108862. -16383l,
  108863. };
  108864. #endif
  108865. #endif
  108866. /********* End of inlined file: lookup_data.h *********/
  108867. #ifdef FLOAT_LOOKUP
  108868. /* interpolated lookup based cos function, domain 0 to PI only */
  108869. float vorbis_coslook(float a){
  108870. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  108871. int i=vorbis_ftoi(d-.5);
  108872. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  108873. }
  108874. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  108875. float vorbis_invsqlook(float a){
  108876. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  108877. int i=vorbis_ftoi(d-.5f);
  108878. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  108879. }
  108880. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  108881. float vorbis_invsq2explook(int a){
  108882. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  108883. }
  108884. #include <stdio.h>
  108885. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  108886. float vorbis_fromdBlook(float a){
  108887. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  108888. return (i<0)?1.f:
  108889. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  108890. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  108891. }
  108892. #endif
  108893. #ifdef INT_LOOKUP
  108894. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  108895. 16.16 format
  108896. returns in m.8 format */
  108897. long vorbis_invsqlook_i(long a,long e){
  108898. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  108899. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  108900. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  108901. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  108902. d)>>16); /* result 1.16 */
  108903. e+=32;
  108904. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  108905. e=(e>>1)-8;
  108906. return(val>>e);
  108907. }
  108908. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  108909. /* a is in n.12 format */
  108910. float vorbis_fromdBlook_i(long a){
  108911. int i=(-a)>>(12-FROMdB2_SHIFT);
  108912. return (i<0)?1.f:
  108913. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  108914. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  108915. }
  108916. /* interpolated lookup based cos function, domain 0 to PI only */
  108917. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  108918. long vorbis_coslook_i(long a){
  108919. int i=a>>COS_LOOKUP_I_SHIFT;
  108920. int d=a&COS_LOOKUP_I_MASK;
  108921. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  108922. COS_LOOKUP_I_SHIFT);
  108923. }
  108924. #endif
  108925. #endif
  108926. /********* End of inlined file: lookup.c *********/
  108927. /* catch this in the build system; we #include for
  108928. compilers (like gcc) that can't inline across
  108929. modules */
  108930. static int MLOOP_1[64]={
  108931. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  108932. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  108933. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  108934. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  108935. };
  108936. static int MLOOP_2[64]={
  108937. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  108938. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  108939. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  108940. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  108941. };
  108942. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  108943. /* side effect: changes *lsp to cosines of lsp */
  108944. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  108945. float amp,float ampoffset){
  108946. /* 0 <= m < 256 */
  108947. /* set up for using all int later */
  108948. int i;
  108949. int ampoffseti=rint(ampoffset*4096.f);
  108950. int ampi=rint(amp*16.f);
  108951. long *ilsp=alloca(m*sizeof(*ilsp));
  108952. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  108953. i=0;
  108954. while(i<n){
  108955. int j,k=map[i];
  108956. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  108957. unsigned long qi=46341;
  108958. int qexp=0,shift;
  108959. long wi=vorbis_coslook_i(k*65536/ln);
  108960. qi*=labs(ilsp[0]-wi);
  108961. pi*=labs(ilsp[1]-wi);
  108962. for(j=3;j<m;j+=2){
  108963. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  108964. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  108965. shift=MLOOP_3[(pi|qi)>>16];
  108966. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  108967. pi=(pi>>shift)*labs(ilsp[j]-wi);
  108968. qexp+=shift;
  108969. }
  108970. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  108971. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  108972. shift=MLOOP_3[(pi|qi)>>16];
  108973. /* pi,qi normalized collectively, both tracked using qexp */
  108974. if(m&1){
  108975. /* odd order filter; slightly assymetric */
  108976. /* the last coefficient */
  108977. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  108978. pi=(pi>>shift)<<14;
  108979. qexp+=shift;
  108980. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  108981. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  108982. shift=MLOOP_3[(pi|qi)>>16];
  108983. pi>>=shift;
  108984. qi>>=shift;
  108985. qexp+=shift-14*((m+1)>>1);
  108986. pi=((pi*pi)>>16);
  108987. qi=((qi*qi)>>16);
  108988. qexp=qexp*2+m;
  108989. pi*=(1<<14)-((wi*wi)>>14);
  108990. qi+=pi>>14;
  108991. }else{
  108992. /* even order filter; still symmetric */
  108993. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  108994. worth tracking step by step */
  108995. pi>>=shift;
  108996. qi>>=shift;
  108997. qexp+=shift-7*m;
  108998. pi=((pi*pi)>>16);
  108999. qi=((qi*qi)>>16);
  109000. qexp=qexp*2+m;
  109001. pi*=(1<<14)-wi;
  109002. qi*=(1<<14)+wi;
  109003. qi=(qi+pi)>>14;
  109004. }
  109005. /* we've let the normalization drift because it wasn't important;
  109006. however, for the lookup, things must be normalized again. We
  109007. need at most one right shift or a number of left shifts */
  109008. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  109009. qi>>=1; qexp++;
  109010. }else
  109011. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  109012. qi<<=1; qexp--;
  109013. }
  109014. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  109015. vorbis_invsqlook_i(qi,qexp)-
  109016. /* m.8, m+n<=8 */
  109017. ampoffseti); /* 8.12[0] */
  109018. curve[i]*=amp;
  109019. while(map[++i]==k)curve[i]*=amp;
  109020. }
  109021. }
  109022. #else
  109023. /* old, nonoptimized but simple version for any poor sap who needs to
  109024. figure out what the hell this code does, or wants the other
  109025. fraction of a dB precision */
  109026. /* side effect: changes *lsp to cosines of lsp */
  109027. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  109028. float amp,float ampoffset){
  109029. int i;
  109030. float wdel=M_PI/ln;
  109031. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  109032. i=0;
  109033. while(i<n){
  109034. int j,k=map[i];
  109035. float p=.5f;
  109036. float q=.5f;
  109037. float w=2.f*cos(wdel*k);
  109038. for(j=1;j<m;j+=2){
  109039. q *= w-lsp[j-1];
  109040. p *= w-lsp[j];
  109041. }
  109042. if(j==m){
  109043. /* odd order filter; slightly assymetric */
  109044. /* the last coefficient */
  109045. q*=w-lsp[j-1];
  109046. p*=p*(4.f-w*w);
  109047. q*=q;
  109048. }else{
  109049. /* even order filter; still symmetric */
  109050. p*=p*(2.f-w);
  109051. q*=q*(2.f+w);
  109052. }
  109053. q=fromdB(amp/sqrt(p+q)-ampoffset);
  109054. curve[i]*=q;
  109055. while(map[++i]==k)curve[i]*=q;
  109056. }
  109057. }
  109058. #endif
  109059. #endif
  109060. static void cheby(float *g, int ord) {
  109061. int i, j;
  109062. g[0] *= .5f;
  109063. for(i=2; i<= ord; i++) {
  109064. for(j=ord; j >= i; j--) {
  109065. g[j-2] -= g[j];
  109066. g[j] += g[j];
  109067. }
  109068. }
  109069. }
  109070. static int comp(const void *a,const void *b){
  109071. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  109072. }
  109073. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  109074. but there are root sets for which it gets into limit cycles
  109075. (exacerbated by zero suppression) and fails. We can't afford to
  109076. fail, even if the failure is 1 in 100,000,000, so we now use
  109077. Laguerre and later polish with Newton-Raphson (which can then
  109078. afford to fail) */
  109079. #define EPSILON 10e-7
  109080. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  109081. int i,m;
  109082. double lastdelta=0.f;
  109083. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  109084. for(i=0;i<=ord;i++)defl[i]=a[i];
  109085. for(m=ord;m>0;m--){
  109086. double newx=0.f,delta;
  109087. /* iterate a root */
  109088. while(1){
  109089. double p=defl[m],pp=0.f,ppp=0.f,denom;
  109090. /* eval the polynomial and its first two derivatives */
  109091. for(i=m;i>0;i--){
  109092. ppp = newx*ppp + pp;
  109093. pp = newx*pp + p;
  109094. p = newx*p + defl[i-1];
  109095. }
  109096. /* Laguerre's method */
  109097. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  109098. if(denom<0)
  109099. return(-1); /* complex root! The LPC generator handed us a bad filter */
  109100. if(pp>0){
  109101. denom = pp + sqrt(denom);
  109102. if(denom<EPSILON)denom=EPSILON;
  109103. }else{
  109104. denom = pp - sqrt(denom);
  109105. if(denom>-(EPSILON))denom=-(EPSILON);
  109106. }
  109107. delta = m*p/denom;
  109108. newx -= delta;
  109109. if(delta<0.f)delta*=-1;
  109110. if(fabs(delta/newx)<10e-12)break;
  109111. lastdelta=delta;
  109112. }
  109113. r[m-1]=newx;
  109114. /* forward deflation */
  109115. for(i=m;i>0;i--)
  109116. defl[i-1]+=newx*defl[i];
  109117. defl++;
  109118. }
  109119. return(0);
  109120. }
  109121. /* for spit-and-polish only */
  109122. static int Newton_Raphson(float *a,int ord,float *r){
  109123. int i, k, count=0;
  109124. double error=1.f;
  109125. double *root=(double*)alloca(ord*sizeof(*root));
  109126. for(i=0; i<ord;i++) root[i] = r[i];
  109127. while(error>1e-20){
  109128. error=0;
  109129. for(i=0; i<ord; i++) { /* Update each point. */
  109130. double pp=0.,delta;
  109131. double rooti=root[i];
  109132. double p=a[ord];
  109133. for(k=ord-1; k>= 0; k--) {
  109134. pp= pp* rooti + p;
  109135. p = p * rooti + a[k];
  109136. }
  109137. delta = p/pp;
  109138. root[i] -= delta;
  109139. error+= delta*delta;
  109140. }
  109141. if(count>40)return(-1);
  109142. count++;
  109143. }
  109144. /* Replaced the original bubble sort with a real sort. With your
  109145. help, we can eliminate the bubble sort in our lifetime. --Monty */
  109146. for(i=0; i<ord;i++) r[i] = root[i];
  109147. return(0);
  109148. }
  109149. /* Convert lpc coefficients to lsp coefficients */
  109150. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  109151. int order2=(m+1)>>1;
  109152. int g1_order,g2_order;
  109153. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  109154. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  109155. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  109156. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  109157. int i;
  109158. /* even and odd are slightly different base cases */
  109159. g1_order=(m+1)>>1;
  109160. g2_order=(m) >>1;
  109161. /* Compute the lengths of the x polynomials. */
  109162. /* Compute the first half of K & R F1 & F2 polynomials. */
  109163. /* Compute half of the symmetric and antisymmetric polynomials. */
  109164. /* Remove the roots at +1 and -1. */
  109165. g1[g1_order] = 1.f;
  109166. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  109167. g2[g2_order] = 1.f;
  109168. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  109169. if(g1_order>g2_order){
  109170. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  109171. }else{
  109172. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  109173. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  109174. }
  109175. /* Convert into polynomials in cos(alpha) */
  109176. cheby(g1,g1_order);
  109177. cheby(g2,g2_order);
  109178. /* Find the roots of the 2 even polynomials.*/
  109179. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  109180. Laguerre_With_Deflation(g2,g2_order,g2r))
  109181. return(-1);
  109182. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  109183. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  109184. qsort(g1r,g1_order,sizeof(*g1r),comp);
  109185. qsort(g2r,g2_order,sizeof(*g2r),comp);
  109186. for(i=0;i<g1_order;i++)
  109187. lsp[i*2] = acos(g1r[i]);
  109188. for(i=0;i<g2_order;i++)
  109189. lsp[i*2+1] = acos(g2r[i]);
  109190. return(0);
  109191. }
  109192. #endif
  109193. /********* End of inlined file: lsp.c *********/
  109194. /********* Start of inlined file: mapping0.c *********/
  109195. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109196. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109197. // tasks..
  109198. #ifdef _MSC_VER
  109199. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109200. #endif
  109201. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109202. #if JUCE_USE_OGGVORBIS
  109203. #include <stdlib.h>
  109204. #include <stdio.h>
  109205. #include <string.h>
  109206. #include <math.h>
  109207. /* simplistic, wasteful way of doing this (unique lookup for each
  109208. mode/submapping); there should be a central repository for
  109209. identical lookups. That will require minor work, so I'm putting it
  109210. off as low priority.
  109211. Why a lookup for each backend in a given mode? Because the
  109212. blocksize is set by the mode, and low backend lookups may require
  109213. parameters from other areas of the mode/mapping */
  109214. static void mapping0_free_info(vorbis_info_mapping *i){
  109215. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  109216. if(info){
  109217. memset(info,0,sizeof(*info));
  109218. _ogg_free(info);
  109219. }
  109220. }
  109221. static int ilog3(unsigned int v){
  109222. int ret=0;
  109223. if(v)--v;
  109224. while(v){
  109225. ret++;
  109226. v>>=1;
  109227. }
  109228. return(ret);
  109229. }
  109230. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  109231. oggpack_buffer *opb){
  109232. int i;
  109233. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  109234. /* another 'we meant to do it this way' hack... up to beta 4, we
  109235. packed 4 binary zeros here to signify one submapping in use. We
  109236. now redefine that to mean four bitflags that indicate use of
  109237. deeper features; bit0:submappings, bit1:coupling,
  109238. bit2,3:reserved. This is backward compatable with all actual uses
  109239. of the beta code. */
  109240. if(info->submaps>1){
  109241. oggpack_write(opb,1,1);
  109242. oggpack_write(opb,info->submaps-1,4);
  109243. }else
  109244. oggpack_write(opb,0,1);
  109245. if(info->coupling_steps>0){
  109246. oggpack_write(opb,1,1);
  109247. oggpack_write(opb,info->coupling_steps-1,8);
  109248. for(i=0;i<info->coupling_steps;i++){
  109249. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  109250. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  109251. }
  109252. }else
  109253. oggpack_write(opb,0,1);
  109254. oggpack_write(opb,0,2); /* 2,3:reserved */
  109255. /* we don't write the channel submappings if we only have one... */
  109256. if(info->submaps>1){
  109257. for(i=0;i<vi->channels;i++)
  109258. oggpack_write(opb,info->chmuxlist[i],4);
  109259. }
  109260. for(i=0;i<info->submaps;i++){
  109261. oggpack_write(opb,0,8); /* time submap unused */
  109262. oggpack_write(opb,info->floorsubmap[i],8);
  109263. oggpack_write(opb,info->residuesubmap[i],8);
  109264. }
  109265. }
  109266. /* also responsible for range checking */
  109267. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  109268. int i;
  109269. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  109270. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109271. memset(info,0,sizeof(*info));
  109272. if(oggpack_read(opb,1))
  109273. info->submaps=oggpack_read(opb,4)+1;
  109274. else
  109275. info->submaps=1;
  109276. if(oggpack_read(opb,1)){
  109277. info->coupling_steps=oggpack_read(opb,8)+1;
  109278. for(i=0;i<info->coupling_steps;i++){
  109279. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  109280. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  109281. if(testM<0 ||
  109282. testA<0 ||
  109283. testM==testA ||
  109284. testM>=vi->channels ||
  109285. testA>=vi->channels) goto err_out;
  109286. }
  109287. }
  109288. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  109289. if(info->submaps>1){
  109290. for(i=0;i<vi->channels;i++){
  109291. info->chmuxlist[i]=oggpack_read(opb,4);
  109292. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  109293. }
  109294. }
  109295. for(i=0;i<info->submaps;i++){
  109296. oggpack_read(opb,8); /* time submap unused */
  109297. info->floorsubmap[i]=oggpack_read(opb,8);
  109298. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  109299. info->residuesubmap[i]=oggpack_read(opb,8);
  109300. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  109301. }
  109302. return info;
  109303. err_out:
  109304. mapping0_free_info(info);
  109305. return(NULL);
  109306. }
  109307. #if 0
  109308. static long seq=0;
  109309. static ogg_int64_t total=0;
  109310. static float FLOOR1_fromdB_LOOKUP[256]={
  109311. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  109312. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  109313. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  109314. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  109315. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  109316. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  109317. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  109318. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  109319. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  109320. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  109321. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  109322. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  109323. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  109324. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  109325. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  109326. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  109327. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  109328. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  109329. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  109330. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  109331. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  109332. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  109333. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  109334. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  109335. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  109336. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  109337. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  109338. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  109339. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  109340. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  109341. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  109342. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  109343. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  109344. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  109345. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  109346. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  109347. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  109348. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  109349. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  109350. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  109351. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  109352. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  109353. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  109354. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  109355. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  109356. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  109357. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  109358. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  109359. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  109360. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  109361. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  109362. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  109363. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  109364. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  109365. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  109366. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  109367. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  109368. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  109369. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  109370. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  109371. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  109372. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  109373. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  109374. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  109375. };
  109376. #endif
  109377. extern int *floor1_fit(vorbis_block *vb,void *look,
  109378. const float *logmdct, /* in */
  109379. const float *logmask);
  109380. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  109381. int *A,int *B,
  109382. int del);
  109383. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  109384. void*look,
  109385. int *post,int *ilogmask);
  109386. static int mapping0_forward(vorbis_block *vb){
  109387. vorbis_dsp_state *vd=vb->vd;
  109388. vorbis_info *vi=vd->vi;
  109389. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109390. private_state *b=(private_state*)vb->vd->backend_state;
  109391. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  109392. int n=vb->pcmend;
  109393. int i,j,k;
  109394. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  109395. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  109396. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  109397. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  109398. float global_ampmax=vbi->ampmax;
  109399. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  109400. int blocktype=vbi->blocktype;
  109401. int modenumber=vb->W;
  109402. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  109403. vorbis_look_psy *psy_look=
  109404. b->psy+blocktype+(vb->W?2:0);
  109405. vb->mode=modenumber;
  109406. for(i=0;i<vi->channels;i++){
  109407. float scale=4.f/n;
  109408. float scale_dB;
  109409. float *pcm =vb->pcm[i];
  109410. float *logfft =pcm;
  109411. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  109412. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  109413. todB estimation used on IEEE 754
  109414. compliant machines had a bug that
  109415. returned dB values about a third
  109416. of a decibel too high. The bug
  109417. was harmless because tunings
  109418. implicitly took that into
  109419. account. However, fixing the bug
  109420. in the estimator requires
  109421. changing all the tunings as well.
  109422. For now, it's easier to sync
  109423. things back up here, and
  109424. recalibrate the tunings in the
  109425. next major model upgrade. */
  109426. #if 0
  109427. if(vi->channels==2)
  109428. if(i==0)
  109429. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  109430. else
  109431. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  109432. #endif
  109433. /* window the PCM data */
  109434. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  109435. #if 0
  109436. if(vi->channels==2)
  109437. if(i==0)
  109438. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  109439. else
  109440. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  109441. #endif
  109442. /* transform the PCM data */
  109443. /* only MDCT right now.... */
  109444. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  109445. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  109446. drft_forward(&b->fft_look[vb->W],pcm);
  109447. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  109448. original todB estimation used on
  109449. IEEE 754 compliant machines had a
  109450. bug that returned dB values about
  109451. a third of a decibel too high.
  109452. The bug was harmless because
  109453. tunings implicitly took that into
  109454. account. However, fixing the bug
  109455. in the estimator requires
  109456. changing all the tunings as well.
  109457. For now, it's easier to sync
  109458. things back up here, and
  109459. recalibrate the tunings in the
  109460. next major model upgrade. */
  109461. local_ampmax[i]=logfft[0];
  109462. for(j=1;j<n-1;j+=2){
  109463. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  109464. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  109465. .345 is a hack; the original todB
  109466. estimation used on IEEE 754
  109467. compliant machines had a bug that
  109468. returned dB values about a third
  109469. of a decibel too high. The bug
  109470. was harmless because tunings
  109471. implicitly took that into
  109472. account. However, fixing the bug
  109473. in the estimator requires
  109474. changing all the tunings as well.
  109475. For now, it's easier to sync
  109476. things back up here, and
  109477. recalibrate the tunings in the
  109478. next major model upgrade. */
  109479. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  109480. }
  109481. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  109482. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  109483. #if 0
  109484. if(vi->channels==2){
  109485. if(i==0){
  109486. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  109487. }else{
  109488. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  109489. }
  109490. }
  109491. #endif
  109492. }
  109493. {
  109494. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  109495. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  109496. for(i=0;i<vi->channels;i++){
  109497. /* the encoder setup assumes that all the modes used by any
  109498. specific bitrate tweaking use the same floor */
  109499. int submap=info->chmuxlist[i];
  109500. /* the following makes things clearer to *me* anyway */
  109501. float *mdct =gmdct[i];
  109502. float *logfft =vb->pcm[i];
  109503. float *logmdct =logfft+n/2;
  109504. float *logmask =logfft;
  109505. vb->mode=modenumber;
  109506. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  109507. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  109508. for(j=0;j<n/2;j++)
  109509. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  109510. todB estimation used on IEEE 754
  109511. compliant machines had a bug that
  109512. returned dB values about a third
  109513. of a decibel too high. The bug
  109514. was harmless because tunings
  109515. implicitly took that into
  109516. account. However, fixing the bug
  109517. in the estimator requires
  109518. changing all the tunings as well.
  109519. For now, it's easier to sync
  109520. things back up here, and
  109521. recalibrate the tunings in the
  109522. next major model upgrade. */
  109523. #if 0
  109524. if(vi->channels==2){
  109525. if(i==0)
  109526. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  109527. else
  109528. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  109529. }else{
  109530. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  109531. }
  109532. #endif
  109533. /* first step; noise masking. Not only does 'noise masking'
  109534. give us curves from which we can decide how much resolution
  109535. to give noise parts of the spectrum, it also implicitly hands
  109536. us a tonality estimate (the larger the value in the
  109537. 'noise_depth' vector, the more tonal that area is) */
  109538. _vp_noisemask(psy_look,
  109539. logmdct,
  109540. noise); /* noise does not have by-frequency offset
  109541. bias applied yet */
  109542. #if 0
  109543. if(vi->channels==2){
  109544. if(i==0)
  109545. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  109546. else
  109547. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  109548. }
  109549. #endif
  109550. /* second step: 'all the other crap'; all the stuff that isn't
  109551. computed/fit for bitrate management goes in the second psy
  109552. vector. This includes tone masking, peak limiting and ATH */
  109553. _vp_tonemask(psy_look,
  109554. logfft,
  109555. tone,
  109556. global_ampmax,
  109557. local_ampmax[i]);
  109558. #if 0
  109559. if(vi->channels==2){
  109560. if(i==0)
  109561. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  109562. else
  109563. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  109564. }
  109565. #endif
  109566. /* third step; we offset the noise vectors, overlay tone
  109567. masking. We then do a floor1-specific line fit. If we're
  109568. performing bitrate management, the line fit is performed
  109569. multiple times for up/down tweakage on demand. */
  109570. #if 0
  109571. {
  109572. float aotuv[psy_look->n];
  109573. #endif
  109574. _vp_offset_and_mix(psy_look,
  109575. noise,
  109576. tone,
  109577. 1,
  109578. logmask,
  109579. mdct,
  109580. logmdct);
  109581. #if 0
  109582. if(vi->channels==2){
  109583. if(i==0)
  109584. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  109585. else
  109586. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  109587. }
  109588. }
  109589. #endif
  109590. #if 0
  109591. if(vi->channels==2){
  109592. if(i==0)
  109593. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  109594. else
  109595. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  109596. }
  109597. #endif
  109598. /* this algorithm is hardwired to floor 1 for now; abort out if
  109599. we're *not* floor1. This won't happen unless someone has
  109600. broken the encode setup lib. Guard it anyway. */
  109601. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  109602. floor_posts[i][PACKETBLOBS/2]=
  109603. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  109604. logmdct,
  109605. logmask);
  109606. /* are we managing bitrate? If so, perform two more fits for
  109607. later rate tweaking (fits represent hi/lo) */
  109608. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  109609. /* higher rate by way of lower noise curve */
  109610. _vp_offset_and_mix(psy_look,
  109611. noise,
  109612. tone,
  109613. 2,
  109614. logmask,
  109615. mdct,
  109616. logmdct);
  109617. #if 0
  109618. if(vi->channels==2){
  109619. if(i==0)
  109620. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  109621. else
  109622. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  109623. }
  109624. #endif
  109625. floor_posts[i][PACKETBLOBS-1]=
  109626. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  109627. logmdct,
  109628. logmask);
  109629. /* lower rate by way of higher noise curve */
  109630. _vp_offset_and_mix(psy_look,
  109631. noise,
  109632. tone,
  109633. 0,
  109634. logmask,
  109635. mdct,
  109636. logmdct);
  109637. #if 0
  109638. if(vi->channels==2)
  109639. if(i==0)
  109640. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  109641. else
  109642. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  109643. #endif
  109644. floor_posts[i][0]=
  109645. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  109646. logmdct,
  109647. logmask);
  109648. /* we also interpolate a range of intermediate curves for
  109649. intermediate rates */
  109650. for(k=1;k<PACKETBLOBS/2;k++)
  109651. floor_posts[i][k]=
  109652. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  109653. floor_posts[i][0],
  109654. floor_posts[i][PACKETBLOBS/2],
  109655. k*65536/(PACKETBLOBS/2));
  109656. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  109657. floor_posts[i][k]=
  109658. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  109659. floor_posts[i][PACKETBLOBS/2],
  109660. floor_posts[i][PACKETBLOBS-1],
  109661. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  109662. }
  109663. }
  109664. }
  109665. vbi->ampmax=global_ampmax;
  109666. /*
  109667. the next phases are performed once for vbr-only and PACKETBLOB
  109668. times for bitrate managed modes.
  109669. 1) encode actual mode being used
  109670. 2) encode the floor for each channel, compute coded mask curve/res
  109671. 3) normalize and couple.
  109672. 4) encode residue
  109673. 5) save packet bytes to the packetblob vector
  109674. */
  109675. /* iterate over the many masking curve fits we've created */
  109676. {
  109677. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  109678. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  109679. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  109680. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  109681. float **mag_memo;
  109682. int **mag_sort;
  109683. if(info->coupling_steps){
  109684. mag_memo=_vp_quantize_couple_memo(vb,
  109685. &ci->psy_g_param,
  109686. psy_look,
  109687. info,
  109688. gmdct);
  109689. mag_sort=_vp_quantize_couple_sort(vb,
  109690. psy_look,
  109691. info,
  109692. mag_memo);
  109693. hf_reduction(&ci->psy_g_param,
  109694. psy_look,
  109695. info,
  109696. mag_memo);
  109697. }
  109698. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  109699. if(psy_look->vi->normal_channel_p){
  109700. for(i=0;i<vi->channels;i++){
  109701. float *mdct =gmdct[i];
  109702. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  109703. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  109704. }
  109705. }
  109706. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  109707. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  109708. k++){
  109709. oggpack_buffer *opb=vbi->packetblob[k];
  109710. /* start out our new packet blob with packet type and mode */
  109711. /* Encode the packet type */
  109712. oggpack_write(opb,0,1);
  109713. /* Encode the modenumber */
  109714. /* Encode frame mode, pre,post windowsize, then dispatch */
  109715. oggpack_write(opb,modenumber,b->modebits);
  109716. if(vb->W){
  109717. oggpack_write(opb,vb->lW,1);
  109718. oggpack_write(opb,vb->nW,1);
  109719. }
  109720. /* encode floor, compute masking curve, sep out residue */
  109721. for(i=0;i<vi->channels;i++){
  109722. int submap=info->chmuxlist[i];
  109723. float *mdct =gmdct[i];
  109724. float *res =vb->pcm[i];
  109725. int *ilogmask=ilogmaskch[i]=
  109726. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  109727. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  109728. floor_posts[i][k],
  109729. ilogmask);
  109730. #if 0
  109731. {
  109732. char buf[80];
  109733. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  109734. float work[n/2];
  109735. for(j=0;j<n/2;j++)
  109736. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  109737. _analysis_output(buf,seq,work,n/2,1,1,0);
  109738. }
  109739. #endif
  109740. _vp_remove_floor(psy_look,
  109741. mdct,
  109742. ilogmask,
  109743. res,
  109744. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  109745. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  109746. #if 0
  109747. {
  109748. char buf[80];
  109749. float work[n/2];
  109750. for(j=0;j<n/2;j++)
  109751. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  109752. sprintf(buf,"resI%c%d",i?'R':'L',k);
  109753. _analysis_output(buf,seq,work,n/2,1,1,0);
  109754. }
  109755. #endif
  109756. }
  109757. /* our iteration is now based on masking curve, not prequant and
  109758. coupling. Only one prequant/coupling step */
  109759. /* quantize/couple */
  109760. /* incomplete implementation that assumes the tree is all depth
  109761. one, or no tree at all */
  109762. if(info->coupling_steps){
  109763. _vp_couple(k,
  109764. &ci->psy_g_param,
  109765. psy_look,
  109766. info,
  109767. vb->pcm,
  109768. mag_memo,
  109769. mag_sort,
  109770. ilogmaskch,
  109771. nonzero,
  109772. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  109773. }
  109774. /* classify and encode by submap */
  109775. for(i=0;i<info->submaps;i++){
  109776. int ch_in_bundle=0;
  109777. long **classifications;
  109778. int resnum=info->residuesubmap[i];
  109779. for(j=0;j<vi->channels;j++){
  109780. if(info->chmuxlist[j]==i){
  109781. zerobundle[ch_in_bundle]=0;
  109782. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  109783. res_bundle[ch_in_bundle]=vb->pcm[j];
  109784. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  109785. }
  109786. }
  109787. classifications=_residue_P[ci->residue_type[resnum]]->
  109788. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  109789. _residue_P[ci->residue_type[resnum]]->
  109790. forward(opb,vb,b->residue[resnum],
  109791. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  109792. }
  109793. /* ok, done encoding. Next protopacket. */
  109794. }
  109795. }
  109796. #if 0
  109797. seq++;
  109798. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  109799. #endif
  109800. return(0);
  109801. }
  109802. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  109803. vorbis_dsp_state *vd=vb->vd;
  109804. vorbis_info *vi=vd->vi;
  109805. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  109806. private_state *b=(private_state*)vd->backend_state;
  109807. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  109808. int i,j;
  109809. long n=vb->pcmend=ci->blocksizes[vb->W];
  109810. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  109811. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  109812. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  109813. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  109814. /* recover the spectral envelope; store it in the PCM vector for now */
  109815. for(i=0;i<vi->channels;i++){
  109816. int submap=info->chmuxlist[i];
  109817. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  109818. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  109819. if(floormemo[i])
  109820. nonzero[i]=1;
  109821. else
  109822. nonzero[i]=0;
  109823. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  109824. }
  109825. /* channel coupling can 'dirty' the nonzero listing */
  109826. for(i=0;i<info->coupling_steps;i++){
  109827. if(nonzero[info->coupling_mag[i]] ||
  109828. nonzero[info->coupling_ang[i]]){
  109829. nonzero[info->coupling_mag[i]]=1;
  109830. nonzero[info->coupling_ang[i]]=1;
  109831. }
  109832. }
  109833. /* recover the residue into our working vectors */
  109834. for(i=0;i<info->submaps;i++){
  109835. int ch_in_bundle=0;
  109836. for(j=0;j<vi->channels;j++){
  109837. if(info->chmuxlist[j]==i){
  109838. if(nonzero[j])
  109839. zerobundle[ch_in_bundle]=1;
  109840. else
  109841. zerobundle[ch_in_bundle]=0;
  109842. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  109843. }
  109844. }
  109845. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  109846. inverse(vb,b->residue[info->residuesubmap[i]],
  109847. pcmbundle,zerobundle,ch_in_bundle);
  109848. }
  109849. /* channel coupling */
  109850. for(i=info->coupling_steps-1;i>=0;i--){
  109851. float *pcmM=vb->pcm[info->coupling_mag[i]];
  109852. float *pcmA=vb->pcm[info->coupling_ang[i]];
  109853. for(j=0;j<n/2;j++){
  109854. float mag=pcmM[j];
  109855. float ang=pcmA[j];
  109856. if(mag>0)
  109857. if(ang>0){
  109858. pcmM[j]=mag;
  109859. pcmA[j]=mag-ang;
  109860. }else{
  109861. pcmA[j]=mag;
  109862. pcmM[j]=mag+ang;
  109863. }
  109864. else
  109865. if(ang>0){
  109866. pcmM[j]=mag;
  109867. pcmA[j]=mag+ang;
  109868. }else{
  109869. pcmA[j]=mag;
  109870. pcmM[j]=mag-ang;
  109871. }
  109872. }
  109873. }
  109874. /* compute and apply spectral envelope */
  109875. for(i=0;i<vi->channels;i++){
  109876. float *pcm=vb->pcm[i];
  109877. int submap=info->chmuxlist[i];
  109878. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  109879. inverse2(vb,b->flr[info->floorsubmap[submap]],
  109880. floormemo[i],pcm);
  109881. }
  109882. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  109883. /* only MDCT right now.... */
  109884. for(i=0;i<vi->channels;i++){
  109885. float *pcm=vb->pcm[i];
  109886. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  109887. }
  109888. /* all done! */
  109889. return(0);
  109890. }
  109891. /* export hooks */
  109892. vorbis_func_mapping mapping0_exportbundle={
  109893. &mapping0_pack,
  109894. &mapping0_unpack,
  109895. &mapping0_free_info,
  109896. &mapping0_forward,
  109897. &mapping0_inverse
  109898. };
  109899. #endif
  109900. /********* End of inlined file: mapping0.c *********/
  109901. /********* Start of inlined file: mdct.c *********/
  109902. /* this can also be run as an integer transform by uncommenting a
  109903. define in mdct.h; the integerization is a first pass and although
  109904. it's likely stable for Vorbis, the dynamic range is constrained and
  109905. roundoff isn't done (so it's noisy). Consider it functional, but
  109906. only a starting point. There's no point on a machine with an FPU */
  109907. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109908. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109909. // tasks..
  109910. #ifdef _MSC_VER
  109911. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109912. #endif
  109913. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109914. #if JUCE_USE_OGGVORBIS
  109915. #include <stdio.h>
  109916. #include <stdlib.h>
  109917. #include <string.h>
  109918. #include <math.h>
  109919. /* build lookups for trig functions; also pre-figure scaling and
  109920. some window function algebra. */
  109921. void mdct_init(mdct_lookup *lookup,int n){
  109922. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  109923. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  109924. int i;
  109925. int n2=n>>1;
  109926. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  109927. lookup->n=n;
  109928. lookup->trig=T;
  109929. lookup->bitrev=bitrev;
  109930. /* trig lookups... */
  109931. for(i=0;i<n/4;i++){
  109932. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  109933. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  109934. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  109935. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  109936. }
  109937. for(i=0;i<n/8;i++){
  109938. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  109939. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  109940. }
  109941. /* bitreverse lookup... */
  109942. {
  109943. int mask=(1<<(log2n-1))-1,i,j;
  109944. int msb=1<<(log2n-2);
  109945. for(i=0;i<n/8;i++){
  109946. int acc=0;
  109947. for(j=0;msb>>j;j++)
  109948. if((msb>>j)&i)acc|=1<<j;
  109949. bitrev[i*2]=((~acc)&mask)-1;
  109950. bitrev[i*2+1]=acc;
  109951. }
  109952. }
  109953. lookup->scale=FLOAT_CONV(4.f/n);
  109954. }
  109955. /* 8 point butterfly (in place, 4 register) */
  109956. STIN void mdct_butterfly_8(DATA_TYPE *x){
  109957. REG_TYPE r0 = x[6] + x[2];
  109958. REG_TYPE r1 = x[6] - x[2];
  109959. REG_TYPE r2 = x[4] + x[0];
  109960. REG_TYPE r3 = x[4] - x[0];
  109961. x[6] = r0 + r2;
  109962. x[4] = r0 - r2;
  109963. r0 = x[5] - x[1];
  109964. r2 = x[7] - x[3];
  109965. x[0] = r1 + r0;
  109966. x[2] = r1 - r0;
  109967. r0 = x[5] + x[1];
  109968. r1 = x[7] + x[3];
  109969. x[3] = r2 + r3;
  109970. x[1] = r2 - r3;
  109971. x[7] = r1 + r0;
  109972. x[5] = r1 - r0;
  109973. }
  109974. /* 16 point butterfly (in place, 4 register) */
  109975. STIN void mdct_butterfly_16(DATA_TYPE *x){
  109976. REG_TYPE r0 = x[1] - x[9];
  109977. REG_TYPE r1 = x[0] - x[8];
  109978. x[8] += x[0];
  109979. x[9] += x[1];
  109980. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  109981. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  109982. r0 = x[3] - x[11];
  109983. r1 = x[10] - x[2];
  109984. x[10] += x[2];
  109985. x[11] += x[3];
  109986. x[2] = r0;
  109987. x[3] = r1;
  109988. r0 = x[12] - x[4];
  109989. r1 = x[13] - x[5];
  109990. x[12] += x[4];
  109991. x[13] += x[5];
  109992. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  109993. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  109994. r0 = x[14] - x[6];
  109995. r1 = x[15] - x[7];
  109996. x[14] += x[6];
  109997. x[15] += x[7];
  109998. x[6] = r0;
  109999. x[7] = r1;
  110000. mdct_butterfly_8(x);
  110001. mdct_butterfly_8(x+8);
  110002. }
  110003. /* 32 point butterfly (in place, 4 register) */
  110004. STIN void mdct_butterfly_32(DATA_TYPE *x){
  110005. REG_TYPE r0 = x[30] - x[14];
  110006. REG_TYPE r1 = x[31] - x[15];
  110007. x[30] += x[14];
  110008. x[31] += x[15];
  110009. x[14] = r0;
  110010. x[15] = r1;
  110011. r0 = x[28] - x[12];
  110012. r1 = x[29] - x[13];
  110013. x[28] += x[12];
  110014. x[29] += x[13];
  110015. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  110016. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  110017. r0 = x[26] - x[10];
  110018. r1 = x[27] - x[11];
  110019. x[26] += x[10];
  110020. x[27] += x[11];
  110021. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  110022. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  110023. r0 = x[24] - x[8];
  110024. r1 = x[25] - x[9];
  110025. x[24] += x[8];
  110026. x[25] += x[9];
  110027. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  110028. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  110029. r0 = x[22] - x[6];
  110030. r1 = x[7] - x[23];
  110031. x[22] += x[6];
  110032. x[23] += x[7];
  110033. x[6] = r1;
  110034. x[7] = r0;
  110035. r0 = x[4] - x[20];
  110036. r1 = x[5] - x[21];
  110037. x[20] += x[4];
  110038. x[21] += x[5];
  110039. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  110040. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  110041. r0 = x[2] - x[18];
  110042. r1 = x[3] - x[19];
  110043. x[18] += x[2];
  110044. x[19] += x[3];
  110045. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  110046. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  110047. r0 = x[0] - x[16];
  110048. r1 = x[1] - x[17];
  110049. x[16] += x[0];
  110050. x[17] += x[1];
  110051. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  110052. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  110053. mdct_butterfly_16(x);
  110054. mdct_butterfly_16(x+16);
  110055. }
  110056. /* N point first stage butterfly (in place, 2 register) */
  110057. STIN void mdct_butterfly_first(DATA_TYPE *T,
  110058. DATA_TYPE *x,
  110059. int points){
  110060. DATA_TYPE *x1 = x + points - 8;
  110061. DATA_TYPE *x2 = x + (points>>1) - 8;
  110062. REG_TYPE r0;
  110063. REG_TYPE r1;
  110064. do{
  110065. r0 = x1[6] - x2[6];
  110066. r1 = x1[7] - x2[7];
  110067. x1[6] += x2[6];
  110068. x1[7] += x2[7];
  110069. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110070. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110071. r0 = x1[4] - x2[4];
  110072. r1 = x1[5] - x2[5];
  110073. x1[4] += x2[4];
  110074. x1[5] += x2[5];
  110075. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  110076. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  110077. r0 = x1[2] - x2[2];
  110078. r1 = x1[3] - x2[3];
  110079. x1[2] += x2[2];
  110080. x1[3] += x2[3];
  110081. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  110082. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  110083. r0 = x1[0] - x2[0];
  110084. r1 = x1[1] - x2[1];
  110085. x1[0] += x2[0];
  110086. x1[1] += x2[1];
  110087. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  110088. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  110089. x1-=8;
  110090. x2-=8;
  110091. T+=16;
  110092. }while(x2>=x);
  110093. }
  110094. /* N/stage point generic N stage butterfly (in place, 2 register) */
  110095. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  110096. DATA_TYPE *x,
  110097. int points,
  110098. int trigint){
  110099. DATA_TYPE *x1 = x + points - 8;
  110100. DATA_TYPE *x2 = x + (points>>1) - 8;
  110101. REG_TYPE r0;
  110102. REG_TYPE r1;
  110103. do{
  110104. r0 = x1[6] - x2[6];
  110105. r1 = x1[7] - x2[7];
  110106. x1[6] += x2[6];
  110107. x1[7] += x2[7];
  110108. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110109. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110110. T+=trigint;
  110111. r0 = x1[4] - x2[4];
  110112. r1 = x1[5] - x2[5];
  110113. x1[4] += x2[4];
  110114. x1[5] += x2[5];
  110115. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110116. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110117. T+=trigint;
  110118. r0 = x1[2] - x2[2];
  110119. r1 = x1[3] - x2[3];
  110120. x1[2] += x2[2];
  110121. x1[3] += x2[3];
  110122. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110123. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110124. T+=trigint;
  110125. r0 = x1[0] - x2[0];
  110126. r1 = x1[1] - x2[1];
  110127. x1[0] += x2[0];
  110128. x1[1] += x2[1];
  110129. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110130. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110131. T+=trigint;
  110132. x1-=8;
  110133. x2-=8;
  110134. }while(x2>=x);
  110135. }
  110136. STIN void mdct_butterflies(mdct_lookup *init,
  110137. DATA_TYPE *x,
  110138. int points){
  110139. DATA_TYPE *T=init->trig;
  110140. int stages=init->log2n-5;
  110141. int i,j;
  110142. if(--stages>0){
  110143. mdct_butterfly_first(T,x,points);
  110144. }
  110145. for(i=1;--stages>0;i++){
  110146. for(j=0;j<(1<<i);j++)
  110147. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  110148. }
  110149. for(j=0;j<points;j+=32)
  110150. mdct_butterfly_32(x+j);
  110151. }
  110152. void mdct_clear(mdct_lookup *l){
  110153. if(l){
  110154. if(l->trig)_ogg_free(l->trig);
  110155. if(l->bitrev)_ogg_free(l->bitrev);
  110156. memset(l,0,sizeof(*l));
  110157. }
  110158. }
  110159. STIN void mdct_bitreverse(mdct_lookup *init,
  110160. DATA_TYPE *x){
  110161. int n = init->n;
  110162. int *bit = init->bitrev;
  110163. DATA_TYPE *w0 = x;
  110164. DATA_TYPE *w1 = x = w0+(n>>1);
  110165. DATA_TYPE *T = init->trig+n;
  110166. do{
  110167. DATA_TYPE *x0 = x+bit[0];
  110168. DATA_TYPE *x1 = x+bit[1];
  110169. REG_TYPE r0 = x0[1] - x1[1];
  110170. REG_TYPE r1 = x0[0] + x1[0];
  110171. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  110172. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  110173. w1 -= 4;
  110174. r0 = HALVE(x0[1] + x1[1]);
  110175. r1 = HALVE(x0[0] - x1[0]);
  110176. w0[0] = r0 + r2;
  110177. w1[2] = r0 - r2;
  110178. w0[1] = r1 + r3;
  110179. w1[3] = r3 - r1;
  110180. x0 = x+bit[2];
  110181. x1 = x+bit[3];
  110182. r0 = x0[1] - x1[1];
  110183. r1 = x0[0] + x1[0];
  110184. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  110185. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  110186. r0 = HALVE(x0[1] + x1[1]);
  110187. r1 = HALVE(x0[0] - x1[0]);
  110188. w0[2] = r0 + r2;
  110189. w1[0] = r0 - r2;
  110190. w0[3] = r1 + r3;
  110191. w1[1] = r3 - r1;
  110192. T += 4;
  110193. bit += 4;
  110194. w0 += 4;
  110195. }while(w0<w1);
  110196. }
  110197. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  110198. int n=init->n;
  110199. int n2=n>>1;
  110200. int n4=n>>2;
  110201. /* rotate */
  110202. DATA_TYPE *iX = in+n2-7;
  110203. DATA_TYPE *oX = out+n2+n4;
  110204. DATA_TYPE *T = init->trig+n4;
  110205. do{
  110206. oX -= 4;
  110207. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  110208. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  110209. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  110210. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  110211. iX -= 8;
  110212. T += 4;
  110213. }while(iX>=in);
  110214. iX = in+n2-8;
  110215. oX = out+n2+n4;
  110216. T = init->trig+n4;
  110217. do{
  110218. T -= 4;
  110219. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  110220. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  110221. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  110222. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  110223. iX -= 8;
  110224. oX += 4;
  110225. }while(iX>=in);
  110226. mdct_butterflies(init,out+n2,n2);
  110227. mdct_bitreverse(init,out);
  110228. /* roatate + window */
  110229. {
  110230. DATA_TYPE *oX1=out+n2+n4;
  110231. DATA_TYPE *oX2=out+n2+n4;
  110232. DATA_TYPE *iX =out;
  110233. T =init->trig+n2;
  110234. do{
  110235. oX1-=4;
  110236. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  110237. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  110238. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  110239. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  110240. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  110241. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  110242. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  110243. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  110244. oX2+=4;
  110245. iX += 8;
  110246. T += 8;
  110247. }while(iX<oX1);
  110248. iX=out+n2+n4;
  110249. oX1=out+n4;
  110250. oX2=oX1;
  110251. do{
  110252. oX1-=4;
  110253. iX-=4;
  110254. oX2[0] = -(oX1[3] = iX[3]);
  110255. oX2[1] = -(oX1[2] = iX[2]);
  110256. oX2[2] = -(oX1[1] = iX[1]);
  110257. oX2[3] = -(oX1[0] = iX[0]);
  110258. oX2+=4;
  110259. }while(oX2<iX);
  110260. iX=out+n2+n4;
  110261. oX1=out+n2+n4;
  110262. oX2=out+n2;
  110263. do{
  110264. oX1-=4;
  110265. oX1[0]= iX[3];
  110266. oX1[1]= iX[2];
  110267. oX1[2]= iX[1];
  110268. oX1[3]= iX[0];
  110269. iX+=4;
  110270. }while(oX1>oX2);
  110271. }
  110272. }
  110273. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  110274. int n=init->n;
  110275. int n2=n>>1;
  110276. int n4=n>>2;
  110277. int n8=n>>3;
  110278. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  110279. DATA_TYPE *w2=w+n2;
  110280. /* rotate */
  110281. /* window + rotate + step 1 */
  110282. REG_TYPE r0;
  110283. REG_TYPE r1;
  110284. DATA_TYPE *x0=in+n2+n4;
  110285. DATA_TYPE *x1=x0+1;
  110286. DATA_TYPE *T=init->trig+n2;
  110287. int i=0;
  110288. for(i=0;i<n8;i+=2){
  110289. x0 -=4;
  110290. T-=2;
  110291. r0= x0[2] + x1[0];
  110292. r1= x0[0] + x1[2];
  110293. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  110294. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  110295. x1 +=4;
  110296. }
  110297. x1=in+1;
  110298. for(;i<n2-n8;i+=2){
  110299. T-=2;
  110300. x0 -=4;
  110301. r0= x0[2] - x1[0];
  110302. r1= x0[0] - x1[2];
  110303. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  110304. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  110305. x1 +=4;
  110306. }
  110307. x0=in+n;
  110308. for(;i<n2;i+=2){
  110309. T-=2;
  110310. x0 -=4;
  110311. r0= -x0[2] - x1[0];
  110312. r1= -x0[0] - x1[2];
  110313. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  110314. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  110315. x1 +=4;
  110316. }
  110317. mdct_butterflies(init,w+n2,n2);
  110318. mdct_bitreverse(init,w);
  110319. /* roatate + window */
  110320. T=init->trig+n2;
  110321. x0=out+n2;
  110322. for(i=0;i<n4;i++){
  110323. x0--;
  110324. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  110325. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  110326. w+=2;
  110327. T+=2;
  110328. }
  110329. }
  110330. #endif
  110331. /********* End of inlined file: mdct.c *********/
  110332. /********* Start of inlined file: psy.c *********/
  110333. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110334. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110335. // tasks..
  110336. #ifdef _MSC_VER
  110337. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110338. #endif
  110339. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110340. #if JUCE_USE_OGGVORBIS
  110341. #include <stdlib.h>
  110342. #include <math.h>
  110343. #include <string.h>
  110344. /********* Start of inlined file: masking.h *********/
  110345. #ifndef _V_MASKING_H_
  110346. #define _V_MASKING_H_
  110347. /* more detailed ATH; the bass if flat to save stressing the floor
  110348. overly for only a bin or two of savings. */
  110349. #define MAX_ATH 88
  110350. static float ATH[]={
  110351. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  110352. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  110353. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  110354. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  110355. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  110356. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  110357. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  110358. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  110359. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  110360. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  110361. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  110362. };
  110363. /* The tone masking curves from Ehmer's and Fielder's papers have been
  110364. replaced by an empirically collected data set. The previously
  110365. published values were, far too often, simply on crack. */
  110366. #define EHMER_OFFSET 16
  110367. #define EHMER_MAX 56
  110368. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  110369. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  110370. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  110371. for collection of these curves) */
  110372. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  110373. /* 62.5 Hz */
  110374. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  110375. -60, -60, -60, -60, -62, -62, -65, -73,
  110376. -69, -68, -68, -67, -70, -70, -72, -74,
  110377. -75, -79, -79, -80, -83, -88, -93, -100,
  110378. -110, -999, -999, -999, -999, -999, -999, -999,
  110379. -999, -999, -999, -999, -999, -999, -999, -999,
  110380. -999, -999, -999, -999, -999, -999, -999, -999},
  110381. { -48, -48, -48, -48, -48, -48, -48, -48,
  110382. -48, -48, -48, -48, -48, -53, -61, -66,
  110383. -66, -68, -67, -70, -76, -76, -72, -73,
  110384. -75, -76, -78, -79, -83, -88, -93, -100,
  110385. -110, -999, -999, -999, -999, -999, -999, -999,
  110386. -999, -999, -999, -999, -999, -999, -999, -999,
  110387. -999, -999, -999, -999, -999, -999, -999, -999},
  110388. { -37, -37, -37, -37, -37, -37, -37, -37,
  110389. -38, -40, -42, -46, -48, -53, -55, -62,
  110390. -65, -58, -56, -56, -61, -60, -65, -67,
  110391. -69, -71, -77, -77, -78, -80, -82, -84,
  110392. -88, -93, -98, -106, -112, -999, -999, -999,
  110393. -999, -999, -999, -999, -999, -999, -999, -999,
  110394. -999, -999, -999, -999, -999, -999, -999, -999},
  110395. { -25, -25, -25, -25, -25, -25, -25, -25,
  110396. -25, -26, -27, -29, -32, -38, -48, -52,
  110397. -52, -50, -48, -48, -51, -52, -54, -60,
  110398. -67, -67, -66, -68, -69, -73, -73, -76,
  110399. -80, -81, -81, -85, -85, -86, -88, -93,
  110400. -100, -110, -999, -999, -999, -999, -999, -999,
  110401. -999, -999, -999, -999, -999, -999, -999, -999},
  110402. { -16, -16, -16, -16, -16, -16, -16, -16,
  110403. -17, -19, -20, -22, -26, -28, -31, -40,
  110404. -47, -39, -39, -40, -42, -43, -47, -51,
  110405. -57, -52, -55, -55, -60, -58, -62, -63,
  110406. -70, -67, -69, -72, -73, -77, -80, -82,
  110407. -83, -87, -90, -94, -98, -104, -115, -999,
  110408. -999, -999, -999, -999, -999, -999, -999, -999},
  110409. { -8, -8, -8, -8, -8, -8, -8, -8,
  110410. -8, -8, -10, -11, -15, -19, -25, -30,
  110411. -34, -31, -30, -31, -29, -32, -35, -42,
  110412. -48, -42, -44, -46, -50, -50, -51, -52,
  110413. -59, -54, -55, -55, -58, -62, -63, -66,
  110414. -72, -73, -76, -75, -78, -80, -80, -81,
  110415. -84, -88, -90, -94, -98, -101, -106, -110}},
  110416. /* 88Hz */
  110417. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  110418. -66, -66, -66, -66, -66, -67, -67, -67,
  110419. -76, -72, -71, -74, -76, -76, -75, -78,
  110420. -79, -79, -81, -83, -86, -89, -93, -97,
  110421. -100, -105, -110, -999, -999, -999, -999, -999,
  110422. -999, -999, -999, -999, -999, -999, -999, -999,
  110423. -999, -999, -999, -999, -999, -999, -999, -999},
  110424. { -47, -47, -47, -47, -47, -47, -47, -47,
  110425. -47, -47, -47, -48, -51, -55, -59, -66,
  110426. -66, -66, -67, -66, -68, -69, -70, -74,
  110427. -79, -77, -77, -78, -80, -81, -82, -84,
  110428. -86, -88, -91, -95, -100, -108, -116, -999,
  110429. -999, -999, -999, -999, -999, -999, -999, -999,
  110430. -999, -999, -999, -999, -999, -999, -999, -999},
  110431. { -36, -36, -36, -36, -36, -36, -36, -36,
  110432. -36, -37, -37, -41, -44, -48, -51, -58,
  110433. -62, -60, -57, -59, -59, -60, -63, -65,
  110434. -72, -71, -70, -72, -74, -77, -76, -78,
  110435. -81, -81, -80, -83, -86, -91, -96, -100,
  110436. -105, -110, -999, -999, -999, -999, -999, -999,
  110437. -999, -999, -999, -999, -999, -999, -999, -999},
  110438. { -28, -28, -28, -28, -28, -28, -28, -28,
  110439. -28, -30, -32, -32, -33, -35, -41, -49,
  110440. -50, -49, -47, -48, -48, -52, -51, -57,
  110441. -65, -61, -59, -61, -64, -69, -70, -74,
  110442. -77, -77, -78, -81, -84, -85, -87, -90,
  110443. -92, -96, -100, -107, -112, -999, -999, -999,
  110444. -999, -999, -999, -999, -999, -999, -999, -999},
  110445. { -19, -19, -19, -19, -19, -19, -19, -19,
  110446. -20, -21, -23, -27, -30, -35, -36, -41,
  110447. -46, -44, -42, -40, -41, -41, -43, -48,
  110448. -55, -53, -52, -53, -56, -59, -58, -60,
  110449. -67, -66, -69, -71, -72, -75, -79, -81,
  110450. -84, -87, -90, -93, -97, -101, -107, -114,
  110451. -999, -999, -999, -999, -999, -999, -999, -999},
  110452. { -9, -9, -9, -9, -9, -9, -9, -9,
  110453. -11, -12, -12, -15, -16, -20, -23, -30,
  110454. -37, -34, -33, -34, -31, -32, -32, -38,
  110455. -47, -44, -41, -40, -47, -49, -46, -46,
  110456. -58, -50, -50, -54, -58, -62, -64, -67,
  110457. -67, -70, -72, -76, -79, -83, -87, -91,
  110458. -96, -100, -104, -110, -999, -999, -999, -999}},
  110459. /* 125 Hz */
  110460. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  110461. -62, -62, -63, -64, -66, -67, -66, -68,
  110462. -75, -72, -76, -75, -76, -78, -79, -82,
  110463. -84, -85, -90, -94, -101, -110, -999, -999,
  110464. -999, -999, -999, -999, -999, -999, -999, -999,
  110465. -999, -999, -999, -999, -999, -999, -999, -999,
  110466. -999, -999, -999, -999, -999, -999, -999, -999},
  110467. { -59, -59, -59, -59, -59, -59, -59, -59,
  110468. -59, -59, -59, -60, -60, -61, -63, -66,
  110469. -71, -68, -70, -70, -71, -72, -72, -75,
  110470. -81, -78, -79, -82, -83, -86, -90, -97,
  110471. -103, -113, -999, -999, -999, -999, -999, -999,
  110472. -999, -999, -999, -999, -999, -999, -999, -999,
  110473. -999, -999, -999, -999, -999, -999, -999, -999},
  110474. { -53, -53, -53, -53, -53, -53, -53, -53,
  110475. -53, -54, -55, -57, -56, -57, -55, -61,
  110476. -65, -60, -60, -62, -63, -63, -66, -68,
  110477. -74, -73, -75, -75, -78, -80, -80, -82,
  110478. -85, -90, -96, -101, -108, -999, -999, -999,
  110479. -999, -999, -999, -999, -999, -999, -999, -999,
  110480. -999, -999, -999, -999, -999, -999, -999, -999},
  110481. { -46, -46, -46, -46, -46, -46, -46, -46,
  110482. -46, -46, -47, -47, -47, -47, -48, -51,
  110483. -57, -51, -49, -50, -51, -53, -54, -59,
  110484. -66, -60, -62, -67, -67, -70, -72, -75,
  110485. -76, -78, -81, -85, -88, -94, -97, -104,
  110486. -112, -999, -999, -999, -999, -999, -999, -999,
  110487. -999, -999, -999, -999, -999, -999, -999, -999},
  110488. { -36, -36, -36, -36, -36, -36, -36, -36,
  110489. -39, -41, -42, -42, -39, -38, -41, -43,
  110490. -52, -44, -40, -39, -37, -37, -40, -47,
  110491. -54, -50, -48, -50, -55, -61, -59, -62,
  110492. -66, -66, -66, -69, -69, -73, -74, -74,
  110493. -75, -77, -79, -82, -87, -91, -95, -100,
  110494. -108, -115, -999, -999, -999, -999, -999, -999},
  110495. { -28, -26, -24, -22, -20, -20, -23, -29,
  110496. -30, -31, -28, -27, -28, -28, -28, -35,
  110497. -40, -33, -32, -29, -30, -30, -30, -37,
  110498. -45, -41, -37, -38, -45, -47, -47, -48,
  110499. -53, -49, -48, -50, -49, -49, -51, -52,
  110500. -58, -56, -57, -56, -60, -61, -62, -70,
  110501. -72, -74, -78, -83, -88, -93, -100, -106}},
  110502. /* 177 Hz */
  110503. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110504. -999, -110, -105, -100, -95, -91, -87, -83,
  110505. -80, -78, -76, -78, -78, -81, -83, -85,
  110506. -86, -85, -86, -87, -90, -97, -107, -999,
  110507. -999, -999, -999, -999, -999, -999, -999, -999,
  110508. -999, -999, -999, -999, -999, -999, -999, -999,
  110509. -999, -999, -999, -999, -999, -999, -999, -999},
  110510. {-999, -999, -999, -110, -105, -100, -95, -90,
  110511. -85, -81, -77, -73, -70, -67, -67, -68,
  110512. -75, -73, -70, -69, -70, -72, -75, -79,
  110513. -84, -83, -84, -86, -88, -89, -89, -93,
  110514. -98, -105, -112, -999, -999, -999, -999, -999,
  110515. -999, -999, -999, -999, -999, -999, -999, -999,
  110516. -999, -999, -999, -999, -999, -999, -999, -999},
  110517. {-105, -100, -95, -90, -85, -80, -76, -71,
  110518. -68, -68, -65, -63, -63, -62, -62, -64,
  110519. -65, -64, -61, -62, -63, -64, -66, -68,
  110520. -73, -73, -74, -75, -76, -81, -83, -85,
  110521. -88, -89, -92, -95, -100, -108, -999, -999,
  110522. -999, -999, -999, -999, -999, -999, -999, -999,
  110523. -999, -999, -999, -999, -999, -999, -999, -999},
  110524. { -80, -75, -71, -68, -65, -63, -62, -61,
  110525. -61, -61, -61, -59, -56, -57, -53, -50,
  110526. -58, -52, -50, -50, -52, -53, -54, -58,
  110527. -67, -63, -67, -68, -72, -75, -78, -80,
  110528. -81, -81, -82, -85, -89, -90, -93, -97,
  110529. -101, -107, -114, -999, -999, -999, -999, -999,
  110530. -999, -999, -999, -999, -999, -999, -999, -999},
  110531. { -65, -61, -59, -57, -56, -55, -55, -56,
  110532. -56, -57, -55, -53, -52, -47, -44, -44,
  110533. -50, -44, -41, -39, -39, -42, -40, -46,
  110534. -51, -49, -50, -53, -54, -63, -60, -61,
  110535. -62, -66, -66, -66, -70, -73, -74, -75,
  110536. -76, -75, -79, -85, -89, -91, -96, -102,
  110537. -110, -999, -999, -999, -999, -999, -999, -999},
  110538. { -52, -50, -49, -49, -48, -48, -48, -49,
  110539. -50, -50, -49, -46, -43, -39, -35, -33,
  110540. -38, -36, -32, -29, -32, -32, -32, -35,
  110541. -44, -39, -38, -38, -46, -50, -45, -46,
  110542. -53, -50, -50, -50, -54, -54, -53, -53,
  110543. -56, -57, -59, -66, -70, -72, -74, -79,
  110544. -83, -85, -90, -97, -114, -999, -999, -999}},
  110545. /* 250 Hz */
  110546. {{-999, -999, -999, -999, -999, -999, -110, -105,
  110547. -100, -95, -90, -86, -80, -75, -75, -79,
  110548. -80, -79, -80, -81, -82, -88, -95, -103,
  110549. -110, -999, -999, -999, -999, -999, -999, -999,
  110550. -999, -999, -999, -999, -999, -999, -999, -999,
  110551. -999, -999, -999, -999, -999, -999, -999, -999,
  110552. -999, -999, -999, -999, -999, -999, -999, -999},
  110553. {-999, -999, -999, -999, -108, -103, -98, -93,
  110554. -88, -83, -79, -78, -75, -71, -67, -68,
  110555. -73, -73, -72, -73, -75, -77, -80, -82,
  110556. -88, -93, -100, -107, -114, -999, -999, -999,
  110557. -999, -999, -999, -999, -999, -999, -999, -999,
  110558. -999, -999, -999, -999, -999, -999, -999, -999,
  110559. -999, -999, -999, -999, -999, -999, -999, -999},
  110560. {-999, -999, -999, -110, -105, -101, -96, -90,
  110561. -86, -81, -77, -73, -69, -66, -61, -62,
  110562. -66, -64, -62, -65, -66, -70, -72, -76,
  110563. -81, -80, -84, -90, -95, -102, -110, -999,
  110564. -999, -999, -999, -999, -999, -999, -999, -999,
  110565. -999, -999, -999, -999, -999, -999, -999, -999,
  110566. -999, -999, -999, -999, -999, -999, -999, -999},
  110567. {-999, -999, -999, -107, -103, -97, -92, -88,
  110568. -83, -79, -74, -70, -66, -59, -53, -58,
  110569. -62, -55, -54, -54, -54, -58, -61, -62,
  110570. -72, -70, -72, -75, -78, -80, -81, -80,
  110571. -83, -83, -88, -93, -100, -107, -115, -999,
  110572. -999, -999, -999, -999, -999, -999, -999, -999,
  110573. -999, -999, -999, -999, -999, -999, -999, -999},
  110574. {-999, -999, -999, -105, -100, -95, -90, -85,
  110575. -80, -75, -70, -66, -62, -56, -48, -44,
  110576. -48, -46, -46, -43, -46, -48, -48, -51,
  110577. -58, -58, -59, -60, -62, -62, -61, -61,
  110578. -65, -64, -65, -68, -70, -74, -75, -78,
  110579. -81, -86, -95, -110, -999, -999, -999, -999,
  110580. -999, -999, -999, -999, -999, -999, -999, -999},
  110581. {-999, -999, -105, -100, -95, -90, -85, -80,
  110582. -75, -70, -65, -61, -55, -49, -39, -33,
  110583. -40, -35, -32, -38, -40, -33, -35, -37,
  110584. -46, -41, -45, -44, -46, -42, -45, -46,
  110585. -52, -50, -50, -50, -54, -54, -55, -57,
  110586. -62, -64, -66, -68, -70, -76, -81, -90,
  110587. -100, -110, -999, -999, -999, -999, -999, -999}},
  110588. /* 354 hz */
  110589. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110590. -105, -98, -90, -85, -82, -83, -80, -78,
  110591. -84, -79, -80, -83, -87, -89, -91, -93,
  110592. -99, -106, -117, -999, -999, -999, -999, -999,
  110593. -999, -999, -999, -999, -999, -999, -999, -999,
  110594. -999, -999, -999, -999, -999, -999, -999, -999,
  110595. -999, -999, -999, -999, -999, -999, -999, -999},
  110596. {-999, -999, -999, -999, -999, -999, -999, -999,
  110597. -105, -98, -90, -85, -80, -75, -70, -68,
  110598. -74, -72, -74, -77, -80, -82, -85, -87,
  110599. -92, -89, -91, -95, -100, -106, -112, -999,
  110600. -999, -999, -999, -999, -999, -999, -999, -999,
  110601. -999, -999, -999, -999, -999, -999, -999, -999,
  110602. -999, -999, -999, -999, -999, -999, -999, -999},
  110603. {-999, -999, -999, -999, -999, -999, -999, -999,
  110604. -105, -98, -90, -83, -75, -71, -63, -64,
  110605. -67, -62, -64, -67, -70, -73, -77, -81,
  110606. -84, -83, -85, -89, -90, -93, -98, -104,
  110607. -109, -114, -999, -999, -999, -999, -999, -999,
  110608. -999, -999, -999, -999, -999, -999, -999, -999,
  110609. -999, -999, -999, -999, -999, -999, -999, -999},
  110610. {-999, -999, -999, -999, -999, -999, -999, -999,
  110611. -103, -96, -88, -81, -75, -68, -58, -54,
  110612. -56, -54, -56, -56, -58, -60, -63, -66,
  110613. -74, -69, -72, -72, -75, -74, -77, -81,
  110614. -81, -82, -84, -87, -93, -96, -99, -104,
  110615. -110, -999, -999, -999, -999, -999, -999, -999,
  110616. -999, -999, -999, -999, -999, -999, -999, -999},
  110617. {-999, -999, -999, -999, -999, -108, -102, -96,
  110618. -91, -85, -80, -74, -68, -60, -51, -46,
  110619. -48, -46, -43, -45, -47, -47, -49, -48,
  110620. -56, -53, -55, -58, -57, -63, -58, -60,
  110621. -66, -64, -67, -70, -70, -74, -77, -84,
  110622. -86, -89, -91, -93, -94, -101, -109, -118,
  110623. -999, -999, -999, -999, -999, -999, -999, -999},
  110624. {-999, -999, -999, -108, -103, -98, -93, -88,
  110625. -83, -78, -73, -68, -60, -53, -44, -35,
  110626. -38, -38, -34, -34, -36, -40, -41, -44,
  110627. -51, -45, -46, -47, -46, -54, -50, -49,
  110628. -50, -50, -50, -51, -54, -57, -58, -60,
  110629. -66, -66, -66, -64, -65, -68, -77, -82,
  110630. -87, -95, -110, -999, -999, -999, -999, -999}},
  110631. /* 500 Hz */
  110632. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110633. -107, -102, -97, -92, -87, -83, -78, -75,
  110634. -82, -79, -83, -85, -89, -92, -95, -98,
  110635. -101, -105, -109, -113, -999, -999, -999, -999,
  110636. -999, -999, -999, -999, -999, -999, -999, -999,
  110637. -999, -999, -999, -999, -999, -999, -999, -999,
  110638. -999, -999, -999, -999, -999, -999, -999, -999},
  110639. {-999, -999, -999, -999, -999, -999, -999, -106,
  110640. -100, -95, -90, -86, -81, -78, -74, -69,
  110641. -74, -74, -76, -79, -83, -84, -86, -89,
  110642. -92, -97, -93, -100, -103, -107, -110, -999,
  110643. -999, -999, -999, -999, -999, -999, -999, -999,
  110644. -999, -999, -999, -999, -999, -999, -999, -999,
  110645. -999, -999, -999, -999, -999, -999, -999, -999},
  110646. {-999, -999, -999, -999, -999, -999, -106, -100,
  110647. -95, -90, -87, -83, -80, -75, -69, -60,
  110648. -66, -66, -68, -70, -74, -78, -79, -81,
  110649. -81, -83, -84, -87, -93, -96, -99, -103,
  110650. -107, -110, -999, -999, -999, -999, -999, -999,
  110651. -999, -999, -999, -999, -999, -999, -999, -999,
  110652. -999, -999, -999, -999, -999, -999, -999, -999},
  110653. {-999, -999, -999, -999, -999, -108, -103, -98,
  110654. -93, -89, -85, -82, -78, -71, -62, -55,
  110655. -58, -58, -54, -54, -55, -59, -61, -62,
  110656. -70, -66, -66, -67, -70, -72, -75, -78,
  110657. -84, -84, -84, -88, -91, -90, -95, -98,
  110658. -102, -103, -106, -110, -999, -999, -999, -999,
  110659. -999, -999, -999, -999, -999, -999, -999, -999},
  110660. {-999, -999, -999, -999, -108, -103, -98, -94,
  110661. -90, -87, -82, -79, -73, -67, -58, -47,
  110662. -50, -45, -41, -45, -48, -44, -44, -49,
  110663. -54, -51, -48, -47, -49, -50, -51, -57,
  110664. -58, -60, -63, -69, -70, -69, -71, -74,
  110665. -78, -82, -90, -95, -101, -105, -110, -999,
  110666. -999, -999, -999, -999, -999, -999, -999, -999},
  110667. {-999, -999, -999, -105, -101, -97, -93, -90,
  110668. -85, -80, -77, -72, -65, -56, -48, -37,
  110669. -40, -36, -34, -40, -50, -47, -38, -41,
  110670. -47, -38, -35, -39, -38, -43, -40, -45,
  110671. -50, -45, -44, -47, -50, -55, -48, -48,
  110672. -52, -66, -70, -76, -82, -90, -97, -105,
  110673. -110, -999, -999, -999, -999, -999, -999, -999}},
  110674. /* 707 Hz */
  110675. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110676. -999, -108, -103, -98, -93, -86, -79, -76,
  110677. -83, -81, -85, -87, -89, -93, -98, -102,
  110678. -107, -112, -999, -999, -999, -999, -999, -999,
  110679. -999, -999, -999, -999, -999, -999, -999, -999,
  110680. -999, -999, -999, -999, -999, -999, -999, -999,
  110681. -999, -999, -999, -999, -999, -999, -999, -999},
  110682. {-999, -999, -999, -999, -999, -999, -999, -999,
  110683. -999, -108, -103, -98, -93, -86, -79, -71,
  110684. -77, -74, -77, -79, -81, -84, -85, -90,
  110685. -92, -93, -92, -98, -101, -108, -112, -999,
  110686. -999, -999, -999, -999, -999, -999, -999, -999,
  110687. -999, -999, -999, -999, -999, -999, -999, -999,
  110688. -999, -999, -999, -999, -999, -999, -999, -999},
  110689. {-999, -999, -999, -999, -999, -999, -999, -999,
  110690. -108, -103, -98, -93, -87, -78, -68, -65,
  110691. -66, -62, -65, -67, -70, -73, -75, -78,
  110692. -82, -82, -83, -84, -91, -93, -98, -102,
  110693. -106, -110, -999, -999, -999, -999, -999, -999,
  110694. -999, -999, -999, -999, -999, -999, -999, -999,
  110695. -999, -999, -999, -999, -999, -999, -999, -999},
  110696. {-999, -999, -999, -999, -999, -999, -999, -999,
  110697. -105, -100, -95, -90, -82, -74, -62, -57,
  110698. -58, -56, -51, -52, -52, -54, -54, -58,
  110699. -66, -59, -60, -63, -66, -69, -73, -79,
  110700. -83, -84, -80, -81, -81, -82, -88, -92,
  110701. -98, -105, -113, -999, -999, -999, -999, -999,
  110702. -999, -999, -999, -999, -999, -999, -999, -999},
  110703. {-999, -999, -999, -999, -999, -999, -999, -107,
  110704. -102, -97, -92, -84, -79, -69, -57, -47,
  110705. -52, -47, -44, -45, -50, -52, -42, -42,
  110706. -53, -43, -43, -48, -51, -56, -55, -52,
  110707. -57, -59, -61, -62, -67, -71, -78, -83,
  110708. -86, -94, -98, -103, -110, -999, -999, -999,
  110709. -999, -999, -999, -999, -999, -999, -999, -999},
  110710. {-999, -999, -999, -999, -999, -999, -105, -100,
  110711. -95, -90, -84, -78, -70, -61, -51, -41,
  110712. -40, -38, -40, -46, -52, -51, -41, -40,
  110713. -46, -40, -38, -38, -41, -46, -41, -46,
  110714. -47, -43, -43, -45, -41, -45, -56, -67,
  110715. -68, -83, -87, -90, -95, -102, -107, -113,
  110716. -999, -999, -999, -999, -999, -999, -999, -999}},
  110717. /* 1000 Hz */
  110718. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110719. -999, -109, -105, -101, -96, -91, -84, -77,
  110720. -82, -82, -85, -89, -94, -100, -106, -110,
  110721. -999, -999, -999, -999, -999, -999, -999, -999,
  110722. -999, -999, -999, -999, -999, -999, -999, -999,
  110723. -999, -999, -999, -999, -999, -999, -999, -999,
  110724. -999, -999, -999, -999, -999, -999, -999, -999},
  110725. {-999, -999, -999, -999, -999, -999, -999, -999,
  110726. -999, -106, -103, -98, -92, -85, -80, -71,
  110727. -75, -72, -76, -80, -84, -86, -89, -93,
  110728. -100, -107, -113, -999, -999, -999, -999, -999,
  110729. -999, -999, -999, -999, -999, -999, -999, -999,
  110730. -999, -999, -999, -999, -999, -999, -999, -999,
  110731. -999, -999, -999, -999, -999, -999, -999, -999},
  110732. {-999, -999, -999, -999, -999, -999, -999, -107,
  110733. -104, -101, -97, -92, -88, -84, -80, -64,
  110734. -66, -63, -64, -66, -69, -73, -77, -83,
  110735. -83, -86, -91, -98, -104, -111, -999, -999,
  110736. -999, -999, -999, -999, -999, -999, -999, -999,
  110737. -999, -999, -999, -999, -999, -999, -999, -999,
  110738. -999, -999, -999, -999, -999, -999, -999, -999},
  110739. {-999, -999, -999, -999, -999, -999, -999, -107,
  110740. -104, -101, -97, -92, -90, -84, -74, -57,
  110741. -58, -52, -55, -54, -50, -52, -50, -52,
  110742. -63, -62, -69, -76, -77, -78, -78, -79,
  110743. -82, -88, -94, -100, -106, -111, -999, -999,
  110744. -999, -999, -999, -999, -999, -999, -999, -999,
  110745. -999, -999, -999, -999, -999, -999, -999, -999},
  110746. {-999, -999, -999, -999, -999, -999, -106, -102,
  110747. -98, -95, -90, -85, -83, -78, -70, -50,
  110748. -50, -41, -44, -49, -47, -50, -50, -44,
  110749. -55, -46, -47, -48, -48, -54, -49, -49,
  110750. -58, -62, -71, -81, -87, -92, -97, -102,
  110751. -108, -114, -999, -999, -999, -999, -999, -999,
  110752. -999, -999, -999, -999, -999, -999, -999, -999},
  110753. {-999, -999, -999, -999, -999, -999, -106, -102,
  110754. -98, -95, -90, -85, -83, -78, -70, -45,
  110755. -43, -41, -47, -50, -51, -50, -49, -45,
  110756. -47, -41, -44, -41, -39, -43, -38, -37,
  110757. -40, -41, -44, -50, -58, -65, -73, -79,
  110758. -85, -92, -97, -101, -105, -109, -113, -999,
  110759. -999, -999, -999, -999, -999, -999, -999, -999}},
  110760. /* 1414 Hz */
  110761. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110762. -999, -999, -999, -107, -100, -95, -87, -81,
  110763. -85, -83, -88, -93, -100, -107, -114, -999,
  110764. -999, -999, -999, -999, -999, -999, -999, -999,
  110765. -999, -999, -999, -999, -999, -999, -999, -999,
  110766. -999, -999, -999, -999, -999, -999, -999, -999,
  110767. -999, -999, -999, -999, -999, -999, -999, -999},
  110768. {-999, -999, -999, -999, -999, -999, -999, -999,
  110769. -999, -999, -107, -101, -95, -88, -83, -76,
  110770. -73, -72, -79, -84, -90, -95, -100, -105,
  110771. -110, -115, -999, -999, -999, -999, -999, -999,
  110772. -999, -999, -999, -999, -999, -999, -999, -999,
  110773. -999, -999, -999, -999, -999, -999, -999, -999,
  110774. -999, -999, -999, -999, -999, -999, -999, -999},
  110775. {-999, -999, -999, -999, -999, -999, -999, -999,
  110776. -999, -999, -104, -98, -92, -87, -81, -70,
  110777. -65, -62, -67, -71, -74, -80, -85, -91,
  110778. -95, -99, -103, -108, -111, -114, -999, -999,
  110779. -999, -999, -999, -999, -999, -999, -999, -999,
  110780. -999, -999, -999, -999, -999, -999, -999, -999,
  110781. -999, -999, -999, -999, -999, -999, -999, -999},
  110782. {-999, -999, -999, -999, -999, -999, -999, -999,
  110783. -999, -999, -103, -97, -90, -85, -76, -60,
  110784. -56, -54, -60, -62, -61, -56, -63, -65,
  110785. -73, -74, -77, -75, -78, -81, -86, -87,
  110786. -88, -91, -94, -98, -103, -110, -999, -999,
  110787. -999, -999, -999, -999, -999, -999, -999, -999,
  110788. -999, -999, -999, -999, -999, -999, -999, -999},
  110789. {-999, -999, -999, -999, -999, -999, -999, -105,
  110790. -100, -97, -92, -86, -81, -79, -70, -57,
  110791. -51, -47, -51, -58, -60, -56, -53, -50,
  110792. -58, -52, -50, -50, -53, -55, -64, -69,
  110793. -71, -85, -82, -78, -81, -85, -95, -102,
  110794. -112, -999, -999, -999, -999, -999, -999, -999,
  110795. -999, -999, -999, -999, -999, -999, -999, -999},
  110796. {-999, -999, -999, -999, -999, -999, -999, -105,
  110797. -100, -97, -92, -85, -83, -79, -72, -49,
  110798. -40, -43, -43, -54, -56, -51, -50, -40,
  110799. -43, -38, -36, -35, -37, -38, -37, -44,
  110800. -54, -60, -57, -60, -70, -75, -84, -92,
  110801. -103, -112, -999, -999, -999, -999, -999, -999,
  110802. -999, -999, -999, -999, -999, -999, -999, -999}},
  110803. /* 2000 Hz */
  110804. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110805. -999, -999, -999, -110, -102, -95, -89, -82,
  110806. -83, -84, -90, -92, -99, -107, -113, -999,
  110807. -999, -999, -999, -999, -999, -999, -999, -999,
  110808. -999, -999, -999, -999, -999, -999, -999, -999,
  110809. -999, -999, -999, -999, -999, -999, -999, -999,
  110810. -999, -999, -999, -999, -999, -999, -999, -999},
  110811. {-999, -999, -999, -999, -999, -999, -999, -999,
  110812. -999, -999, -107, -101, -95, -89, -83, -72,
  110813. -74, -78, -85, -88, -88, -90, -92, -98,
  110814. -105, -111, -999, -999, -999, -999, -999, -999,
  110815. -999, -999, -999, -999, -999, -999, -999, -999,
  110816. -999, -999, -999, -999, -999, -999, -999, -999,
  110817. -999, -999, -999, -999, -999, -999, -999, -999},
  110818. {-999, -999, -999, -999, -999, -999, -999, -999,
  110819. -999, -109, -103, -97, -93, -87, -81, -70,
  110820. -70, -67, -75, -73, -76, -79, -81, -83,
  110821. -88, -89, -97, -103, -110, -999, -999, -999,
  110822. -999, -999, -999, -999, -999, -999, -999, -999,
  110823. -999, -999, -999, -999, -999, -999, -999, -999,
  110824. -999, -999, -999, -999, -999, -999, -999, -999},
  110825. {-999, -999, -999, -999, -999, -999, -999, -999,
  110826. -999, -107, -100, -94, -88, -83, -75, -63,
  110827. -59, -59, -63, -66, -60, -62, -67, -67,
  110828. -77, -76, -81, -88, -86, -92, -96, -102,
  110829. -109, -116, -999, -999, -999, -999, -999, -999,
  110830. -999, -999, -999, -999, -999, -999, -999, -999,
  110831. -999, -999, -999, -999, -999, -999, -999, -999},
  110832. {-999, -999, -999, -999, -999, -999, -999, -999,
  110833. -999, -105, -98, -92, -86, -81, -73, -56,
  110834. -52, -47, -55, -60, -58, -52, -51, -45,
  110835. -49, -50, -53, -54, -61, -71, -70, -69,
  110836. -78, -79, -87, -90, -96, -104, -112, -999,
  110837. -999, -999, -999, -999, -999, -999, -999, -999,
  110838. -999, -999, -999, -999, -999, -999, -999, -999},
  110839. {-999, -999, -999, -999, -999, -999, -999, -999,
  110840. -999, -103, -96, -90, -86, -78, -70, -51,
  110841. -42, -47, -48, -55, -54, -54, -53, -42,
  110842. -35, -28, -33, -38, -37, -44, -47, -49,
  110843. -54, -63, -68, -78, -82, -89, -94, -99,
  110844. -104, -109, -114, -999, -999, -999, -999, -999,
  110845. -999, -999, -999, -999, -999, -999, -999, -999}},
  110846. /* 2828 Hz */
  110847. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110848. -999, -999, -999, -999, -110, -100, -90, -79,
  110849. -85, -81, -82, -82, -89, -94, -99, -103,
  110850. -109, -115, -999, -999, -999, -999, -999, -999,
  110851. -999, -999, -999, -999, -999, -999, -999, -999,
  110852. -999, -999, -999, -999, -999, -999, -999, -999,
  110853. -999, -999, -999, -999, -999, -999, -999, -999},
  110854. {-999, -999, -999, -999, -999, -999, -999, -999,
  110855. -999, -999, -999, -999, -105, -97, -85, -72,
  110856. -74, -70, -70, -70, -76, -85, -91, -93,
  110857. -97, -103, -109, -115, -999, -999, -999, -999,
  110858. -999, -999, -999, -999, -999, -999, -999, -999,
  110859. -999, -999, -999, -999, -999, -999, -999, -999,
  110860. -999, -999, -999, -999, -999, -999, -999, -999},
  110861. {-999, -999, -999, -999, -999, -999, -999, -999,
  110862. -999, -999, -999, -999, -112, -93, -81, -68,
  110863. -62, -60, -60, -57, -63, -70, -77, -82,
  110864. -90, -93, -98, -104, -109, -113, -999, -999,
  110865. -999, -999, -999, -999, -999, -999, -999, -999,
  110866. -999, -999, -999, -999, -999, -999, -999, -999,
  110867. -999, -999, -999, -999, -999, -999, -999, -999},
  110868. {-999, -999, -999, -999, -999, -999, -999, -999,
  110869. -999, -999, -999, -113, -100, -93, -84, -63,
  110870. -58, -48, -53, -54, -52, -52, -57, -64,
  110871. -66, -76, -83, -81, -85, -85, -90, -95,
  110872. -98, -101, -103, -106, -108, -111, -999, -999,
  110873. -999, -999, -999, -999, -999, -999, -999, -999,
  110874. -999, -999, -999, -999, -999, -999, -999, -999},
  110875. {-999, -999, -999, -999, -999, -999, -999, -999,
  110876. -999, -999, -999, -105, -95, -86, -74, -53,
  110877. -50, -38, -43, -49, -43, -42, -39, -39,
  110878. -46, -52, -57, -56, -72, -69, -74, -81,
  110879. -87, -92, -94, -97, -99, -102, -105, -108,
  110880. -999, -999, -999, -999, -999, -999, -999, -999,
  110881. -999, -999, -999, -999, -999, -999, -999, -999},
  110882. {-999, -999, -999, -999, -999, -999, -999, -999,
  110883. -999, -999, -108, -99, -90, -76, -66, -45,
  110884. -43, -41, -44, -47, -43, -47, -40, -30,
  110885. -31, -31, -39, -33, -40, -41, -43, -53,
  110886. -59, -70, -73, -77, -79, -82, -84, -87,
  110887. -999, -999, -999, -999, -999, -999, -999, -999,
  110888. -999, -999, -999, -999, -999, -999, -999, -999}},
  110889. /* 4000 Hz */
  110890. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110891. -999, -999, -999, -999, -999, -110, -91, -76,
  110892. -75, -85, -93, -98, -104, -110, -999, -999,
  110893. -999, -999, -999, -999, -999, -999, -999, -999,
  110894. -999, -999, -999, -999, -999, -999, -999, -999,
  110895. -999, -999, -999, -999, -999, -999, -999, -999,
  110896. -999, -999, -999, -999, -999, -999, -999, -999},
  110897. {-999, -999, -999, -999, -999, -999, -999, -999,
  110898. -999, -999, -999, -999, -999, -110, -91, -70,
  110899. -70, -75, -86, -89, -94, -98, -101, -106,
  110900. -110, -999, -999, -999, -999, -999, -999, -999,
  110901. -999, -999, -999, -999, -999, -999, -999, -999,
  110902. -999, -999, -999, -999, -999, -999, -999, -999,
  110903. -999, -999, -999, -999, -999, -999, -999, -999},
  110904. {-999, -999, -999, -999, -999, -999, -999, -999,
  110905. -999, -999, -999, -999, -110, -95, -80, -60,
  110906. -65, -64, -74, -83, -88, -91, -95, -99,
  110907. -103, -107, -110, -999, -999, -999, -999, -999,
  110908. -999, -999, -999, -999, -999, -999, -999, -999,
  110909. -999, -999, -999, -999, -999, -999, -999, -999,
  110910. -999, -999, -999, -999, -999, -999, -999, -999},
  110911. {-999, -999, -999, -999, -999, -999, -999, -999,
  110912. -999, -999, -999, -999, -110, -95, -80, -58,
  110913. -55, -49, -66, -68, -71, -78, -78, -80,
  110914. -88, -85, -89, -97, -100, -105, -110, -999,
  110915. -999, -999, -999, -999, -999, -999, -999, -999,
  110916. -999, -999, -999, -999, -999, -999, -999, -999,
  110917. -999, -999, -999, -999, -999, -999, -999, -999},
  110918. {-999, -999, -999, -999, -999, -999, -999, -999,
  110919. -999, -999, -999, -999, -110, -95, -80, -53,
  110920. -52, -41, -59, -59, -49, -58, -56, -63,
  110921. -86, -79, -90, -93, -98, -103, -107, -112,
  110922. -999, -999, -999, -999, -999, -999, -999, -999,
  110923. -999, -999, -999, -999, -999, -999, -999, -999,
  110924. -999, -999, -999, -999, -999, -999, -999, -999},
  110925. {-999, -999, -999, -999, -999, -999, -999, -999,
  110926. -999, -999, -999, -110, -97, -91, -73, -45,
  110927. -40, -33, -53, -61, -49, -54, -50, -50,
  110928. -60, -52, -67, -74, -81, -92, -96, -100,
  110929. -105, -110, -999, -999, -999, -999, -999, -999,
  110930. -999, -999, -999, -999, -999, -999, -999, -999,
  110931. -999, -999, -999, -999, -999, -999, -999, -999}},
  110932. /* 5657 Hz */
  110933. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110934. -999, -999, -999, -113, -106, -99, -92, -77,
  110935. -80, -88, -97, -106, -115, -999, -999, -999,
  110936. -999, -999, -999, -999, -999, -999, -999, -999,
  110937. -999, -999, -999, -999, -999, -999, -999, -999,
  110938. -999, -999, -999, -999, -999, -999, -999, -999,
  110939. -999, -999, -999, -999, -999, -999, -999, -999},
  110940. {-999, -999, -999, -999, -999, -999, -999, -999,
  110941. -999, -999, -116, -109, -102, -95, -89, -74,
  110942. -72, -88, -87, -95, -102, -109, -116, -999,
  110943. -999, -999, -999, -999, -999, -999, -999, -999,
  110944. -999, -999, -999, -999, -999, -999, -999, -999,
  110945. -999, -999, -999, -999, -999, -999, -999, -999,
  110946. -999, -999, -999, -999, -999, -999, -999, -999},
  110947. {-999, -999, -999, -999, -999, -999, -999, -999,
  110948. -999, -999, -116, -109, -102, -95, -89, -75,
  110949. -66, -74, -77, -78, -86, -87, -90, -96,
  110950. -105, -115, -999, -999, -999, -999, -999, -999,
  110951. -999, -999, -999, -999, -999, -999, -999, -999,
  110952. -999, -999, -999, -999, -999, -999, -999, -999,
  110953. -999, -999, -999, -999, -999, -999, -999, -999},
  110954. {-999, -999, -999, -999, -999, -999, -999, -999,
  110955. -999, -999, -115, -108, -101, -94, -88, -66,
  110956. -56, -61, -70, -65, -78, -72, -83, -84,
  110957. -93, -98, -105, -110, -999, -999, -999, -999,
  110958. -999, -999, -999, -999, -999, -999, -999, -999,
  110959. -999, -999, -999, -999, -999, -999, -999, -999,
  110960. -999, -999, -999, -999, -999, -999, -999, -999},
  110961. {-999, -999, -999, -999, -999, -999, -999, -999,
  110962. -999, -999, -110, -105, -95, -89, -82, -57,
  110963. -52, -52, -59, -56, -59, -58, -69, -67,
  110964. -88, -82, -82, -89, -94, -100, -108, -999,
  110965. -999, -999, -999, -999, -999, -999, -999, -999,
  110966. -999, -999, -999, -999, -999, -999, -999, -999,
  110967. -999, -999, -999, -999, -999, -999, -999, -999},
  110968. {-999, -999, -999, -999, -999, -999, -999, -999,
  110969. -999, -110, -101, -96, -90, -83, -77, -54,
  110970. -43, -38, -50, -48, -52, -48, -42, -42,
  110971. -51, -52, -53, -59, -65, -71, -78, -85,
  110972. -95, -999, -999, -999, -999, -999, -999, -999,
  110973. -999, -999, -999, -999, -999, -999, -999, -999,
  110974. -999, -999, -999, -999, -999, -999, -999, -999}},
  110975. /* 8000 Hz */
  110976. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110977. -999, -999, -999, -999, -120, -105, -86, -68,
  110978. -78, -79, -90, -100, -110, -999, -999, -999,
  110979. -999, -999, -999, -999, -999, -999, -999, -999,
  110980. -999, -999, -999, -999, -999, -999, -999, -999,
  110981. -999, -999, -999, -999, -999, -999, -999, -999,
  110982. -999, -999, -999, -999, -999, -999, -999, -999},
  110983. {-999, -999, -999, -999, -999, -999, -999, -999,
  110984. -999, -999, -999, -999, -120, -105, -86, -66,
  110985. -73, -77, -88, -96, -105, -115, -999, -999,
  110986. -999, -999, -999, -999, -999, -999, -999, -999,
  110987. -999, -999, -999, -999, -999, -999, -999, -999,
  110988. -999, -999, -999, -999, -999, -999, -999, -999,
  110989. -999, -999, -999, -999, -999, -999, -999, -999},
  110990. {-999, -999, -999, -999, -999, -999, -999, -999,
  110991. -999, -999, -999, -120, -105, -92, -80, -61,
  110992. -64, -68, -80, -87, -92, -100, -110, -999,
  110993. -999, -999, -999, -999, -999, -999, -999, -999,
  110994. -999, -999, -999, -999, -999, -999, -999, -999,
  110995. -999, -999, -999, -999, -999, -999, -999, -999,
  110996. -999, -999, -999, -999, -999, -999, -999, -999},
  110997. {-999, -999, -999, -999, -999, -999, -999, -999,
  110998. -999, -999, -999, -120, -104, -91, -79, -52,
  110999. -60, -54, -64, -69, -77, -80, -82, -84,
  111000. -85, -87, -88, -90, -999, -999, -999, -999,
  111001. -999, -999, -999, -999, -999, -999, -999, -999,
  111002. -999, -999, -999, -999, -999, -999, -999, -999,
  111003. -999, -999, -999, -999, -999, -999, -999, -999},
  111004. {-999, -999, -999, -999, -999, -999, -999, -999,
  111005. -999, -999, -999, -118, -100, -87, -77, -49,
  111006. -50, -44, -58, -61, -61, -67, -65, -62,
  111007. -62, -62, -65, -68, -999, -999, -999, -999,
  111008. -999, -999, -999, -999, -999, -999, -999, -999,
  111009. -999, -999, -999, -999, -999, -999, -999, -999,
  111010. -999, -999, -999, -999, -999, -999, -999, -999},
  111011. {-999, -999, -999, -999, -999, -999, -999, -999,
  111012. -999, -999, -999, -115, -98, -84, -62, -49,
  111013. -44, -38, -46, -49, -49, -46, -39, -37,
  111014. -39, -40, -42, -43, -999, -999, -999, -999,
  111015. -999, -999, -999, -999, -999, -999, -999, -999,
  111016. -999, -999, -999, -999, -999, -999, -999, -999,
  111017. -999, -999, -999, -999, -999, -999, -999, -999}},
  111018. /* 11314 Hz */
  111019. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111020. -999, -999, -999, -999, -999, -110, -88, -74,
  111021. -77, -82, -82, -85, -90, -94, -99, -104,
  111022. -999, -999, -999, -999, -999, -999, -999, -999,
  111023. -999, -999, -999, -999, -999, -999, -999, -999,
  111024. -999, -999, -999, -999, -999, -999, -999, -999,
  111025. -999, -999, -999, -999, -999, -999, -999, -999},
  111026. {-999, -999, -999, -999, -999, -999, -999, -999,
  111027. -999, -999, -999, -999, -999, -110, -88, -66,
  111028. -70, -81, -80, -81, -84, -88, -91, -93,
  111029. -999, -999, -999, -999, -999, -999, -999, -999,
  111030. -999, -999, -999, -999, -999, -999, -999, -999,
  111031. -999, -999, -999, -999, -999, -999, -999, -999,
  111032. -999, -999, -999, -999, -999, -999, -999, -999},
  111033. {-999, -999, -999, -999, -999, -999, -999, -999,
  111034. -999, -999, -999, -999, -999, -110, -88, -61,
  111035. -63, -70, -71, -74, -77, -80, -83, -85,
  111036. -999, -999, -999, -999, -999, -999, -999, -999,
  111037. -999, -999, -999, -999, -999, -999, -999, -999,
  111038. -999, -999, -999, -999, -999, -999, -999, -999,
  111039. -999, -999, -999, -999, -999, -999, -999, -999},
  111040. {-999, -999, -999, -999, -999, -999, -999, -999,
  111041. -999, -999, -999, -999, -999, -110, -86, -62,
  111042. -63, -62, -62, -58, -52, -50, -50, -52,
  111043. -54, -999, -999, -999, -999, -999, -999, -999,
  111044. -999, -999, -999, -999, -999, -999, -999, -999,
  111045. -999, -999, -999, -999, -999, -999, -999, -999,
  111046. -999, -999, -999, -999, -999, -999, -999, -999},
  111047. {-999, -999, -999, -999, -999, -999, -999, -999,
  111048. -999, -999, -999, -999, -118, -108, -84, -53,
  111049. -50, -50, -50, -55, -47, -45, -40, -40,
  111050. -40, -999, -999, -999, -999, -999, -999, -999,
  111051. -999, -999, -999, -999, -999, -999, -999, -999,
  111052. -999, -999, -999, -999, -999, -999, -999, -999,
  111053. -999, -999, -999, -999, -999, -999, -999, -999},
  111054. {-999, -999, -999, -999, -999, -999, -999, -999,
  111055. -999, -999, -999, -999, -118, -100, -73, -43,
  111056. -37, -42, -43, -53, -38, -37, -35, -35,
  111057. -38, -999, -999, -999, -999, -999, -999, -999,
  111058. -999, -999, -999, -999, -999, -999, -999, -999,
  111059. -999, -999, -999, -999, -999, -999, -999, -999,
  111060. -999, -999, -999, -999, -999, -999, -999, -999}},
  111061. /* 16000 Hz */
  111062. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111063. -999, -999, -999, -110, -100, -91, -84, -74,
  111064. -80, -80, -80, -80, -80, -999, -999, -999,
  111065. -999, -999, -999, -999, -999, -999, -999, -999,
  111066. -999, -999, -999, -999, -999, -999, -999, -999,
  111067. -999, -999, -999, -999, -999, -999, -999, -999,
  111068. -999, -999, -999, -999, -999, -999, -999, -999},
  111069. {-999, -999, -999, -999, -999, -999, -999, -999,
  111070. -999, -999, -999, -110, -100, -91, -84, -74,
  111071. -68, -68, -68, -68, -68, -999, -999, -999,
  111072. -999, -999, -999, -999, -999, -999, -999, -999,
  111073. -999, -999, -999, -999, -999, -999, -999, -999,
  111074. -999, -999, -999, -999, -999, -999, -999, -999,
  111075. -999, -999, -999, -999, -999, -999, -999, -999},
  111076. {-999, -999, -999, -999, -999, -999, -999, -999,
  111077. -999, -999, -999, -110, -100, -86, -78, -70,
  111078. -60, -45, -30, -21, -999, -999, -999, -999,
  111079. -999, -999, -999, -999, -999, -999, -999, -999,
  111080. -999, -999, -999, -999, -999, -999, -999, -999,
  111081. -999, -999, -999, -999, -999, -999, -999, -999,
  111082. -999, -999, -999, -999, -999, -999, -999, -999},
  111083. {-999, -999, -999, -999, -999, -999, -999, -999,
  111084. -999, -999, -999, -110, -100, -87, -78, -67,
  111085. -48, -38, -29, -21, -999, -999, -999, -999,
  111086. -999, -999, -999, -999, -999, -999, -999, -999,
  111087. -999, -999, -999, -999, -999, -999, -999, -999,
  111088. -999, -999, -999, -999, -999, -999, -999, -999,
  111089. -999, -999, -999, -999, -999, -999, -999, -999},
  111090. {-999, -999, -999, -999, -999, -999, -999, -999,
  111091. -999, -999, -999, -110, -100, -86, -69, -56,
  111092. -45, -35, -33, -29, -999, -999, -999, -999,
  111093. -999, -999, -999, -999, -999, -999, -999, -999,
  111094. -999, -999, -999, -999, -999, -999, -999, -999,
  111095. -999, -999, -999, -999, -999, -999, -999, -999,
  111096. -999, -999, -999, -999, -999, -999, -999, -999},
  111097. {-999, -999, -999, -999, -999, -999, -999, -999,
  111098. -999, -999, -999, -110, -100, -83, -71, -48,
  111099. -27, -38, -37, -34, -999, -999, -999, -999,
  111100. -999, -999, -999, -999, -999, -999, -999, -999,
  111101. -999, -999, -999, -999, -999, -999, -999, -999,
  111102. -999, -999, -999, -999, -999, -999, -999, -999,
  111103. -999, -999, -999, -999, -999, -999, -999, -999}}
  111104. };
  111105. #endif
  111106. /********* End of inlined file: masking.h *********/
  111107. #define NEGINF -9999.f
  111108. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  111109. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  111110. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  111111. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111112. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111113. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  111114. look->channels=vi->channels;
  111115. look->ampmax=-9999.;
  111116. look->gi=gi;
  111117. return(look);
  111118. }
  111119. void _vp_global_free(vorbis_look_psy_global *look){
  111120. if(look){
  111121. memset(look,0,sizeof(*look));
  111122. _ogg_free(look);
  111123. }
  111124. }
  111125. void _vi_gpsy_free(vorbis_info_psy_global *i){
  111126. if(i){
  111127. memset(i,0,sizeof(*i));
  111128. _ogg_free(i);
  111129. }
  111130. }
  111131. void _vi_psy_free(vorbis_info_psy *i){
  111132. if(i){
  111133. memset(i,0,sizeof(*i));
  111134. _ogg_free(i);
  111135. }
  111136. }
  111137. static void min_curve(float *c,
  111138. float *c2){
  111139. int i;
  111140. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  111141. }
  111142. static void max_curve(float *c,
  111143. float *c2){
  111144. int i;
  111145. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  111146. }
  111147. static void attenuate_curve(float *c,float att){
  111148. int i;
  111149. for(i=0;i<EHMER_MAX;i++)
  111150. c[i]+=att;
  111151. }
  111152. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  111153. float center_boost, float center_decay_rate){
  111154. int i,j,k,m;
  111155. float ath[EHMER_MAX];
  111156. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  111157. float athc[P_LEVELS][EHMER_MAX];
  111158. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  111159. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  111160. memset(workc,0,sizeof(workc));
  111161. for(i=0;i<P_BANDS;i++){
  111162. /* we add back in the ATH to avoid low level curves falling off to
  111163. -infinity and unnecessarily cutting off high level curves in the
  111164. curve limiting (last step). */
  111165. /* A half-band's settings must be valid over the whole band, and
  111166. it's better to mask too little than too much */
  111167. int ath_offset=i*4;
  111168. for(j=0;j<EHMER_MAX;j++){
  111169. float min=999.;
  111170. for(k=0;k<4;k++)
  111171. if(j+k+ath_offset<MAX_ATH){
  111172. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  111173. }else{
  111174. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  111175. }
  111176. ath[j]=min;
  111177. }
  111178. /* copy curves into working space, replicate the 50dB curve to 30
  111179. and 40, replicate the 100dB curve to 110 */
  111180. for(j=0;j<6;j++)
  111181. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  111182. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  111183. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  111184. /* apply centered curve boost/decay */
  111185. for(j=0;j<P_LEVELS;j++){
  111186. for(k=0;k<EHMER_MAX;k++){
  111187. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  111188. if(adj<0. && center_boost>0)adj=0.;
  111189. if(adj>0. && center_boost<0)adj=0.;
  111190. workc[i][j][k]+=adj;
  111191. }
  111192. }
  111193. /* normalize curves so the driving amplitude is 0dB */
  111194. /* make temp curves with the ATH overlayed */
  111195. for(j=0;j<P_LEVELS;j++){
  111196. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  111197. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  111198. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  111199. max_curve(athc[j],workc[i][j]);
  111200. }
  111201. /* Now limit the louder curves.
  111202. the idea is this: We don't know what the playback attenuation
  111203. will be; 0dB SL moves every time the user twiddles the volume
  111204. knob. So that means we have to use a single 'most pessimal' curve
  111205. for all masking amplitudes, right? Wrong. The *loudest* sound
  111206. can be in (we assume) a range of ...+100dB] SL. However, sounds
  111207. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  111208. etc... */
  111209. for(j=1;j<P_LEVELS;j++){
  111210. min_curve(athc[j],athc[j-1]);
  111211. min_curve(workc[i][j],athc[j]);
  111212. }
  111213. }
  111214. for(i=0;i<P_BANDS;i++){
  111215. int hi_curve,lo_curve,bin;
  111216. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  111217. /* low frequency curves are measured with greater resolution than
  111218. the MDCT/FFT will actually give us; we want the curve applied
  111219. to the tone data to be pessimistic and thus apply the minimum
  111220. masking possible for a given bin. That means that a single bin
  111221. could span more than one octave and that the curve will be a
  111222. composite of multiple octaves. It also may mean that a single
  111223. bin may span > an eighth of an octave and that the eighth
  111224. octave values may also be composited. */
  111225. /* which octave curves will we be compositing? */
  111226. bin=floor(fromOC(i*.5)/binHz);
  111227. lo_curve= ceil(toOC(bin*binHz+1)*2);
  111228. hi_curve= floor(toOC((bin+1)*binHz)*2);
  111229. if(lo_curve>i)lo_curve=i;
  111230. if(lo_curve<0)lo_curve=0;
  111231. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  111232. for(m=0;m<P_LEVELS;m++){
  111233. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  111234. for(j=0;j<n;j++)brute_buffer[j]=999.;
  111235. /* render the curve into bins, then pull values back into curve.
  111236. The point is that any inherent subsampling aliasing results in
  111237. a safe minimum */
  111238. for(k=lo_curve;k<=hi_curve;k++){
  111239. int l=0;
  111240. for(j=0;j<EHMER_MAX;j++){
  111241. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  111242. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  111243. if(lo_bin<0)lo_bin=0;
  111244. if(lo_bin>n)lo_bin=n;
  111245. if(lo_bin<l)l=lo_bin;
  111246. if(hi_bin<0)hi_bin=0;
  111247. if(hi_bin>n)hi_bin=n;
  111248. for(;l<hi_bin && l<n;l++)
  111249. if(brute_buffer[l]>workc[k][m][j])
  111250. brute_buffer[l]=workc[k][m][j];
  111251. }
  111252. for(;l<n;l++)
  111253. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  111254. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  111255. }
  111256. /* be equally paranoid about being valid up to next half ocatve */
  111257. if(i+1<P_BANDS){
  111258. int l=0;
  111259. k=i+1;
  111260. for(j=0;j<EHMER_MAX;j++){
  111261. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  111262. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  111263. if(lo_bin<0)lo_bin=0;
  111264. if(lo_bin>n)lo_bin=n;
  111265. if(lo_bin<l)l=lo_bin;
  111266. if(hi_bin<0)hi_bin=0;
  111267. if(hi_bin>n)hi_bin=n;
  111268. for(;l<hi_bin && l<n;l++)
  111269. if(brute_buffer[l]>workc[k][m][j])
  111270. brute_buffer[l]=workc[k][m][j];
  111271. }
  111272. for(;l<n;l++)
  111273. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  111274. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  111275. }
  111276. for(j=0;j<EHMER_MAX;j++){
  111277. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  111278. if(bin<0){
  111279. ret[i][m][j+2]=-999.;
  111280. }else{
  111281. if(bin>=n){
  111282. ret[i][m][j+2]=-999.;
  111283. }else{
  111284. ret[i][m][j+2]=brute_buffer[bin];
  111285. }
  111286. }
  111287. }
  111288. /* add fenceposts */
  111289. for(j=0;j<EHMER_OFFSET;j++)
  111290. if(ret[i][m][j+2]>-200.f)break;
  111291. ret[i][m][0]=j;
  111292. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  111293. if(ret[i][m][j+2]>-200.f)
  111294. break;
  111295. ret[i][m][1]=j;
  111296. }
  111297. }
  111298. return(ret);
  111299. }
  111300. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  111301. vorbis_info_psy_global *gi,int n,long rate){
  111302. long i,j,lo=-99,hi=1;
  111303. long maxoc;
  111304. memset(p,0,sizeof(*p));
  111305. p->eighth_octave_lines=gi->eighth_octave_lines;
  111306. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  111307. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  111308. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  111309. p->total_octave_lines=maxoc-p->firstoc+1;
  111310. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  111311. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  111312. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  111313. p->vi=vi;
  111314. p->n=n;
  111315. p->rate=rate;
  111316. /* AoTuV HF weighting */
  111317. p->m_val = 1.;
  111318. if(rate < 26000) p->m_val = 0;
  111319. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  111320. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  111321. /* set up the lookups for a given blocksize and sample rate */
  111322. for(i=0,j=0;i<MAX_ATH-1;i++){
  111323. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  111324. float base=ATH[i];
  111325. if(j<endpos){
  111326. float delta=(ATH[i+1]-base)/(endpos-j);
  111327. for(;j<endpos && j<n;j++){
  111328. p->ath[j]=base+100.;
  111329. base+=delta;
  111330. }
  111331. }
  111332. }
  111333. for(i=0;i<n;i++){
  111334. float bark=toBARK(rate/(2*n)*i);
  111335. for(;lo+vi->noisewindowlomin<i &&
  111336. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  111337. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  111338. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  111339. p->bark[i]=((lo-1)<<16)+(hi-1);
  111340. }
  111341. for(i=0;i<n;i++)
  111342. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  111343. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  111344. vi->tone_centerboost,vi->tone_decay);
  111345. /* set up rolling noise median */
  111346. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  111347. for(i=0;i<P_NOISECURVES;i++)
  111348. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  111349. for(i=0;i<n;i++){
  111350. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  111351. int inthalfoc;
  111352. float del;
  111353. if(halfoc<0)halfoc=0;
  111354. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  111355. inthalfoc=(int)halfoc;
  111356. del=halfoc-inthalfoc;
  111357. for(j=0;j<P_NOISECURVES;j++)
  111358. p->noiseoffset[j][i]=
  111359. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  111360. p->vi->noiseoff[j][inthalfoc+1]*del;
  111361. }
  111362. #if 0
  111363. {
  111364. static int ls=0;
  111365. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  111366. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  111367. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  111368. }
  111369. #endif
  111370. }
  111371. void _vp_psy_clear(vorbis_look_psy *p){
  111372. int i,j;
  111373. if(p){
  111374. if(p->ath)_ogg_free(p->ath);
  111375. if(p->octave)_ogg_free(p->octave);
  111376. if(p->bark)_ogg_free(p->bark);
  111377. if(p->tonecurves){
  111378. for(i=0;i<P_BANDS;i++){
  111379. for(j=0;j<P_LEVELS;j++){
  111380. _ogg_free(p->tonecurves[i][j]);
  111381. }
  111382. _ogg_free(p->tonecurves[i]);
  111383. }
  111384. _ogg_free(p->tonecurves);
  111385. }
  111386. if(p->noiseoffset){
  111387. for(i=0;i<P_NOISECURVES;i++){
  111388. _ogg_free(p->noiseoffset[i]);
  111389. }
  111390. _ogg_free(p->noiseoffset);
  111391. }
  111392. memset(p,0,sizeof(*p));
  111393. }
  111394. }
  111395. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  111396. static void seed_curve(float *seed,
  111397. const float **curves,
  111398. float amp,
  111399. int oc, int n,
  111400. int linesper,float dBoffset){
  111401. int i,post1;
  111402. int seedptr;
  111403. const float *posts,*curve;
  111404. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  111405. choice=max(choice,0);
  111406. choice=min(choice,P_LEVELS-1);
  111407. posts=curves[choice];
  111408. curve=posts+2;
  111409. post1=(int)posts[1];
  111410. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  111411. for(i=posts[0];i<post1;i++){
  111412. if(seedptr>0){
  111413. float lin=amp+curve[i];
  111414. if(seed[seedptr]<lin)seed[seedptr]=lin;
  111415. }
  111416. seedptr+=linesper;
  111417. if(seedptr>=n)break;
  111418. }
  111419. }
  111420. static void seed_loop(vorbis_look_psy *p,
  111421. const float ***curves,
  111422. const float *f,
  111423. const float *flr,
  111424. float *seed,
  111425. float specmax){
  111426. vorbis_info_psy *vi=p->vi;
  111427. long n=p->n,i;
  111428. float dBoffset=vi->max_curve_dB-specmax;
  111429. /* prime the working vector with peak values */
  111430. for(i=0;i<n;i++){
  111431. float max=f[i];
  111432. long oc=p->octave[i];
  111433. while(i+1<n && p->octave[i+1]==oc){
  111434. i++;
  111435. if(f[i]>max)max=f[i];
  111436. }
  111437. if(max+6.f>flr[i]){
  111438. oc=oc>>p->shiftoc;
  111439. if(oc>=P_BANDS)oc=P_BANDS-1;
  111440. if(oc<0)oc=0;
  111441. seed_curve(seed,
  111442. curves[oc],
  111443. max,
  111444. p->octave[i]-p->firstoc,
  111445. p->total_octave_lines,
  111446. p->eighth_octave_lines,
  111447. dBoffset);
  111448. }
  111449. }
  111450. }
  111451. static void seed_chase(float *seeds, int linesper, long n){
  111452. long *posstack=(long*)alloca(n*sizeof(*posstack));
  111453. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  111454. long stack=0;
  111455. long pos=0;
  111456. long i;
  111457. for(i=0;i<n;i++){
  111458. if(stack<2){
  111459. posstack[stack]=i;
  111460. ampstack[stack++]=seeds[i];
  111461. }else{
  111462. while(1){
  111463. if(seeds[i]<ampstack[stack-1]){
  111464. posstack[stack]=i;
  111465. ampstack[stack++]=seeds[i];
  111466. break;
  111467. }else{
  111468. if(i<posstack[stack-1]+linesper){
  111469. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  111470. i<posstack[stack-2]+linesper){
  111471. /* we completely overlap, making stack-1 irrelevant. pop it */
  111472. stack--;
  111473. continue;
  111474. }
  111475. }
  111476. posstack[stack]=i;
  111477. ampstack[stack++]=seeds[i];
  111478. break;
  111479. }
  111480. }
  111481. }
  111482. }
  111483. /* the stack now contains only the positions that are relevant. Scan
  111484. 'em straight through */
  111485. for(i=0;i<stack;i++){
  111486. long endpos;
  111487. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  111488. endpos=posstack[i+1];
  111489. }else{
  111490. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  111491. discarded in short frames */
  111492. }
  111493. if(endpos>n)endpos=n;
  111494. for(;pos<endpos;pos++)
  111495. seeds[pos]=ampstack[i];
  111496. }
  111497. /* there. Linear time. I now remember this was on a problem set I
  111498. had in Grad Skool... I didn't solve it at the time ;-) */
  111499. }
  111500. /* bleaugh, this is more complicated than it needs to be */
  111501. #include<stdio.h>
  111502. static void max_seeds(vorbis_look_psy *p,
  111503. float *seed,
  111504. float *flr){
  111505. long n=p->total_octave_lines;
  111506. int linesper=p->eighth_octave_lines;
  111507. long linpos=0;
  111508. long pos;
  111509. seed_chase(seed,linesper,n); /* for masking */
  111510. pos=p->octave[0]-p->firstoc-(linesper>>1);
  111511. while(linpos+1<p->n){
  111512. float minV=seed[pos];
  111513. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  111514. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  111515. while(pos+1<=end){
  111516. pos++;
  111517. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  111518. minV=seed[pos];
  111519. }
  111520. end=pos+p->firstoc;
  111521. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  111522. if(flr[linpos]<minV)flr[linpos]=minV;
  111523. }
  111524. {
  111525. float minV=seed[p->total_octave_lines-1];
  111526. for(;linpos<p->n;linpos++)
  111527. if(flr[linpos]<minV)flr[linpos]=minV;
  111528. }
  111529. }
  111530. static void bark_noise_hybridmp(int n,const long *b,
  111531. const float *f,
  111532. float *noise,
  111533. const float offset,
  111534. const int fixed){
  111535. float *N=(float*) alloca(n*sizeof(*N));
  111536. float *X=(float*) alloca(n*sizeof(*N));
  111537. float *XX=(float*) alloca(n*sizeof(*N));
  111538. float *Y=(float*) alloca(n*sizeof(*N));
  111539. float *XY=(float*) alloca(n*sizeof(*N));
  111540. float tN, tX, tXX, tY, tXY;
  111541. int i;
  111542. int lo, hi;
  111543. float R, A, B, D;
  111544. float w, x, y;
  111545. tN = tX = tXX = tY = tXY = 0.f;
  111546. y = f[0] + offset;
  111547. if (y < 1.f) y = 1.f;
  111548. w = y * y * .5;
  111549. tN += w;
  111550. tX += w;
  111551. tY += w * y;
  111552. N[0] = tN;
  111553. X[0] = tX;
  111554. XX[0] = tXX;
  111555. Y[0] = tY;
  111556. XY[0] = tXY;
  111557. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  111558. y = f[i] + offset;
  111559. if (y < 1.f) y = 1.f;
  111560. w = y * y;
  111561. tN += w;
  111562. tX += w * x;
  111563. tXX += w * x * x;
  111564. tY += w * y;
  111565. tXY += w * x * y;
  111566. N[i] = tN;
  111567. X[i] = tX;
  111568. XX[i] = tXX;
  111569. Y[i] = tY;
  111570. XY[i] = tXY;
  111571. }
  111572. for (i = 0, x = 0.f;; i++, x += 1.f) {
  111573. lo = b[i] >> 16;
  111574. if( lo>=0 ) break;
  111575. hi = b[i] & 0xffff;
  111576. tN = N[hi] + N[-lo];
  111577. tX = X[hi] - X[-lo];
  111578. tXX = XX[hi] + XX[-lo];
  111579. tY = Y[hi] + Y[-lo];
  111580. tXY = XY[hi] - XY[-lo];
  111581. A = tY * tXX - tX * tXY;
  111582. B = tN * tXY - tX * tY;
  111583. D = tN * tXX - tX * tX;
  111584. R = (A + x * B) / D;
  111585. if (R < 0.f)
  111586. R = 0.f;
  111587. noise[i] = R - offset;
  111588. }
  111589. for ( ;; i++, x += 1.f) {
  111590. lo = b[i] >> 16;
  111591. hi = b[i] & 0xffff;
  111592. if(hi>=n)break;
  111593. tN = N[hi] - N[lo];
  111594. tX = X[hi] - X[lo];
  111595. tXX = XX[hi] - XX[lo];
  111596. tY = Y[hi] - Y[lo];
  111597. tXY = XY[hi] - XY[lo];
  111598. A = tY * tXX - tX * tXY;
  111599. B = tN * tXY - tX * tY;
  111600. D = tN * tXX - tX * tX;
  111601. R = (A + x * B) / D;
  111602. if (R < 0.f) R = 0.f;
  111603. noise[i] = R - offset;
  111604. }
  111605. for ( ; i < n; i++, x += 1.f) {
  111606. R = (A + x * B) / D;
  111607. if (R < 0.f) R = 0.f;
  111608. noise[i] = R - offset;
  111609. }
  111610. if (fixed <= 0) return;
  111611. for (i = 0, x = 0.f;; i++, x += 1.f) {
  111612. hi = i + fixed / 2;
  111613. lo = hi - fixed;
  111614. if(lo>=0)break;
  111615. tN = N[hi] + N[-lo];
  111616. tX = X[hi] - X[-lo];
  111617. tXX = XX[hi] + XX[-lo];
  111618. tY = Y[hi] + Y[-lo];
  111619. tXY = XY[hi] - XY[-lo];
  111620. A = tY * tXX - tX * tXY;
  111621. B = tN * tXY - tX * tY;
  111622. D = tN * tXX - tX * tX;
  111623. R = (A + x * B) / D;
  111624. if (R - offset < noise[i]) noise[i] = R - offset;
  111625. }
  111626. for ( ;; i++, x += 1.f) {
  111627. hi = i + fixed / 2;
  111628. lo = hi - fixed;
  111629. if(hi>=n)break;
  111630. tN = N[hi] - N[lo];
  111631. tX = X[hi] - X[lo];
  111632. tXX = XX[hi] - XX[lo];
  111633. tY = Y[hi] - Y[lo];
  111634. tXY = XY[hi] - XY[lo];
  111635. A = tY * tXX - tX * tXY;
  111636. B = tN * tXY - tX * tY;
  111637. D = tN * tXX - tX * tX;
  111638. R = (A + x * B) / D;
  111639. if (R - offset < noise[i]) noise[i] = R - offset;
  111640. }
  111641. for ( ; i < n; i++, x += 1.f) {
  111642. R = (A + x * B) / D;
  111643. if (R - offset < noise[i]) noise[i] = R - offset;
  111644. }
  111645. }
  111646. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  111647. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  111648. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  111649. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  111650. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  111651. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  111652. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  111653. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  111654. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  111655. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  111656. 973377.F, 913981.F, 858210.F, 805842.F,
  111657. 756669.F, 710497.F, 667142.F, 626433.F,
  111658. 588208.F, 552316.F, 518613.F, 486967.F,
  111659. 457252.F, 429351.F, 403152.F, 378551.F,
  111660. 355452.F, 333762.F, 313396.F, 294273.F,
  111661. 276316.F, 259455.F, 243623.F, 228757.F,
  111662. 214798.F, 201691.F, 189384.F, 177828.F,
  111663. 166977.F, 156788.F, 147221.F, 138237.F,
  111664. 129802.F, 121881.F, 114444.F, 107461.F,
  111665. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  111666. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  111667. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  111668. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  111669. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  111670. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  111671. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  111672. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  111673. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  111674. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  111675. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  111676. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  111677. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  111678. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  111679. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  111680. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  111681. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  111682. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  111683. 1084.32F, 1018.15F, 956.024F, 897.687F,
  111684. 842.910F, 791.475F, 743.179F, 697.830F,
  111685. 655.249F, 615.265F, 577.722F, 542.469F,
  111686. 509.367F, 478.286F, 449.101F, 421.696F,
  111687. 395.964F, 371.803F, 349.115F, 327.812F,
  111688. 307.809F, 289.026F, 271.390F, 254.830F,
  111689. 239.280F, 224.679F, 210.969F, 198.096F,
  111690. 186.008F, 174.658F, 164.000F, 153.993F,
  111691. 144.596F, 135.773F, 127.488F, 119.708F,
  111692. 112.404F, 105.545F, 99.1046F, 93.0572F,
  111693. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  111694. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  111695. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  111696. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  111697. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  111698. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  111699. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  111700. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  111701. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  111702. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  111703. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  111704. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  111705. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  111706. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  111707. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  111708. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  111709. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  111710. 1.20790F, 1.13419F, 1.06499F, 1.F
  111711. };
  111712. void _vp_remove_floor(vorbis_look_psy *p,
  111713. float *mdct,
  111714. int *codedflr,
  111715. float *residue,
  111716. int sliding_lowpass){
  111717. int i,n=p->n;
  111718. if(sliding_lowpass>n)sliding_lowpass=n;
  111719. for(i=0;i<sliding_lowpass;i++){
  111720. residue[i]=
  111721. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  111722. }
  111723. for(;i<n;i++)
  111724. residue[i]=0.;
  111725. }
  111726. void _vp_noisemask(vorbis_look_psy *p,
  111727. float *logmdct,
  111728. float *logmask){
  111729. int i,n=p->n;
  111730. float *work=(float*) alloca(n*sizeof(*work));
  111731. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  111732. 140.,-1);
  111733. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  111734. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  111735. p->vi->noisewindowfixed);
  111736. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  111737. #if 0
  111738. {
  111739. static int seq=0;
  111740. float work2[n];
  111741. for(i=0;i<n;i++){
  111742. work2[i]=logmask[i]+work[i];
  111743. }
  111744. if(seq&1)
  111745. _analysis_output("median2R",seq/2,work,n,1,0,0);
  111746. else
  111747. _analysis_output("median2L",seq/2,work,n,1,0,0);
  111748. if(seq&1)
  111749. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  111750. else
  111751. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  111752. seq++;
  111753. }
  111754. #endif
  111755. for(i=0;i<n;i++){
  111756. int dB=logmask[i]+.5;
  111757. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  111758. if(dB<0)dB=0;
  111759. logmask[i]= work[i]+p->vi->noisecompand[dB];
  111760. }
  111761. }
  111762. void _vp_tonemask(vorbis_look_psy *p,
  111763. float *logfft,
  111764. float *logmask,
  111765. float global_specmax,
  111766. float local_specmax){
  111767. int i,n=p->n;
  111768. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  111769. float att=local_specmax+p->vi->ath_adjatt;
  111770. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  111771. /* set the ATH (floating below localmax, not global max by a
  111772. specified att) */
  111773. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  111774. for(i=0;i<n;i++)
  111775. logmask[i]=p->ath[i]+att;
  111776. /* tone masking */
  111777. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  111778. max_seeds(p,seed,logmask);
  111779. }
  111780. void _vp_offset_and_mix(vorbis_look_psy *p,
  111781. float *noise,
  111782. float *tone,
  111783. int offset_select,
  111784. float *logmask,
  111785. float *mdct,
  111786. float *logmdct){
  111787. int i,n=p->n;
  111788. float de, coeffi, cx;/* AoTuV */
  111789. float toneatt=p->vi->tone_masteratt[offset_select];
  111790. cx = p->m_val;
  111791. for(i=0;i<n;i++){
  111792. float val= noise[i]+p->noiseoffset[offset_select][i];
  111793. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  111794. logmask[i]=max(val,tone[i]+toneatt);
  111795. /* AoTuV */
  111796. /** @ M1 **
  111797. The following codes improve a noise problem.
  111798. A fundamental idea uses the value of masking and carries out
  111799. the relative compensation of the MDCT.
  111800. However, this code is not perfect and all noise problems cannot be solved.
  111801. by Aoyumi @ 2004/04/18
  111802. */
  111803. if(offset_select == 1) {
  111804. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  111805. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  111806. if(val > coeffi){
  111807. /* mdct value is > -17.2 dB below floor */
  111808. de = 1.0-((val-coeffi)*0.005*cx);
  111809. /* pro-rated attenuation:
  111810. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  111811. -0.77 dB boost if mdct value is 0dB (relative to floor)
  111812. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  111813. etc... */
  111814. if(de < 0) de = 0.0001;
  111815. }else
  111816. /* mdct value is <= -17.2 dB below floor */
  111817. de = 1.0-((val-coeffi)*0.0003*cx);
  111818. /* pro-rated attenuation:
  111819. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  111820. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  111821. etc... */
  111822. mdct[i] *= de;
  111823. }
  111824. }
  111825. }
  111826. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  111827. vorbis_info *vi=vd->vi;
  111828. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111829. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111830. int n=ci->blocksizes[vd->W]/2;
  111831. float secs=(float)n/vi->rate;
  111832. amp+=secs*gi->ampmax_att_per_sec;
  111833. if(amp<-9999)amp=-9999;
  111834. return(amp);
  111835. }
  111836. static void couple_lossless(float A, float B,
  111837. float *qA, float *qB){
  111838. int test1=fabs(*qA)>fabs(*qB);
  111839. test1-= fabs(*qA)<fabs(*qB);
  111840. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  111841. if(test1==1){
  111842. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  111843. }else{
  111844. float temp=*qB;
  111845. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  111846. *qA=temp;
  111847. }
  111848. if(*qB>fabs(*qA)*1.9999f){
  111849. *qB= -fabs(*qA)*2.f;
  111850. *qA= -*qA;
  111851. }
  111852. }
  111853. static float hypot_lookup[32]={
  111854. -0.009935, -0.011245, -0.012726, -0.014397,
  111855. -0.016282, -0.018407, -0.020800, -0.023494,
  111856. -0.026522, -0.029923, -0.033737, -0.038010,
  111857. -0.042787, -0.048121, -0.054064, -0.060671,
  111858. -0.068000, -0.076109, -0.085054, -0.094892,
  111859. -0.105675, -0.117451, -0.130260, -0.144134,
  111860. -0.159093, -0.175146, -0.192286, -0.210490,
  111861. -0.229718, -0.249913, -0.271001, -0.292893};
  111862. static void precomputed_couple_point(float premag,
  111863. int floorA,int floorB,
  111864. float *mag, float *ang){
  111865. int test=(floorA>floorB)-1;
  111866. int offset=31-abs(floorA-floorB);
  111867. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  111868. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  111869. *mag=premag*floormag;
  111870. *ang=0.f;
  111871. }
  111872. /* just like below, this is currently set up to only do
  111873. single-step-depth coupling. Otherwise, we'd have to do more
  111874. copying (which will be inevitable later) */
  111875. /* doing the real circular magnitude calculation is audibly superior
  111876. to (A+B)/sqrt(2) */
  111877. static float dipole_hypot(float a, float b){
  111878. if(a>0.){
  111879. if(b>0.)return sqrt(a*a+b*b);
  111880. if(a>-b)return sqrt(a*a-b*b);
  111881. return -sqrt(b*b-a*a);
  111882. }
  111883. if(b<0.)return -sqrt(a*a+b*b);
  111884. if(-a>b)return -sqrt(a*a-b*b);
  111885. return sqrt(b*b-a*a);
  111886. }
  111887. static float round_hypot(float a, float b){
  111888. if(a>0.){
  111889. if(b>0.)return sqrt(a*a+b*b);
  111890. if(a>-b)return sqrt(a*a+b*b);
  111891. return -sqrt(b*b+a*a);
  111892. }
  111893. if(b<0.)return -sqrt(a*a+b*b);
  111894. if(-a>b)return -sqrt(a*a+b*b);
  111895. return sqrt(b*b+a*a);
  111896. }
  111897. /* revert to round hypot for now */
  111898. float **_vp_quantize_couple_memo(vorbis_block *vb,
  111899. vorbis_info_psy_global *g,
  111900. vorbis_look_psy *p,
  111901. vorbis_info_mapping0 *vi,
  111902. float **mdct){
  111903. int i,j,n=p->n;
  111904. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  111905. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  111906. for(i=0;i<vi->coupling_steps;i++){
  111907. float *mdctM=mdct[vi->coupling_mag[i]];
  111908. float *mdctA=mdct[vi->coupling_ang[i]];
  111909. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  111910. for(j=0;j<limit;j++)
  111911. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  111912. for(;j<n;j++)
  111913. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  111914. }
  111915. return(ret);
  111916. }
  111917. /* this is for per-channel noise normalization */
  111918. static int apsort(const void *a, const void *b){
  111919. float f1=fabs(**(float**)a);
  111920. float f2=fabs(**(float**)b);
  111921. return (f1<f2)-(f1>f2);
  111922. }
  111923. int **_vp_quantize_couple_sort(vorbis_block *vb,
  111924. vorbis_look_psy *p,
  111925. vorbis_info_mapping0 *vi,
  111926. float **mags){
  111927. if(p->vi->normal_point_p){
  111928. int i,j,k,n=p->n;
  111929. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  111930. int partition=p->vi->normal_partition;
  111931. float **work=(float**) alloca(sizeof(*work)*partition);
  111932. for(i=0;i<vi->coupling_steps;i++){
  111933. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  111934. for(j=0;j<n;j+=partition){
  111935. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  111936. qsort(work,partition,sizeof(*work),apsort);
  111937. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  111938. }
  111939. }
  111940. return(ret);
  111941. }
  111942. return(NULL);
  111943. }
  111944. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  111945. float *magnitudes,int *sortedindex){
  111946. int i,j,n=p->n;
  111947. vorbis_info_psy *vi=p->vi;
  111948. int partition=vi->normal_partition;
  111949. float **work=(float**) alloca(sizeof(*work)*partition);
  111950. int start=vi->normal_start;
  111951. for(j=start;j<n;j+=partition){
  111952. if(j+partition>n)partition=n-j;
  111953. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  111954. qsort(work,partition,sizeof(*work),apsort);
  111955. for(i=0;i<partition;i++){
  111956. sortedindex[i+j-start]=work[i]-magnitudes;
  111957. }
  111958. }
  111959. }
  111960. void _vp_noise_normalize(vorbis_look_psy *p,
  111961. float *in,float *out,int *sortedindex){
  111962. int flag=0,i,j=0,n=p->n;
  111963. vorbis_info_psy *vi=p->vi;
  111964. int partition=vi->normal_partition;
  111965. int start=vi->normal_start;
  111966. if(start>n)start=n;
  111967. if(vi->normal_channel_p){
  111968. for(;j<start;j++)
  111969. out[j]=rint(in[j]);
  111970. for(;j+partition<=n;j+=partition){
  111971. float acc=0.;
  111972. int k;
  111973. for(i=j;i<j+partition;i++)
  111974. acc+=in[i]*in[i];
  111975. for(i=0;i<partition;i++){
  111976. k=sortedindex[i+j-start];
  111977. if(in[k]*in[k]>=.25f){
  111978. out[k]=rint(in[k]);
  111979. acc-=in[k]*in[k];
  111980. flag=1;
  111981. }else{
  111982. if(acc<vi->normal_thresh)break;
  111983. out[k]=unitnorm(in[k]);
  111984. acc-=1.;
  111985. }
  111986. }
  111987. for(;i<partition;i++){
  111988. k=sortedindex[i+j-start];
  111989. out[k]=0.;
  111990. }
  111991. }
  111992. }
  111993. for(;j<n;j++)
  111994. out[j]=rint(in[j]);
  111995. }
  111996. void _vp_couple(int blobno,
  111997. vorbis_info_psy_global *g,
  111998. vorbis_look_psy *p,
  111999. vorbis_info_mapping0 *vi,
  112000. float **res,
  112001. float **mag_memo,
  112002. int **mag_sort,
  112003. int **ifloor,
  112004. int *nonzero,
  112005. int sliding_lowpass){
  112006. int i,j,k,n=p->n;
  112007. /* perform any requested channel coupling */
  112008. /* point stereo can only be used in a first stage (in this encoder)
  112009. because of the dependency on floor lookups */
  112010. for(i=0;i<vi->coupling_steps;i++){
  112011. /* once we're doing multistage coupling in which a channel goes
  112012. through more than one coupling step, the floor vector
  112013. magnitudes will also have to be recalculated an propogated
  112014. along with PCM. Right now, we're not (that will wait until 5.1
  112015. most likely), so the code isn't here yet. The memory management
  112016. here is all assuming single depth couplings anyway. */
  112017. /* make sure coupling a zero and a nonzero channel results in two
  112018. nonzero channels. */
  112019. if(nonzero[vi->coupling_mag[i]] ||
  112020. nonzero[vi->coupling_ang[i]]){
  112021. float *rM=res[vi->coupling_mag[i]];
  112022. float *rA=res[vi->coupling_ang[i]];
  112023. float *qM=rM+n;
  112024. float *qA=rA+n;
  112025. int *floorM=ifloor[vi->coupling_mag[i]];
  112026. int *floorA=ifloor[vi->coupling_ang[i]];
  112027. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  112028. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  112029. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  112030. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  112031. int pointlimit=limit;
  112032. nonzero[vi->coupling_mag[i]]=1;
  112033. nonzero[vi->coupling_ang[i]]=1;
  112034. /* The threshold of a stereo is changed with the size of n */
  112035. if(n > 1000)
  112036. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  112037. for(j=0;j<p->n;j+=partition){
  112038. float acc=0.f;
  112039. for(k=0;k<partition;k++){
  112040. int l=k+j;
  112041. if(l<sliding_lowpass){
  112042. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  112043. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  112044. precomputed_couple_point(mag_memo[i][l],
  112045. floorM[l],floorA[l],
  112046. qM+l,qA+l);
  112047. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  112048. }else{
  112049. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  112050. }
  112051. }else{
  112052. qM[l]=0.;
  112053. qA[l]=0.;
  112054. }
  112055. }
  112056. if(p->vi->normal_point_p){
  112057. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  112058. int l=mag_sort[i][j+k];
  112059. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  112060. qM[l]=unitnorm(qM[l]);
  112061. acc-=1.f;
  112062. }
  112063. }
  112064. }
  112065. }
  112066. }
  112067. }
  112068. }
  112069. /* AoTuV */
  112070. /** @ M2 **
  112071. The boost problem by the combination of noise normalization and point stereo is eased.
  112072. However, this is a temporary patch.
  112073. by Aoyumi @ 2004/04/18
  112074. */
  112075. void hf_reduction(vorbis_info_psy_global *g,
  112076. vorbis_look_psy *p,
  112077. vorbis_info_mapping0 *vi,
  112078. float **mdct){
  112079. int i,j,n=p->n, de=0.3*p->m_val;
  112080. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  112081. for(i=0; i<vi->coupling_steps; i++){
  112082. /* for(j=start; j<limit; j++){} // ???*/
  112083. for(j=limit; j<n; j++)
  112084. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  112085. }
  112086. }
  112087. #endif
  112088. /********* End of inlined file: psy.c *********/
  112089. /********* Start of inlined file: registry.c *********/
  112090. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  112091. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112092. // tasks..
  112093. #ifdef _MSC_VER
  112094. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112095. #endif
  112096. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  112097. #if JUCE_USE_OGGVORBIS
  112098. /* seems like major overkill now; the backend numbers will grow into
  112099. the infrastructure soon enough */
  112100. extern vorbis_func_floor floor0_exportbundle;
  112101. extern vorbis_func_floor floor1_exportbundle;
  112102. extern vorbis_func_residue residue0_exportbundle;
  112103. extern vorbis_func_residue residue1_exportbundle;
  112104. extern vorbis_func_residue residue2_exportbundle;
  112105. extern vorbis_func_mapping mapping0_exportbundle;
  112106. vorbis_func_floor *_floor_P[]={
  112107. &floor0_exportbundle,
  112108. &floor1_exportbundle,
  112109. };
  112110. vorbis_func_residue *_residue_P[]={
  112111. &residue0_exportbundle,
  112112. &residue1_exportbundle,
  112113. &residue2_exportbundle,
  112114. };
  112115. vorbis_func_mapping *_mapping_P[]={
  112116. &mapping0_exportbundle,
  112117. };
  112118. #endif
  112119. /********* End of inlined file: registry.c *********/
  112120. /********* Start of inlined file: res0.c *********/
  112121. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  112122. encode/decode loops are coded for clarity and performance is not
  112123. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  112124. it's slow. */
  112125. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  112126. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112127. // tasks..
  112128. #ifdef _MSC_VER
  112129. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112130. #endif
  112131. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  112132. #if JUCE_USE_OGGVORBIS
  112133. #include <stdlib.h>
  112134. #include <string.h>
  112135. #include <math.h>
  112136. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  112137. #include <stdio.h>
  112138. #endif
  112139. typedef struct {
  112140. vorbis_info_residue0 *info;
  112141. int parts;
  112142. int stages;
  112143. codebook *fullbooks;
  112144. codebook *phrasebook;
  112145. codebook ***partbooks;
  112146. int partvals;
  112147. int **decodemap;
  112148. long postbits;
  112149. long phrasebits;
  112150. long frames;
  112151. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  112152. int train_seq;
  112153. long *training_data[8][64];
  112154. float training_max[8][64];
  112155. float training_min[8][64];
  112156. float tmin;
  112157. float tmax;
  112158. #endif
  112159. } vorbis_look_residue0;
  112160. void res0_free_info(vorbis_info_residue *i){
  112161. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  112162. if(info){
  112163. memset(info,0,sizeof(*info));
  112164. _ogg_free(info);
  112165. }
  112166. }
  112167. void res0_free_look(vorbis_look_residue *i){
  112168. int j;
  112169. if(i){
  112170. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  112171. #ifdef TRAIN_RES
  112172. {
  112173. int j,k,l;
  112174. for(j=0;j<look->parts;j++){
  112175. /*fprintf(stderr,"partition %d: ",j);*/
  112176. for(k=0;k<8;k++)
  112177. if(look->training_data[k][j]){
  112178. char buffer[80];
  112179. FILE *of;
  112180. codebook *statebook=look->partbooks[j][k];
  112181. /* long and short into the same bucket by current convention */
  112182. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  112183. of=fopen(buffer,"a");
  112184. for(l=0;l<statebook->entries;l++)
  112185. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  112186. fclose(of);
  112187. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  112188. look->training_min[k][j],look->training_max[k][j]);*/
  112189. _ogg_free(look->training_data[k][j]);
  112190. look->training_data[k][j]=NULL;
  112191. }
  112192. /*fprintf(stderr,"\n");*/
  112193. }
  112194. }
  112195. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  112196. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  112197. (float)look->phrasebits/look->frames,
  112198. (float)look->postbits/look->frames,
  112199. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112200. #endif
  112201. /*vorbis_info_residue0 *info=look->info;
  112202. fprintf(stderr,
  112203. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  112204. "(%g/frame) \n",look->frames,look->phrasebits,
  112205. look->resbitsflat,
  112206. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  112207. for(j=0;j<look->parts;j++){
  112208. long acc=0;
  112209. fprintf(stderr,"\t[%d] == ",j);
  112210. for(k=0;k<look->stages;k++)
  112211. if((info->secondstages[j]>>k)&1){
  112212. fprintf(stderr,"%ld,",look->resbits[j][k]);
  112213. acc+=look->resbits[j][k];
  112214. }
  112215. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  112216. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  112217. }
  112218. fprintf(stderr,"\n");*/
  112219. for(j=0;j<look->parts;j++)
  112220. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  112221. _ogg_free(look->partbooks);
  112222. for(j=0;j<look->partvals;j++)
  112223. _ogg_free(look->decodemap[j]);
  112224. _ogg_free(look->decodemap);
  112225. memset(look,0,sizeof(*look));
  112226. _ogg_free(look);
  112227. }
  112228. }
  112229. static int icount(unsigned int v){
  112230. int ret=0;
  112231. while(v){
  112232. ret+=v&1;
  112233. v>>=1;
  112234. }
  112235. return(ret);
  112236. }
  112237. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  112238. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  112239. int j,acc=0;
  112240. oggpack_write(opb,info->begin,24);
  112241. oggpack_write(opb,info->end,24);
  112242. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  112243. code with a partitioned book */
  112244. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  112245. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  112246. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  112247. bitmask of one indicates this partition class has bits to write
  112248. this pass */
  112249. for(j=0;j<info->partitions;j++){
  112250. if(ilog(info->secondstages[j])>3){
  112251. /* yes, this is a minor hack due to not thinking ahead */
  112252. oggpack_write(opb,info->secondstages[j],3);
  112253. oggpack_write(opb,1,1);
  112254. oggpack_write(opb,info->secondstages[j]>>3,5);
  112255. }else
  112256. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  112257. acc+=icount(info->secondstages[j]);
  112258. }
  112259. for(j=0;j<acc;j++)
  112260. oggpack_write(opb,info->booklist[j],8);
  112261. }
  112262. /* vorbis_info is for range checking */
  112263. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  112264. int j,acc=0;
  112265. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  112266. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  112267. info->begin=oggpack_read(opb,24);
  112268. info->end=oggpack_read(opb,24);
  112269. info->grouping=oggpack_read(opb,24)+1;
  112270. info->partitions=oggpack_read(opb,6)+1;
  112271. info->groupbook=oggpack_read(opb,8);
  112272. for(j=0;j<info->partitions;j++){
  112273. int cascade=oggpack_read(opb,3);
  112274. if(oggpack_read(opb,1))
  112275. cascade|=(oggpack_read(opb,5)<<3);
  112276. info->secondstages[j]=cascade;
  112277. acc+=icount(cascade);
  112278. }
  112279. for(j=0;j<acc;j++)
  112280. info->booklist[j]=oggpack_read(opb,8);
  112281. if(info->groupbook>=ci->books)goto errout;
  112282. for(j=0;j<acc;j++)
  112283. if(info->booklist[j]>=ci->books)goto errout;
  112284. return(info);
  112285. errout:
  112286. res0_free_info(info);
  112287. return(NULL);
  112288. }
  112289. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  112290. vorbis_info_residue *vr){
  112291. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  112292. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  112293. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  112294. int j,k,acc=0;
  112295. int dim;
  112296. int maxstage=0;
  112297. look->info=info;
  112298. look->parts=info->partitions;
  112299. look->fullbooks=ci->fullbooks;
  112300. look->phrasebook=ci->fullbooks+info->groupbook;
  112301. dim=look->phrasebook->dim;
  112302. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  112303. for(j=0;j<look->parts;j++){
  112304. int stages=ilog(info->secondstages[j]);
  112305. if(stages){
  112306. if(stages>maxstage)maxstage=stages;
  112307. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  112308. for(k=0;k<stages;k++)
  112309. if(info->secondstages[j]&(1<<k)){
  112310. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  112311. #ifdef TRAIN_RES
  112312. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  112313. sizeof(***look->training_data));
  112314. #endif
  112315. }
  112316. }
  112317. }
  112318. look->partvals=rint(pow((float)look->parts,(float)dim));
  112319. look->stages=maxstage;
  112320. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  112321. for(j=0;j<look->partvals;j++){
  112322. long val=j;
  112323. long mult=look->partvals/look->parts;
  112324. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  112325. for(k=0;k<dim;k++){
  112326. long deco=val/mult;
  112327. val-=deco*mult;
  112328. mult/=look->parts;
  112329. look->decodemap[j][k]=deco;
  112330. }
  112331. }
  112332. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  112333. {
  112334. static int train_seq=0;
  112335. look->train_seq=train_seq++;
  112336. }
  112337. #endif
  112338. return(look);
  112339. }
  112340. /* break an abstraction and copy some code for performance purposes */
  112341. static int local_book_besterror(codebook *book,float *a){
  112342. int dim=book->dim,i,k,o;
  112343. int best=0;
  112344. encode_aux_threshmatch *tt=book->c->thresh_tree;
  112345. /* find the quant val of each scalar */
  112346. for(k=0,o=dim;k<dim;++k){
  112347. float val=a[--o];
  112348. i=tt->threshvals>>1;
  112349. if(val<tt->quantthresh[i]){
  112350. if(val<tt->quantthresh[i-1]){
  112351. for(--i;i>0;--i)
  112352. if(val>=tt->quantthresh[i-1])
  112353. break;
  112354. }
  112355. }else{
  112356. for(++i;i<tt->threshvals-1;++i)
  112357. if(val<tt->quantthresh[i])break;
  112358. }
  112359. best=(best*tt->quantvals)+tt->quantmap[i];
  112360. }
  112361. /* regular lattices are easy :-) */
  112362. if(book->c->lengthlist[best]<=0){
  112363. const static_codebook *c=book->c;
  112364. int i,j;
  112365. float bestf=0.f;
  112366. float *e=book->valuelist;
  112367. best=-1;
  112368. for(i=0;i<book->entries;i++){
  112369. if(c->lengthlist[i]>0){
  112370. float thisx=0.f;
  112371. for(j=0;j<dim;j++){
  112372. float val=(e[j]-a[j]);
  112373. thisx+=val*val;
  112374. }
  112375. if(best==-1 || thisx<bestf){
  112376. bestf=thisx;
  112377. best=i;
  112378. }
  112379. }
  112380. e+=dim;
  112381. }
  112382. }
  112383. {
  112384. float *ptr=book->valuelist+best*dim;
  112385. for(i=0;i<dim;i++)
  112386. *a++ -= *ptr++;
  112387. }
  112388. return(best);
  112389. }
  112390. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  112391. codebook *book,long *acc){
  112392. int i,bits=0;
  112393. int dim=book->dim;
  112394. int step=n/dim;
  112395. for(i=0;i<step;i++){
  112396. int entry=local_book_besterror(book,vec+i*dim);
  112397. #ifdef TRAIN_RES
  112398. acc[entry]++;
  112399. #endif
  112400. bits+=vorbis_book_encode(book,entry,opb);
  112401. }
  112402. return(bits);
  112403. }
  112404. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  112405. float **in,int ch){
  112406. long i,j,k;
  112407. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  112408. vorbis_info_residue0 *info=look->info;
  112409. /* move all this setup out later */
  112410. int samples_per_partition=info->grouping;
  112411. int possible_partitions=info->partitions;
  112412. int n=info->end-info->begin;
  112413. int partvals=n/samples_per_partition;
  112414. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  112415. float scale=100./samples_per_partition;
  112416. /* we find the partition type for each partition of each
  112417. channel. We'll go back and do the interleaved encoding in a
  112418. bit. For now, clarity */
  112419. for(i=0;i<ch;i++){
  112420. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  112421. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  112422. }
  112423. for(i=0;i<partvals;i++){
  112424. int offset=i*samples_per_partition+info->begin;
  112425. for(j=0;j<ch;j++){
  112426. float max=0.;
  112427. float ent=0.;
  112428. for(k=0;k<samples_per_partition;k++){
  112429. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  112430. ent+=fabs(rint(in[j][offset+k]));
  112431. }
  112432. ent*=scale;
  112433. for(k=0;k<possible_partitions-1;k++)
  112434. if(max<=info->classmetric1[k] &&
  112435. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  112436. break;
  112437. partword[j][i]=k;
  112438. }
  112439. }
  112440. #ifdef TRAIN_RESAUX
  112441. {
  112442. FILE *of;
  112443. char buffer[80];
  112444. for(i=0;i<ch;i++){
  112445. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  112446. of=fopen(buffer,"a");
  112447. for(j=0;j<partvals;j++)
  112448. fprintf(of,"%ld, ",partword[i][j]);
  112449. fprintf(of,"\n");
  112450. fclose(of);
  112451. }
  112452. }
  112453. #endif
  112454. look->frames++;
  112455. return(partword);
  112456. }
  112457. /* designed for stereo or other modes where the partition size is an
  112458. integer multiple of the number of channels encoded in the current
  112459. submap */
  112460. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  112461. int ch){
  112462. long i,j,k,l;
  112463. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  112464. vorbis_info_residue0 *info=look->info;
  112465. /* move all this setup out later */
  112466. int samples_per_partition=info->grouping;
  112467. int possible_partitions=info->partitions;
  112468. int n=info->end-info->begin;
  112469. int partvals=n/samples_per_partition;
  112470. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  112471. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  112472. FILE *of;
  112473. char buffer[80];
  112474. #endif
  112475. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  112476. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  112477. for(i=0,l=info->begin/ch;i<partvals;i++){
  112478. float magmax=0.f;
  112479. float angmax=0.f;
  112480. for(j=0;j<samples_per_partition;j+=ch){
  112481. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  112482. for(k=1;k<ch;k++)
  112483. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  112484. l++;
  112485. }
  112486. for(j=0;j<possible_partitions-1;j++)
  112487. if(magmax<=info->classmetric1[j] &&
  112488. angmax<=info->classmetric2[j])
  112489. break;
  112490. partword[0][i]=j;
  112491. }
  112492. #ifdef TRAIN_RESAUX
  112493. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  112494. of=fopen(buffer,"a");
  112495. for(i=0;i<partvals;i++)
  112496. fprintf(of,"%ld, ",partword[0][i]);
  112497. fprintf(of,"\n");
  112498. fclose(of);
  112499. #endif
  112500. look->frames++;
  112501. return(partword);
  112502. }
  112503. static int _01forward(oggpack_buffer *opb,
  112504. vorbis_block *vb,vorbis_look_residue *vl,
  112505. float **in,int ch,
  112506. long **partword,
  112507. int (*encode)(oggpack_buffer *,float *,int,
  112508. codebook *,long *)){
  112509. long i,j,k,s;
  112510. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  112511. vorbis_info_residue0 *info=look->info;
  112512. /* move all this setup out later */
  112513. int samples_per_partition=info->grouping;
  112514. int possible_partitions=info->partitions;
  112515. int partitions_per_word=look->phrasebook->dim;
  112516. int n=info->end-info->begin;
  112517. int partvals=n/samples_per_partition;
  112518. long resbits[128];
  112519. long resvals[128];
  112520. #ifdef TRAIN_RES
  112521. for(i=0;i<ch;i++)
  112522. for(j=info->begin;j<info->end;j++){
  112523. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  112524. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  112525. }
  112526. #endif
  112527. memset(resbits,0,sizeof(resbits));
  112528. memset(resvals,0,sizeof(resvals));
  112529. /* we code the partition words for each channel, then the residual
  112530. words for a partition per channel until we've written all the
  112531. residual words for that partition word. Then write the next
  112532. partition channel words... */
  112533. for(s=0;s<look->stages;s++){
  112534. for(i=0;i<partvals;){
  112535. /* first we encode a partition codeword for each channel */
  112536. if(s==0){
  112537. for(j=0;j<ch;j++){
  112538. long val=partword[j][i];
  112539. for(k=1;k<partitions_per_word;k++){
  112540. val*=possible_partitions;
  112541. if(i+k<partvals)
  112542. val+=partword[j][i+k];
  112543. }
  112544. /* training hack */
  112545. if(val<look->phrasebook->entries)
  112546. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  112547. #if 0 /*def TRAIN_RES*/
  112548. else
  112549. fprintf(stderr,"!");
  112550. #endif
  112551. }
  112552. }
  112553. /* now we encode interleaved residual values for the partitions */
  112554. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  112555. long offset=i*samples_per_partition+info->begin;
  112556. for(j=0;j<ch;j++){
  112557. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  112558. if(info->secondstages[partword[j][i]]&(1<<s)){
  112559. codebook *statebook=look->partbooks[partword[j][i]][s];
  112560. if(statebook){
  112561. int ret;
  112562. long *accumulator=NULL;
  112563. #ifdef TRAIN_RES
  112564. accumulator=look->training_data[s][partword[j][i]];
  112565. {
  112566. int l;
  112567. float *samples=in[j]+offset;
  112568. for(l=0;l<samples_per_partition;l++){
  112569. if(samples[l]<look->training_min[s][partword[j][i]])
  112570. look->training_min[s][partword[j][i]]=samples[l];
  112571. if(samples[l]>look->training_max[s][partword[j][i]])
  112572. look->training_max[s][partword[j][i]]=samples[l];
  112573. }
  112574. }
  112575. #endif
  112576. ret=encode(opb,in[j]+offset,samples_per_partition,
  112577. statebook,accumulator);
  112578. look->postbits+=ret;
  112579. resbits[partword[j][i]]+=ret;
  112580. }
  112581. }
  112582. }
  112583. }
  112584. }
  112585. }
  112586. /*{
  112587. long total=0;
  112588. long totalbits=0;
  112589. fprintf(stderr,"%d :: ",vb->mode);
  112590. for(k=0;k<possible_partitions;k++){
  112591. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  112592. total+=resvals[k];
  112593. totalbits+=resbits[k];
  112594. }
  112595. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  112596. }*/
  112597. return(0);
  112598. }
  112599. /* a truncated packet here just means 'stop working'; it's not an error */
  112600. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  112601. float **in,int ch,
  112602. long (*decodepart)(codebook *, float *,
  112603. oggpack_buffer *,int)){
  112604. long i,j,k,l,s;
  112605. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  112606. vorbis_info_residue0 *info=look->info;
  112607. /* move all this setup out later */
  112608. int samples_per_partition=info->grouping;
  112609. int partitions_per_word=look->phrasebook->dim;
  112610. int n=info->end-info->begin;
  112611. int partvals=n/samples_per_partition;
  112612. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  112613. int ***partword=(int***)alloca(ch*sizeof(*partword));
  112614. for(j=0;j<ch;j++)
  112615. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  112616. for(s=0;s<look->stages;s++){
  112617. /* each loop decodes on partition codeword containing
  112618. partitions_pre_word partitions */
  112619. for(i=0,l=0;i<partvals;l++){
  112620. if(s==0){
  112621. /* fetch the partition word for each channel */
  112622. for(j=0;j<ch;j++){
  112623. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  112624. if(temp==-1)goto eopbreak;
  112625. partword[j][l]=look->decodemap[temp];
  112626. if(partword[j][l]==NULL)goto errout;
  112627. }
  112628. }
  112629. /* now we decode residual values for the partitions */
  112630. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  112631. for(j=0;j<ch;j++){
  112632. long offset=info->begin+i*samples_per_partition;
  112633. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  112634. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  112635. if(stagebook){
  112636. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  112637. samples_per_partition)==-1)goto eopbreak;
  112638. }
  112639. }
  112640. }
  112641. }
  112642. }
  112643. errout:
  112644. eopbreak:
  112645. return(0);
  112646. }
  112647. #if 0
  112648. /* residue 0 and 1 are just slight variants of one another. 0 is
  112649. interleaved, 1 is not */
  112650. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  112651. float **in,int *nonzero,int ch){
  112652. /* we encode only the nonzero parts of a bundle */
  112653. int i,used=0;
  112654. for(i=0;i<ch;i++)
  112655. if(nonzero[i])
  112656. in[used++]=in[i];
  112657. if(used)
  112658. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  112659. return(_01class(vb,vl,in,used));
  112660. else
  112661. return(0);
  112662. }
  112663. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  112664. float **in,float **out,int *nonzero,int ch,
  112665. long **partword){
  112666. /* we encode only the nonzero parts of a bundle */
  112667. int i,j,used=0,n=vb->pcmend/2;
  112668. for(i=0;i<ch;i++)
  112669. if(nonzero[i]){
  112670. if(out)
  112671. for(j=0;j<n;j++)
  112672. out[i][j]+=in[i][j];
  112673. in[used++]=in[i];
  112674. }
  112675. if(used){
  112676. int ret=_01forward(vb,vl,in,used,partword,
  112677. _interleaved_encodepart);
  112678. if(out){
  112679. used=0;
  112680. for(i=0;i<ch;i++)
  112681. if(nonzero[i]){
  112682. for(j=0;j<n;j++)
  112683. out[i][j]-=in[used][j];
  112684. used++;
  112685. }
  112686. }
  112687. return(ret);
  112688. }else{
  112689. return(0);
  112690. }
  112691. }
  112692. #endif
  112693. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  112694. float **in,int *nonzero,int ch){
  112695. int i,used=0;
  112696. for(i=0;i<ch;i++)
  112697. if(nonzero[i])
  112698. in[used++]=in[i];
  112699. if(used)
  112700. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  112701. else
  112702. return(0);
  112703. }
  112704. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  112705. float **in,float **out,int *nonzero,int ch,
  112706. long **partword){
  112707. int i,j,used=0,n=vb->pcmend/2;
  112708. for(i=0;i<ch;i++)
  112709. if(nonzero[i]){
  112710. if(out)
  112711. for(j=0;j<n;j++)
  112712. out[i][j]+=in[i][j];
  112713. in[used++]=in[i];
  112714. }
  112715. if(used){
  112716. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  112717. if(out){
  112718. used=0;
  112719. for(i=0;i<ch;i++)
  112720. if(nonzero[i]){
  112721. for(j=0;j<n;j++)
  112722. out[i][j]-=in[used][j];
  112723. used++;
  112724. }
  112725. }
  112726. return(ret);
  112727. }else{
  112728. return(0);
  112729. }
  112730. }
  112731. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  112732. float **in,int *nonzero,int ch){
  112733. int i,used=0;
  112734. for(i=0;i<ch;i++)
  112735. if(nonzero[i])
  112736. in[used++]=in[i];
  112737. if(used)
  112738. return(_01class(vb,vl,in,used));
  112739. else
  112740. return(0);
  112741. }
  112742. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  112743. float **in,int *nonzero,int ch){
  112744. int i,used=0;
  112745. for(i=0;i<ch;i++)
  112746. if(nonzero[i])
  112747. in[used++]=in[i];
  112748. if(used)
  112749. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  112750. else
  112751. return(0);
  112752. }
  112753. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  112754. float **in,int *nonzero,int ch){
  112755. int i,used=0;
  112756. for(i=0;i<ch;i++)
  112757. if(nonzero[i])used++;
  112758. if(used)
  112759. return(_2class(vb,vl,in,ch));
  112760. else
  112761. return(0);
  112762. }
  112763. /* res2 is slightly more different; all the channels are interleaved
  112764. into a single vector and encoded. */
  112765. int res2_forward(oggpack_buffer *opb,
  112766. vorbis_block *vb,vorbis_look_residue *vl,
  112767. float **in,float **out,int *nonzero,int ch,
  112768. long **partword){
  112769. long i,j,k,n=vb->pcmend/2,used=0;
  112770. /* don't duplicate the code; use a working vector hack for now and
  112771. reshape ourselves into a single channel res1 */
  112772. /* ugly; reallocs for each coupling pass :-( */
  112773. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  112774. for(i=0;i<ch;i++){
  112775. float *pcm=in[i];
  112776. if(nonzero[i])used++;
  112777. for(j=0,k=i;j<n;j++,k+=ch)
  112778. work[k]=pcm[j];
  112779. }
  112780. if(used){
  112781. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  112782. /* update the sofar vector */
  112783. if(out){
  112784. for(i=0;i<ch;i++){
  112785. float *pcm=in[i];
  112786. float *sofar=out[i];
  112787. for(j=0,k=i;j<n;j++,k+=ch)
  112788. sofar[j]+=pcm[j]-work[k];
  112789. }
  112790. }
  112791. return(ret);
  112792. }else{
  112793. return(0);
  112794. }
  112795. }
  112796. /* duplicate code here as speed is somewhat more important */
  112797. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  112798. float **in,int *nonzero,int ch){
  112799. long i,k,l,s;
  112800. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  112801. vorbis_info_residue0 *info=look->info;
  112802. /* move all this setup out later */
  112803. int samples_per_partition=info->grouping;
  112804. int partitions_per_word=look->phrasebook->dim;
  112805. int n=info->end-info->begin;
  112806. int partvals=n/samples_per_partition;
  112807. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  112808. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  112809. for(i=0;i<ch;i++)if(nonzero[i])break;
  112810. if(i==ch)return(0); /* no nonzero vectors */
  112811. for(s=0;s<look->stages;s++){
  112812. for(i=0,l=0;i<partvals;l++){
  112813. if(s==0){
  112814. /* fetch the partition word */
  112815. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  112816. if(temp==-1)goto eopbreak;
  112817. partword[l]=look->decodemap[temp];
  112818. if(partword[l]==NULL)goto errout;
  112819. }
  112820. /* now we decode residual values for the partitions */
  112821. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  112822. if(info->secondstages[partword[l][k]]&(1<<s)){
  112823. codebook *stagebook=look->partbooks[partword[l][k]][s];
  112824. if(stagebook){
  112825. if(vorbis_book_decodevv_add(stagebook,in,
  112826. i*samples_per_partition+info->begin,ch,
  112827. &vb->opb,samples_per_partition)==-1)
  112828. goto eopbreak;
  112829. }
  112830. }
  112831. }
  112832. }
  112833. errout:
  112834. eopbreak:
  112835. return(0);
  112836. }
  112837. vorbis_func_residue residue0_exportbundle={
  112838. NULL,
  112839. &res0_unpack,
  112840. &res0_look,
  112841. &res0_free_info,
  112842. &res0_free_look,
  112843. NULL,
  112844. NULL,
  112845. &res0_inverse
  112846. };
  112847. vorbis_func_residue residue1_exportbundle={
  112848. &res0_pack,
  112849. &res0_unpack,
  112850. &res0_look,
  112851. &res0_free_info,
  112852. &res0_free_look,
  112853. &res1_class,
  112854. &res1_forward,
  112855. &res1_inverse
  112856. };
  112857. vorbis_func_residue residue2_exportbundle={
  112858. &res0_pack,
  112859. &res0_unpack,
  112860. &res0_look,
  112861. &res0_free_info,
  112862. &res0_free_look,
  112863. &res2_class,
  112864. &res2_forward,
  112865. &res2_inverse
  112866. };
  112867. #endif
  112868. /********* End of inlined file: res0.c *********/
  112869. /********* Start of inlined file: sharedbook.c *********/
  112870. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  112871. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112872. // tasks..
  112873. #ifdef _MSC_VER
  112874. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112875. #endif
  112876. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  112877. #if JUCE_USE_OGGVORBIS
  112878. #include <stdlib.h>
  112879. #include <math.h>
  112880. #include <string.h>
  112881. /**** pack/unpack helpers ******************************************/
  112882. int _ilog(unsigned int v){
  112883. int ret=0;
  112884. while(v){
  112885. ret++;
  112886. v>>=1;
  112887. }
  112888. return(ret);
  112889. }
  112890. /* 32 bit float (not IEEE; nonnormalized mantissa +
  112891. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  112892. Why not IEEE? It's just not that important here. */
  112893. #define VQ_FEXP 10
  112894. #define VQ_FMAN 21
  112895. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  112896. /* doesn't currently guard under/overflow */
  112897. long _float32_pack(float val){
  112898. int sign=0;
  112899. long exp;
  112900. long mant;
  112901. if(val<0){
  112902. sign=0x80000000;
  112903. val= -val;
  112904. }
  112905. exp= floor(log(val)/log(2.f));
  112906. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  112907. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  112908. return(sign|exp|mant);
  112909. }
  112910. float _float32_unpack(long val){
  112911. double mant=val&0x1fffff;
  112912. int sign=val&0x80000000;
  112913. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  112914. if(sign)mant= -mant;
  112915. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  112916. }
  112917. /* given a list of word lengths, generate a list of codewords. Works
  112918. for length ordered or unordered, always assigns the lowest valued
  112919. codewords first. Extended to handle unused entries (length 0) */
  112920. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  112921. long i,j,count=0;
  112922. ogg_uint32_t marker[33];
  112923. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  112924. memset(marker,0,sizeof(marker));
  112925. for(i=0;i<n;i++){
  112926. long length=l[i];
  112927. if(length>0){
  112928. ogg_uint32_t entry=marker[length];
  112929. /* when we claim a node for an entry, we also claim the nodes
  112930. below it (pruning off the imagined tree that may have dangled
  112931. from it) as well as blocking the use of any nodes directly
  112932. above for leaves */
  112933. /* update ourself */
  112934. if(length<32 && (entry>>length)){
  112935. /* error condition; the lengths must specify an overpopulated tree */
  112936. _ogg_free(r);
  112937. return(NULL);
  112938. }
  112939. r[count++]=entry;
  112940. /* Look to see if the next shorter marker points to the node
  112941. above. if so, update it and repeat. */
  112942. {
  112943. for(j=length;j>0;j--){
  112944. if(marker[j]&1){
  112945. /* have to jump branches */
  112946. if(j==1)
  112947. marker[1]++;
  112948. else
  112949. marker[j]=marker[j-1]<<1;
  112950. break; /* invariant says next upper marker would already
  112951. have been moved if it was on the same path */
  112952. }
  112953. marker[j]++;
  112954. }
  112955. }
  112956. /* prune the tree; the implicit invariant says all the longer
  112957. markers were dangling from our just-taken node. Dangle them
  112958. from our *new* node. */
  112959. for(j=length+1;j<33;j++)
  112960. if((marker[j]>>1) == entry){
  112961. entry=marker[j];
  112962. marker[j]=marker[j-1]<<1;
  112963. }else
  112964. break;
  112965. }else
  112966. if(sparsecount==0)count++;
  112967. }
  112968. /* bitreverse the words because our bitwise packer/unpacker is LSb
  112969. endian */
  112970. for(i=0,count=0;i<n;i++){
  112971. ogg_uint32_t temp=0;
  112972. for(j=0;j<l[i];j++){
  112973. temp<<=1;
  112974. temp|=(r[count]>>j)&1;
  112975. }
  112976. if(sparsecount){
  112977. if(l[i])
  112978. r[count++]=temp;
  112979. }else
  112980. r[count++]=temp;
  112981. }
  112982. return(r);
  112983. }
  112984. /* there might be a straightforward one-line way to do the below
  112985. that's portable and totally safe against roundoff, but I haven't
  112986. thought of it. Therefore, we opt on the side of caution */
  112987. long _book_maptype1_quantvals(const static_codebook *b){
  112988. long vals=floor(pow((float)b->entries,1.f/b->dim));
  112989. /* the above *should* be reliable, but we'll not assume that FP is
  112990. ever reliable when bitstream sync is at stake; verify via integer
  112991. means that vals really is the greatest value of dim for which
  112992. vals^b->bim <= b->entries */
  112993. /* treat the above as an initial guess */
  112994. while(1){
  112995. long acc=1;
  112996. long acc1=1;
  112997. int i;
  112998. for(i=0;i<b->dim;i++){
  112999. acc*=vals;
  113000. acc1*=vals+1;
  113001. }
  113002. if(acc<=b->entries && acc1>b->entries){
  113003. return(vals);
  113004. }else{
  113005. if(acc>b->entries){
  113006. vals--;
  113007. }else{
  113008. vals++;
  113009. }
  113010. }
  113011. }
  113012. }
  113013. /* unpack the quantized list of values for encode/decode ***********/
  113014. /* we need to deal with two map types: in map type 1, the values are
  113015. generated algorithmically (each column of the vector counts through
  113016. the values in the quant vector). in map type 2, all the values came
  113017. in in an explicit list. Both value lists must be unpacked */
  113018. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  113019. long j,k,count=0;
  113020. if(b->maptype==1 || b->maptype==2){
  113021. int quantvals;
  113022. float mindel=_float32_unpack(b->q_min);
  113023. float delta=_float32_unpack(b->q_delta);
  113024. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  113025. /* maptype 1 and 2 both use a quantized value vector, but
  113026. different sizes */
  113027. switch(b->maptype){
  113028. case 1:
  113029. /* most of the time, entries%dimensions == 0, but we need to be
  113030. well defined. We define that the possible vales at each
  113031. scalar is values == entries/dim. If entries%dim != 0, we'll
  113032. have 'too few' values (values*dim<entries), which means that
  113033. we'll have 'left over' entries; left over entries use zeroed
  113034. values (and are wasted). So don't generate codebooks like
  113035. that */
  113036. quantvals=_book_maptype1_quantvals(b);
  113037. for(j=0;j<b->entries;j++){
  113038. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  113039. float last=0.f;
  113040. int indexdiv=1;
  113041. for(k=0;k<b->dim;k++){
  113042. int index= (j/indexdiv)%quantvals;
  113043. float val=b->quantlist[index];
  113044. val=fabs(val)*delta+mindel+last;
  113045. if(b->q_sequencep)last=val;
  113046. if(sparsemap)
  113047. r[sparsemap[count]*b->dim+k]=val;
  113048. else
  113049. r[count*b->dim+k]=val;
  113050. indexdiv*=quantvals;
  113051. }
  113052. count++;
  113053. }
  113054. }
  113055. break;
  113056. case 2:
  113057. for(j=0;j<b->entries;j++){
  113058. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  113059. float last=0.f;
  113060. for(k=0;k<b->dim;k++){
  113061. float val=b->quantlist[j*b->dim+k];
  113062. val=fabs(val)*delta+mindel+last;
  113063. if(b->q_sequencep)last=val;
  113064. if(sparsemap)
  113065. r[sparsemap[count]*b->dim+k]=val;
  113066. else
  113067. r[count*b->dim+k]=val;
  113068. }
  113069. count++;
  113070. }
  113071. }
  113072. break;
  113073. }
  113074. return(r);
  113075. }
  113076. return(NULL);
  113077. }
  113078. void vorbis_staticbook_clear(static_codebook *b){
  113079. if(b->allocedp){
  113080. if(b->quantlist)_ogg_free(b->quantlist);
  113081. if(b->lengthlist)_ogg_free(b->lengthlist);
  113082. if(b->nearest_tree){
  113083. _ogg_free(b->nearest_tree->ptr0);
  113084. _ogg_free(b->nearest_tree->ptr1);
  113085. _ogg_free(b->nearest_tree->p);
  113086. _ogg_free(b->nearest_tree->q);
  113087. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  113088. _ogg_free(b->nearest_tree);
  113089. }
  113090. if(b->thresh_tree){
  113091. _ogg_free(b->thresh_tree->quantthresh);
  113092. _ogg_free(b->thresh_tree->quantmap);
  113093. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  113094. _ogg_free(b->thresh_tree);
  113095. }
  113096. memset(b,0,sizeof(*b));
  113097. }
  113098. }
  113099. void vorbis_staticbook_destroy(static_codebook *b){
  113100. if(b->allocedp){
  113101. vorbis_staticbook_clear(b);
  113102. _ogg_free(b);
  113103. }
  113104. }
  113105. void vorbis_book_clear(codebook *b){
  113106. /* static book is not cleared; we're likely called on the lookup and
  113107. the static codebook belongs to the info struct */
  113108. if(b->valuelist)_ogg_free(b->valuelist);
  113109. if(b->codelist)_ogg_free(b->codelist);
  113110. if(b->dec_index)_ogg_free(b->dec_index);
  113111. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  113112. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  113113. memset(b,0,sizeof(*b));
  113114. }
  113115. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  113116. memset(c,0,sizeof(*c));
  113117. c->c=s;
  113118. c->entries=s->entries;
  113119. c->used_entries=s->entries;
  113120. c->dim=s->dim;
  113121. c->codelist=_make_words(s->lengthlist,s->entries,0);
  113122. c->valuelist=_book_unquantize(s,s->entries,NULL);
  113123. return(0);
  113124. }
  113125. static int sort32a(const void *a,const void *b){
  113126. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  113127. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  113128. }
  113129. /* decode codebook arrangement is more heavily optimized than encode */
  113130. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  113131. int i,j,n=0,tabn;
  113132. int *sortindex;
  113133. memset(c,0,sizeof(*c));
  113134. /* count actually used entries */
  113135. for(i=0;i<s->entries;i++)
  113136. if(s->lengthlist[i]>0)
  113137. n++;
  113138. c->entries=s->entries;
  113139. c->used_entries=n;
  113140. c->dim=s->dim;
  113141. /* two different remappings go on here.
  113142. First, we collapse the likely sparse codebook down only to
  113143. actually represented values/words. This collapsing needs to be
  113144. indexed as map-valueless books are used to encode original entry
  113145. positions as integers.
  113146. Second, we reorder all vectors, including the entry index above,
  113147. by sorted bitreversed codeword to allow treeless decode. */
  113148. {
  113149. /* perform sort */
  113150. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  113151. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  113152. if(codes==NULL)goto err_out;
  113153. for(i=0;i<n;i++){
  113154. codes[i]=bitreverse(codes[i]);
  113155. codep[i]=codes+i;
  113156. }
  113157. qsort(codep,n,sizeof(*codep),sort32a);
  113158. sortindex=(int*)alloca(n*sizeof(*sortindex));
  113159. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  113160. /* the index is a reverse index */
  113161. for(i=0;i<n;i++){
  113162. int position=codep[i]-codes;
  113163. sortindex[position]=i;
  113164. }
  113165. for(i=0;i<n;i++)
  113166. c->codelist[sortindex[i]]=codes[i];
  113167. _ogg_free(codes);
  113168. }
  113169. c->valuelist=_book_unquantize(s,n,sortindex);
  113170. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  113171. for(n=0,i=0;i<s->entries;i++)
  113172. if(s->lengthlist[i]>0)
  113173. c->dec_index[sortindex[n++]]=i;
  113174. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  113175. for(n=0,i=0;i<s->entries;i++)
  113176. if(s->lengthlist[i]>0)
  113177. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  113178. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  113179. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  113180. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  113181. tabn=1<<c->dec_firsttablen;
  113182. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  113183. c->dec_maxlength=0;
  113184. for(i=0;i<n;i++){
  113185. if(c->dec_maxlength<c->dec_codelengths[i])
  113186. c->dec_maxlength=c->dec_codelengths[i];
  113187. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  113188. ogg_uint32_t orig=bitreverse(c->codelist[i]);
  113189. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  113190. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  113191. }
  113192. }
  113193. /* now fill in 'unused' entries in the firsttable with hi/lo search
  113194. hints for the non-direct-hits */
  113195. {
  113196. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  113197. long lo=0,hi=0;
  113198. for(i=0;i<tabn;i++){
  113199. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  113200. if(c->dec_firsttable[bitreverse(word)]==0){
  113201. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  113202. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  113203. /* we only actually have 15 bits per hint to play with here.
  113204. In order to overflow gracefully (nothing breaks, efficiency
  113205. just drops), encode as the difference from the extremes. */
  113206. {
  113207. unsigned long loval=lo;
  113208. unsigned long hival=n-hi;
  113209. if(loval>0x7fff)loval=0x7fff;
  113210. if(hival>0x7fff)hival=0x7fff;
  113211. c->dec_firsttable[bitreverse(word)]=
  113212. 0x80000000UL | (loval<<15) | hival;
  113213. }
  113214. }
  113215. }
  113216. }
  113217. return(0);
  113218. err_out:
  113219. vorbis_book_clear(c);
  113220. return(-1);
  113221. }
  113222. static float _dist(int el,float *ref, float *b,int step){
  113223. int i;
  113224. float acc=0.f;
  113225. for(i=0;i<el;i++){
  113226. float val=(ref[i]-b[i*step]);
  113227. acc+=val*val;
  113228. }
  113229. return(acc);
  113230. }
  113231. int _best(codebook *book, float *a, int step){
  113232. encode_aux_threshmatch *tt=book->c->thresh_tree;
  113233. #if 0
  113234. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  113235. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  113236. #endif
  113237. int dim=book->dim;
  113238. int k,o;
  113239. /*int savebest=-1;
  113240. float saverr;*/
  113241. /* do we have a threshhold encode hint? */
  113242. if(tt){
  113243. int index=0,i;
  113244. /* find the quant val of each scalar */
  113245. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  113246. i=tt->threshvals>>1;
  113247. if(a[o]<tt->quantthresh[i]){
  113248. for(;i>0;i--)
  113249. if(a[o]>=tt->quantthresh[i-1])
  113250. break;
  113251. }else{
  113252. for(i++;i<tt->threshvals-1;i++)
  113253. if(a[o]<tt->quantthresh[i])break;
  113254. }
  113255. index=(index*tt->quantvals)+tt->quantmap[i];
  113256. }
  113257. /* regular lattices are easy :-) */
  113258. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  113259. use a decision tree after all
  113260. and fall through*/
  113261. return(index);
  113262. }
  113263. #if 0
  113264. /* do we have a pigeonhole encode hint? */
  113265. if(pt){
  113266. const static_codebook *c=book->c;
  113267. int i,besti=-1;
  113268. float best=0.f;
  113269. int entry=0;
  113270. /* dealing with sequentialness is a pain in the ass */
  113271. if(c->q_sequencep){
  113272. int pv;
  113273. long mul=1;
  113274. float qlast=0;
  113275. for(k=0,o=0;k<dim;k++,o+=step){
  113276. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  113277. if(pv<0 || pv>=pt->mapentries)break;
  113278. entry+=pt->pigeonmap[pv]*mul;
  113279. mul*=pt->quantvals;
  113280. qlast+=pv*pt->del+pt->min;
  113281. }
  113282. }else{
  113283. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  113284. int pv=(int)((a[o]-pt->min)/pt->del);
  113285. if(pv<0 || pv>=pt->mapentries)break;
  113286. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  113287. }
  113288. }
  113289. /* must be within the pigeonholable range; if we quant outside (or
  113290. in an entry that we define no list for), brute force it */
  113291. if(k==dim && pt->fitlength[entry]){
  113292. /* search the abbreviated list */
  113293. long *list=pt->fitlist+pt->fitmap[entry];
  113294. for(i=0;i<pt->fitlength[entry];i++){
  113295. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  113296. if(besti==-1 || this<best){
  113297. best=this;
  113298. besti=list[i];
  113299. }
  113300. }
  113301. return(besti);
  113302. }
  113303. }
  113304. if(nt){
  113305. /* optimized using the decision tree */
  113306. while(1){
  113307. float c=0.f;
  113308. float *p=book->valuelist+nt->p[ptr];
  113309. float *q=book->valuelist+nt->q[ptr];
  113310. for(k=0,o=0;k<dim;k++,o+=step)
  113311. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  113312. if(c>0.f) /* in A */
  113313. ptr= -nt->ptr0[ptr];
  113314. else /* in B */
  113315. ptr= -nt->ptr1[ptr];
  113316. if(ptr<=0)break;
  113317. }
  113318. return(-ptr);
  113319. }
  113320. #endif
  113321. /* brute force it! */
  113322. {
  113323. const static_codebook *c=book->c;
  113324. int i,besti=-1;
  113325. float best=0.f;
  113326. float *e=book->valuelist;
  113327. for(i=0;i<book->entries;i++){
  113328. if(c->lengthlist[i]>0){
  113329. float thisx=_dist(dim,e,a,step);
  113330. if(besti==-1 || thisx<best){
  113331. best=thisx;
  113332. besti=i;
  113333. }
  113334. }
  113335. e+=dim;
  113336. }
  113337. /*if(savebest!=-1 && savebest!=besti){
  113338. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  113339. "original:");
  113340. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  113341. fprintf(stderr,"\n"
  113342. "pigeonhole (entry %d, err %g):",savebest,saverr);
  113343. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  113344. (book->valuelist+savebest*dim)[i]);
  113345. fprintf(stderr,"\n"
  113346. "bruteforce (entry %d, err %g):",besti,best);
  113347. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  113348. (book->valuelist+besti*dim)[i]);
  113349. fprintf(stderr,"\n");
  113350. }*/
  113351. return(besti);
  113352. }
  113353. }
  113354. long vorbis_book_codeword(codebook *book,int entry){
  113355. if(book->c) /* only use with encode; decode optimizations are
  113356. allowed to break this */
  113357. return book->codelist[entry];
  113358. return -1;
  113359. }
  113360. long vorbis_book_codelen(codebook *book,int entry){
  113361. if(book->c) /* only use with encode; decode optimizations are
  113362. allowed to break this */
  113363. return book->c->lengthlist[entry];
  113364. return -1;
  113365. }
  113366. #ifdef _V_SELFTEST
  113367. /* Unit tests of the dequantizer; this stuff will be OK
  113368. cross-platform, I simply want to be sure that special mapping cases
  113369. actually work properly; a bug could go unnoticed for a while */
  113370. #include <stdio.h>
  113371. /* cases:
  113372. no mapping
  113373. full, explicit mapping
  113374. algorithmic mapping
  113375. nonsequential
  113376. sequential
  113377. */
  113378. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  113379. static long partial_quantlist1[]={0,7,2};
  113380. /* no mapping */
  113381. static_codebook test1={
  113382. 4,16,
  113383. NULL,
  113384. 0,
  113385. 0,0,0,0,
  113386. NULL,
  113387. NULL,NULL
  113388. };
  113389. static float *test1_result=NULL;
  113390. /* linear, full mapping, nonsequential */
  113391. static_codebook test2={
  113392. 4,3,
  113393. NULL,
  113394. 2,
  113395. -533200896,1611661312,4,0,
  113396. full_quantlist1,
  113397. NULL,NULL
  113398. };
  113399. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  113400. /* linear, full mapping, sequential */
  113401. static_codebook test3={
  113402. 4,3,
  113403. NULL,
  113404. 2,
  113405. -533200896,1611661312,4,1,
  113406. full_quantlist1,
  113407. NULL,NULL
  113408. };
  113409. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  113410. /* linear, algorithmic mapping, nonsequential */
  113411. static_codebook test4={
  113412. 3,27,
  113413. NULL,
  113414. 1,
  113415. -533200896,1611661312,4,0,
  113416. partial_quantlist1,
  113417. NULL,NULL
  113418. };
  113419. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  113420. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  113421. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  113422. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  113423. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  113424. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  113425. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  113426. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  113427. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  113428. /* linear, algorithmic mapping, sequential */
  113429. static_codebook test5={
  113430. 3,27,
  113431. NULL,
  113432. 1,
  113433. -533200896,1611661312,4,1,
  113434. partial_quantlist1,
  113435. NULL,NULL
  113436. };
  113437. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  113438. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  113439. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  113440. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  113441. -3, 1, 5, 4, 8,12, -1, 3, 7,
  113442. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  113443. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  113444. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  113445. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  113446. void run_test(static_codebook *b,float *comp){
  113447. float *out=_book_unquantize(b,b->entries,NULL);
  113448. int i;
  113449. if(comp){
  113450. if(!out){
  113451. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  113452. exit(1);
  113453. }
  113454. for(i=0;i<b->entries*b->dim;i++)
  113455. if(fabs(out[i]-comp[i])>.0001){
  113456. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  113457. "position %d, %g != %g\n",i,out[i],comp[i]);
  113458. exit(1);
  113459. }
  113460. }else{
  113461. if(out){
  113462. fprintf(stderr,"_book_unquantize returned a value array: \n"
  113463. " correct result should have been NULL\n");
  113464. exit(1);
  113465. }
  113466. }
  113467. }
  113468. int main(){
  113469. /* run the nine dequant tests, and compare to the hand-rolled results */
  113470. fprintf(stderr,"Dequant test 1... ");
  113471. run_test(&test1,test1_result);
  113472. fprintf(stderr,"OK\nDequant test 2... ");
  113473. run_test(&test2,test2_result);
  113474. fprintf(stderr,"OK\nDequant test 3... ");
  113475. run_test(&test3,test3_result);
  113476. fprintf(stderr,"OK\nDequant test 4... ");
  113477. run_test(&test4,test4_result);
  113478. fprintf(stderr,"OK\nDequant test 5... ");
  113479. run_test(&test5,test5_result);
  113480. fprintf(stderr,"OK\n\n");
  113481. return(0);
  113482. }
  113483. #endif
  113484. #endif
  113485. /********* End of inlined file: sharedbook.c *********/
  113486. /********* Start of inlined file: smallft.c *********/
  113487. /* FFT implementation from OggSquish, minus cosine transforms,
  113488. * minus all but radix 2/4 case. In Vorbis we only need this
  113489. * cut-down version.
  113490. *
  113491. * To do more than just power-of-two sized vectors, see the full
  113492. * version I wrote for NetLib.
  113493. *
  113494. * Note that the packing is a little strange; rather than the FFT r/i
  113495. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  113496. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  113497. * FORTRAN version
  113498. */
  113499. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113500. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113501. // tasks..
  113502. #ifdef _MSC_VER
  113503. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113504. #endif
  113505. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113506. #if JUCE_USE_OGGVORBIS
  113507. #include <stdlib.h>
  113508. #include <string.h>
  113509. #include <math.h>
  113510. static void drfti1(int n, float *wa, int *ifac){
  113511. static int ntryh[4] = { 4,2,3,5 };
  113512. static float tpi = 6.28318530717958648f;
  113513. float arg,argh,argld,fi;
  113514. int ntry=0,i,j=-1;
  113515. int k1, l1, l2, ib;
  113516. int ld, ii, ip, is, nq, nr;
  113517. int ido, ipm, nfm1;
  113518. int nl=n;
  113519. int nf=0;
  113520. L101:
  113521. j++;
  113522. if (j < 4)
  113523. ntry=ntryh[j];
  113524. else
  113525. ntry+=2;
  113526. L104:
  113527. nq=nl/ntry;
  113528. nr=nl-ntry*nq;
  113529. if (nr!=0) goto L101;
  113530. nf++;
  113531. ifac[nf+1]=ntry;
  113532. nl=nq;
  113533. if(ntry!=2)goto L107;
  113534. if(nf==1)goto L107;
  113535. for (i=1;i<nf;i++){
  113536. ib=nf-i+1;
  113537. ifac[ib+1]=ifac[ib];
  113538. }
  113539. ifac[2] = 2;
  113540. L107:
  113541. if(nl!=1)goto L104;
  113542. ifac[0]=n;
  113543. ifac[1]=nf;
  113544. argh=tpi/n;
  113545. is=0;
  113546. nfm1=nf-1;
  113547. l1=1;
  113548. if(nfm1==0)return;
  113549. for (k1=0;k1<nfm1;k1++){
  113550. ip=ifac[k1+2];
  113551. ld=0;
  113552. l2=l1*ip;
  113553. ido=n/l2;
  113554. ipm=ip-1;
  113555. for (j=0;j<ipm;j++){
  113556. ld+=l1;
  113557. i=is;
  113558. argld=(float)ld*argh;
  113559. fi=0.f;
  113560. for (ii=2;ii<ido;ii+=2){
  113561. fi+=1.f;
  113562. arg=fi*argld;
  113563. wa[i++]=cos(arg);
  113564. wa[i++]=sin(arg);
  113565. }
  113566. is+=ido;
  113567. }
  113568. l1=l2;
  113569. }
  113570. }
  113571. static void fdrffti(int n, float *wsave, int *ifac){
  113572. if (n == 1) return;
  113573. drfti1(n, wsave+n, ifac);
  113574. }
  113575. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  113576. int i,k;
  113577. float ti2,tr2;
  113578. int t0,t1,t2,t3,t4,t5,t6;
  113579. t1=0;
  113580. t0=(t2=l1*ido);
  113581. t3=ido<<1;
  113582. for(k=0;k<l1;k++){
  113583. ch[t1<<1]=cc[t1]+cc[t2];
  113584. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  113585. t1+=ido;
  113586. t2+=ido;
  113587. }
  113588. if(ido<2)return;
  113589. if(ido==2)goto L105;
  113590. t1=0;
  113591. t2=t0;
  113592. for(k=0;k<l1;k++){
  113593. t3=t2;
  113594. t4=(t1<<1)+(ido<<1);
  113595. t5=t1;
  113596. t6=t1+t1;
  113597. for(i=2;i<ido;i+=2){
  113598. t3+=2;
  113599. t4-=2;
  113600. t5+=2;
  113601. t6+=2;
  113602. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  113603. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  113604. ch[t6]=cc[t5]+ti2;
  113605. ch[t4]=ti2-cc[t5];
  113606. ch[t6-1]=cc[t5-1]+tr2;
  113607. ch[t4-1]=cc[t5-1]-tr2;
  113608. }
  113609. t1+=ido;
  113610. t2+=ido;
  113611. }
  113612. if(ido%2==1)return;
  113613. L105:
  113614. t3=(t2=(t1=ido)-1);
  113615. t2+=t0;
  113616. for(k=0;k<l1;k++){
  113617. ch[t1]=-cc[t2];
  113618. ch[t1-1]=cc[t3];
  113619. t1+=ido<<1;
  113620. t2+=ido;
  113621. t3+=ido;
  113622. }
  113623. }
  113624. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  113625. float *wa2,float *wa3){
  113626. static float hsqt2 = .70710678118654752f;
  113627. int i,k,t0,t1,t2,t3,t4,t5,t6;
  113628. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  113629. t0=l1*ido;
  113630. t1=t0;
  113631. t4=t1<<1;
  113632. t2=t1+(t1<<1);
  113633. t3=0;
  113634. for(k=0;k<l1;k++){
  113635. tr1=cc[t1]+cc[t2];
  113636. tr2=cc[t3]+cc[t4];
  113637. ch[t5=t3<<2]=tr1+tr2;
  113638. ch[(ido<<2)+t5-1]=tr2-tr1;
  113639. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  113640. ch[t5]=cc[t2]-cc[t1];
  113641. t1+=ido;
  113642. t2+=ido;
  113643. t3+=ido;
  113644. t4+=ido;
  113645. }
  113646. if(ido<2)return;
  113647. if(ido==2)goto L105;
  113648. t1=0;
  113649. for(k=0;k<l1;k++){
  113650. t2=t1;
  113651. t4=t1<<2;
  113652. t5=(t6=ido<<1)+t4;
  113653. for(i=2;i<ido;i+=2){
  113654. t3=(t2+=2);
  113655. t4+=2;
  113656. t5-=2;
  113657. t3+=t0;
  113658. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  113659. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  113660. t3+=t0;
  113661. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  113662. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  113663. t3+=t0;
  113664. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  113665. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  113666. tr1=cr2+cr4;
  113667. tr4=cr4-cr2;
  113668. ti1=ci2+ci4;
  113669. ti4=ci2-ci4;
  113670. ti2=cc[t2]+ci3;
  113671. ti3=cc[t2]-ci3;
  113672. tr2=cc[t2-1]+cr3;
  113673. tr3=cc[t2-1]-cr3;
  113674. ch[t4-1]=tr1+tr2;
  113675. ch[t4]=ti1+ti2;
  113676. ch[t5-1]=tr3-ti4;
  113677. ch[t5]=tr4-ti3;
  113678. ch[t4+t6-1]=ti4+tr3;
  113679. ch[t4+t6]=tr4+ti3;
  113680. ch[t5+t6-1]=tr2-tr1;
  113681. ch[t5+t6]=ti1-ti2;
  113682. }
  113683. t1+=ido;
  113684. }
  113685. if(ido&1)return;
  113686. L105:
  113687. t2=(t1=t0+ido-1)+(t0<<1);
  113688. t3=ido<<2;
  113689. t4=ido;
  113690. t5=ido<<1;
  113691. t6=ido;
  113692. for(k=0;k<l1;k++){
  113693. ti1=-hsqt2*(cc[t1]+cc[t2]);
  113694. tr1=hsqt2*(cc[t1]-cc[t2]);
  113695. ch[t4-1]=tr1+cc[t6-1];
  113696. ch[t4+t5-1]=cc[t6-1]-tr1;
  113697. ch[t4]=ti1-cc[t1+t0];
  113698. ch[t4+t5]=ti1+cc[t1+t0];
  113699. t1+=ido;
  113700. t2+=ido;
  113701. t4+=t3;
  113702. t6+=ido;
  113703. }
  113704. }
  113705. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  113706. float *c2,float *ch,float *ch2,float *wa){
  113707. static float tpi=6.283185307179586f;
  113708. int idij,ipph,i,j,k,l,ic,ik,is;
  113709. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  113710. float dc2,ai1,ai2,ar1,ar2,ds2;
  113711. int nbd;
  113712. float dcp,arg,dsp,ar1h,ar2h;
  113713. int idp2,ipp2;
  113714. arg=tpi/(float)ip;
  113715. dcp=cos(arg);
  113716. dsp=sin(arg);
  113717. ipph=(ip+1)>>1;
  113718. ipp2=ip;
  113719. idp2=ido;
  113720. nbd=(ido-1)>>1;
  113721. t0=l1*ido;
  113722. t10=ip*ido;
  113723. if(ido==1)goto L119;
  113724. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  113725. t1=0;
  113726. for(j=1;j<ip;j++){
  113727. t1+=t0;
  113728. t2=t1;
  113729. for(k=0;k<l1;k++){
  113730. ch[t2]=c1[t2];
  113731. t2+=ido;
  113732. }
  113733. }
  113734. is=-ido;
  113735. t1=0;
  113736. if(nbd>l1){
  113737. for(j=1;j<ip;j++){
  113738. t1+=t0;
  113739. is+=ido;
  113740. t2= -ido+t1;
  113741. for(k=0;k<l1;k++){
  113742. idij=is-1;
  113743. t2+=ido;
  113744. t3=t2;
  113745. for(i=2;i<ido;i+=2){
  113746. idij+=2;
  113747. t3+=2;
  113748. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  113749. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  113750. }
  113751. }
  113752. }
  113753. }else{
  113754. for(j=1;j<ip;j++){
  113755. is+=ido;
  113756. idij=is-1;
  113757. t1+=t0;
  113758. t2=t1;
  113759. for(i=2;i<ido;i+=2){
  113760. idij+=2;
  113761. t2+=2;
  113762. t3=t2;
  113763. for(k=0;k<l1;k++){
  113764. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  113765. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  113766. t3+=ido;
  113767. }
  113768. }
  113769. }
  113770. }
  113771. t1=0;
  113772. t2=ipp2*t0;
  113773. if(nbd<l1){
  113774. for(j=1;j<ipph;j++){
  113775. t1+=t0;
  113776. t2-=t0;
  113777. t3=t1;
  113778. t4=t2;
  113779. for(i=2;i<ido;i+=2){
  113780. t3+=2;
  113781. t4+=2;
  113782. t5=t3-ido;
  113783. t6=t4-ido;
  113784. for(k=0;k<l1;k++){
  113785. t5+=ido;
  113786. t6+=ido;
  113787. c1[t5-1]=ch[t5-1]+ch[t6-1];
  113788. c1[t6-1]=ch[t5]-ch[t6];
  113789. c1[t5]=ch[t5]+ch[t6];
  113790. c1[t6]=ch[t6-1]-ch[t5-1];
  113791. }
  113792. }
  113793. }
  113794. }else{
  113795. for(j=1;j<ipph;j++){
  113796. t1+=t0;
  113797. t2-=t0;
  113798. t3=t1;
  113799. t4=t2;
  113800. for(k=0;k<l1;k++){
  113801. t5=t3;
  113802. t6=t4;
  113803. for(i=2;i<ido;i+=2){
  113804. t5+=2;
  113805. t6+=2;
  113806. c1[t5-1]=ch[t5-1]+ch[t6-1];
  113807. c1[t6-1]=ch[t5]-ch[t6];
  113808. c1[t5]=ch[t5]+ch[t6];
  113809. c1[t6]=ch[t6-1]-ch[t5-1];
  113810. }
  113811. t3+=ido;
  113812. t4+=ido;
  113813. }
  113814. }
  113815. }
  113816. L119:
  113817. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  113818. t1=0;
  113819. t2=ipp2*idl1;
  113820. for(j=1;j<ipph;j++){
  113821. t1+=t0;
  113822. t2-=t0;
  113823. t3=t1-ido;
  113824. t4=t2-ido;
  113825. for(k=0;k<l1;k++){
  113826. t3+=ido;
  113827. t4+=ido;
  113828. c1[t3]=ch[t3]+ch[t4];
  113829. c1[t4]=ch[t4]-ch[t3];
  113830. }
  113831. }
  113832. ar1=1.f;
  113833. ai1=0.f;
  113834. t1=0;
  113835. t2=ipp2*idl1;
  113836. t3=(ip-1)*idl1;
  113837. for(l=1;l<ipph;l++){
  113838. t1+=idl1;
  113839. t2-=idl1;
  113840. ar1h=dcp*ar1-dsp*ai1;
  113841. ai1=dcp*ai1+dsp*ar1;
  113842. ar1=ar1h;
  113843. t4=t1;
  113844. t5=t2;
  113845. t6=t3;
  113846. t7=idl1;
  113847. for(ik=0;ik<idl1;ik++){
  113848. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  113849. ch2[t5++]=ai1*c2[t6++];
  113850. }
  113851. dc2=ar1;
  113852. ds2=ai1;
  113853. ar2=ar1;
  113854. ai2=ai1;
  113855. t4=idl1;
  113856. t5=(ipp2-1)*idl1;
  113857. for(j=2;j<ipph;j++){
  113858. t4+=idl1;
  113859. t5-=idl1;
  113860. ar2h=dc2*ar2-ds2*ai2;
  113861. ai2=dc2*ai2+ds2*ar2;
  113862. ar2=ar2h;
  113863. t6=t1;
  113864. t7=t2;
  113865. t8=t4;
  113866. t9=t5;
  113867. for(ik=0;ik<idl1;ik++){
  113868. ch2[t6++]+=ar2*c2[t8++];
  113869. ch2[t7++]+=ai2*c2[t9++];
  113870. }
  113871. }
  113872. }
  113873. t1=0;
  113874. for(j=1;j<ipph;j++){
  113875. t1+=idl1;
  113876. t2=t1;
  113877. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  113878. }
  113879. if(ido<l1)goto L132;
  113880. t1=0;
  113881. t2=0;
  113882. for(k=0;k<l1;k++){
  113883. t3=t1;
  113884. t4=t2;
  113885. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  113886. t1+=ido;
  113887. t2+=t10;
  113888. }
  113889. goto L135;
  113890. L132:
  113891. for(i=0;i<ido;i++){
  113892. t1=i;
  113893. t2=i;
  113894. for(k=0;k<l1;k++){
  113895. cc[t2]=ch[t1];
  113896. t1+=ido;
  113897. t2+=t10;
  113898. }
  113899. }
  113900. L135:
  113901. t1=0;
  113902. t2=ido<<1;
  113903. t3=0;
  113904. t4=ipp2*t0;
  113905. for(j=1;j<ipph;j++){
  113906. t1+=t2;
  113907. t3+=t0;
  113908. t4-=t0;
  113909. t5=t1;
  113910. t6=t3;
  113911. t7=t4;
  113912. for(k=0;k<l1;k++){
  113913. cc[t5-1]=ch[t6];
  113914. cc[t5]=ch[t7];
  113915. t5+=t10;
  113916. t6+=ido;
  113917. t7+=ido;
  113918. }
  113919. }
  113920. if(ido==1)return;
  113921. if(nbd<l1)goto L141;
  113922. t1=-ido;
  113923. t3=0;
  113924. t4=0;
  113925. t5=ipp2*t0;
  113926. for(j=1;j<ipph;j++){
  113927. t1+=t2;
  113928. t3+=t2;
  113929. t4+=t0;
  113930. t5-=t0;
  113931. t6=t1;
  113932. t7=t3;
  113933. t8=t4;
  113934. t9=t5;
  113935. for(k=0;k<l1;k++){
  113936. for(i=2;i<ido;i+=2){
  113937. ic=idp2-i;
  113938. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  113939. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  113940. cc[i+t7]=ch[i+t8]+ch[i+t9];
  113941. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  113942. }
  113943. t6+=t10;
  113944. t7+=t10;
  113945. t8+=ido;
  113946. t9+=ido;
  113947. }
  113948. }
  113949. return;
  113950. L141:
  113951. t1=-ido;
  113952. t3=0;
  113953. t4=0;
  113954. t5=ipp2*t0;
  113955. for(j=1;j<ipph;j++){
  113956. t1+=t2;
  113957. t3+=t2;
  113958. t4+=t0;
  113959. t5-=t0;
  113960. for(i=2;i<ido;i+=2){
  113961. t6=idp2+t1-i;
  113962. t7=i+t3;
  113963. t8=i+t4;
  113964. t9=i+t5;
  113965. for(k=0;k<l1;k++){
  113966. cc[t7-1]=ch[t8-1]+ch[t9-1];
  113967. cc[t6-1]=ch[t8-1]-ch[t9-1];
  113968. cc[t7]=ch[t8]+ch[t9];
  113969. cc[t6]=ch[t9]-ch[t8];
  113970. t6+=t10;
  113971. t7+=t10;
  113972. t8+=ido;
  113973. t9+=ido;
  113974. }
  113975. }
  113976. }
  113977. }
  113978. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  113979. int i,k1,l1,l2;
  113980. int na,kh,nf;
  113981. int ip,iw,ido,idl1,ix2,ix3;
  113982. nf=ifac[1];
  113983. na=1;
  113984. l2=n;
  113985. iw=n;
  113986. for(k1=0;k1<nf;k1++){
  113987. kh=nf-k1;
  113988. ip=ifac[kh+1];
  113989. l1=l2/ip;
  113990. ido=n/l2;
  113991. idl1=ido*l1;
  113992. iw-=(ip-1)*ido;
  113993. na=1-na;
  113994. if(ip!=4)goto L102;
  113995. ix2=iw+ido;
  113996. ix3=ix2+ido;
  113997. if(na!=0)
  113998. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  113999. else
  114000. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  114001. goto L110;
  114002. L102:
  114003. if(ip!=2)goto L104;
  114004. if(na!=0)goto L103;
  114005. dradf2(ido,l1,c,ch,wa+iw-1);
  114006. goto L110;
  114007. L103:
  114008. dradf2(ido,l1,ch,c,wa+iw-1);
  114009. goto L110;
  114010. L104:
  114011. if(ido==1)na=1-na;
  114012. if(na!=0)goto L109;
  114013. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  114014. na=1;
  114015. goto L110;
  114016. L109:
  114017. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  114018. na=0;
  114019. L110:
  114020. l2=l1;
  114021. }
  114022. if(na==1)return;
  114023. for(i=0;i<n;i++)c[i]=ch[i];
  114024. }
  114025. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  114026. int i,k,t0,t1,t2,t3,t4,t5,t6;
  114027. float ti2,tr2;
  114028. t0=l1*ido;
  114029. t1=0;
  114030. t2=0;
  114031. t3=(ido<<1)-1;
  114032. for(k=0;k<l1;k++){
  114033. ch[t1]=cc[t2]+cc[t3+t2];
  114034. ch[t1+t0]=cc[t2]-cc[t3+t2];
  114035. t2=(t1+=ido)<<1;
  114036. }
  114037. if(ido<2)return;
  114038. if(ido==2)goto L105;
  114039. t1=0;
  114040. t2=0;
  114041. for(k=0;k<l1;k++){
  114042. t3=t1;
  114043. t5=(t4=t2)+(ido<<1);
  114044. t6=t0+t1;
  114045. for(i=2;i<ido;i+=2){
  114046. t3+=2;
  114047. t4+=2;
  114048. t5-=2;
  114049. t6+=2;
  114050. ch[t3-1]=cc[t4-1]+cc[t5-1];
  114051. tr2=cc[t4-1]-cc[t5-1];
  114052. ch[t3]=cc[t4]-cc[t5];
  114053. ti2=cc[t4]+cc[t5];
  114054. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  114055. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  114056. }
  114057. t2=(t1+=ido)<<1;
  114058. }
  114059. if(ido%2==1)return;
  114060. L105:
  114061. t1=ido-1;
  114062. t2=ido-1;
  114063. for(k=0;k<l1;k++){
  114064. ch[t1]=cc[t2]+cc[t2];
  114065. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  114066. t1+=ido;
  114067. t2+=ido<<1;
  114068. }
  114069. }
  114070. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  114071. float *wa2){
  114072. static float taur = -.5f;
  114073. static float taui = .8660254037844386f;
  114074. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  114075. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  114076. t0=l1*ido;
  114077. t1=0;
  114078. t2=t0<<1;
  114079. t3=ido<<1;
  114080. t4=ido+(ido<<1);
  114081. t5=0;
  114082. for(k=0;k<l1;k++){
  114083. tr2=cc[t3-1]+cc[t3-1];
  114084. cr2=cc[t5]+(taur*tr2);
  114085. ch[t1]=cc[t5]+tr2;
  114086. ci3=taui*(cc[t3]+cc[t3]);
  114087. ch[t1+t0]=cr2-ci3;
  114088. ch[t1+t2]=cr2+ci3;
  114089. t1+=ido;
  114090. t3+=t4;
  114091. t5+=t4;
  114092. }
  114093. if(ido==1)return;
  114094. t1=0;
  114095. t3=ido<<1;
  114096. for(k=0;k<l1;k++){
  114097. t7=t1+(t1<<1);
  114098. t6=(t5=t7+t3);
  114099. t8=t1;
  114100. t10=(t9=t1+t0)+t0;
  114101. for(i=2;i<ido;i+=2){
  114102. t5+=2;
  114103. t6-=2;
  114104. t7+=2;
  114105. t8+=2;
  114106. t9+=2;
  114107. t10+=2;
  114108. tr2=cc[t5-1]+cc[t6-1];
  114109. cr2=cc[t7-1]+(taur*tr2);
  114110. ch[t8-1]=cc[t7-1]+tr2;
  114111. ti2=cc[t5]-cc[t6];
  114112. ci2=cc[t7]+(taur*ti2);
  114113. ch[t8]=cc[t7]+ti2;
  114114. cr3=taui*(cc[t5-1]-cc[t6-1]);
  114115. ci3=taui*(cc[t5]+cc[t6]);
  114116. dr2=cr2-ci3;
  114117. dr3=cr2+ci3;
  114118. di2=ci2+cr3;
  114119. di3=ci2-cr3;
  114120. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  114121. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  114122. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  114123. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  114124. }
  114125. t1+=ido;
  114126. }
  114127. }
  114128. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  114129. float *wa2,float *wa3){
  114130. static float sqrt2=1.414213562373095f;
  114131. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  114132. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  114133. t0=l1*ido;
  114134. t1=0;
  114135. t2=ido<<2;
  114136. t3=0;
  114137. t6=ido<<1;
  114138. for(k=0;k<l1;k++){
  114139. t4=t3+t6;
  114140. t5=t1;
  114141. tr3=cc[t4-1]+cc[t4-1];
  114142. tr4=cc[t4]+cc[t4];
  114143. tr1=cc[t3]-cc[(t4+=t6)-1];
  114144. tr2=cc[t3]+cc[t4-1];
  114145. ch[t5]=tr2+tr3;
  114146. ch[t5+=t0]=tr1-tr4;
  114147. ch[t5+=t0]=tr2-tr3;
  114148. ch[t5+=t0]=tr1+tr4;
  114149. t1+=ido;
  114150. t3+=t2;
  114151. }
  114152. if(ido<2)return;
  114153. if(ido==2)goto L105;
  114154. t1=0;
  114155. for(k=0;k<l1;k++){
  114156. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  114157. t7=t1;
  114158. for(i=2;i<ido;i+=2){
  114159. t2+=2;
  114160. t3+=2;
  114161. t4-=2;
  114162. t5-=2;
  114163. t7+=2;
  114164. ti1=cc[t2]+cc[t5];
  114165. ti2=cc[t2]-cc[t5];
  114166. ti3=cc[t3]-cc[t4];
  114167. tr4=cc[t3]+cc[t4];
  114168. tr1=cc[t2-1]-cc[t5-1];
  114169. tr2=cc[t2-1]+cc[t5-1];
  114170. ti4=cc[t3-1]-cc[t4-1];
  114171. tr3=cc[t3-1]+cc[t4-1];
  114172. ch[t7-1]=tr2+tr3;
  114173. cr3=tr2-tr3;
  114174. ch[t7]=ti2+ti3;
  114175. ci3=ti2-ti3;
  114176. cr2=tr1-tr4;
  114177. cr4=tr1+tr4;
  114178. ci2=ti1+ti4;
  114179. ci4=ti1-ti4;
  114180. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  114181. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  114182. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  114183. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  114184. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  114185. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  114186. }
  114187. t1+=ido;
  114188. }
  114189. if(ido%2 == 1)return;
  114190. L105:
  114191. t1=ido;
  114192. t2=ido<<2;
  114193. t3=ido-1;
  114194. t4=ido+(ido<<1);
  114195. for(k=0;k<l1;k++){
  114196. t5=t3;
  114197. ti1=cc[t1]+cc[t4];
  114198. ti2=cc[t4]-cc[t1];
  114199. tr1=cc[t1-1]-cc[t4-1];
  114200. tr2=cc[t1-1]+cc[t4-1];
  114201. ch[t5]=tr2+tr2;
  114202. ch[t5+=t0]=sqrt2*(tr1-ti1);
  114203. ch[t5+=t0]=ti2+ti2;
  114204. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  114205. t3+=ido;
  114206. t1+=t2;
  114207. t4+=t2;
  114208. }
  114209. }
  114210. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  114211. float *c2,float *ch,float *ch2,float *wa){
  114212. static float tpi=6.283185307179586f;
  114213. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  114214. t11,t12;
  114215. float dc2,ai1,ai2,ar1,ar2,ds2;
  114216. int nbd;
  114217. float dcp,arg,dsp,ar1h,ar2h;
  114218. int ipp2;
  114219. t10=ip*ido;
  114220. t0=l1*ido;
  114221. arg=tpi/(float)ip;
  114222. dcp=cos(arg);
  114223. dsp=sin(arg);
  114224. nbd=(ido-1)>>1;
  114225. ipp2=ip;
  114226. ipph=(ip+1)>>1;
  114227. if(ido<l1)goto L103;
  114228. t1=0;
  114229. t2=0;
  114230. for(k=0;k<l1;k++){
  114231. t3=t1;
  114232. t4=t2;
  114233. for(i=0;i<ido;i++){
  114234. ch[t3]=cc[t4];
  114235. t3++;
  114236. t4++;
  114237. }
  114238. t1+=ido;
  114239. t2+=t10;
  114240. }
  114241. goto L106;
  114242. L103:
  114243. t1=0;
  114244. for(i=0;i<ido;i++){
  114245. t2=t1;
  114246. t3=t1;
  114247. for(k=0;k<l1;k++){
  114248. ch[t2]=cc[t3];
  114249. t2+=ido;
  114250. t3+=t10;
  114251. }
  114252. t1++;
  114253. }
  114254. L106:
  114255. t1=0;
  114256. t2=ipp2*t0;
  114257. t7=(t5=ido<<1);
  114258. for(j=1;j<ipph;j++){
  114259. t1+=t0;
  114260. t2-=t0;
  114261. t3=t1;
  114262. t4=t2;
  114263. t6=t5;
  114264. for(k=0;k<l1;k++){
  114265. ch[t3]=cc[t6-1]+cc[t6-1];
  114266. ch[t4]=cc[t6]+cc[t6];
  114267. t3+=ido;
  114268. t4+=ido;
  114269. t6+=t10;
  114270. }
  114271. t5+=t7;
  114272. }
  114273. if (ido == 1)goto L116;
  114274. if(nbd<l1)goto L112;
  114275. t1=0;
  114276. t2=ipp2*t0;
  114277. t7=0;
  114278. for(j=1;j<ipph;j++){
  114279. t1+=t0;
  114280. t2-=t0;
  114281. t3=t1;
  114282. t4=t2;
  114283. t7+=(ido<<1);
  114284. t8=t7;
  114285. for(k=0;k<l1;k++){
  114286. t5=t3;
  114287. t6=t4;
  114288. t9=t8;
  114289. t11=t8;
  114290. for(i=2;i<ido;i+=2){
  114291. t5+=2;
  114292. t6+=2;
  114293. t9+=2;
  114294. t11-=2;
  114295. ch[t5-1]=cc[t9-1]+cc[t11-1];
  114296. ch[t6-1]=cc[t9-1]-cc[t11-1];
  114297. ch[t5]=cc[t9]-cc[t11];
  114298. ch[t6]=cc[t9]+cc[t11];
  114299. }
  114300. t3+=ido;
  114301. t4+=ido;
  114302. t8+=t10;
  114303. }
  114304. }
  114305. goto L116;
  114306. L112:
  114307. t1=0;
  114308. t2=ipp2*t0;
  114309. t7=0;
  114310. for(j=1;j<ipph;j++){
  114311. t1+=t0;
  114312. t2-=t0;
  114313. t3=t1;
  114314. t4=t2;
  114315. t7+=(ido<<1);
  114316. t8=t7;
  114317. t9=t7;
  114318. for(i=2;i<ido;i+=2){
  114319. t3+=2;
  114320. t4+=2;
  114321. t8+=2;
  114322. t9-=2;
  114323. t5=t3;
  114324. t6=t4;
  114325. t11=t8;
  114326. t12=t9;
  114327. for(k=0;k<l1;k++){
  114328. ch[t5-1]=cc[t11-1]+cc[t12-1];
  114329. ch[t6-1]=cc[t11-1]-cc[t12-1];
  114330. ch[t5]=cc[t11]-cc[t12];
  114331. ch[t6]=cc[t11]+cc[t12];
  114332. t5+=ido;
  114333. t6+=ido;
  114334. t11+=t10;
  114335. t12+=t10;
  114336. }
  114337. }
  114338. }
  114339. L116:
  114340. ar1=1.f;
  114341. ai1=0.f;
  114342. t1=0;
  114343. t9=(t2=ipp2*idl1);
  114344. t3=(ip-1)*idl1;
  114345. for(l=1;l<ipph;l++){
  114346. t1+=idl1;
  114347. t2-=idl1;
  114348. ar1h=dcp*ar1-dsp*ai1;
  114349. ai1=dcp*ai1+dsp*ar1;
  114350. ar1=ar1h;
  114351. t4=t1;
  114352. t5=t2;
  114353. t6=0;
  114354. t7=idl1;
  114355. t8=t3;
  114356. for(ik=0;ik<idl1;ik++){
  114357. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  114358. c2[t5++]=ai1*ch2[t8++];
  114359. }
  114360. dc2=ar1;
  114361. ds2=ai1;
  114362. ar2=ar1;
  114363. ai2=ai1;
  114364. t6=idl1;
  114365. t7=t9-idl1;
  114366. for(j=2;j<ipph;j++){
  114367. t6+=idl1;
  114368. t7-=idl1;
  114369. ar2h=dc2*ar2-ds2*ai2;
  114370. ai2=dc2*ai2+ds2*ar2;
  114371. ar2=ar2h;
  114372. t4=t1;
  114373. t5=t2;
  114374. t11=t6;
  114375. t12=t7;
  114376. for(ik=0;ik<idl1;ik++){
  114377. c2[t4++]+=ar2*ch2[t11++];
  114378. c2[t5++]+=ai2*ch2[t12++];
  114379. }
  114380. }
  114381. }
  114382. t1=0;
  114383. for(j=1;j<ipph;j++){
  114384. t1+=idl1;
  114385. t2=t1;
  114386. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  114387. }
  114388. t1=0;
  114389. t2=ipp2*t0;
  114390. for(j=1;j<ipph;j++){
  114391. t1+=t0;
  114392. t2-=t0;
  114393. t3=t1;
  114394. t4=t2;
  114395. for(k=0;k<l1;k++){
  114396. ch[t3]=c1[t3]-c1[t4];
  114397. ch[t4]=c1[t3]+c1[t4];
  114398. t3+=ido;
  114399. t4+=ido;
  114400. }
  114401. }
  114402. if(ido==1)goto L132;
  114403. if(nbd<l1)goto L128;
  114404. t1=0;
  114405. t2=ipp2*t0;
  114406. for(j=1;j<ipph;j++){
  114407. t1+=t0;
  114408. t2-=t0;
  114409. t3=t1;
  114410. t4=t2;
  114411. for(k=0;k<l1;k++){
  114412. t5=t3;
  114413. t6=t4;
  114414. for(i=2;i<ido;i+=2){
  114415. t5+=2;
  114416. t6+=2;
  114417. ch[t5-1]=c1[t5-1]-c1[t6];
  114418. ch[t6-1]=c1[t5-1]+c1[t6];
  114419. ch[t5]=c1[t5]+c1[t6-1];
  114420. ch[t6]=c1[t5]-c1[t6-1];
  114421. }
  114422. t3+=ido;
  114423. t4+=ido;
  114424. }
  114425. }
  114426. goto L132;
  114427. L128:
  114428. t1=0;
  114429. t2=ipp2*t0;
  114430. for(j=1;j<ipph;j++){
  114431. t1+=t0;
  114432. t2-=t0;
  114433. t3=t1;
  114434. t4=t2;
  114435. for(i=2;i<ido;i+=2){
  114436. t3+=2;
  114437. t4+=2;
  114438. t5=t3;
  114439. t6=t4;
  114440. for(k=0;k<l1;k++){
  114441. ch[t5-1]=c1[t5-1]-c1[t6];
  114442. ch[t6-1]=c1[t5-1]+c1[t6];
  114443. ch[t5]=c1[t5]+c1[t6-1];
  114444. ch[t6]=c1[t5]-c1[t6-1];
  114445. t5+=ido;
  114446. t6+=ido;
  114447. }
  114448. }
  114449. }
  114450. L132:
  114451. if(ido==1)return;
  114452. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  114453. t1=0;
  114454. for(j=1;j<ip;j++){
  114455. t2=(t1+=t0);
  114456. for(k=0;k<l1;k++){
  114457. c1[t2]=ch[t2];
  114458. t2+=ido;
  114459. }
  114460. }
  114461. if(nbd>l1)goto L139;
  114462. is= -ido-1;
  114463. t1=0;
  114464. for(j=1;j<ip;j++){
  114465. is+=ido;
  114466. t1+=t0;
  114467. idij=is;
  114468. t2=t1;
  114469. for(i=2;i<ido;i+=2){
  114470. t2+=2;
  114471. idij+=2;
  114472. t3=t2;
  114473. for(k=0;k<l1;k++){
  114474. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  114475. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  114476. t3+=ido;
  114477. }
  114478. }
  114479. }
  114480. return;
  114481. L139:
  114482. is= -ido-1;
  114483. t1=0;
  114484. for(j=1;j<ip;j++){
  114485. is+=ido;
  114486. t1+=t0;
  114487. t2=t1;
  114488. for(k=0;k<l1;k++){
  114489. idij=is;
  114490. t3=t2;
  114491. for(i=2;i<ido;i+=2){
  114492. idij+=2;
  114493. t3+=2;
  114494. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  114495. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  114496. }
  114497. t2+=ido;
  114498. }
  114499. }
  114500. }
  114501. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  114502. int i,k1,l1,l2;
  114503. int na;
  114504. int nf,ip,iw,ix2,ix3,ido,idl1;
  114505. nf=ifac[1];
  114506. na=0;
  114507. l1=1;
  114508. iw=1;
  114509. for(k1=0;k1<nf;k1++){
  114510. ip=ifac[k1 + 2];
  114511. l2=ip*l1;
  114512. ido=n/l2;
  114513. idl1=ido*l1;
  114514. if(ip!=4)goto L103;
  114515. ix2=iw+ido;
  114516. ix3=ix2+ido;
  114517. if(na!=0)
  114518. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  114519. else
  114520. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  114521. na=1-na;
  114522. goto L115;
  114523. L103:
  114524. if(ip!=2)goto L106;
  114525. if(na!=0)
  114526. dradb2(ido,l1,ch,c,wa+iw-1);
  114527. else
  114528. dradb2(ido,l1,c,ch,wa+iw-1);
  114529. na=1-na;
  114530. goto L115;
  114531. L106:
  114532. if(ip!=3)goto L109;
  114533. ix2=iw+ido;
  114534. if(na!=0)
  114535. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  114536. else
  114537. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  114538. na=1-na;
  114539. goto L115;
  114540. L109:
  114541. /* The radix five case can be translated later..... */
  114542. /* if(ip!=5)goto L112;
  114543. ix2=iw+ido;
  114544. ix3=ix2+ido;
  114545. ix4=ix3+ido;
  114546. if(na!=0)
  114547. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  114548. else
  114549. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  114550. na=1-na;
  114551. goto L115;
  114552. L112:*/
  114553. if(na!=0)
  114554. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  114555. else
  114556. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  114557. if(ido==1)na=1-na;
  114558. L115:
  114559. l1=l2;
  114560. iw+=(ip-1)*ido;
  114561. }
  114562. if(na==0)return;
  114563. for(i=0;i<n;i++)c[i]=ch[i];
  114564. }
  114565. void drft_forward(drft_lookup *l,float *data){
  114566. if(l->n==1)return;
  114567. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  114568. }
  114569. void drft_backward(drft_lookup *l,float *data){
  114570. if (l->n==1)return;
  114571. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  114572. }
  114573. void drft_init(drft_lookup *l,int n){
  114574. l->n=n;
  114575. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  114576. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  114577. fdrffti(n, l->trigcache, l->splitcache);
  114578. }
  114579. void drft_clear(drft_lookup *l){
  114580. if(l){
  114581. if(l->trigcache)_ogg_free(l->trigcache);
  114582. if(l->splitcache)_ogg_free(l->splitcache);
  114583. memset(l,0,sizeof(*l));
  114584. }
  114585. }
  114586. #endif
  114587. /********* End of inlined file: smallft.c *********/
  114588. /********* Start of inlined file: synthesis.c *********/
  114589. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  114590. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114591. // tasks..
  114592. #ifdef _MSC_VER
  114593. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114594. #endif
  114595. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  114596. #if JUCE_USE_OGGVORBIS
  114597. #include <stdio.h>
  114598. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  114599. vorbis_dsp_state *vd=vb->vd;
  114600. private_state *b=(private_state*)vd->backend_state;
  114601. vorbis_info *vi=vd->vi;
  114602. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  114603. oggpack_buffer *opb=&vb->opb;
  114604. int type,mode,i;
  114605. /* first things first. Make sure decode is ready */
  114606. _vorbis_block_ripcord(vb);
  114607. oggpack_readinit(opb,op->packet,op->bytes);
  114608. /* Check the packet type */
  114609. if(oggpack_read(opb,1)!=0){
  114610. /* Oops. This is not an audio data packet */
  114611. return(OV_ENOTAUDIO);
  114612. }
  114613. /* read our mode and pre/post windowsize */
  114614. mode=oggpack_read(opb,b->modebits);
  114615. if(mode==-1)return(OV_EBADPACKET);
  114616. vb->mode=mode;
  114617. vb->W=ci->mode_param[mode]->blockflag;
  114618. if(vb->W){
  114619. /* this doesn;t get mapped through mode selection as it's used
  114620. only for window selection */
  114621. vb->lW=oggpack_read(opb,1);
  114622. vb->nW=oggpack_read(opb,1);
  114623. if(vb->nW==-1) return(OV_EBADPACKET);
  114624. }else{
  114625. vb->lW=0;
  114626. vb->nW=0;
  114627. }
  114628. /* more setup */
  114629. vb->granulepos=op->granulepos;
  114630. vb->sequence=op->packetno;
  114631. vb->eofflag=op->e_o_s;
  114632. /* alloc pcm passback storage */
  114633. vb->pcmend=ci->blocksizes[vb->W];
  114634. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  114635. for(i=0;i<vi->channels;i++)
  114636. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  114637. /* unpack_header enforces range checking */
  114638. type=ci->map_type[ci->mode_param[mode]->mapping];
  114639. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  114640. mapping]));
  114641. }
  114642. /* used to track pcm position without actually performing decode.
  114643. Useful for sequential 'fast forward' */
  114644. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  114645. vorbis_dsp_state *vd=vb->vd;
  114646. private_state *b=(private_state*)vd->backend_state;
  114647. vorbis_info *vi=vd->vi;
  114648. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114649. oggpack_buffer *opb=&vb->opb;
  114650. int mode;
  114651. /* first things first. Make sure decode is ready */
  114652. _vorbis_block_ripcord(vb);
  114653. oggpack_readinit(opb,op->packet,op->bytes);
  114654. /* Check the packet type */
  114655. if(oggpack_read(opb,1)!=0){
  114656. /* Oops. This is not an audio data packet */
  114657. return(OV_ENOTAUDIO);
  114658. }
  114659. /* read our mode and pre/post windowsize */
  114660. mode=oggpack_read(opb,b->modebits);
  114661. if(mode==-1)return(OV_EBADPACKET);
  114662. vb->mode=mode;
  114663. vb->W=ci->mode_param[mode]->blockflag;
  114664. if(vb->W){
  114665. vb->lW=oggpack_read(opb,1);
  114666. vb->nW=oggpack_read(opb,1);
  114667. if(vb->nW==-1) return(OV_EBADPACKET);
  114668. }else{
  114669. vb->lW=0;
  114670. vb->nW=0;
  114671. }
  114672. /* more setup */
  114673. vb->granulepos=op->granulepos;
  114674. vb->sequence=op->packetno;
  114675. vb->eofflag=op->e_o_s;
  114676. /* no pcm */
  114677. vb->pcmend=0;
  114678. vb->pcm=NULL;
  114679. return(0);
  114680. }
  114681. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  114682. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114683. oggpack_buffer opb;
  114684. int mode;
  114685. oggpack_readinit(&opb,op->packet,op->bytes);
  114686. /* Check the packet type */
  114687. if(oggpack_read(&opb,1)!=0){
  114688. /* Oops. This is not an audio data packet */
  114689. return(OV_ENOTAUDIO);
  114690. }
  114691. {
  114692. int modebits=0;
  114693. int v=ci->modes;
  114694. while(v>1){
  114695. modebits++;
  114696. v>>=1;
  114697. }
  114698. /* read our mode and pre/post windowsize */
  114699. mode=oggpack_read(&opb,modebits);
  114700. }
  114701. if(mode==-1)return(OV_EBADPACKET);
  114702. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  114703. }
  114704. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  114705. /* set / clear half-sample-rate mode */
  114706. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114707. /* right now, our MDCT can't handle < 64 sample windows. */
  114708. if(ci->blocksizes[0]<=64 && flag)return -1;
  114709. ci->halfrate_flag=(flag?1:0);
  114710. return 0;
  114711. }
  114712. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  114713. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114714. return ci->halfrate_flag;
  114715. }
  114716. #endif
  114717. /********* End of inlined file: synthesis.c *********/
  114718. /********* Start of inlined file: vorbisenc.c *********/
  114719. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  114720. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114721. // tasks..
  114722. #ifdef _MSC_VER
  114723. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114724. #endif
  114725. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  114726. #if JUCE_USE_OGGVORBIS
  114727. #include <stdlib.h>
  114728. #include <string.h>
  114729. #include <math.h>
  114730. /* careful with this; it's using static array sizing to make managing
  114731. all the modes a little less annoying. If we use a residue backend
  114732. with > 12 partition types, or a different division of iteration,
  114733. this needs to be updated. */
  114734. typedef struct {
  114735. static_codebook *books[12][3];
  114736. } static_bookblock;
  114737. typedef struct {
  114738. int res_type;
  114739. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  114740. vorbis_info_residue0 *res;
  114741. static_codebook *book_aux;
  114742. static_codebook *book_aux_managed;
  114743. static_bookblock *books_base;
  114744. static_bookblock *books_base_managed;
  114745. } vorbis_residue_template;
  114746. typedef struct {
  114747. vorbis_info_mapping0 *map;
  114748. vorbis_residue_template *res;
  114749. } vorbis_mapping_template;
  114750. typedef struct vp_adjblock{
  114751. int block[P_BANDS];
  114752. } vp_adjblock;
  114753. typedef struct {
  114754. int data[NOISE_COMPAND_LEVELS];
  114755. } compandblock;
  114756. /* high level configuration information for setting things up
  114757. step-by-step with the detailed vorbis_encode_ctl interface.
  114758. There's a fair amount of redundancy such that interactive setup
  114759. does not directly deal with any vorbis_info or codec_setup_info
  114760. initialization; it's all stored (until full init) in this highlevel
  114761. setup, then flushed out to the real codec setup structs later. */
  114762. typedef struct {
  114763. int att[P_NOISECURVES];
  114764. float boost;
  114765. float decay;
  114766. } att3;
  114767. typedef struct { int data[P_NOISECURVES]; } adj3;
  114768. typedef struct {
  114769. int pre[PACKETBLOBS];
  114770. int post[PACKETBLOBS];
  114771. float kHz[PACKETBLOBS];
  114772. float lowpasskHz[PACKETBLOBS];
  114773. } adj_stereo;
  114774. typedef struct {
  114775. int lo;
  114776. int hi;
  114777. int fixed;
  114778. } noiseguard;
  114779. typedef struct {
  114780. int data[P_NOISECURVES][17];
  114781. } noise3;
  114782. typedef struct {
  114783. int mappings;
  114784. double *rate_mapping;
  114785. double *quality_mapping;
  114786. int coupling_restriction;
  114787. long samplerate_min_restriction;
  114788. long samplerate_max_restriction;
  114789. int *blocksize_short;
  114790. int *blocksize_long;
  114791. att3 *psy_tone_masteratt;
  114792. int *psy_tone_0dB;
  114793. int *psy_tone_dBsuppress;
  114794. vp_adjblock *psy_tone_adj_impulse;
  114795. vp_adjblock *psy_tone_adj_long;
  114796. vp_adjblock *psy_tone_adj_other;
  114797. noiseguard *psy_noiseguards;
  114798. noise3 *psy_noise_bias_impulse;
  114799. noise3 *psy_noise_bias_padding;
  114800. noise3 *psy_noise_bias_trans;
  114801. noise3 *psy_noise_bias_long;
  114802. int *psy_noise_dBsuppress;
  114803. compandblock *psy_noise_compand;
  114804. double *psy_noise_compand_short_mapping;
  114805. double *psy_noise_compand_long_mapping;
  114806. int *psy_noise_normal_start[2];
  114807. int *psy_noise_normal_partition[2];
  114808. double *psy_noise_normal_thresh;
  114809. int *psy_ath_float;
  114810. int *psy_ath_abs;
  114811. double *psy_lowpass;
  114812. vorbis_info_psy_global *global_params;
  114813. double *global_mapping;
  114814. adj_stereo *stereo_modes;
  114815. static_codebook ***floor_books;
  114816. vorbis_info_floor1 *floor_params;
  114817. int *floor_short_mapping;
  114818. int *floor_long_mapping;
  114819. vorbis_mapping_template *maps;
  114820. } ve_setup_data_template;
  114821. /* a few static coder conventions */
  114822. static vorbis_info_mode _mode_template[2]={
  114823. {0,0,0,0},
  114824. {1,0,0,1}
  114825. };
  114826. static vorbis_info_mapping0 _map_nominal[2]={
  114827. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  114828. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  114829. };
  114830. /********* Start of inlined file: setup_44.h *********/
  114831. /********* Start of inlined file: floor_all.h *********/
  114832. /********* Start of inlined file: floor_books.h *********/
  114833. static long _huff_lengthlist_line_256x7_0sub1[] = {
  114834. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  114835. };
  114836. static static_codebook _huff_book_line_256x7_0sub1 = {
  114837. 1, 9,
  114838. _huff_lengthlist_line_256x7_0sub1,
  114839. 0, 0, 0, 0, 0,
  114840. NULL,
  114841. NULL,
  114842. NULL,
  114843. NULL,
  114844. 0
  114845. };
  114846. static long _huff_lengthlist_line_256x7_0sub2[] = {
  114847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  114848. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  114849. };
  114850. static static_codebook _huff_book_line_256x7_0sub2 = {
  114851. 1, 25,
  114852. _huff_lengthlist_line_256x7_0sub2,
  114853. 0, 0, 0, 0, 0,
  114854. NULL,
  114855. NULL,
  114856. NULL,
  114857. NULL,
  114858. 0
  114859. };
  114860. static long _huff_lengthlist_line_256x7_0sub3[] = {
  114861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  114863. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  114864. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  114865. };
  114866. static static_codebook _huff_book_line_256x7_0sub3 = {
  114867. 1, 64,
  114868. _huff_lengthlist_line_256x7_0sub3,
  114869. 0, 0, 0, 0, 0,
  114870. NULL,
  114871. NULL,
  114872. NULL,
  114873. NULL,
  114874. 0
  114875. };
  114876. static long _huff_lengthlist_line_256x7_1sub1[] = {
  114877. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  114878. };
  114879. static static_codebook _huff_book_line_256x7_1sub1 = {
  114880. 1, 9,
  114881. _huff_lengthlist_line_256x7_1sub1,
  114882. 0, 0, 0, 0, 0,
  114883. NULL,
  114884. NULL,
  114885. NULL,
  114886. NULL,
  114887. 0
  114888. };
  114889. static long _huff_lengthlist_line_256x7_1sub2[] = {
  114890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  114891. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  114892. };
  114893. static static_codebook _huff_book_line_256x7_1sub2 = {
  114894. 1, 25,
  114895. _huff_lengthlist_line_256x7_1sub2,
  114896. 0, 0, 0, 0, 0,
  114897. NULL,
  114898. NULL,
  114899. NULL,
  114900. NULL,
  114901. 0
  114902. };
  114903. static long _huff_lengthlist_line_256x7_1sub3[] = {
  114904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  114906. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  114907. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  114908. };
  114909. static static_codebook _huff_book_line_256x7_1sub3 = {
  114910. 1, 64,
  114911. _huff_lengthlist_line_256x7_1sub3,
  114912. 0, 0, 0, 0, 0,
  114913. NULL,
  114914. NULL,
  114915. NULL,
  114916. NULL,
  114917. 0
  114918. };
  114919. static long _huff_lengthlist_line_256x7_class0[] = {
  114920. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  114921. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  114922. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  114923. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  114924. };
  114925. static static_codebook _huff_book_line_256x7_class0 = {
  114926. 1, 64,
  114927. _huff_lengthlist_line_256x7_class0,
  114928. 0, 0, 0, 0, 0,
  114929. NULL,
  114930. NULL,
  114931. NULL,
  114932. NULL,
  114933. 0
  114934. };
  114935. static long _huff_lengthlist_line_256x7_class1[] = {
  114936. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  114937. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  114938. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  114939. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  114940. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  114941. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  114942. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  114943. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  114944. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  114945. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  114946. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  114947. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  114948. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  114949. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  114950. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  114951. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  114952. };
  114953. static static_codebook _huff_book_line_256x7_class1 = {
  114954. 1, 256,
  114955. _huff_lengthlist_line_256x7_class1,
  114956. 0, 0, 0, 0, 0,
  114957. NULL,
  114958. NULL,
  114959. NULL,
  114960. NULL,
  114961. 0
  114962. };
  114963. static long _huff_lengthlist_line_512x17_0sub0[] = {
  114964. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  114965. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  114966. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  114967. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  114968. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  114969. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  114970. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  114971. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  114972. };
  114973. static static_codebook _huff_book_line_512x17_0sub0 = {
  114974. 1, 128,
  114975. _huff_lengthlist_line_512x17_0sub0,
  114976. 0, 0, 0, 0, 0,
  114977. NULL,
  114978. NULL,
  114979. NULL,
  114980. NULL,
  114981. 0
  114982. };
  114983. static long _huff_lengthlist_line_512x17_1sub0[] = {
  114984. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  114985. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  114986. };
  114987. static static_codebook _huff_book_line_512x17_1sub0 = {
  114988. 1, 32,
  114989. _huff_lengthlist_line_512x17_1sub0,
  114990. 0, 0, 0, 0, 0,
  114991. NULL,
  114992. NULL,
  114993. NULL,
  114994. NULL,
  114995. 0
  114996. };
  114997. static long _huff_lengthlist_line_512x17_1sub1[] = {
  114998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115000. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  115001. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  115002. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  115003. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  115004. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  115005. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  115006. };
  115007. static static_codebook _huff_book_line_512x17_1sub1 = {
  115008. 1, 128,
  115009. _huff_lengthlist_line_512x17_1sub1,
  115010. 0, 0, 0, 0, 0,
  115011. NULL,
  115012. NULL,
  115013. NULL,
  115014. NULL,
  115015. 0
  115016. };
  115017. static long _huff_lengthlist_line_512x17_2sub1[] = {
  115018. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  115019. 5, 3,
  115020. };
  115021. static static_codebook _huff_book_line_512x17_2sub1 = {
  115022. 1, 18,
  115023. _huff_lengthlist_line_512x17_2sub1,
  115024. 0, 0, 0, 0, 0,
  115025. NULL,
  115026. NULL,
  115027. NULL,
  115028. NULL,
  115029. 0
  115030. };
  115031. static long _huff_lengthlist_line_512x17_2sub2[] = {
  115032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115033. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  115034. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  115035. 9, 8,
  115036. };
  115037. static static_codebook _huff_book_line_512x17_2sub2 = {
  115038. 1, 50,
  115039. _huff_lengthlist_line_512x17_2sub2,
  115040. 0, 0, 0, 0, 0,
  115041. NULL,
  115042. NULL,
  115043. NULL,
  115044. NULL,
  115045. 0
  115046. };
  115047. static long _huff_lengthlist_line_512x17_2sub3[] = {
  115048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115051. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  115052. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  115053. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  115054. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  115055. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  115056. };
  115057. static static_codebook _huff_book_line_512x17_2sub3 = {
  115058. 1, 128,
  115059. _huff_lengthlist_line_512x17_2sub3,
  115060. 0, 0, 0, 0, 0,
  115061. NULL,
  115062. NULL,
  115063. NULL,
  115064. NULL,
  115065. 0
  115066. };
  115067. static long _huff_lengthlist_line_512x17_3sub1[] = {
  115068. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  115069. 5, 5,
  115070. };
  115071. static static_codebook _huff_book_line_512x17_3sub1 = {
  115072. 1, 18,
  115073. _huff_lengthlist_line_512x17_3sub1,
  115074. 0, 0, 0, 0, 0,
  115075. NULL,
  115076. NULL,
  115077. NULL,
  115078. NULL,
  115079. 0
  115080. };
  115081. static long _huff_lengthlist_line_512x17_3sub2[] = {
  115082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115083. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  115084. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  115085. 11,14,
  115086. };
  115087. static static_codebook _huff_book_line_512x17_3sub2 = {
  115088. 1, 50,
  115089. _huff_lengthlist_line_512x17_3sub2,
  115090. 0, 0, 0, 0, 0,
  115091. NULL,
  115092. NULL,
  115093. NULL,
  115094. NULL,
  115095. 0
  115096. };
  115097. static long _huff_lengthlist_line_512x17_3sub3[] = {
  115098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115101. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  115102. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115103. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115104. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115105. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115106. };
  115107. static static_codebook _huff_book_line_512x17_3sub3 = {
  115108. 1, 128,
  115109. _huff_lengthlist_line_512x17_3sub3,
  115110. 0, 0, 0, 0, 0,
  115111. NULL,
  115112. NULL,
  115113. NULL,
  115114. NULL,
  115115. 0
  115116. };
  115117. static long _huff_lengthlist_line_512x17_class1[] = {
  115118. 1, 2, 3, 6, 5, 4, 7, 7,
  115119. };
  115120. static static_codebook _huff_book_line_512x17_class1 = {
  115121. 1, 8,
  115122. _huff_lengthlist_line_512x17_class1,
  115123. 0, 0, 0, 0, 0,
  115124. NULL,
  115125. NULL,
  115126. NULL,
  115127. NULL,
  115128. 0
  115129. };
  115130. static long _huff_lengthlist_line_512x17_class2[] = {
  115131. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  115132. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  115133. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  115134. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  115135. };
  115136. static static_codebook _huff_book_line_512x17_class2 = {
  115137. 1, 64,
  115138. _huff_lengthlist_line_512x17_class2,
  115139. 0, 0, 0, 0, 0,
  115140. NULL,
  115141. NULL,
  115142. NULL,
  115143. NULL,
  115144. 0
  115145. };
  115146. static long _huff_lengthlist_line_512x17_class3[] = {
  115147. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  115148. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  115149. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  115150. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  115151. };
  115152. static static_codebook _huff_book_line_512x17_class3 = {
  115153. 1, 64,
  115154. _huff_lengthlist_line_512x17_class3,
  115155. 0, 0, 0, 0, 0,
  115156. NULL,
  115157. NULL,
  115158. NULL,
  115159. NULL,
  115160. 0
  115161. };
  115162. static long _huff_lengthlist_line_128x4_class0[] = {
  115163. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  115164. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  115165. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  115166. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  115167. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  115168. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  115169. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  115170. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  115171. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  115172. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  115173. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  115174. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  115175. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  115176. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  115177. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  115178. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  115179. };
  115180. static static_codebook _huff_book_line_128x4_class0 = {
  115181. 1, 256,
  115182. _huff_lengthlist_line_128x4_class0,
  115183. 0, 0, 0, 0, 0,
  115184. NULL,
  115185. NULL,
  115186. NULL,
  115187. NULL,
  115188. 0
  115189. };
  115190. static long _huff_lengthlist_line_128x4_0sub0[] = {
  115191. 2, 2, 2, 2,
  115192. };
  115193. static static_codebook _huff_book_line_128x4_0sub0 = {
  115194. 1, 4,
  115195. _huff_lengthlist_line_128x4_0sub0,
  115196. 0, 0, 0, 0, 0,
  115197. NULL,
  115198. NULL,
  115199. NULL,
  115200. NULL,
  115201. 0
  115202. };
  115203. static long _huff_lengthlist_line_128x4_0sub1[] = {
  115204. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  115205. };
  115206. static static_codebook _huff_book_line_128x4_0sub1 = {
  115207. 1, 10,
  115208. _huff_lengthlist_line_128x4_0sub1,
  115209. 0, 0, 0, 0, 0,
  115210. NULL,
  115211. NULL,
  115212. NULL,
  115213. NULL,
  115214. 0
  115215. };
  115216. static long _huff_lengthlist_line_128x4_0sub2[] = {
  115217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  115218. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  115219. };
  115220. static static_codebook _huff_book_line_128x4_0sub2 = {
  115221. 1, 25,
  115222. _huff_lengthlist_line_128x4_0sub2,
  115223. 0, 0, 0, 0, 0,
  115224. NULL,
  115225. NULL,
  115226. NULL,
  115227. NULL,
  115228. 0
  115229. };
  115230. static long _huff_lengthlist_line_128x4_0sub3[] = {
  115231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  115233. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  115234. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  115235. };
  115236. static static_codebook _huff_book_line_128x4_0sub3 = {
  115237. 1, 64,
  115238. _huff_lengthlist_line_128x4_0sub3,
  115239. 0, 0, 0, 0, 0,
  115240. NULL,
  115241. NULL,
  115242. NULL,
  115243. NULL,
  115244. 0
  115245. };
  115246. static long _huff_lengthlist_line_256x4_class0[] = {
  115247. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  115248. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  115249. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  115250. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  115251. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  115252. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  115253. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  115254. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  115255. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  115256. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  115257. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  115258. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  115259. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  115260. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  115261. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  115262. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  115263. };
  115264. static static_codebook _huff_book_line_256x4_class0 = {
  115265. 1, 256,
  115266. _huff_lengthlist_line_256x4_class0,
  115267. 0, 0, 0, 0, 0,
  115268. NULL,
  115269. NULL,
  115270. NULL,
  115271. NULL,
  115272. 0
  115273. };
  115274. static long _huff_lengthlist_line_256x4_0sub0[] = {
  115275. 2, 2, 2, 2,
  115276. };
  115277. static static_codebook _huff_book_line_256x4_0sub0 = {
  115278. 1, 4,
  115279. _huff_lengthlist_line_256x4_0sub0,
  115280. 0, 0, 0, 0, 0,
  115281. NULL,
  115282. NULL,
  115283. NULL,
  115284. NULL,
  115285. 0
  115286. };
  115287. static long _huff_lengthlist_line_256x4_0sub1[] = {
  115288. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  115289. };
  115290. static static_codebook _huff_book_line_256x4_0sub1 = {
  115291. 1, 10,
  115292. _huff_lengthlist_line_256x4_0sub1,
  115293. 0, 0, 0, 0, 0,
  115294. NULL,
  115295. NULL,
  115296. NULL,
  115297. NULL,
  115298. 0
  115299. };
  115300. static long _huff_lengthlist_line_256x4_0sub2[] = {
  115301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  115302. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  115303. };
  115304. static static_codebook _huff_book_line_256x4_0sub2 = {
  115305. 1, 25,
  115306. _huff_lengthlist_line_256x4_0sub2,
  115307. 0, 0, 0, 0, 0,
  115308. NULL,
  115309. NULL,
  115310. NULL,
  115311. NULL,
  115312. 0
  115313. };
  115314. static long _huff_lengthlist_line_256x4_0sub3[] = {
  115315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  115317. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  115318. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  115319. };
  115320. static static_codebook _huff_book_line_256x4_0sub3 = {
  115321. 1, 64,
  115322. _huff_lengthlist_line_256x4_0sub3,
  115323. 0, 0, 0, 0, 0,
  115324. NULL,
  115325. NULL,
  115326. NULL,
  115327. NULL,
  115328. 0
  115329. };
  115330. static long _huff_lengthlist_line_128x7_class0[] = {
  115331. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  115332. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  115333. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  115334. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  115335. };
  115336. static static_codebook _huff_book_line_128x7_class0 = {
  115337. 1, 64,
  115338. _huff_lengthlist_line_128x7_class0,
  115339. 0, 0, 0, 0, 0,
  115340. NULL,
  115341. NULL,
  115342. NULL,
  115343. NULL,
  115344. 0
  115345. };
  115346. static long _huff_lengthlist_line_128x7_class1[] = {
  115347. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  115348. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  115349. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  115350. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  115351. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  115352. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  115353. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  115354. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  115355. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  115356. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  115357. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  115358. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  115359. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  115360. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  115361. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  115362. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  115363. };
  115364. static static_codebook _huff_book_line_128x7_class1 = {
  115365. 1, 256,
  115366. _huff_lengthlist_line_128x7_class1,
  115367. 0, 0, 0, 0, 0,
  115368. NULL,
  115369. NULL,
  115370. NULL,
  115371. NULL,
  115372. 0
  115373. };
  115374. static long _huff_lengthlist_line_128x7_0sub1[] = {
  115375. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  115376. };
  115377. static static_codebook _huff_book_line_128x7_0sub1 = {
  115378. 1, 9,
  115379. _huff_lengthlist_line_128x7_0sub1,
  115380. 0, 0, 0, 0, 0,
  115381. NULL,
  115382. NULL,
  115383. NULL,
  115384. NULL,
  115385. 0
  115386. };
  115387. static long _huff_lengthlist_line_128x7_0sub2[] = {
  115388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  115389. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  115390. };
  115391. static static_codebook _huff_book_line_128x7_0sub2 = {
  115392. 1, 25,
  115393. _huff_lengthlist_line_128x7_0sub2,
  115394. 0, 0, 0, 0, 0,
  115395. NULL,
  115396. NULL,
  115397. NULL,
  115398. NULL,
  115399. 0
  115400. };
  115401. static long _huff_lengthlist_line_128x7_0sub3[] = {
  115402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  115404. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115405. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  115406. };
  115407. static static_codebook _huff_book_line_128x7_0sub3 = {
  115408. 1, 64,
  115409. _huff_lengthlist_line_128x7_0sub3,
  115410. 0, 0, 0, 0, 0,
  115411. NULL,
  115412. NULL,
  115413. NULL,
  115414. NULL,
  115415. 0
  115416. };
  115417. static long _huff_lengthlist_line_128x7_1sub1[] = {
  115418. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  115419. };
  115420. static static_codebook _huff_book_line_128x7_1sub1 = {
  115421. 1, 9,
  115422. _huff_lengthlist_line_128x7_1sub1,
  115423. 0, 0, 0, 0, 0,
  115424. NULL,
  115425. NULL,
  115426. NULL,
  115427. NULL,
  115428. 0
  115429. };
  115430. static long _huff_lengthlist_line_128x7_1sub2[] = {
  115431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  115432. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  115433. };
  115434. static static_codebook _huff_book_line_128x7_1sub2 = {
  115435. 1, 25,
  115436. _huff_lengthlist_line_128x7_1sub2,
  115437. 0, 0, 0, 0, 0,
  115438. NULL,
  115439. NULL,
  115440. NULL,
  115441. NULL,
  115442. 0
  115443. };
  115444. static long _huff_lengthlist_line_128x7_1sub3[] = {
  115445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  115447. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  115448. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  115449. };
  115450. static static_codebook _huff_book_line_128x7_1sub3 = {
  115451. 1, 64,
  115452. _huff_lengthlist_line_128x7_1sub3,
  115453. 0, 0, 0, 0, 0,
  115454. NULL,
  115455. NULL,
  115456. NULL,
  115457. NULL,
  115458. 0
  115459. };
  115460. static long _huff_lengthlist_line_128x11_class1[] = {
  115461. 1, 6, 3, 7, 2, 4, 5, 7,
  115462. };
  115463. static static_codebook _huff_book_line_128x11_class1 = {
  115464. 1, 8,
  115465. _huff_lengthlist_line_128x11_class1,
  115466. 0, 0, 0, 0, 0,
  115467. NULL,
  115468. NULL,
  115469. NULL,
  115470. NULL,
  115471. 0
  115472. };
  115473. static long _huff_lengthlist_line_128x11_class2[] = {
  115474. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  115475. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  115476. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  115477. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  115478. };
  115479. static static_codebook _huff_book_line_128x11_class2 = {
  115480. 1, 64,
  115481. _huff_lengthlist_line_128x11_class2,
  115482. 0, 0, 0, 0, 0,
  115483. NULL,
  115484. NULL,
  115485. NULL,
  115486. NULL,
  115487. 0
  115488. };
  115489. static long _huff_lengthlist_line_128x11_class3[] = {
  115490. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  115491. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  115492. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  115493. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  115494. };
  115495. static static_codebook _huff_book_line_128x11_class3 = {
  115496. 1, 64,
  115497. _huff_lengthlist_line_128x11_class3,
  115498. 0, 0, 0, 0, 0,
  115499. NULL,
  115500. NULL,
  115501. NULL,
  115502. NULL,
  115503. 0
  115504. };
  115505. static long _huff_lengthlist_line_128x11_0sub0[] = {
  115506. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115507. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  115508. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  115509. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  115510. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  115511. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  115512. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  115513. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  115514. };
  115515. static static_codebook _huff_book_line_128x11_0sub0 = {
  115516. 1, 128,
  115517. _huff_lengthlist_line_128x11_0sub0,
  115518. 0, 0, 0, 0, 0,
  115519. NULL,
  115520. NULL,
  115521. NULL,
  115522. NULL,
  115523. 0
  115524. };
  115525. static long _huff_lengthlist_line_128x11_1sub0[] = {
  115526. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  115527. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  115528. };
  115529. static static_codebook _huff_book_line_128x11_1sub0 = {
  115530. 1, 32,
  115531. _huff_lengthlist_line_128x11_1sub0,
  115532. 0, 0, 0, 0, 0,
  115533. NULL,
  115534. NULL,
  115535. NULL,
  115536. NULL,
  115537. 0
  115538. };
  115539. static long _huff_lengthlist_line_128x11_1sub1[] = {
  115540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115542. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  115543. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  115544. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  115545. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  115546. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  115547. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  115548. };
  115549. static static_codebook _huff_book_line_128x11_1sub1 = {
  115550. 1, 128,
  115551. _huff_lengthlist_line_128x11_1sub1,
  115552. 0, 0, 0, 0, 0,
  115553. NULL,
  115554. NULL,
  115555. NULL,
  115556. NULL,
  115557. 0
  115558. };
  115559. static long _huff_lengthlist_line_128x11_2sub1[] = {
  115560. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  115561. 5, 5,
  115562. };
  115563. static static_codebook _huff_book_line_128x11_2sub1 = {
  115564. 1, 18,
  115565. _huff_lengthlist_line_128x11_2sub1,
  115566. 0, 0, 0, 0, 0,
  115567. NULL,
  115568. NULL,
  115569. NULL,
  115570. NULL,
  115571. 0
  115572. };
  115573. static long _huff_lengthlist_line_128x11_2sub2[] = {
  115574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115575. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  115576. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  115577. 8,11,
  115578. };
  115579. static static_codebook _huff_book_line_128x11_2sub2 = {
  115580. 1, 50,
  115581. _huff_lengthlist_line_128x11_2sub2,
  115582. 0, 0, 0, 0, 0,
  115583. NULL,
  115584. NULL,
  115585. NULL,
  115586. NULL,
  115587. 0
  115588. };
  115589. static long _huff_lengthlist_line_128x11_2sub3[] = {
  115590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115593. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  115594. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115595. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115596. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115597. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115598. };
  115599. static static_codebook _huff_book_line_128x11_2sub3 = {
  115600. 1, 128,
  115601. _huff_lengthlist_line_128x11_2sub3,
  115602. 0, 0, 0, 0, 0,
  115603. NULL,
  115604. NULL,
  115605. NULL,
  115606. NULL,
  115607. 0
  115608. };
  115609. static long _huff_lengthlist_line_128x11_3sub1[] = {
  115610. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  115611. 5, 4,
  115612. };
  115613. static static_codebook _huff_book_line_128x11_3sub1 = {
  115614. 1, 18,
  115615. _huff_lengthlist_line_128x11_3sub1,
  115616. 0, 0, 0, 0, 0,
  115617. NULL,
  115618. NULL,
  115619. NULL,
  115620. NULL,
  115621. 0
  115622. };
  115623. static long _huff_lengthlist_line_128x11_3sub2[] = {
  115624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115625. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  115626. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  115627. 12, 6,
  115628. };
  115629. static static_codebook _huff_book_line_128x11_3sub2 = {
  115630. 1, 50,
  115631. _huff_lengthlist_line_128x11_3sub2,
  115632. 0, 0, 0, 0, 0,
  115633. NULL,
  115634. NULL,
  115635. NULL,
  115636. NULL,
  115637. 0
  115638. };
  115639. static long _huff_lengthlist_line_128x11_3sub3[] = {
  115640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115643. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  115644. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  115645. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  115646. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  115647. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  115648. };
  115649. static static_codebook _huff_book_line_128x11_3sub3 = {
  115650. 1, 128,
  115651. _huff_lengthlist_line_128x11_3sub3,
  115652. 0, 0, 0, 0, 0,
  115653. NULL,
  115654. NULL,
  115655. NULL,
  115656. NULL,
  115657. 0
  115658. };
  115659. static long _huff_lengthlist_line_128x17_class1[] = {
  115660. 1, 3, 4, 7, 2, 5, 6, 7,
  115661. };
  115662. static static_codebook _huff_book_line_128x17_class1 = {
  115663. 1, 8,
  115664. _huff_lengthlist_line_128x17_class1,
  115665. 0, 0, 0, 0, 0,
  115666. NULL,
  115667. NULL,
  115668. NULL,
  115669. NULL,
  115670. 0
  115671. };
  115672. static long _huff_lengthlist_line_128x17_class2[] = {
  115673. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  115674. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  115675. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  115676. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  115677. };
  115678. static static_codebook _huff_book_line_128x17_class2 = {
  115679. 1, 64,
  115680. _huff_lengthlist_line_128x17_class2,
  115681. 0, 0, 0, 0, 0,
  115682. NULL,
  115683. NULL,
  115684. NULL,
  115685. NULL,
  115686. 0
  115687. };
  115688. static long _huff_lengthlist_line_128x17_class3[] = {
  115689. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  115690. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  115691. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  115692. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  115693. };
  115694. static static_codebook _huff_book_line_128x17_class3 = {
  115695. 1, 64,
  115696. _huff_lengthlist_line_128x17_class3,
  115697. 0, 0, 0, 0, 0,
  115698. NULL,
  115699. NULL,
  115700. NULL,
  115701. NULL,
  115702. 0
  115703. };
  115704. static long _huff_lengthlist_line_128x17_0sub0[] = {
  115705. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115706. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  115707. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  115708. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  115709. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  115710. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  115711. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  115712. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  115713. };
  115714. static static_codebook _huff_book_line_128x17_0sub0 = {
  115715. 1, 128,
  115716. _huff_lengthlist_line_128x17_0sub0,
  115717. 0, 0, 0, 0, 0,
  115718. NULL,
  115719. NULL,
  115720. NULL,
  115721. NULL,
  115722. 0
  115723. };
  115724. static long _huff_lengthlist_line_128x17_1sub0[] = {
  115725. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  115726. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  115727. };
  115728. static static_codebook _huff_book_line_128x17_1sub0 = {
  115729. 1, 32,
  115730. _huff_lengthlist_line_128x17_1sub0,
  115731. 0, 0, 0, 0, 0,
  115732. NULL,
  115733. NULL,
  115734. NULL,
  115735. NULL,
  115736. 0
  115737. };
  115738. static long _huff_lengthlist_line_128x17_1sub1[] = {
  115739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115741. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  115742. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  115743. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  115744. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  115745. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  115746. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  115747. };
  115748. static static_codebook _huff_book_line_128x17_1sub1 = {
  115749. 1, 128,
  115750. _huff_lengthlist_line_128x17_1sub1,
  115751. 0, 0, 0, 0, 0,
  115752. NULL,
  115753. NULL,
  115754. NULL,
  115755. NULL,
  115756. 0
  115757. };
  115758. static long _huff_lengthlist_line_128x17_2sub1[] = {
  115759. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  115760. 9, 4,
  115761. };
  115762. static static_codebook _huff_book_line_128x17_2sub1 = {
  115763. 1, 18,
  115764. _huff_lengthlist_line_128x17_2sub1,
  115765. 0, 0, 0, 0, 0,
  115766. NULL,
  115767. NULL,
  115768. NULL,
  115769. NULL,
  115770. 0
  115771. };
  115772. static long _huff_lengthlist_line_128x17_2sub2[] = {
  115773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115774. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  115775. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  115776. 13,13,
  115777. };
  115778. static static_codebook _huff_book_line_128x17_2sub2 = {
  115779. 1, 50,
  115780. _huff_lengthlist_line_128x17_2sub2,
  115781. 0, 0, 0, 0, 0,
  115782. NULL,
  115783. NULL,
  115784. NULL,
  115785. NULL,
  115786. 0
  115787. };
  115788. static long _huff_lengthlist_line_128x17_2sub3[] = {
  115789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115792. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115793. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  115794. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  115795. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  115796. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  115797. };
  115798. static static_codebook _huff_book_line_128x17_2sub3 = {
  115799. 1, 128,
  115800. _huff_lengthlist_line_128x17_2sub3,
  115801. 0, 0, 0, 0, 0,
  115802. NULL,
  115803. NULL,
  115804. NULL,
  115805. NULL,
  115806. 0
  115807. };
  115808. static long _huff_lengthlist_line_128x17_3sub1[] = {
  115809. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  115810. 6, 4,
  115811. };
  115812. static static_codebook _huff_book_line_128x17_3sub1 = {
  115813. 1, 18,
  115814. _huff_lengthlist_line_128x17_3sub1,
  115815. 0, 0, 0, 0, 0,
  115816. NULL,
  115817. NULL,
  115818. NULL,
  115819. NULL,
  115820. 0
  115821. };
  115822. static long _huff_lengthlist_line_128x17_3sub2[] = {
  115823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115824. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  115825. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  115826. 10, 8,
  115827. };
  115828. static static_codebook _huff_book_line_128x17_3sub2 = {
  115829. 1, 50,
  115830. _huff_lengthlist_line_128x17_3sub2,
  115831. 0, 0, 0, 0, 0,
  115832. NULL,
  115833. NULL,
  115834. NULL,
  115835. NULL,
  115836. 0
  115837. };
  115838. static long _huff_lengthlist_line_128x17_3sub3[] = {
  115839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115842. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  115843. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  115844. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  115845. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  115846. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  115847. };
  115848. static static_codebook _huff_book_line_128x17_3sub3 = {
  115849. 1, 128,
  115850. _huff_lengthlist_line_128x17_3sub3,
  115851. 0, 0, 0, 0, 0,
  115852. NULL,
  115853. NULL,
  115854. NULL,
  115855. NULL,
  115856. 0
  115857. };
  115858. static long _huff_lengthlist_line_1024x27_class1[] = {
  115859. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  115860. };
  115861. static static_codebook _huff_book_line_1024x27_class1 = {
  115862. 1, 16,
  115863. _huff_lengthlist_line_1024x27_class1,
  115864. 0, 0, 0, 0, 0,
  115865. NULL,
  115866. NULL,
  115867. NULL,
  115868. NULL,
  115869. 0
  115870. };
  115871. static long _huff_lengthlist_line_1024x27_class2[] = {
  115872. 1, 4, 2, 6, 3, 7, 5, 7,
  115873. };
  115874. static static_codebook _huff_book_line_1024x27_class2 = {
  115875. 1, 8,
  115876. _huff_lengthlist_line_1024x27_class2,
  115877. 0, 0, 0, 0, 0,
  115878. NULL,
  115879. NULL,
  115880. NULL,
  115881. NULL,
  115882. 0
  115883. };
  115884. static long _huff_lengthlist_line_1024x27_class3[] = {
  115885. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  115886. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  115887. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  115888. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  115889. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  115890. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  115891. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  115892. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  115893. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  115894. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  115895. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  115896. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  115897. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  115898. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  115899. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  115900. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  115901. };
  115902. static static_codebook _huff_book_line_1024x27_class3 = {
  115903. 1, 256,
  115904. _huff_lengthlist_line_1024x27_class3,
  115905. 0, 0, 0, 0, 0,
  115906. NULL,
  115907. NULL,
  115908. NULL,
  115909. NULL,
  115910. 0
  115911. };
  115912. static long _huff_lengthlist_line_1024x27_class4[] = {
  115913. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  115914. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  115915. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  115916. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  115917. };
  115918. static static_codebook _huff_book_line_1024x27_class4 = {
  115919. 1, 64,
  115920. _huff_lengthlist_line_1024x27_class4,
  115921. 0, 0, 0, 0, 0,
  115922. NULL,
  115923. NULL,
  115924. NULL,
  115925. NULL,
  115926. 0
  115927. };
  115928. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  115929. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115930. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  115931. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  115932. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  115933. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  115934. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  115935. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  115936. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  115937. };
  115938. static static_codebook _huff_book_line_1024x27_0sub0 = {
  115939. 1, 128,
  115940. _huff_lengthlist_line_1024x27_0sub0,
  115941. 0, 0, 0, 0, 0,
  115942. NULL,
  115943. NULL,
  115944. NULL,
  115945. NULL,
  115946. 0
  115947. };
  115948. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  115949. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  115950. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  115951. };
  115952. static static_codebook _huff_book_line_1024x27_1sub0 = {
  115953. 1, 32,
  115954. _huff_lengthlist_line_1024x27_1sub0,
  115955. 0, 0, 0, 0, 0,
  115956. NULL,
  115957. NULL,
  115958. NULL,
  115959. NULL,
  115960. 0
  115961. };
  115962. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  115963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115965. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  115966. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  115967. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  115968. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  115969. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  115970. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  115971. };
  115972. static static_codebook _huff_book_line_1024x27_1sub1 = {
  115973. 1, 128,
  115974. _huff_lengthlist_line_1024x27_1sub1,
  115975. 0, 0, 0, 0, 0,
  115976. NULL,
  115977. NULL,
  115978. NULL,
  115979. NULL,
  115980. 0
  115981. };
  115982. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  115983. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115984. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  115985. };
  115986. static static_codebook _huff_book_line_1024x27_2sub0 = {
  115987. 1, 32,
  115988. _huff_lengthlist_line_1024x27_2sub0,
  115989. 0, 0, 0, 0, 0,
  115990. NULL,
  115991. NULL,
  115992. NULL,
  115993. NULL,
  115994. 0
  115995. };
  115996. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  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. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  116000. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  116001. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  116002. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  116003. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  116004. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  116005. };
  116006. static static_codebook _huff_book_line_1024x27_2sub1 = {
  116007. 1, 128,
  116008. _huff_lengthlist_line_1024x27_2sub1,
  116009. 0, 0, 0, 0, 0,
  116010. NULL,
  116011. NULL,
  116012. NULL,
  116013. NULL,
  116014. 0
  116015. };
  116016. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  116017. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  116018. 5, 5,
  116019. };
  116020. static static_codebook _huff_book_line_1024x27_3sub1 = {
  116021. 1, 18,
  116022. _huff_lengthlist_line_1024x27_3sub1,
  116023. 0, 0, 0, 0, 0,
  116024. NULL,
  116025. NULL,
  116026. NULL,
  116027. NULL,
  116028. 0
  116029. };
  116030. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  116031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116032. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  116033. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  116034. 9,11,
  116035. };
  116036. static static_codebook _huff_book_line_1024x27_3sub2 = {
  116037. 1, 50,
  116038. _huff_lengthlist_line_1024x27_3sub2,
  116039. 0, 0, 0, 0, 0,
  116040. NULL,
  116041. NULL,
  116042. NULL,
  116043. NULL,
  116044. 0
  116045. };
  116046. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  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, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  116051. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  116052. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  116053. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  116054. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  116055. };
  116056. static static_codebook _huff_book_line_1024x27_3sub3 = {
  116057. 1, 128,
  116058. _huff_lengthlist_line_1024x27_3sub3,
  116059. 0, 0, 0, 0, 0,
  116060. NULL,
  116061. NULL,
  116062. NULL,
  116063. NULL,
  116064. 0
  116065. };
  116066. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  116067. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  116068. 5, 4,
  116069. };
  116070. static static_codebook _huff_book_line_1024x27_4sub1 = {
  116071. 1, 18,
  116072. _huff_lengthlist_line_1024x27_4sub1,
  116073. 0, 0, 0, 0, 0,
  116074. NULL,
  116075. NULL,
  116076. NULL,
  116077. NULL,
  116078. 0
  116079. };
  116080. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  116081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116082. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  116083. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  116084. 9,12,
  116085. };
  116086. static static_codebook _huff_book_line_1024x27_4sub2 = {
  116087. 1, 50,
  116088. _huff_lengthlist_line_1024x27_4sub2,
  116089. 0, 0, 0, 0, 0,
  116090. NULL,
  116091. NULL,
  116092. NULL,
  116093. NULL,
  116094. 0
  116095. };
  116096. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  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, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  116101. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  116102. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  116103. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  116104. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  116105. };
  116106. static static_codebook _huff_book_line_1024x27_4sub3 = {
  116107. 1, 128,
  116108. _huff_lengthlist_line_1024x27_4sub3,
  116109. 0, 0, 0, 0, 0,
  116110. NULL,
  116111. NULL,
  116112. NULL,
  116113. NULL,
  116114. 0
  116115. };
  116116. static long _huff_lengthlist_line_2048x27_class1[] = {
  116117. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  116118. };
  116119. static static_codebook _huff_book_line_2048x27_class1 = {
  116120. 1, 16,
  116121. _huff_lengthlist_line_2048x27_class1,
  116122. 0, 0, 0, 0, 0,
  116123. NULL,
  116124. NULL,
  116125. NULL,
  116126. NULL,
  116127. 0
  116128. };
  116129. static long _huff_lengthlist_line_2048x27_class2[] = {
  116130. 1, 2, 3, 6, 4, 7, 5, 7,
  116131. };
  116132. static static_codebook _huff_book_line_2048x27_class2 = {
  116133. 1, 8,
  116134. _huff_lengthlist_line_2048x27_class2,
  116135. 0, 0, 0, 0, 0,
  116136. NULL,
  116137. NULL,
  116138. NULL,
  116139. NULL,
  116140. 0
  116141. };
  116142. static long _huff_lengthlist_line_2048x27_class3[] = {
  116143. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  116144. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  116145. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  116146. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  116147. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  116148. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  116149. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  116150. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  116151. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  116152. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  116153. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  116154. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  116155. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  116156. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  116157. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  116158. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  116159. };
  116160. static static_codebook _huff_book_line_2048x27_class3 = {
  116161. 1, 256,
  116162. _huff_lengthlist_line_2048x27_class3,
  116163. 0, 0, 0, 0, 0,
  116164. NULL,
  116165. NULL,
  116166. NULL,
  116167. NULL,
  116168. 0
  116169. };
  116170. static long _huff_lengthlist_line_2048x27_class4[] = {
  116171. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  116172. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  116173. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  116174. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  116175. };
  116176. static static_codebook _huff_book_line_2048x27_class4 = {
  116177. 1, 64,
  116178. _huff_lengthlist_line_2048x27_class4,
  116179. 0, 0, 0, 0, 0,
  116180. NULL,
  116181. NULL,
  116182. NULL,
  116183. NULL,
  116184. 0
  116185. };
  116186. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  116187. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  116188. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  116189. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  116190. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  116191. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  116192. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  116193. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  116194. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  116195. };
  116196. static static_codebook _huff_book_line_2048x27_0sub0 = {
  116197. 1, 128,
  116198. _huff_lengthlist_line_2048x27_0sub0,
  116199. 0, 0, 0, 0, 0,
  116200. NULL,
  116201. NULL,
  116202. NULL,
  116203. NULL,
  116204. 0
  116205. };
  116206. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  116207. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  116208. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  116209. };
  116210. static static_codebook _huff_book_line_2048x27_1sub0 = {
  116211. 1, 32,
  116212. _huff_lengthlist_line_2048x27_1sub0,
  116213. 0, 0, 0, 0, 0,
  116214. NULL,
  116215. NULL,
  116216. NULL,
  116217. NULL,
  116218. 0
  116219. };
  116220. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  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. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  116224. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  116225. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  116226. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  116227. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  116228. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  116229. };
  116230. static static_codebook _huff_book_line_2048x27_1sub1 = {
  116231. 1, 128,
  116232. _huff_lengthlist_line_2048x27_1sub1,
  116233. 0, 0, 0, 0, 0,
  116234. NULL,
  116235. NULL,
  116236. NULL,
  116237. NULL,
  116238. 0
  116239. };
  116240. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  116241. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  116242. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  116243. };
  116244. static static_codebook _huff_book_line_2048x27_2sub0 = {
  116245. 1, 32,
  116246. _huff_lengthlist_line_2048x27_2sub0,
  116247. 0, 0, 0, 0, 0,
  116248. NULL,
  116249. NULL,
  116250. NULL,
  116251. NULL,
  116252. 0
  116253. };
  116254. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  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. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  116258. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  116259. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  116260. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  116261. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  116262. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  116263. };
  116264. static static_codebook _huff_book_line_2048x27_2sub1 = {
  116265. 1, 128,
  116266. _huff_lengthlist_line_2048x27_2sub1,
  116267. 0, 0, 0, 0, 0,
  116268. NULL,
  116269. NULL,
  116270. NULL,
  116271. NULL,
  116272. 0
  116273. };
  116274. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  116275. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  116276. 5, 5,
  116277. };
  116278. static static_codebook _huff_book_line_2048x27_3sub1 = {
  116279. 1, 18,
  116280. _huff_lengthlist_line_2048x27_3sub1,
  116281. 0, 0, 0, 0, 0,
  116282. NULL,
  116283. NULL,
  116284. NULL,
  116285. NULL,
  116286. 0
  116287. };
  116288. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  116289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116290. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  116291. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  116292. 10,12,
  116293. };
  116294. static static_codebook _huff_book_line_2048x27_3sub2 = {
  116295. 1, 50,
  116296. _huff_lengthlist_line_2048x27_3sub2,
  116297. 0, 0, 0, 0, 0,
  116298. NULL,
  116299. NULL,
  116300. NULL,
  116301. NULL,
  116302. 0
  116303. };
  116304. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  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, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  116309. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116310. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116311. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116312. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116313. };
  116314. static static_codebook _huff_book_line_2048x27_3sub3 = {
  116315. 1, 128,
  116316. _huff_lengthlist_line_2048x27_3sub3,
  116317. 0, 0, 0, 0, 0,
  116318. NULL,
  116319. NULL,
  116320. NULL,
  116321. NULL,
  116322. 0
  116323. };
  116324. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  116325. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  116326. 4, 5,
  116327. };
  116328. static static_codebook _huff_book_line_2048x27_4sub1 = {
  116329. 1, 18,
  116330. _huff_lengthlist_line_2048x27_4sub1,
  116331. 0, 0, 0, 0, 0,
  116332. NULL,
  116333. NULL,
  116334. NULL,
  116335. NULL,
  116336. 0
  116337. };
  116338. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  116339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116340. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  116341. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  116342. 10,10,
  116343. };
  116344. static static_codebook _huff_book_line_2048x27_4sub2 = {
  116345. 1, 50,
  116346. _huff_lengthlist_line_2048x27_4sub2,
  116347. 0, 0, 0, 0, 0,
  116348. NULL,
  116349. NULL,
  116350. NULL,
  116351. NULL,
  116352. 0
  116353. };
  116354. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  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, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  116359. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  116360. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116361. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116362. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  116363. };
  116364. static static_codebook _huff_book_line_2048x27_4sub3 = {
  116365. 1, 128,
  116366. _huff_lengthlist_line_2048x27_4sub3,
  116367. 0, 0, 0, 0, 0,
  116368. NULL,
  116369. NULL,
  116370. NULL,
  116371. NULL,
  116372. 0
  116373. };
  116374. static long _huff_lengthlist_line_256x4low_class0[] = {
  116375. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  116376. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  116377. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  116378. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  116379. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  116380. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  116381. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  116382. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  116383. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  116384. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  116385. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  116386. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  116387. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  116388. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  116389. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  116390. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  116391. };
  116392. static static_codebook _huff_book_line_256x4low_class0 = {
  116393. 1, 256,
  116394. _huff_lengthlist_line_256x4low_class0,
  116395. 0, 0, 0, 0, 0,
  116396. NULL,
  116397. NULL,
  116398. NULL,
  116399. NULL,
  116400. 0
  116401. };
  116402. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  116403. 1, 3, 2, 3,
  116404. };
  116405. static static_codebook _huff_book_line_256x4low_0sub0 = {
  116406. 1, 4,
  116407. _huff_lengthlist_line_256x4low_0sub0,
  116408. 0, 0, 0, 0, 0,
  116409. NULL,
  116410. NULL,
  116411. NULL,
  116412. NULL,
  116413. 0
  116414. };
  116415. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  116416. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  116417. };
  116418. static static_codebook _huff_book_line_256x4low_0sub1 = {
  116419. 1, 10,
  116420. _huff_lengthlist_line_256x4low_0sub1,
  116421. 0, 0, 0, 0, 0,
  116422. NULL,
  116423. NULL,
  116424. NULL,
  116425. NULL,
  116426. 0
  116427. };
  116428. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  116429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  116430. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  116431. };
  116432. static static_codebook _huff_book_line_256x4low_0sub2 = {
  116433. 1, 25,
  116434. _huff_lengthlist_line_256x4low_0sub2,
  116435. 0, 0, 0, 0, 0,
  116436. NULL,
  116437. NULL,
  116438. NULL,
  116439. NULL,
  116440. 0
  116441. };
  116442. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  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, 3, 4, 2, 4, 3, 5, 4,
  116445. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  116446. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  116447. };
  116448. static static_codebook _huff_book_line_256x4low_0sub3 = {
  116449. 1, 64,
  116450. _huff_lengthlist_line_256x4low_0sub3,
  116451. 0, 0, 0, 0, 0,
  116452. NULL,
  116453. NULL,
  116454. NULL,
  116455. NULL,
  116456. 0
  116457. };
  116458. /********* End of inlined file: floor_books.h *********/
  116459. static static_codebook *_floor_128x4_books[]={
  116460. &_huff_book_line_128x4_class0,
  116461. &_huff_book_line_128x4_0sub0,
  116462. &_huff_book_line_128x4_0sub1,
  116463. &_huff_book_line_128x4_0sub2,
  116464. &_huff_book_line_128x4_0sub3,
  116465. };
  116466. static static_codebook *_floor_256x4_books[]={
  116467. &_huff_book_line_256x4_class0,
  116468. &_huff_book_line_256x4_0sub0,
  116469. &_huff_book_line_256x4_0sub1,
  116470. &_huff_book_line_256x4_0sub2,
  116471. &_huff_book_line_256x4_0sub3,
  116472. };
  116473. static static_codebook *_floor_128x7_books[]={
  116474. &_huff_book_line_128x7_class0,
  116475. &_huff_book_line_128x7_class1,
  116476. &_huff_book_line_128x7_0sub1,
  116477. &_huff_book_line_128x7_0sub2,
  116478. &_huff_book_line_128x7_0sub3,
  116479. &_huff_book_line_128x7_1sub1,
  116480. &_huff_book_line_128x7_1sub2,
  116481. &_huff_book_line_128x7_1sub3,
  116482. };
  116483. static static_codebook *_floor_256x7_books[]={
  116484. &_huff_book_line_256x7_class0,
  116485. &_huff_book_line_256x7_class1,
  116486. &_huff_book_line_256x7_0sub1,
  116487. &_huff_book_line_256x7_0sub2,
  116488. &_huff_book_line_256x7_0sub3,
  116489. &_huff_book_line_256x7_1sub1,
  116490. &_huff_book_line_256x7_1sub2,
  116491. &_huff_book_line_256x7_1sub3,
  116492. };
  116493. static static_codebook *_floor_128x11_books[]={
  116494. &_huff_book_line_128x11_class1,
  116495. &_huff_book_line_128x11_class2,
  116496. &_huff_book_line_128x11_class3,
  116497. &_huff_book_line_128x11_0sub0,
  116498. &_huff_book_line_128x11_1sub0,
  116499. &_huff_book_line_128x11_1sub1,
  116500. &_huff_book_line_128x11_2sub1,
  116501. &_huff_book_line_128x11_2sub2,
  116502. &_huff_book_line_128x11_2sub3,
  116503. &_huff_book_line_128x11_3sub1,
  116504. &_huff_book_line_128x11_3sub2,
  116505. &_huff_book_line_128x11_3sub3,
  116506. };
  116507. static static_codebook *_floor_128x17_books[]={
  116508. &_huff_book_line_128x17_class1,
  116509. &_huff_book_line_128x17_class2,
  116510. &_huff_book_line_128x17_class3,
  116511. &_huff_book_line_128x17_0sub0,
  116512. &_huff_book_line_128x17_1sub0,
  116513. &_huff_book_line_128x17_1sub1,
  116514. &_huff_book_line_128x17_2sub1,
  116515. &_huff_book_line_128x17_2sub2,
  116516. &_huff_book_line_128x17_2sub3,
  116517. &_huff_book_line_128x17_3sub1,
  116518. &_huff_book_line_128x17_3sub2,
  116519. &_huff_book_line_128x17_3sub3,
  116520. };
  116521. static static_codebook *_floor_256x4low_books[]={
  116522. &_huff_book_line_256x4low_class0,
  116523. &_huff_book_line_256x4low_0sub0,
  116524. &_huff_book_line_256x4low_0sub1,
  116525. &_huff_book_line_256x4low_0sub2,
  116526. &_huff_book_line_256x4low_0sub3,
  116527. };
  116528. static static_codebook *_floor_1024x27_books[]={
  116529. &_huff_book_line_1024x27_class1,
  116530. &_huff_book_line_1024x27_class2,
  116531. &_huff_book_line_1024x27_class3,
  116532. &_huff_book_line_1024x27_class4,
  116533. &_huff_book_line_1024x27_0sub0,
  116534. &_huff_book_line_1024x27_1sub0,
  116535. &_huff_book_line_1024x27_1sub1,
  116536. &_huff_book_line_1024x27_2sub0,
  116537. &_huff_book_line_1024x27_2sub1,
  116538. &_huff_book_line_1024x27_3sub1,
  116539. &_huff_book_line_1024x27_3sub2,
  116540. &_huff_book_line_1024x27_3sub3,
  116541. &_huff_book_line_1024x27_4sub1,
  116542. &_huff_book_line_1024x27_4sub2,
  116543. &_huff_book_line_1024x27_4sub3,
  116544. };
  116545. static static_codebook *_floor_2048x27_books[]={
  116546. &_huff_book_line_2048x27_class1,
  116547. &_huff_book_line_2048x27_class2,
  116548. &_huff_book_line_2048x27_class3,
  116549. &_huff_book_line_2048x27_class4,
  116550. &_huff_book_line_2048x27_0sub0,
  116551. &_huff_book_line_2048x27_1sub0,
  116552. &_huff_book_line_2048x27_1sub1,
  116553. &_huff_book_line_2048x27_2sub0,
  116554. &_huff_book_line_2048x27_2sub1,
  116555. &_huff_book_line_2048x27_3sub1,
  116556. &_huff_book_line_2048x27_3sub2,
  116557. &_huff_book_line_2048x27_3sub3,
  116558. &_huff_book_line_2048x27_4sub1,
  116559. &_huff_book_line_2048x27_4sub2,
  116560. &_huff_book_line_2048x27_4sub3,
  116561. };
  116562. static static_codebook *_floor_512x17_books[]={
  116563. &_huff_book_line_512x17_class1,
  116564. &_huff_book_line_512x17_class2,
  116565. &_huff_book_line_512x17_class3,
  116566. &_huff_book_line_512x17_0sub0,
  116567. &_huff_book_line_512x17_1sub0,
  116568. &_huff_book_line_512x17_1sub1,
  116569. &_huff_book_line_512x17_2sub1,
  116570. &_huff_book_line_512x17_2sub2,
  116571. &_huff_book_line_512x17_2sub3,
  116572. &_huff_book_line_512x17_3sub1,
  116573. &_huff_book_line_512x17_3sub2,
  116574. &_huff_book_line_512x17_3sub3,
  116575. };
  116576. static static_codebook **_floor_books[10]={
  116577. _floor_128x4_books,
  116578. _floor_256x4_books,
  116579. _floor_128x7_books,
  116580. _floor_256x7_books,
  116581. _floor_128x11_books,
  116582. _floor_128x17_books,
  116583. _floor_256x4low_books,
  116584. _floor_1024x27_books,
  116585. _floor_2048x27_books,
  116586. _floor_512x17_books,
  116587. };
  116588. static vorbis_info_floor1 _floor[10]={
  116589. /* 128 x 4 */
  116590. {
  116591. 1,{0},{4},{2},{0},
  116592. {{1,2,3,4}},
  116593. 4,{0,128, 33,8,16,70},
  116594. 60,30,500, 1.,18., -1
  116595. },
  116596. /* 256 x 4 */
  116597. {
  116598. 1,{0},{4},{2},{0},
  116599. {{1,2,3,4}},
  116600. 4,{0,256, 66,16,32,140},
  116601. 60,30,500, 1.,18., -1
  116602. },
  116603. /* 128 x 7 */
  116604. {
  116605. 2,{0,1},{3,4},{2,2},{0,1},
  116606. {{-1,2,3,4},{-1,5,6,7}},
  116607. 4,{0,128, 14,4,58, 2,8,28,90},
  116608. 60,30,500, 1.,18., -1
  116609. },
  116610. /* 256 x 7 */
  116611. {
  116612. 2,{0,1},{3,4},{2,2},{0,1},
  116613. {{-1,2,3,4},{-1,5,6,7}},
  116614. 4,{0,256, 28,8,116, 4,16,56,180},
  116615. 60,30,500, 1.,18., -1
  116616. },
  116617. /* 128 x 11 */
  116618. {
  116619. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  116620. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  116621. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  116622. 60,30,500, 1,18., -1
  116623. },
  116624. /* 128 x 17 */
  116625. {
  116626. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  116627. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  116628. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  116629. 60,30,500, 1,18., -1
  116630. },
  116631. /* 256 x 4 (low bitrate version) */
  116632. {
  116633. 1,{0},{4},{2},{0},
  116634. {{1,2,3,4}},
  116635. 4,{0,256, 66,16,32,140},
  116636. 60,30,500, 1.,18., -1
  116637. },
  116638. /* 1024 x 27 */
  116639. {
  116640. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  116641. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  116642. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  116643. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  116644. 60,30,500, 3,18., -1 /* lowpass */
  116645. },
  116646. /* 2048 x 27 */
  116647. {
  116648. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  116649. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  116650. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  116651. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  116652. 60,30,500, 3,18., -1 /* lowpass */
  116653. },
  116654. /* 512 x 17 */
  116655. {
  116656. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  116657. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  116658. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  116659. 7,23,39, 55,79,110, 156,232,360},
  116660. 60,30,500, 1,18., -1 /* lowpass! */
  116661. },
  116662. };
  116663. /********* End of inlined file: floor_all.h *********/
  116664. /********* Start of inlined file: residue_44.h *********/
  116665. /********* Start of inlined file: res_books_stereo.h *********/
  116666. static long _vq_quantlist__16c0_s_p1_0[] = {
  116667. 1,
  116668. 0,
  116669. 2,
  116670. };
  116671. static long _vq_lengthlist__16c0_s_p1_0[] = {
  116672. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  116673. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116677. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  116678. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116682. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  116683. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  116718. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  116719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  116723. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  116724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  116728. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  116729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116763. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  116764. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116768. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  116769. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  116770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116773. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  116774. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  116775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117082. 0,
  117083. };
  117084. static float _vq_quantthresh__16c0_s_p1_0[] = {
  117085. -0.5, 0.5,
  117086. };
  117087. static long _vq_quantmap__16c0_s_p1_0[] = {
  117088. 1, 0, 2,
  117089. };
  117090. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  117091. _vq_quantthresh__16c0_s_p1_0,
  117092. _vq_quantmap__16c0_s_p1_0,
  117093. 3,
  117094. 3
  117095. };
  117096. static static_codebook _16c0_s_p1_0 = {
  117097. 8, 6561,
  117098. _vq_lengthlist__16c0_s_p1_0,
  117099. 1, -535822336, 1611661312, 2, 0,
  117100. _vq_quantlist__16c0_s_p1_0,
  117101. NULL,
  117102. &_vq_auxt__16c0_s_p1_0,
  117103. NULL,
  117104. 0
  117105. };
  117106. static long _vq_quantlist__16c0_s_p2_0[] = {
  117107. 2,
  117108. 1,
  117109. 3,
  117110. 0,
  117111. 4,
  117112. };
  117113. static long _vq_lengthlist__16c0_s_p2_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, 0, 0, 0, 0, 0, 0, 0,
  117127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117153. 0,
  117154. };
  117155. static float _vq_quantthresh__16c0_s_p2_0[] = {
  117156. -1.5, -0.5, 0.5, 1.5,
  117157. };
  117158. static long _vq_quantmap__16c0_s_p2_0[] = {
  117159. 3, 1, 0, 2, 4,
  117160. };
  117161. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  117162. _vq_quantthresh__16c0_s_p2_0,
  117163. _vq_quantmap__16c0_s_p2_0,
  117164. 5,
  117165. 5
  117166. };
  117167. static static_codebook _16c0_s_p2_0 = {
  117168. 4, 625,
  117169. _vq_lengthlist__16c0_s_p2_0,
  117170. 1, -533725184, 1611661312, 3, 0,
  117171. _vq_quantlist__16c0_s_p2_0,
  117172. NULL,
  117173. &_vq_auxt__16c0_s_p2_0,
  117174. NULL,
  117175. 0
  117176. };
  117177. static long _vq_quantlist__16c0_s_p3_0[] = {
  117178. 2,
  117179. 1,
  117180. 3,
  117181. 0,
  117182. 4,
  117183. };
  117184. static long _vq_lengthlist__16c0_s_p3_0[] = {
  117185. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  117187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117188. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  117190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117191. 0, 0, 0, 0, 6, 6, 6, 9, 9, 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,
  117225. };
  117226. static float _vq_quantthresh__16c0_s_p3_0[] = {
  117227. -1.5, -0.5, 0.5, 1.5,
  117228. };
  117229. static long _vq_quantmap__16c0_s_p3_0[] = {
  117230. 3, 1, 0, 2, 4,
  117231. };
  117232. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  117233. _vq_quantthresh__16c0_s_p3_0,
  117234. _vq_quantmap__16c0_s_p3_0,
  117235. 5,
  117236. 5
  117237. };
  117238. static static_codebook _16c0_s_p3_0 = {
  117239. 4, 625,
  117240. _vq_lengthlist__16c0_s_p3_0,
  117241. 1, -533725184, 1611661312, 3, 0,
  117242. _vq_quantlist__16c0_s_p3_0,
  117243. NULL,
  117244. &_vq_auxt__16c0_s_p3_0,
  117245. NULL,
  117246. 0
  117247. };
  117248. static long _vq_quantlist__16c0_s_p4_0[] = {
  117249. 4,
  117250. 3,
  117251. 5,
  117252. 2,
  117253. 6,
  117254. 1,
  117255. 7,
  117256. 0,
  117257. 8,
  117258. };
  117259. static long _vq_lengthlist__16c0_s_p4_0[] = {
  117260. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  117261. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  117262. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  117263. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  117264. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117265. 0,
  117266. };
  117267. static float _vq_quantthresh__16c0_s_p4_0[] = {
  117268. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  117269. };
  117270. static long _vq_quantmap__16c0_s_p4_0[] = {
  117271. 7, 5, 3, 1, 0, 2, 4, 6,
  117272. 8,
  117273. };
  117274. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  117275. _vq_quantthresh__16c0_s_p4_0,
  117276. _vq_quantmap__16c0_s_p4_0,
  117277. 9,
  117278. 9
  117279. };
  117280. static static_codebook _16c0_s_p4_0 = {
  117281. 2, 81,
  117282. _vq_lengthlist__16c0_s_p4_0,
  117283. 1, -531628032, 1611661312, 4, 0,
  117284. _vq_quantlist__16c0_s_p4_0,
  117285. NULL,
  117286. &_vq_auxt__16c0_s_p4_0,
  117287. NULL,
  117288. 0
  117289. };
  117290. static long _vq_quantlist__16c0_s_p5_0[] = {
  117291. 4,
  117292. 3,
  117293. 5,
  117294. 2,
  117295. 6,
  117296. 1,
  117297. 7,
  117298. 0,
  117299. 8,
  117300. };
  117301. static long _vq_lengthlist__16c0_s_p5_0[] = {
  117302. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  117303. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  117304. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  117305. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  117306. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  117307. 10,
  117308. };
  117309. static float _vq_quantthresh__16c0_s_p5_0[] = {
  117310. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  117311. };
  117312. static long _vq_quantmap__16c0_s_p5_0[] = {
  117313. 7, 5, 3, 1, 0, 2, 4, 6,
  117314. 8,
  117315. };
  117316. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  117317. _vq_quantthresh__16c0_s_p5_0,
  117318. _vq_quantmap__16c0_s_p5_0,
  117319. 9,
  117320. 9
  117321. };
  117322. static static_codebook _16c0_s_p5_0 = {
  117323. 2, 81,
  117324. _vq_lengthlist__16c0_s_p5_0,
  117325. 1, -531628032, 1611661312, 4, 0,
  117326. _vq_quantlist__16c0_s_p5_0,
  117327. NULL,
  117328. &_vq_auxt__16c0_s_p5_0,
  117329. NULL,
  117330. 0
  117331. };
  117332. static long _vq_quantlist__16c0_s_p6_0[] = {
  117333. 8,
  117334. 7,
  117335. 9,
  117336. 6,
  117337. 10,
  117338. 5,
  117339. 11,
  117340. 4,
  117341. 12,
  117342. 3,
  117343. 13,
  117344. 2,
  117345. 14,
  117346. 1,
  117347. 15,
  117348. 0,
  117349. 16,
  117350. };
  117351. static long _vq_lengthlist__16c0_s_p6_0[] = {
  117352. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  117353. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  117354. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  117355. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  117356. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  117357. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  117358. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  117359. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  117360. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  117361. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  117362. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  117363. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  117364. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  117365. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  117366. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  117367. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  117368. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  117369. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  117370. 14,
  117371. };
  117372. static float _vq_quantthresh__16c0_s_p6_0[] = {
  117373. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  117374. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  117375. };
  117376. static long _vq_quantmap__16c0_s_p6_0[] = {
  117377. 15, 13, 11, 9, 7, 5, 3, 1,
  117378. 0, 2, 4, 6, 8, 10, 12, 14,
  117379. 16,
  117380. };
  117381. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  117382. _vq_quantthresh__16c0_s_p6_0,
  117383. _vq_quantmap__16c0_s_p6_0,
  117384. 17,
  117385. 17
  117386. };
  117387. static static_codebook _16c0_s_p6_0 = {
  117388. 2, 289,
  117389. _vq_lengthlist__16c0_s_p6_0,
  117390. 1, -529530880, 1611661312, 5, 0,
  117391. _vq_quantlist__16c0_s_p6_0,
  117392. NULL,
  117393. &_vq_auxt__16c0_s_p6_0,
  117394. NULL,
  117395. 0
  117396. };
  117397. static long _vq_quantlist__16c0_s_p7_0[] = {
  117398. 1,
  117399. 0,
  117400. 2,
  117401. };
  117402. static long _vq_lengthlist__16c0_s_p7_0[] = {
  117403. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  117404. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  117405. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  117406. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  117407. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  117408. 13,
  117409. };
  117410. static float _vq_quantthresh__16c0_s_p7_0[] = {
  117411. -5.5, 5.5,
  117412. };
  117413. static long _vq_quantmap__16c0_s_p7_0[] = {
  117414. 1, 0, 2,
  117415. };
  117416. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  117417. _vq_quantthresh__16c0_s_p7_0,
  117418. _vq_quantmap__16c0_s_p7_0,
  117419. 3,
  117420. 3
  117421. };
  117422. static static_codebook _16c0_s_p7_0 = {
  117423. 4, 81,
  117424. _vq_lengthlist__16c0_s_p7_0,
  117425. 1, -529137664, 1618345984, 2, 0,
  117426. _vq_quantlist__16c0_s_p7_0,
  117427. NULL,
  117428. &_vq_auxt__16c0_s_p7_0,
  117429. NULL,
  117430. 0
  117431. };
  117432. static long _vq_quantlist__16c0_s_p7_1[] = {
  117433. 5,
  117434. 4,
  117435. 6,
  117436. 3,
  117437. 7,
  117438. 2,
  117439. 8,
  117440. 1,
  117441. 9,
  117442. 0,
  117443. 10,
  117444. };
  117445. static long _vq_lengthlist__16c0_s_p7_1[] = {
  117446. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  117447. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  117448. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  117449. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  117450. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  117451. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  117452. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  117453. 11,11,11, 9, 9, 9, 9,10,10,
  117454. };
  117455. static float _vq_quantthresh__16c0_s_p7_1[] = {
  117456. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  117457. 3.5, 4.5,
  117458. };
  117459. static long _vq_quantmap__16c0_s_p7_1[] = {
  117460. 9, 7, 5, 3, 1, 0, 2, 4,
  117461. 6, 8, 10,
  117462. };
  117463. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  117464. _vq_quantthresh__16c0_s_p7_1,
  117465. _vq_quantmap__16c0_s_p7_1,
  117466. 11,
  117467. 11
  117468. };
  117469. static static_codebook _16c0_s_p7_1 = {
  117470. 2, 121,
  117471. _vq_lengthlist__16c0_s_p7_1,
  117472. 1, -531365888, 1611661312, 4, 0,
  117473. _vq_quantlist__16c0_s_p7_1,
  117474. NULL,
  117475. &_vq_auxt__16c0_s_p7_1,
  117476. NULL,
  117477. 0
  117478. };
  117479. static long _vq_quantlist__16c0_s_p8_0[] = {
  117480. 6,
  117481. 5,
  117482. 7,
  117483. 4,
  117484. 8,
  117485. 3,
  117486. 9,
  117487. 2,
  117488. 10,
  117489. 1,
  117490. 11,
  117491. 0,
  117492. 12,
  117493. };
  117494. static long _vq_lengthlist__16c0_s_p8_0[] = {
  117495. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  117496. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  117497. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  117498. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  117499. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  117500. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  117501. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  117502. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  117503. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  117504. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  117505. 0,12,13,13,12,13,14,14,14,
  117506. };
  117507. static float _vq_quantthresh__16c0_s_p8_0[] = {
  117508. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  117509. 12.5, 17.5, 22.5, 27.5,
  117510. };
  117511. static long _vq_quantmap__16c0_s_p8_0[] = {
  117512. 11, 9, 7, 5, 3, 1, 0, 2,
  117513. 4, 6, 8, 10, 12,
  117514. };
  117515. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  117516. _vq_quantthresh__16c0_s_p8_0,
  117517. _vq_quantmap__16c0_s_p8_0,
  117518. 13,
  117519. 13
  117520. };
  117521. static static_codebook _16c0_s_p8_0 = {
  117522. 2, 169,
  117523. _vq_lengthlist__16c0_s_p8_0,
  117524. 1, -526516224, 1616117760, 4, 0,
  117525. _vq_quantlist__16c0_s_p8_0,
  117526. NULL,
  117527. &_vq_auxt__16c0_s_p8_0,
  117528. NULL,
  117529. 0
  117530. };
  117531. static long _vq_quantlist__16c0_s_p8_1[] = {
  117532. 2,
  117533. 1,
  117534. 3,
  117535. 0,
  117536. 4,
  117537. };
  117538. static long _vq_lengthlist__16c0_s_p8_1[] = {
  117539. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  117540. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  117541. };
  117542. static float _vq_quantthresh__16c0_s_p8_1[] = {
  117543. -1.5, -0.5, 0.5, 1.5,
  117544. };
  117545. static long _vq_quantmap__16c0_s_p8_1[] = {
  117546. 3, 1, 0, 2, 4,
  117547. };
  117548. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  117549. _vq_quantthresh__16c0_s_p8_1,
  117550. _vq_quantmap__16c0_s_p8_1,
  117551. 5,
  117552. 5
  117553. };
  117554. static static_codebook _16c0_s_p8_1 = {
  117555. 2, 25,
  117556. _vq_lengthlist__16c0_s_p8_1,
  117557. 1, -533725184, 1611661312, 3, 0,
  117558. _vq_quantlist__16c0_s_p8_1,
  117559. NULL,
  117560. &_vq_auxt__16c0_s_p8_1,
  117561. NULL,
  117562. 0
  117563. };
  117564. static long _vq_quantlist__16c0_s_p9_0[] = {
  117565. 1,
  117566. 0,
  117567. 2,
  117568. };
  117569. static long _vq_lengthlist__16c0_s_p9_0[] = {
  117570. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117571. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117572. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117573. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117574. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117575. 7,
  117576. };
  117577. static float _vq_quantthresh__16c0_s_p9_0[] = {
  117578. -157.5, 157.5,
  117579. };
  117580. static long _vq_quantmap__16c0_s_p9_0[] = {
  117581. 1, 0, 2,
  117582. };
  117583. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  117584. _vq_quantthresh__16c0_s_p9_0,
  117585. _vq_quantmap__16c0_s_p9_0,
  117586. 3,
  117587. 3
  117588. };
  117589. static static_codebook _16c0_s_p9_0 = {
  117590. 4, 81,
  117591. _vq_lengthlist__16c0_s_p9_0,
  117592. 1, -518803456, 1628680192, 2, 0,
  117593. _vq_quantlist__16c0_s_p9_0,
  117594. NULL,
  117595. &_vq_auxt__16c0_s_p9_0,
  117596. NULL,
  117597. 0
  117598. };
  117599. static long _vq_quantlist__16c0_s_p9_1[] = {
  117600. 7,
  117601. 6,
  117602. 8,
  117603. 5,
  117604. 9,
  117605. 4,
  117606. 10,
  117607. 3,
  117608. 11,
  117609. 2,
  117610. 12,
  117611. 1,
  117612. 13,
  117613. 0,
  117614. 14,
  117615. };
  117616. static long _vq_lengthlist__16c0_s_p9_1[] = {
  117617. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  117618. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  117619. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  117620. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  117621. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117622. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117623. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117624. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117625. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117626. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117627. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117628. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117629. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117630. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117631. 10,
  117632. };
  117633. static float _vq_quantthresh__16c0_s_p9_1[] = {
  117634. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  117635. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  117636. };
  117637. static long _vq_quantmap__16c0_s_p9_1[] = {
  117638. 13, 11, 9, 7, 5, 3, 1, 0,
  117639. 2, 4, 6, 8, 10, 12, 14,
  117640. };
  117641. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  117642. _vq_quantthresh__16c0_s_p9_1,
  117643. _vq_quantmap__16c0_s_p9_1,
  117644. 15,
  117645. 15
  117646. };
  117647. static static_codebook _16c0_s_p9_1 = {
  117648. 2, 225,
  117649. _vq_lengthlist__16c0_s_p9_1,
  117650. 1, -520986624, 1620377600, 4, 0,
  117651. _vq_quantlist__16c0_s_p9_1,
  117652. NULL,
  117653. &_vq_auxt__16c0_s_p9_1,
  117654. NULL,
  117655. 0
  117656. };
  117657. static long _vq_quantlist__16c0_s_p9_2[] = {
  117658. 10,
  117659. 9,
  117660. 11,
  117661. 8,
  117662. 12,
  117663. 7,
  117664. 13,
  117665. 6,
  117666. 14,
  117667. 5,
  117668. 15,
  117669. 4,
  117670. 16,
  117671. 3,
  117672. 17,
  117673. 2,
  117674. 18,
  117675. 1,
  117676. 19,
  117677. 0,
  117678. 20,
  117679. };
  117680. static long _vq_lengthlist__16c0_s_p9_2[] = {
  117681. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  117682. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  117683. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  117684. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  117685. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  117686. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  117687. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  117688. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  117689. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  117690. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  117691. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  117692. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  117693. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  117694. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  117695. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  117696. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  117697. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  117698. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  117699. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  117700. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  117701. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  117702. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  117703. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  117704. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  117705. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  117706. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  117707. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  117708. 10,11,10,10,11, 9,10,10,10,
  117709. };
  117710. static float _vq_quantthresh__16c0_s_p9_2[] = {
  117711. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  117712. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  117713. 6.5, 7.5, 8.5, 9.5,
  117714. };
  117715. static long _vq_quantmap__16c0_s_p9_2[] = {
  117716. 19, 17, 15, 13, 11, 9, 7, 5,
  117717. 3, 1, 0, 2, 4, 6, 8, 10,
  117718. 12, 14, 16, 18, 20,
  117719. };
  117720. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  117721. _vq_quantthresh__16c0_s_p9_2,
  117722. _vq_quantmap__16c0_s_p9_2,
  117723. 21,
  117724. 21
  117725. };
  117726. static static_codebook _16c0_s_p9_2 = {
  117727. 2, 441,
  117728. _vq_lengthlist__16c0_s_p9_2,
  117729. 1, -529268736, 1611661312, 5, 0,
  117730. _vq_quantlist__16c0_s_p9_2,
  117731. NULL,
  117732. &_vq_auxt__16c0_s_p9_2,
  117733. NULL,
  117734. 0
  117735. };
  117736. static long _huff_lengthlist__16c0_s_single[] = {
  117737. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  117738. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  117739. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  117740. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  117741. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  117742. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  117743. 16,16,18,18,
  117744. };
  117745. static static_codebook _huff_book__16c0_s_single = {
  117746. 2, 100,
  117747. _huff_lengthlist__16c0_s_single,
  117748. 0, 0, 0, 0, 0,
  117749. NULL,
  117750. NULL,
  117751. NULL,
  117752. NULL,
  117753. 0
  117754. };
  117755. static long _huff_lengthlist__16c1_s_long[] = {
  117756. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  117757. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  117758. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  117759. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  117760. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  117761. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  117762. 12,11,11,13,
  117763. };
  117764. static static_codebook _huff_book__16c1_s_long = {
  117765. 2, 100,
  117766. _huff_lengthlist__16c1_s_long,
  117767. 0, 0, 0, 0, 0,
  117768. NULL,
  117769. NULL,
  117770. NULL,
  117771. NULL,
  117772. 0
  117773. };
  117774. static long _vq_quantlist__16c1_s_p1_0[] = {
  117775. 1,
  117776. 0,
  117777. 2,
  117778. };
  117779. static long _vq_lengthlist__16c1_s_p1_0[] = {
  117780. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  117781. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117785. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  117786. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117790. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  117791. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  117826. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  117827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  117831. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  117832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  117836. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  117837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117871. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  117872. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117876. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  117877. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  117878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117881. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  117882. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  117883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118190. 0,
  118191. };
  118192. static float _vq_quantthresh__16c1_s_p1_0[] = {
  118193. -0.5, 0.5,
  118194. };
  118195. static long _vq_quantmap__16c1_s_p1_0[] = {
  118196. 1, 0, 2,
  118197. };
  118198. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  118199. _vq_quantthresh__16c1_s_p1_0,
  118200. _vq_quantmap__16c1_s_p1_0,
  118201. 3,
  118202. 3
  118203. };
  118204. static static_codebook _16c1_s_p1_0 = {
  118205. 8, 6561,
  118206. _vq_lengthlist__16c1_s_p1_0,
  118207. 1, -535822336, 1611661312, 2, 0,
  118208. _vq_quantlist__16c1_s_p1_0,
  118209. NULL,
  118210. &_vq_auxt__16c1_s_p1_0,
  118211. NULL,
  118212. 0
  118213. };
  118214. static long _vq_quantlist__16c1_s_p2_0[] = {
  118215. 2,
  118216. 1,
  118217. 3,
  118218. 0,
  118219. 4,
  118220. };
  118221. static long _vq_lengthlist__16c1_s_p2_0[] = {
  118222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0,
  118256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  118262. };
  118263. static float _vq_quantthresh__16c1_s_p2_0[] = {
  118264. -1.5, -0.5, 0.5, 1.5,
  118265. };
  118266. static long _vq_quantmap__16c1_s_p2_0[] = {
  118267. 3, 1, 0, 2, 4,
  118268. };
  118269. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  118270. _vq_quantthresh__16c1_s_p2_0,
  118271. _vq_quantmap__16c1_s_p2_0,
  118272. 5,
  118273. 5
  118274. };
  118275. static static_codebook _16c1_s_p2_0 = {
  118276. 4, 625,
  118277. _vq_lengthlist__16c1_s_p2_0,
  118278. 1, -533725184, 1611661312, 3, 0,
  118279. _vq_quantlist__16c1_s_p2_0,
  118280. NULL,
  118281. &_vq_auxt__16c1_s_p2_0,
  118282. NULL,
  118283. 0
  118284. };
  118285. static long _vq_quantlist__16c1_s_p3_0[] = {
  118286. 2,
  118287. 1,
  118288. 3,
  118289. 0,
  118290. 4,
  118291. };
  118292. static long _vq_lengthlist__16c1_s_p3_0[] = {
  118293. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  118295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118296. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  118298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118299. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  118300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118332. 0,
  118333. };
  118334. static float _vq_quantthresh__16c1_s_p3_0[] = {
  118335. -1.5, -0.5, 0.5, 1.5,
  118336. };
  118337. static long _vq_quantmap__16c1_s_p3_0[] = {
  118338. 3, 1, 0, 2, 4,
  118339. };
  118340. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  118341. _vq_quantthresh__16c1_s_p3_0,
  118342. _vq_quantmap__16c1_s_p3_0,
  118343. 5,
  118344. 5
  118345. };
  118346. static static_codebook _16c1_s_p3_0 = {
  118347. 4, 625,
  118348. _vq_lengthlist__16c1_s_p3_0,
  118349. 1, -533725184, 1611661312, 3, 0,
  118350. _vq_quantlist__16c1_s_p3_0,
  118351. NULL,
  118352. &_vq_auxt__16c1_s_p3_0,
  118353. NULL,
  118354. 0
  118355. };
  118356. static long _vq_quantlist__16c1_s_p4_0[] = {
  118357. 4,
  118358. 3,
  118359. 5,
  118360. 2,
  118361. 6,
  118362. 1,
  118363. 7,
  118364. 0,
  118365. 8,
  118366. };
  118367. static long _vq_lengthlist__16c1_s_p4_0[] = {
  118368. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  118369. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  118370. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  118371. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  118372. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118373. 0,
  118374. };
  118375. static float _vq_quantthresh__16c1_s_p4_0[] = {
  118376. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  118377. };
  118378. static long _vq_quantmap__16c1_s_p4_0[] = {
  118379. 7, 5, 3, 1, 0, 2, 4, 6,
  118380. 8,
  118381. };
  118382. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  118383. _vq_quantthresh__16c1_s_p4_0,
  118384. _vq_quantmap__16c1_s_p4_0,
  118385. 9,
  118386. 9
  118387. };
  118388. static static_codebook _16c1_s_p4_0 = {
  118389. 2, 81,
  118390. _vq_lengthlist__16c1_s_p4_0,
  118391. 1, -531628032, 1611661312, 4, 0,
  118392. _vq_quantlist__16c1_s_p4_0,
  118393. NULL,
  118394. &_vq_auxt__16c1_s_p4_0,
  118395. NULL,
  118396. 0
  118397. };
  118398. static long _vq_quantlist__16c1_s_p5_0[] = {
  118399. 4,
  118400. 3,
  118401. 5,
  118402. 2,
  118403. 6,
  118404. 1,
  118405. 7,
  118406. 0,
  118407. 8,
  118408. };
  118409. static long _vq_lengthlist__16c1_s_p5_0[] = {
  118410. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  118411. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  118412. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  118413. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  118414. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  118415. 10,
  118416. };
  118417. static float _vq_quantthresh__16c1_s_p5_0[] = {
  118418. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  118419. };
  118420. static long _vq_quantmap__16c1_s_p5_0[] = {
  118421. 7, 5, 3, 1, 0, 2, 4, 6,
  118422. 8,
  118423. };
  118424. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  118425. _vq_quantthresh__16c1_s_p5_0,
  118426. _vq_quantmap__16c1_s_p5_0,
  118427. 9,
  118428. 9
  118429. };
  118430. static static_codebook _16c1_s_p5_0 = {
  118431. 2, 81,
  118432. _vq_lengthlist__16c1_s_p5_0,
  118433. 1, -531628032, 1611661312, 4, 0,
  118434. _vq_quantlist__16c1_s_p5_0,
  118435. NULL,
  118436. &_vq_auxt__16c1_s_p5_0,
  118437. NULL,
  118438. 0
  118439. };
  118440. static long _vq_quantlist__16c1_s_p6_0[] = {
  118441. 8,
  118442. 7,
  118443. 9,
  118444. 6,
  118445. 10,
  118446. 5,
  118447. 11,
  118448. 4,
  118449. 12,
  118450. 3,
  118451. 13,
  118452. 2,
  118453. 14,
  118454. 1,
  118455. 15,
  118456. 0,
  118457. 16,
  118458. };
  118459. static long _vq_lengthlist__16c1_s_p6_0[] = {
  118460. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  118461. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  118462. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  118463. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  118464. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  118465. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  118466. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  118467. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  118468. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  118469. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  118470. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  118471. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  118472. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  118473. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  118474. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  118475. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  118476. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  118477. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  118478. 14,
  118479. };
  118480. static float _vq_quantthresh__16c1_s_p6_0[] = {
  118481. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  118482. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  118483. };
  118484. static long _vq_quantmap__16c1_s_p6_0[] = {
  118485. 15, 13, 11, 9, 7, 5, 3, 1,
  118486. 0, 2, 4, 6, 8, 10, 12, 14,
  118487. 16,
  118488. };
  118489. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  118490. _vq_quantthresh__16c1_s_p6_0,
  118491. _vq_quantmap__16c1_s_p6_0,
  118492. 17,
  118493. 17
  118494. };
  118495. static static_codebook _16c1_s_p6_0 = {
  118496. 2, 289,
  118497. _vq_lengthlist__16c1_s_p6_0,
  118498. 1, -529530880, 1611661312, 5, 0,
  118499. _vq_quantlist__16c1_s_p6_0,
  118500. NULL,
  118501. &_vq_auxt__16c1_s_p6_0,
  118502. NULL,
  118503. 0
  118504. };
  118505. static long _vq_quantlist__16c1_s_p7_0[] = {
  118506. 1,
  118507. 0,
  118508. 2,
  118509. };
  118510. static long _vq_lengthlist__16c1_s_p7_0[] = {
  118511. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  118512. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  118513. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  118514. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  118515. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  118516. 11,
  118517. };
  118518. static float _vq_quantthresh__16c1_s_p7_0[] = {
  118519. -5.5, 5.5,
  118520. };
  118521. static long _vq_quantmap__16c1_s_p7_0[] = {
  118522. 1, 0, 2,
  118523. };
  118524. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  118525. _vq_quantthresh__16c1_s_p7_0,
  118526. _vq_quantmap__16c1_s_p7_0,
  118527. 3,
  118528. 3
  118529. };
  118530. static static_codebook _16c1_s_p7_0 = {
  118531. 4, 81,
  118532. _vq_lengthlist__16c1_s_p7_0,
  118533. 1, -529137664, 1618345984, 2, 0,
  118534. _vq_quantlist__16c1_s_p7_0,
  118535. NULL,
  118536. &_vq_auxt__16c1_s_p7_0,
  118537. NULL,
  118538. 0
  118539. };
  118540. static long _vq_quantlist__16c1_s_p7_1[] = {
  118541. 5,
  118542. 4,
  118543. 6,
  118544. 3,
  118545. 7,
  118546. 2,
  118547. 8,
  118548. 1,
  118549. 9,
  118550. 0,
  118551. 10,
  118552. };
  118553. static long _vq_lengthlist__16c1_s_p7_1[] = {
  118554. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  118555. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  118556. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  118557. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  118558. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  118559. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  118560. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  118561. 10,10,10, 8, 8, 8, 8, 9, 9,
  118562. };
  118563. static float _vq_quantthresh__16c1_s_p7_1[] = {
  118564. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  118565. 3.5, 4.5,
  118566. };
  118567. static long _vq_quantmap__16c1_s_p7_1[] = {
  118568. 9, 7, 5, 3, 1, 0, 2, 4,
  118569. 6, 8, 10,
  118570. };
  118571. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  118572. _vq_quantthresh__16c1_s_p7_1,
  118573. _vq_quantmap__16c1_s_p7_1,
  118574. 11,
  118575. 11
  118576. };
  118577. static static_codebook _16c1_s_p7_1 = {
  118578. 2, 121,
  118579. _vq_lengthlist__16c1_s_p7_1,
  118580. 1, -531365888, 1611661312, 4, 0,
  118581. _vq_quantlist__16c1_s_p7_1,
  118582. NULL,
  118583. &_vq_auxt__16c1_s_p7_1,
  118584. NULL,
  118585. 0
  118586. };
  118587. static long _vq_quantlist__16c1_s_p8_0[] = {
  118588. 6,
  118589. 5,
  118590. 7,
  118591. 4,
  118592. 8,
  118593. 3,
  118594. 9,
  118595. 2,
  118596. 10,
  118597. 1,
  118598. 11,
  118599. 0,
  118600. 12,
  118601. };
  118602. static long _vq_lengthlist__16c1_s_p8_0[] = {
  118603. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  118604. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  118605. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  118606. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  118607. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  118608. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  118609. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  118610. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  118611. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  118612. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  118613. 0,12,12,12,12,13,13,14,15,
  118614. };
  118615. static float _vq_quantthresh__16c1_s_p8_0[] = {
  118616. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  118617. 12.5, 17.5, 22.5, 27.5,
  118618. };
  118619. static long _vq_quantmap__16c1_s_p8_0[] = {
  118620. 11, 9, 7, 5, 3, 1, 0, 2,
  118621. 4, 6, 8, 10, 12,
  118622. };
  118623. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  118624. _vq_quantthresh__16c1_s_p8_0,
  118625. _vq_quantmap__16c1_s_p8_0,
  118626. 13,
  118627. 13
  118628. };
  118629. static static_codebook _16c1_s_p8_0 = {
  118630. 2, 169,
  118631. _vq_lengthlist__16c1_s_p8_0,
  118632. 1, -526516224, 1616117760, 4, 0,
  118633. _vq_quantlist__16c1_s_p8_0,
  118634. NULL,
  118635. &_vq_auxt__16c1_s_p8_0,
  118636. NULL,
  118637. 0
  118638. };
  118639. static long _vq_quantlist__16c1_s_p8_1[] = {
  118640. 2,
  118641. 1,
  118642. 3,
  118643. 0,
  118644. 4,
  118645. };
  118646. static long _vq_lengthlist__16c1_s_p8_1[] = {
  118647. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  118648. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  118649. };
  118650. static float _vq_quantthresh__16c1_s_p8_1[] = {
  118651. -1.5, -0.5, 0.5, 1.5,
  118652. };
  118653. static long _vq_quantmap__16c1_s_p8_1[] = {
  118654. 3, 1, 0, 2, 4,
  118655. };
  118656. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  118657. _vq_quantthresh__16c1_s_p8_1,
  118658. _vq_quantmap__16c1_s_p8_1,
  118659. 5,
  118660. 5
  118661. };
  118662. static static_codebook _16c1_s_p8_1 = {
  118663. 2, 25,
  118664. _vq_lengthlist__16c1_s_p8_1,
  118665. 1, -533725184, 1611661312, 3, 0,
  118666. _vq_quantlist__16c1_s_p8_1,
  118667. NULL,
  118668. &_vq_auxt__16c1_s_p8_1,
  118669. NULL,
  118670. 0
  118671. };
  118672. static long _vq_quantlist__16c1_s_p9_0[] = {
  118673. 6,
  118674. 5,
  118675. 7,
  118676. 4,
  118677. 8,
  118678. 3,
  118679. 9,
  118680. 2,
  118681. 10,
  118682. 1,
  118683. 11,
  118684. 0,
  118685. 12,
  118686. };
  118687. static long _vq_lengthlist__16c1_s_p9_0[] = {
  118688. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118689. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118690. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118691. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118692. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118693. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118694. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118695. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118696. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118697. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118698. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118699. };
  118700. static float _vq_quantthresh__16c1_s_p9_0[] = {
  118701. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  118702. 787.5, 1102.5, 1417.5, 1732.5,
  118703. };
  118704. static long _vq_quantmap__16c1_s_p9_0[] = {
  118705. 11, 9, 7, 5, 3, 1, 0, 2,
  118706. 4, 6, 8, 10, 12,
  118707. };
  118708. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  118709. _vq_quantthresh__16c1_s_p9_0,
  118710. _vq_quantmap__16c1_s_p9_0,
  118711. 13,
  118712. 13
  118713. };
  118714. static static_codebook _16c1_s_p9_0 = {
  118715. 2, 169,
  118716. _vq_lengthlist__16c1_s_p9_0,
  118717. 1, -513964032, 1628680192, 4, 0,
  118718. _vq_quantlist__16c1_s_p9_0,
  118719. NULL,
  118720. &_vq_auxt__16c1_s_p9_0,
  118721. NULL,
  118722. 0
  118723. };
  118724. static long _vq_quantlist__16c1_s_p9_1[] = {
  118725. 7,
  118726. 6,
  118727. 8,
  118728. 5,
  118729. 9,
  118730. 4,
  118731. 10,
  118732. 3,
  118733. 11,
  118734. 2,
  118735. 12,
  118736. 1,
  118737. 13,
  118738. 0,
  118739. 14,
  118740. };
  118741. static long _vq_lengthlist__16c1_s_p9_1[] = {
  118742. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  118743. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  118744. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  118745. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  118746. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  118747. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  118748. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  118749. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  118750. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118751. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  118752. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118753. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118754. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  118755. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118756. 13,
  118757. };
  118758. static float _vq_quantthresh__16c1_s_p9_1[] = {
  118759. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  118760. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  118761. };
  118762. static long _vq_quantmap__16c1_s_p9_1[] = {
  118763. 13, 11, 9, 7, 5, 3, 1, 0,
  118764. 2, 4, 6, 8, 10, 12, 14,
  118765. };
  118766. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  118767. _vq_quantthresh__16c1_s_p9_1,
  118768. _vq_quantmap__16c1_s_p9_1,
  118769. 15,
  118770. 15
  118771. };
  118772. static static_codebook _16c1_s_p9_1 = {
  118773. 2, 225,
  118774. _vq_lengthlist__16c1_s_p9_1,
  118775. 1, -520986624, 1620377600, 4, 0,
  118776. _vq_quantlist__16c1_s_p9_1,
  118777. NULL,
  118778. &_vq_auxt__16c1_s_p9_1,
  118779. NULL,
  118780. 0
  118781. };
  118782. static long _vq_quantlist__16c1_s_p9_2[] = {
  118783. 10,
  118784. 9,
  118785. 11,
  118786. 8,
  118787. 12,
  118788. 7,
  118789. 13,
  118790. 6,
  118791. 14,
  118792. 5,
  118793. 15,
  118794. 4,
  118795. 16,
  118796. 3,
  118797. 17,
  118798. 2,
  118799. 18,
  118800. 1,
  118801. 19,
  118802. 0,
  118803. 20,
  118804. };
  118805. static long _vq_lengthlist__16c1_s_p9_2[] = {
  118806. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  118807. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  118808. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  118809. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  118810. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  118811. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  118812. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  118813. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  118814. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  118815. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  118816. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  118817. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  118818. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  118819. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  118820. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  118821. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  118822. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  118823. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  118824. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  118825. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  118826. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  118827. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  118828. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  118829. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  118830. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  118831. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  118832. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  118833. 11,11,11,11,12,11,11,12,11,
  118834. };
  118835. static float _vq_quantthresh__16c1_s_p9_2[] = {
  118836. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  118837. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  118838. 6.5, 7.5, 8.5, 9.5,
  118839. };
  118840. static long _vq_quantmap__16c1_s_p9_2[] = {
  118841. 19, 17, 15, 13, 11, 9, 7, 5,
  118842. 3, 1, 0, 2, 4, 6, 8, 10,
  118843. 12, 14, 16, 18, 20,
  118844. };
  118845. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  118846. _vq_quantthresh__16c1_s_p9_2,
  118847. _vq_quantmap__16c1_s_p9_2,
  118848. 21,
  118849. 21
  118850. };
  118851. static static_codebook _16c1_s_p9_2 = {
  118852. 2, 441,
  118853. _vq_lengthlist__16c1_s_p9_2,
  118854. 1, -529268736, 1611661312, 5, 0,
  118855. _vq_quantlist__16c1_s_p9_2,
  118856. NULL,
  118857. &_vq_auxt__16c1_s_p9_2,
  118858. NULL,
  118859. 0
  118860. };
  118861. static long _huff_lengthlist__16c1_s_short[] = {
  118862. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  118863. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  118864. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  118865. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  118866. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  118867. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  118868. 9, 9,10,13,
  118869. };
  118870. static static_codebook _huff_book__16c1_s_short = {
  118871. 2, 100,
  118872. _huff_lengthlist__16c1_s_short,
  118873. 0, 0, 0, 0, 0,
  118874. NULL,
  118875. NULL,
  118876. NULL,
  118877. NULL,
  118878. 0
  118879. };
  118880. static long _huff_lengthlist__16c2_s_long[] = {
  118881. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  118882. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  118883. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  118884. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  118885. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  118886. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  118887. 14,14,16,18,
  118888. };
  118889. static static_codebook _huff_book__16c2_s_long = {
  118890. 2, 100,
  118891. _huff_lengthlist__16c2_s_long,
  118892. 0, 0, 0, 0, 0,
  118893. NULL,
  118894. NULL,
  118895. NULL,
  118896. NULL,
  118897. 0
  118898. };
  118899. static long _vq_quantlist__16c2_s_p1_0[] = {
  118900. 1,
  118901. 0,
  118902. 2,
  118903. };
  118904. static long _vq_lengthlist__16c2_s_p1_0[] = {
  118905. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  118906. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118910. 0,
  118911. };
  118912. static float _vq_quantthresh__16c2_s_p1_0[] = {
  118913. -0.5, 0.5,
  118914. };
  118915. static long _vq_quantmap__16c2_s_p1_0[] = {
  118916. 1, 0, 2,
  118917. };
  118918. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  118919. _vq_quantthresh__16c2_s_p1_0,
  118920. _vq_quantmap__16c2_s_p1_0,
  118921. 3,
  118922. 3
  118923. };
  118924. static static_codebook _16c2_s_p1_0 = {
  118925. 4, 81,
  118926. _vq_lengthlist__16c2_s_p1_0,
  118927. 1, -535822336, 1611661312, 2, 0,
  118928. _vq_quantlist__16c2_s_p1_0,
  118929. NULL,
  118930. &_vq_auxt__16c2_s_p1_0,
  118931. NULL,
  118932. 0
  118933. };
  118934. static long _vq_quantlist__16c2_s_p2_0[] = {
  118935. 2,
  118936. 1,
  118937. 3,
  118938. 0,
  118939. 4,
  118940. };
  118941. static long _vq_lengthlist__16c2_s_p2_0[] = {
  118942. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  118943. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  118944. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  118945. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  118946. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  118947. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  118948. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  118949. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  118950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118954. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  118955. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  118956. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  118957. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  118958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118962. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  118963. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  118964. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  118965. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118970. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  118971. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  118972. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  118973. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  118978. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  118979. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  118980. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  118981. 13,
  118982. };
  118983. static float _vq_quantthresh__16c2_s_p2_0[] = {
  118984. -1.5, -0.5, 0.5, 1.5,
  118985. };
  118986. static long _vq_quantmap__16c2_s_p2_0[] = {
  118987. 3, 1, 0, 2, 4,
  118988. };
  118989. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  118990. _vq_quantthresh__16c2_s_p2_0,
  118991. _vq_quantmap__16c2_s_p2_0,
  118992. 5,
  118993. 5
  118994. };
  118995. static static_codebook _16c2_s_p2_0 = {
  118996. 4, 625,
  118997. _vq_lengthlist__16c2_s_p2_0,
  118998. 1, -533725184, 1611661312, 3, 0,
  118999. _vq_quantlist__16c2_s_p2_0,
  119000. NULL,
  119001. &_vq_auxt__16c2_s_p2_0,
  119002. NULL,
  119003. 0
  119004. };
  119005. static long _vq_quantlist__16c2_s_p3_0[] = {
  119006. 4,
  119007. 3,
  119008. 5,
  119009. 2,
  119010. 6,
  119011. 1,
  119012. 7,
  119013. 0,
  119014. 8,
  119015. };
  119016. static long _vq_lengthlist__16c2_s_p3_0[] = {
  119017. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  119018. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  119019. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  119020. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  119021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119022. 0,
  119023. };
  119024. static float _vq_quantthresh__16c2_s_p3_0[] = {
  119025. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119026. };
  119027. static long _vq_quantmap__16c2_s_p3_0[] = {
  119028. 7, 5, 3, 1, 0, 2, 4, 6,
  119029. 8,
  119030. };
  119031. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  119032. _vq_quantthresh__16c2_s_p3_0,
  119033. _vq_quantmap__16c2_s_p3_0,
  119034. 9,
  119035. 9
  119036. };
  119037. static static_codebook _16c2_s_p3_0 = {
  119038. 2, 81,
  119039. _vq_lengthlist__16c2_s_p3_0,
  119040. 1, -531628032, 1611661312, 4, 0,
  119041. _vq_quantlist__16c2_s_p3_0,
  119042. NULL,
  119043. &_vq_auxt__16c2_s_p3_0,
  119044. NULL,
  119045. 0
  119046. };
  119047. static long _vq_quantlist__16c2_s_p4_0[] = {
  119048. 8,
  119049. 7,
  119050. 9,
  119051. 6,
  119052. 10,
  119053. 5,
  119054. 11,
  119055. 4,
  119056. 12,
  119057. 3,
  119058. 13,
  119059. 2,
  119060. 14,
  119061. 1,
  119062. 15,
  119063. 0,
  119064. 16,
  119065. };
  119066. static long _vq_lengthlist__16c2_s_p4_0[] = {
  119067. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  119068. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  119069. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  119070. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  119071. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  119072. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  119073. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  119074. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  119075. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  119076. 9,10,10,11,11,12,12,12,12, 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,
  119086. };
  119087. static float _vq_quantthresh__16c2_s_p4_0[] = {
  119088. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  119089. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  119090. };
  119091. static long _vq_quantmap__16c2_s_p4_0[] = {
  119092. 15, 13, 11, 9, 7, 5, 3, 1,
  119093. 0, 2, 4, 6, 8, 10, 12, 14,
  119094. 16,
  119095. };
  119096. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  119097. _vq_quantthresh__16c2_s_p4_0,
  119098. _vq_quantmap__16c2_s_p4_0,
  119099. 17,
  119100. 17
  119101. };
  119102. static static_codebook _16c2_s_p4_0 = {
  119103. 2, 289,
  119104. _vq_lengthlist__16c2_s_p4_0,
  119105. 1, -529530880, 1611661312, 5, 0,
  119106. _vq_quantlist__16c2_s_p4_0,
  119107. NULL,
  119108. &_vq_auxt__16c2_s_p4_0,
  119109. NULL,
  119110. 0
  119111. };
  119112. static long _vq_quantlist__16c2_s_p5_0[] = {
  119113. 1,
  119114. 0,
  119115. 2,
  119116. };
  119117. static long _vq_lengthlist__16c2_s_p5_0[] = {
  119118. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  119119. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  119120. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  119121. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  119122. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  119123. 12,
  119124. };
  119125. static float _vq_quantthresh__16c2_s_p5_0[] = {
  119126. -5.5, 5.5,
  119127. };
  119128. static long _vq_quantmap__16c2_s_p5_0[] = {
  119129. 1, 0, 2,
  119130. };
  119131. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  119132. _vq_quantthresh__16c2_s_p5_0,
  119133. _vq_quantmap__16c2_s_p5_0,
  119134. 3,
  119135. 3
  119136. };
  119137. static static_codebook _16c2_s_p5_0 = {
  119138. 4, 81,
  119139. _vq_lengthlist__16c2_s_p5_0,
  119140. 1, -529137664, 1618345984, 2, 0,
  119141. _vq_quantlist__16c2_s_p5_0,
  119142. NULL,
  119143. &_vq_auxt__16c2_s_p5_0,
  119144. NULL,
  119145. 0
  119146. };
  119147. static long _vq_quantlist__16c2_s_p5_1[] = {
  119148. 5,
  119149. 4,
  119150. 6,
  119151. 3,
  119152. 7,
  119153. 2,
  119154. 8,
  119155. 1,
  119156. 9,
  119157. 0,
  119158. 10,
  119159. };
  119160. static long _vq_lengthlist__16c2_s_p5_1[] = {
  119161. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  119162. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  119163. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  119164. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  119165. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  119166. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  119167. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  119168. 11,11,11, 7, 7, 8, 8, 8, 8,
  119169. };
  119170. static float _vq_quantthresh__16c2_s_p5_1[] = {
  119171. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  119172. 3.5, 4.5,
  119173. };
  119174. static long _vq_quantmap__16c2_s_p5_1[] = {
  119175. 9, 7, 5, 3, 1, 0, 2, 4,
  119176. 6, 8, 10,
  119177. };
  119178. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  119179. _vq_quantthresh__16c2_s_p5_1,
  119180. _vq_quantmap__16c2_s_p5_1,
  119181. 11,
  119182. 11
  119183. };
  119184. static static_codebook _16c2_s_p5_1 = {
  119185. 2, 121,
  119186. _vq_lengthlist__16c2_s_p5_1,
  119187. 1, -531365888, 1611661312, 4, 0,
  119188. _vq_quantlist__16c2_s_p5_1,
  119189. NULL,
  119190. &_vq_auxt__16c2_s_p5_1,
  119191. NULL,
  119192. 0
  119193. };
  119194. static long _vq_quantlist__16c2_s_p6_0[] = {
  119195. 6,
  119196. 5,
  119197. 7,
  119198. 4,
  119199. 8,
  119200. 3,
  119201. 9,
  119202. 2,
  119203. 10,
  119204. 1,
  119205. 11,
  119206. 0,
  119207. 12,
  119208. };
  119209. static long _vq_lengthlist__16c2_s_p6_0[] = {
  119210. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  119211. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  119212. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  119213. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  119214. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  119215. 12, 8, 8,10,10,11,11,12,12,13,13, 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,
  119221. };
  119222. static float _vq_quantthresh__16c2_s_p6_0[] = {
  119223. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  119224. 12.5, 17.5, 22.5, 27.5,
  119225. };
  119226. static long _vq_quantmap__16c2_s_p6_0[] = {
  119227. 11, 9, 7, 5, 3, 1, 0, 2,
  119228. 4, 6, 8, 10, 12,
  119229. };
  119230. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  119231. _vq_quantthresh__16c2_s_p6_0,
  119232. _vq_quantmap__16c2_s_p6_0,
  119233. 13,
  119234. 13
  119235. };
  119236. static static_codebook _16c2_s_p6_0 = {
  119237. 2, 169,
  119238. _vq_lengthlist__16c2_s_p6_0,
  119239. 1, -526516224, 1616117760, 4, 0,
  119240. _vq_quantlist__16c2_s_p6_0,
  119241. NULL,
  119242. &_vq_auxt__16c2_s_p6_0,
  119243. NULL,
  119244. 0
  119245. };
  119246. static long _vq_quantlist__16c2_s_p6_1[] = {
  119247. 2,
  119248. 1,
  119249. 3,
  119250. 0,
  119251. 4,
  119252. };
  119253. static long _vq_lengthlist__16c2_s_p6_1[] = {
  119254. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  119255. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  119256. };
  119257. static float _vq_quantthresh__16c2_s_p6_1[] = {
  119258. -1.5, -0.5, 0.5, 1.5,
  119259. };
  119260. static long _vq_quantmap__16c2_s_p6_1[] = {
  119261. 3, 1, 0, 2, 4,
  119262. };
  119263. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  119264. _vq_quantthresh__16c2_s_p6_1,
  119265. _vq_quantmap__16c2_s_p6_1,
  119266. 5,
  119267. 5
  119268. };
  119269. static static_codebook _16c2_s_p6_1 = {
  119270. 2, 25,
  119271. _vq_lengthlist__16c2_s_p6_1,
  119272. 1, -533725184, 1611661312, 3, 0,
  119273. _vq_quantlist__16c2_s_p6_1,
  119274. NULL,
  119275. &_vq_auxt__16c2_s_p6_1,
  119276. NULL,
  119277. 0
  119278. };
  119279. static long _vq_quantlist__16c2_s_p7_0[] = {
  119280. 6,
  119281. 5,
  119282. 7,
  119283. 4,
  119284. 8,
  119285. 3,
  119286. 9,
  119287. 2,
  119288. 10,
  119289. 1,
  119290. 11,
  119291. 0,
  119292. 12,
  119293. };
  119294. static long _vq_lengthlist__16c2_s_p7_0[] = {
  119295. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  119296. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  119297. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  119298. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  119299. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  119300. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  119301. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  119302. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  119303. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  119304. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  119305. 18,13,14,13,13,14,13,15,14,
  119306. };
  119307. static float _vq_quantthresh__16c2_s_p7_0[] = {
  119308. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  119309. 27.5, 38.5, 49.5, 60.5,
  119310. };
  119311. static long _vq_quantmap__16c2_s_p7_0[] = {
  119312. 11, 9, 7, 5, 3, 1, 0, 2,
  119313. 4, 6, 8, 10, 12,
  119314. };
  119315. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  119316. _vq_quantthresh__16c2_s_p7_0,
  119317. _vq_quantmap__16c2_s_p7_0,
  119318. 13,
  119319. 13
  119320. };
  119321. static static_codebook _16c2_s_p7_0 = {
  119322. 2, 169,
  119323. _vq_lengthlist__16c2_s_p7_0,
  119324. 1, -523206656, 1618345984, 4, 0,
  119325. _vq_quantlist__16c2_s_p7_0,
  119326. NULL,
  119327. &_vq_auxt__16c2_s_p7_0,
  119328. NULL,
  119329. 0
  119330. };
  119331. static long _vq_quantlist__16c2_s_p7_1[] = {
  119332. 5,
  119333. 4,
  119334. 6,
  119335. 3,
  119336. 7,
  119337. 2,
  119338. 8,
  119339. 1,
  119340. 9,
  119341. 0,
  119342. 10,
  119343. };
  119344. static long _vq_lengthlist__16c2_s_p7_1[] = {
  119345. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  119346. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  119347. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  119348. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  119349. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  119350. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  119351. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  119352. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  119353. };
  119354. static float _vq_quantthresh__16c2_s_p7_1[] = {
  119355. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  119356. 3.5, 4.5,
  119357. };
  119358. static long _vq_quantmap__16c2_s_p7_1[] = {
  119359. 9, 7, 5, 3, 1, 0, 2, 4,
  119360. 6, 8, 10,
  119361. };
  119362. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  119363. _vq_quantthresh__16c2_s_p7_1,
  119364. _vq_quantmap__16c2_s_p7_1,
  119365. 11,
  119366. 11
  119367. };
  119368. static static_codebook _16c2_s_p7_1 = {
  119369. 2, 121,
  119370. _vq_lengthlist__16c2_s_p7_1,
  119371. 1, -531365888, 1611661312, 4, 0,
  119372. _vq_quantlist__16c2_s_p7_1,
  119373. NULL,
  119374. &_vq_auxt__16c2_s_p7_1,
  119375. NULL,
  119376. 0
  119377. };
  119378. static long _vq_quantlist__16c2_s_p8_0[] = {
  119379. 7,
  119380. 6,
  119381. 8,
  119382. 5,
  119383. 9,
  119384. 4,
  119385. 10,
  119386. 3,
  119387. 11,
  119388. 2,
  119389. 12,
  119390. 1,
  119391. 13,
  119392. 0,
  119393. 14,
  119394. };
  119395. static long _vq_lengthlist__16c2_s_p8_0[] = {
  119396. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  119397. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  119398. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  119399. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  119400. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  119401. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  119402. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  119403. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  119404. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  119405. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  119406. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  119407. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  119408. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  119409. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  119410. 13,
  119411. };
  119412. static float _vq_quantthresh__16c2_s_p8_0[] = {
  119413. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  119414. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  119415. };
  119416. static long _vq_quantmap__16c2_s_p8_0[] = {
  119417. 13, 11, 9, 7, 5, 3, 1, 0,
  119418. 2, 4, 6, 8, 10, 12, 14,
  119419. };
  119420. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  119421. _vq_quantthresh__16c2_s_p8_0,
  119422. _vq_quantmap__16c2_s_p8_0,
  119423. 15,
  119424. 15
  119425. };
  119426. static static_codebook _16c2_s_p8_0 = {
  119427. 2, 225,
  119428. _vq_lengthlist__16c2_s_p8_0,
  119429. 1, -520986624, 1620377600, 4, 0,
  119430. _vq_quantlist__16c2_s_p8_0,
  119431. NULL,
  119432. &_vq_auxt__16c2_s_p8_0,
  119433. NULL,
  119434. 0
  119435. };
  119436. static long _vq_quantlist__16c2_s_p8_1[] = {
  119437. 10,
  119438. 9,
  119439. 11,
  119440. 8,
  119441. 12,
  119442. 7,
  119443. 13,
  119444. 6,
  119445. 14,
  119446. 5,
  119447. 15,
  119448. 4,
  119449. 16,
  119450. 3,
  119451. 17,
  119452. 2,
  119453. 18,
  119454. 1,
  119455. 19,
  119456. 0,
  119457. 20,
  119458. };
  119459. static long _vq_lengthlist__16c2_s_p8_1[] = {
  119460. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  119461. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  119462. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  119463. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  119464. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  119465. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  119466. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  119467. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  119468. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  119469. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  119470. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  119471. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  119472. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  119473. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  119474. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  119475. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  119476. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  119477. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  119478. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  119479. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  119480. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  119481. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  119482. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  119483. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  119484. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  119485. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  119486. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  119487. 10,11,10,10,10,10,10,10,10,
  119488. };
  119489. static float _vq_quantthresh__16c2_s_p8_1[] = {
  119490. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  119491. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  119492. 6.5, 7.5, 8.5, 9.5,
  119493. };
  119494. static long _vq_quantmap__16c2_s_p8_1[] = {
  119495. 19, 17, 15, 13, 11, 9, 7, 5,
  119496. 3, 1, 0, 2, 4, 6, 8, 10,
  119497. 12, 14, 16, 18, 20,
  119498. };
  119499. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  119500. _vq_quantthresh__16c2_s_p8_1,
  119501. _vq_quantmap__16c2_s_p8_1,
  119502. 21,
  119503. 21
  119504. };
  119505. static static_codebook _16c2_s_p8_1 = {
  119506. 2, 441,
  119507. _vq_lengthlist__16c2_s_p8_1,
  119508. 1, -529268736, 1611661312, 5, 0,
  119509. _vq_quantlist__16c2_s_p8_1,
  119510. NULL,
  119511. &_vq_auxt__16c2_s_p8_1,
  119512. NULL,
  119513. 0
  119514. };
  119515. static long _vq_quantlist__16c2_s_p9_0[] = {
  119516. 6,
  119517. 5,
  119518. 7,
  119519. 4,
  119520. 8,
  119521. 3,
  119522. 9,
  119523. 2,
  119524. 10,
  119525. 1,
  119526. 11,
  119527. 0,
  119528. 12,
  119529. };
  119530. static long _vq_lengthlist__16c2_s_p9_0[] = {
  119531. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119532. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119533. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119534. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119535. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119536. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119537. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119538. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119539. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119540. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119541. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119542. };
  119543. static float _vq_quantthresh__16c2_s_p9_0[] = {
  119544. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  119545. 2327.5, 3258.5, 4189.5, 5120.5,
  119546. };
  119547. static long _vq_quantmap__16c2_s_p9_0[] = {
  119548. 11, 9, 7, 5, 3, 1, 0, 2,
  119549. 4, 6, 8, 10, 12,
  119550. };
  119551. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  119552. _vq_quantthresh__16c2_s_p9_0,
  119553. _vq_quantmap__16c2_s_p9_0,
  119554. 13,
  119555. 13
  119556. };
  119557. static static_codebook _16c2_s_p9_0 = {
  119558. 2, 169,
  119559. _vq_lengthlist__16c2_s_p9_0,
  119560. 1, -510275072, 1631393792, 4, 0,
  119561. _vq_quantlist__16c2_s_p9_0,
  119562. NULL,
  119563. &_vq_auxt__16c2_s_p9_0,
  119564. NULL,
  119565. 0
  119566. };
  119567. static long _vq_quantlist__16c2_s_p9_1[] = {
  119568. 8,
  119569. 7,
  119570. 9,
  119571. 6,
  119572. 10,
  119573. 5,
  119574. 11,
  119575. 4,
  119576. 12,
  119577. 3,
  119578. 13,
  119579. 2,
  119580. 14,
  119581. 1,
  119582. 15,
  119583. 0,
  119584. 16,
  119585. };
  119586. static long _vq_lengthlist__16c2_s_p9_1[] = {
  119587. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  119588. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  119589. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  119590. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  119591. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  119592. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  119593. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  119594. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  119595. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  119596. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  119597. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119598. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119599. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119600. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119601. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119602. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  119603. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  119604. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119605. 10,
  119606. };
  119607. static float _vq_quantthresh__16c2_s_p9_1[] = {
  119608. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  119609. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  119610. };
  119611. static long _vq_quantmap__16c2_s_p9_1[] = {
  119612. 15, 13, 11, 9, 7, 5, 3, 1,
  119613. 0, 2, 4, 6, 8, 10, 12, 14,
  119614. 16,
  119615. };
  119616. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  119617. _vq_quantthresh__16c2_s_p9_1,
  119618. _vq_quantmap__16c2_s_p9_1,
  119619. 17,
  119620. 17
  119621. };
  119622. static static_codebook _16c2_s_p9_1 = {
  119623. 2, 289,
  119624. _vq_lengthlist__16c2_s_p9_1,
  119625. 1, -518488064, 1622704128, 5, 0,
  119626. _vq_quantlist__16c2_s_p9_1,
  119627. NULL,
  119628. &_vq_auxt__16c2_s_p9_1,
  119629. NULL,
  119630. 0
  119631. };
  119632. static long _vq_quantlist__16c2_s_p9_2[] = {
  119633. 13,
  119634. 12,
  119635. 14,
  119636. 11,
  119637. 15,
  119638. 10,
  119639. 16,
  119640. 9,
  119641. 17,
  119642. 8,
  119643. 18,
  119644. 7,
  119645. 19,
  119646. 6,
  119647. 20,
  119648. 5,
  119649. 21,
  119650. 4,
  119651. 22,
  119652. 3,
  119653. 23,
  119654. 2,
  119655. 24,
  119656. 1,
  119657. 25,
  119658. 0,
  119659. 26,
  119660. };
  119661. static long _vq_lengthlist__16c2_s_p9_2[] = {
  119662. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  119663. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  119664. };
  119665. static float _vq_quantthresh__16c2_s_p9_2[] = {
  119666. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  119667. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  119668. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  119669. 11.5, 12.5,
  119670. };
  119671. static long _vq_quantmap__16c2_s_p9_2[] = {
  119672. 25, 23, 21, 19, 17, 15, 13, 11,
  119673. 9, 7, 5, 3, 1, 0, 2, 4,
  119674. 6, 8, 10, 12, 14, 16, 18, 20,
  119675. 22, 24, 26,
  119676. };
  119677. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  119678. _vq_quantthresh__16c2_s_p9_2,
  119679. _vq_quantmap__16c2_s_p9_2,
  119680. 27,
  119681. 27
  119682. };
  119683. static static_codebook _16c2_s_p9_2 = {
  119684. 1, 27,
  119685. _vq_lengthlist__16c2_s_p9_2,
  119686. 1, -528875520, 1611661312, 5, 0,
  119687. _vq_quantlist__16c2_s_p9_2,
  119688. NULL,
  119689. &_vq_auxt__16c2_s_p9_2,
  119690. NULL,
  119691. 0
  119692. };
  119693. static long _huff_lengthlist__16c2_s_short[] = {
  119694. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  119695. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  119696. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  119697. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  119698. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  119699. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  119700. 15,12,14,14,
  119701. };
  119702. static static_codebook _huff_book__16c2_s_short = {
  119703. 2, 100,
  119704. _huff_lengthlist__16c2_s_short,
  119705. 0, 0, 0, 0, 0,
  119706. NULL,
  119707. NULL,
  119708. NULL,
  119709. NULL,
  119710. 0
  119711. };
  119712. static long _vq_quantlist__8c0_s_p1_0[] = {
  119713. 1,
  119714. 0,
  119715. 2,
  119716. };
  119717. static long _vq_lengthlist__8c0_s_p1_0[] = {
  119718. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  119719. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119723. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  119724. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119728. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  119729. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  119764. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  119765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  119769. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  119770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  119774. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  119775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119809. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  119810. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119814. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  119815. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  119816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119819. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  119820. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  119821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120128. 0,
  120129. };
  120130. static float _vq_quantthresh__8c0_s_p1_0[] = {
  120131. -0.5, 0.5,
  120132. };
  120133. static long _vq_quantmap__8c0_s_p1_0[] = {
  120134. 1, 0, 2,
  120135. };
  120136. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  120137. _vq_quantthresh__8c0_s_p1_0,
  120138. _vq_quantmap__8c0_s_p1_0,
  120139. 3,
  120140. 3
  120141. };
  120142. static static_codebook _8c0_s_p1_0 = {
  120143. 8, 6561,
  120144. _vq_lengthlist__8c0_s_p1_0,
  120145. 1, -535822336, 1611661312, 2, 0,
  120146. _vq_quantlist__8c0_s_p1_0,
  120147. NULL,
  120148. &_vq_auxt__8c0_s_p1_0,
  120149. NULL,
  120150. 0
  120151. };
  120152. static long _vq_quantlist__8c0_s_p2_0[] = {
  120153. 2,
  120154. 1,
  120155. 3,
  120156. 0,
  120157. 4,
  120158. };
  120159. static long _vq_lengthlist__8c0_s_p2_0[] = {
  120160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120185. 0, 0, 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,
  120200. };
  120201. static float _vq_quantthresh__8c0_s_p2_0[] = {
  120202. -1.5, -0.5, 0.5, 1.5,
  120203. };
  120204. static long _vq_quantmap__8c0_s_p2_0[] = {
  120205. 3, 1, 0, 2, 4,
  120206. };
  120207. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  120208. _vq_quantthresh__8c0_s_p2_0,
  120209. _vq_quantmap__8c0_s_p2_0,
  120210. 5,
  120211. 5
  120212. };
  120213. static static_codebook _8c0_s_p2_0 = {
  120214. 4, 625,
  120215. _vq_lengthlist__8c0_s_p2_0,
  120216. 1, -533725184, 1611661312, 3, 0,
  120217. _vq_quantlist__8c0_s_p2_0,
  120218. NULL,
  120219. &_vq_auxt__8c0_s_p2_0,
  120220. NULL,
  120221. 0
  120222. };
  120223. static long _vq_quantlist__8c0_s_p3_0[] = {
  120224. 2,
  120225. 1,
  120226. 3,
  120227. 0,
  120228. 4,
  120229. };
  120230. static long _vq_lengthlist__8c0_s_p3_0[] = {
  120231. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  120233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120234. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  120236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120237. 0, 0, 0, 0, 6, 7, 7, 8, 8, 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,
  120271. };
  120272. static float _vq_quantthresh__8c0_s_p3_0[] = {
  120273. -1.5, -0.5, 0.5, 1.5,
  120274. };
  120275. static long _vq_quantmap__8c0_s_p3_0[] = {
  120276. 3, 1, 0, 2, 4,
  120277. };
  120278. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  120279. _vq_quantthresh__8c0_s_p3_0,
  120280. _vq_quantmap__8c0_s_p3_0,
  120281. 5,
  120282. 5
  120283. };
  120284. static static_codebook _8c0_s_p3_0 = {
  120285. 4, 625,
  120286. _vq_lengthlist__8c0_s_p3_0,
  120287. 1, -533725184, 1611661312, 3, 0,
  120288. _vq_quantlist__8c0_s_p3_0,
  120289. NULL,
  120290. &_vq_auxt__8c0_s_p3_0,
  120291. NULL,
  120292. 0
  120293. };
  120294. static long _vq_quantlist__8c0_s_p4_0[] = {
  120295. 4,
  120296. 3,
  120297. 5,
  120298. 2,
  120299. 6,
  120300. 1,
  120301. 7,
  120302. 0,
  120303. 8,
  120304. };
  120305. static long _vq_lengthlist__8c0_s_p4_0[] = {
  120306. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  120307. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  120308. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  120309. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  120310. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120311. 0,
  120312. };
  120313. static float _vq_quantthresh__8c0_s_p4_0[] = {
  120314. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120315. };
  120316. static long _vq_quantmap__8c0_s_p4_0[] = {
  120317. 7, 5, 3, 1, 0, 2, 4, 6,
  120318. 8,
  120319. };
  120320. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  120321. _vq_quantthresh__8c0_s_p4_0,
  120322. _vq_quantmap__8c0_s_p4_0,
  120323. 9,
  120324. 9
  120325. };
  120326. static static_codebook _8c0_s_p4_0 = {
  120327. 2, 81,
  120328. _vq_lengthlist__8c0_s_p4_0,
  120329. 1, -531628032, 1611661312, 4, 0,
  120330. _vq_quantlist__8c0_s_p4_0,
  120331. NULL,
  120332. &_vq_auxt__8c0_s_p4_0,
  120333. NULL,
  120334. 0
  120335. };
  120336. static long _vq_quantlist__8c0_s_p5_0[] = {
  120337. 4,
  120338. 3,
  120339. 5,
  120340. 2,
  120341. 6,
  120342. 1,
  120343. 7,
  120344. 0,
  120345. 8,
  120346. };
  120347. static long _vq_lengthlist__8c0_s_p5_0[] = {
  120348. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  120349. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  120350. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  120351. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  120352. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  120353. 10,
  120354. };
  120355. static float _vq_quantthresh__8c0_s_p5_0[] = {
  120356. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120357. };
  120358. static long _vq_quantmap__8c0_s_p5_0[] = {
  120359. 7, 5, 3, 1, 0, 2, 4, 6,
  120360. 8,
  120361. };
  120362. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  120363. _vq_quantthresh__8c0_s_p5_0,
  120364. _vq_quantmap__8c0_s_p5_0,
  120365. 9,
  120366. 9
  120367. };
  120368. static static_codebook _8c0_s_p5_0 = {
  120369. 2, 81,
  120370. _vq_lengthlist__8c0_s_p5_0,
  120371. 1, -531628032, 1611661312, 4, 0,
  120372. _vq_quantlist__8c0_s_p5_0,
  120373. NULL,
  120374. &_vq_auxt__8c0_s_p5_0,
  120375. NULL,
  120376. 0
  120377. };
  120378. static long _vq_quantlist__8c0_s_p6_0[] = {
  120379. 8,
  120380. 7,
  120381. 9,
  120382. 6,
  120383. 10,
  120384. 5,
  120385. 11,
  120386. 4,
  120387. 12,
  120388. 3,
  120389. 13,
  120390. 2,
  120391. 14,
  120392. 1,
  120393. 15,
  120394. 0,
  120395. 16,
  120396. };
  120397. static long _vq_lengthlist__8c0_s_p6_0[] = {
  120398. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  120399. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  120400. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  120401. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  120402. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  120403. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  120404. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  120405. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  120406. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  120407. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  120408. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  120409. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  120410. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  120411. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  120412. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  120413. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  120414. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  120415. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  120416. 14,
  120417. };
  120418. static float _vq_quantthresh__8c0_s_p6_0[] = {
  120419. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  120420. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  120421. };
  120422. static long _vq_quantmap__8c0_s_p6_0[] = {
  120423. 15, 13, 11, 9, 7, 5, 3, 1,
  120424. 0, 2, 4, 6, 8, 10, 12, 14,
  120425. 16,
  120426. };
  120427. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  120428. _vq_quantthresh__8c0_s_p6_0,
  120429. _vq_quantmap__8c0_s_p6_0,
  120430. 17,
  120431. 17
  120432. };
  120433. static static_codebook _8c0_s_p6_0 = {
  120434. 2, 289,
  120435. _vq_lengthlist__8c0_s_p6_0,
  120436. 1, -529530880, 1611661312, 5, 0,
  120437. _vq_quantlist__8c0_s_p6_0,
  120438. NULL,
  120439. &_vq_auxt__8c0_s_p6_0,
  120440. NULL,
  120441. 0
  120442. };
  120443. static long _vq_quantlist__8c0_s_p7_0[] = {
  120444. 1,
  120445. 0,
  120446. 2,
  120447. };
  120448. static long _vq_lengthlist__8c0_s_p7_0[] = {
  120449. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  120450. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  120451. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  120452. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  120453. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  120454. 10,
  120455. };
  120456. static float _vq_quantthresh__8c0_s_p7_0[] = {
  120457. -5.5, 5.5,
  120458. };
  120459. static long _vq_quantmap__8c0_s_p7_0[] = {
  120460. 1, 0, 2,
  120461. };
  120462. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  120463. _vq_quantthresh__8c0_s_p7_0,
  120464. _vq_quantmap__8c0_s_p7_0,
  120465. 3,
  120466. 3
  120467. };
  120468. static static_codebook _8c0_s_p7_0 = {
  120469. 4, 81,
  120470. _vq_lengthlist__8c0_s_p7_0,
  120471. 1, -529137664, 1618345984, 2, 0,
  120472. _vq_quantlist__8c0_s_p7_0,
  120473. NULL,
  120474. &_vq_auxt__8c0_s_p7_0,
  120475. NULL,
  120476. 0
  120477. };
  120478. static long _vq_quantlist__8c0_s_p7_1[] = {
  120479. 5,
  120480. 4,
  120481. 6,
  120482. 3,
  120483. 7,
  120484. 2,
  120485. 8,
  120486. 1,
  120487. 9,
  120488. 0,
  120489. 10,
  120490. };
  120491. static long _vq_lengthlist__8c0_s_p7_1[] = {
  120492. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  120493. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  120494. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  120495. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  120496. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  120497. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  120498. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  120499. 10,10,10, 9, 9, 9,10,10,10,
  120500. };
  120501. static float _vq_quantthresh__8c0_s_p7_1[] = {
  120502. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120503. 3.5, 4.5,
  120504. };
  120505. static long _vq_quantmap__8c0_s_p7_1[] = {
  120506. 9, 7, 5, 3, 1, 0, 2, 4,
  120507. 6, 8, 10,
  120508. };
  120509. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  120510. _vq_quantthresh__8c0_s_p7_1,
  120511. _vq_quantmap__8c0_s_p7_1,
  120512. 11,
  120513. 11
  120514. };
  120515. static static_codebook _8c0_s_p7_1 = {
  120516. 2, 121,
  120517. _vq_lengthlist__8c0_s_p7_1,
  120518. 1, -531365888, 1611661312, 4, 0,
  120519. _vq_quantlist__8c0_s_p7_1,
  120520. NULL,
  120521. &_vq_auxt__8c0_s_p7_1,
  120522. NULL,
  120523. 0
  120524. };
  120525. static long _vq_quantlist__8c0_s_p8_0[] = {
  120526. 6,
  120527. 5,
  120528. 7,
  120529. 4,
  120530. 8,
  120531. 3,
  120532. 9,
  120533. 2,
  120534. 10,
  120535. 1,
  120536. 11,
  120537. 0,
  120538. 12,
  120539. };
  120540. static long _vq_lengthlist__8c0_s_p8_0[] = {
  120541. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  120542. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  120543. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  120544. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  120545. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  120546. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  120547. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  120548. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  120549. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  120550. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  120551. 0, 0,13,13,11,13,13,11,12,
  120552. };
  120553. static float _vq_quantthresh__8c0_s_p8_0[] = {
  120554. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  120555. 12.5, 17.5, 22.5, 27.5,
  120556. };
  120557. static long _vq_quantmap__8c0_s_p8_0[] = {
  120558. 11, 9, 7, 5, 3, 1, 0, 2,
  120559. 4, 6, 8, 10, 12,
  120560. };
  120561. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  120562. _vq_quantthresh__8c0_s_p8_0,
  120563. _vq_quantmap__8c0_s_p8_0,
  120564. 13,
  120565. 13
  120566. };
  120567. static static_codebook _8c0_s_p8_0 = {
  120568. 2, 169,
  120569. _vq_lengthlist__8c0_s_p8_0,
  120570. 1, -526516224, 1616117760, 4, 0,
  120571. _vq_quantlist__8c0_s_p8_0,
  120572. NULL,
  120573. &_vq_auxt__8c0_s_p8_0,
  120574. NULL,
  120575. 0
  120576. };
  120577. static long _vq_quantlist__8c0_s_p8_1[] = {
  120578. 2,
  120579. 1,
  120580. 3,
  120581. 0,
  120582. 4,
  120583. };
  120584. static long _vq_lengthlist__8c0_s_p8_1[] = {
  120585. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  120586. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  120587. };
  120588. static float _vq_quantthresh__8c0_s_p8_1[] = {
  120589. -1.5, -0.5, 0.5, 1.5,
  120590. };
  120591. static long _vq_quantmap__8c0_s_p8_1[] = {
  120592. 3, 1, 0, 2, 4,
  120593. };
  120594. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  120595. _vq_quantthresh__8c0_s_p8_1,
  120596. _vq_quantmap__8c0_s_p8_1,
  120597. 5,
  120598. 5
  120599. };
  120600. static static_codebook _8c0_s_p8_1 = {
  120601. 2, 25,
  120602. _vq_lengthlist__8c0_s_p8_1,
  120603. 1, -533725184, 1611661312, 3, 0,
  120604. _vq_quantlist__8c0_s_p8_1,
  120605. NULL,
  120606. &_vq_auxt__8c0_s_p8_1,
  120607. NULL,
  120608. 0
  120609. };
  120610. static long _vq_quantlist__8c0_s_p9_0[] = {
  120611. 1,
  120612. 0,
  120613. 2,
  120614. };
  120615. static long _vq_lengthlist__8c0_s_p9_0[] = {
  120616. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120617. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120618. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120619. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120620. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120621. 7,
  120622. };
  120623. static float _vq_quantthresh__8c0_s_p9_0[] = {
  120624. -157.5, 157.5,
  120625. };
  120626. static long _vq_quantmap__8c0_s_p9_0[] = {
  120627. 1, 0, 2,
  120628. };
  120629. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  120630. _vq_quantthresh__8c0_s_p9_0,
  120631. _vq_quantmap__8c0_s_p9_0,
  120632. 3,
  120633. 3
  120634. };
  120635. static static_codebook _8c0_s_p9_0 = {
  120636. 4, 81,
  120637. _vq_lengthlist__8c0_s_p9_0,
  120638. 1, -518803456, 1628680192, 2, 0,
  120639. _vq_quantlist__8c0_s_p9_0,
  120640. NULL,
  120641. &_vq_auxt__8c0_s_p9_0,
  120642. NULL,
  120643. 0
  120644. };
  120645. static long _vq_quantlist__8c0_s_p9_1[] = {
  120646. 7,
  120647. 6,
  120648. 8,
  120649. 5,
  120650. 9,
  120651. 4,
  120652. 10,
  120653. 3,
  120654. 11,
  120655. 2,
  120656. 12,
  120657. 1,
  120658. 13,
  120659. 0,
  120660. 14,
  120661. };
  120662. static long _vq_lengthlist__8c0_s_p9_1[] = {
  120663. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  120664. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  120665. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  120666. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  120667. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  120668. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  120669. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120670. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120671. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120672. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120673. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120674. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120675. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120676. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120677. 11,
  120678. };
  120679. static float _vq_quantthresh__8c0_s_p9_1[] = {
  120680. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  120681. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  120682. };
  120683. static long _vq_quantmap__8c0_s_p9_1[] = {
  120684. 13, 11, 9, 7, 5, 3, 1, 0,
  120685. 2, 4, 6, 8, 10, 12, 14,
  120686. };
  120687. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  120688. _vq_quantthresh__8c0_s_p9_1,
  120689. _vq_quantmap__8c0_s_p9_1,
  120690. 15,
  120691. 15
  120692. };
  120693. static static_codebook _8c0_s_p9_1 = {
  120694. 2, 225,
  120695. _vq_lengthlist__8c0_s_p9_1,
  120696. 1, -520986624, 1620377600, 4, 0,
  120697. _vq_quantlist__8c0_s_p9_1,
  120698. NULL,
  120699. &_vq_auxt__8c0_s_p9_1,
  120700. NULL,
  120701. 0
  120702. };
  120703. static long _vq_quantlist__8c0_s_p9_2[] = {
  120704. 10,
  120705. 9,
  120706. 11,
  120707. 8,
  120708. 12,
  120709. 7,
  120710. 13,
  120711. 6,
  120712. 14,
  120713. 5,
  120714. 15,
  120715. 4,
  120716. 16,
  120717. 3,
  120718. 17,
  120719. 2,
  120720. 18,
  120721. 1,
  120722. 19,
  120723. 0,
  120724. 20,
  120725. };
  120726. static long _vq_lengthlist__8c0_s_p9_2[] = {
  120727. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  120728. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  120729. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  120730. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  120731. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  120732. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  120733. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  120734. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  120735. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  120736. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  120737. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  120738. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  120739. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  120740. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  120741. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  120742. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  120743. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  120744. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  120745. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  120746. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  120747. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  120748. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  120749. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  120750. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  120751. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  120752. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  120753. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  120754. 10,11, 9,11,10, 9,10, 9,10,
  120755. };
  120756. static float _vq_quantthresh__8c0_s_p9_2[] = {
  120757. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  120758. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  120759. 6.5, 7.5, 8.5, 9.5,
  120760. };
  120761. static long _vq_quantmap__8c0_s_p9_2[] = {
  120762. 19, 17, 15, 13, 11, 9, 7, 5,
  120763. 3, 1, 0, 2, 4, 6, 8, 10,
  120764. 12, 14, 16, 18, 20,
  120765. };
  120766. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  120767. _vq_quantthresh__8c0_s_p9_2,
  120768. _vq_quantmap__8c0_s_p9_2,
  120769. 21,
  120770. 21
  120771. };
  120772. static static_codebook _8c0_s_p9_2 = {
  120773. 2, 441,
  120774. _vq_lengthlist__8c0_s_p9_2,
  120775. 1, -529268736, 1611661312, 5, 0,
  120776. _vq_quantlist__8c0_s_p9_2,
  120777. NULL,
  120778. &_vq_auxt__8c0_s_p9_2,
  120779. NULL,
  120780. 0
  120781. };
  120782. static long _huff_lengthlist__8c0_s_single[] = {
  120783. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  120784. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  120785. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  120786. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  120787. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  120788. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  120789. 17,16,17,17,
  120790. };
  120791. static static_codebook _huff_book__8c0_s_single = {
  120792. 2, 100,
  120793. _huff_lengthlist__8c0_s_single,
  120794. 0, 0, 0, 0, 0,
  120795. NULL,
  120796. NULL,
  120797. NULL,
  120798. NULL,
  120799. 0
  120800. };
  120801. static long _vq_quantlist__8c1_s_p1_0[] = {
  120802. 1,
  120803. 0,
  120804. 2,
  120805. };
  120806. static long _vq_lengthlist__8c1_s_p1_0[] = {
  120807. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  120808. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120812. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  120813. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120817. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  120818. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  120853. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  120854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  120858. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  120859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  120863. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  120864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120898. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  120899. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120903. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  120904. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  120905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120908. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  120909. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  120910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121217. 0,
  121218. };
  121219. static float _vq_quantthresh__8c1_s_p1_0[] = {
  121220. -0.5, 0.5,
  121221. };
  121222. static long _vq_quantmap__8c1_s_p1_0[] = {
  121223. 1, 0, 2,
  121224. };
  121225. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  121226. _vq_quantthresh__8c1_s_p1_0,
  121227. _vq_quantmap__8c1_s_p1_0,
  121228. 3,
  121229. 3
  121230. };
  121231. static static_codebook _8c1_s_p1_0 = {
  121232. 8, 6561,
  121233. _vq_lengthlist__8c1_s_p1_0,
  121234. 1, -535822336, 1611661312, 2, 0,
  121235. _vq_quantlist__8c1_s_p1_0,
  121236. NULL,
  121237. &_vq_auxt__8c1_s_p1_0,
  121238. NULL,
  121239. 0
  121240. };
  121241. static long _vq_quantlist__8c1_s_p2_0[] = {
  121242. 2,
  121243. 1,
  121244. 3,
  121245. 0,
  121246. 4,
  121247. };
  121248. static long _vq_lengthlist__8c1_s_p2_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, 0, 0, 0, 0, 0, 0, 0,
  121279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121288. 0,
  121289. };
  121290. static float _vq_quantthresh__8c1_s_p2_0[] = {
  121291. -1.5, -0.5, 0.5, 1.5,
  121292. };
  121293. static long _vq_quantmap__8c1_s_p2_0[] = {
  121294. 3, 1, 0, 2, 4,
  121295. };
  121296. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  121297. _vq_quantthresh__8c1_s_p2_0,
  121298. _vq_quantmap__8c1_s_p2_0,
  121299. 5,
  121300. 5
  121301. };
  121302. static static_codebook _8c1_s_p2_0 = {
  121303. 4, 625,
  121304. _vq_lengthlist__8c1_s_p2_0,
  121305. 1, -533725184, 1611661312, 3, 0,
  121306. _vq_quantlist__8c1_s_p2_0,
  121307. NULL,
  121308. &_vq_auxt__8c1_s_p2_0,
  121309. NULL,
  121310. 0
  121311. };
  121312. static long _vq_quantlist__8c1_s_p3_0[] = {
  121313. 2,
  121314. 1,
  121315. 3,
  121316. 0,
  121317. 4,
  121318. };
  121319. static long _vq_lengthlist__8c1_s_p3_0[] = {
  121320. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  121322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121323. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  121325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121326. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  121327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121359. 0,
  121360. };
  121361. static float _vq_quantthresh__8c1_s_p3_0[] = {
  121362. -1.5, -0.5, 0.5, 1.5,
  121363. };
  121364. static long _vq_quantmap__8c1_s_p3_0[] = {
  121365. 3, 1, 0, 2, 4,
  121366. };
  121367. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  121368. _vq_quantthresh__8c1_s_p3_0,
  121369. _vq_quantmap__8c1_s_p3_0,
  121370. 5,
  121371. 5
  121372. };
  121373. static static_codebook _8c1_s_p3_0 = {
  121374. 4, 625,
  121375. _vq_lengthlist__8c1_s_p3_0,
  121376. 1, -533725184, 1611661312, 3, 0,
  121377. _vq_quantlist__8c1_s_p3_0,
  121378. NULL,
  121379. &_vq_auxt__8c1_s_p3_0,
  121380. NULL,
  121381. 0
  121382. };
  121383. static long _vq_quantlist__8c1_s_p4_0[] = {
  121384. 4,
  121385. 3,
  121386. 5,
  121387. 2,
  121388. 6,
  121389. 1,
  121390. 7,
  121391. 0,
  121392. 8,
  121393. };
  121394. static long _vq_lengthlist__8c1_s_p4_0[] = {
  121395. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  121396. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  121397. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  121398. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  121399. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121400. 0,
  121401. };
  121402. static float _vq_quantthresh__8c1_s_p4_0[] = {
  121403. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121404. };
  121405. static long _vq_quantmap__8c1_s_p4_0[] = {
  121406. 7, 5, 3, 1, 0, 2, 4, 6,
  121407. 8,
  121408. };
  121409. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  121410. _vq_quantthresh__8c1_s_p4_0,
  121411. _vq_quantmap__8c1_s_p4_0,
  121412. 9,
  121413. 9
  121414. };
  121415. static static_codebook _8c1_s_p4_0 = {
  121416. 2, 81,
  121417. _vq_lengthlist__8c1_s_p4_0,
  121418. 1, -531628032, 1611661312, 4, 0,
  121419. _vq_quantlist__8c1_s_p4_0,
  121420. NULL,
  121421. &_vq_auxt__8c1_s_p4_0,
  121422. NULL,
  121423. 0
  121424. };
  121425. static long _vq_quantlist__8c1_s_p5_0[] = {
  121426. 4,
  121427. 3,
  121428. 5,
  121429. 2,
  121430. 6,
  121431. 1,
  121432. 7,
  121433. 0,
  121434. 8,
  121435. };
  121436. static long _vq_lengthlist__8c1_s_p5_0[] = {
  121437. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  121438. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  121439. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  121440. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  121441. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  121442. 10,
  121443. };
  121444. static float _vq_quantthresh__8c1_s_p5_0[] = {
  121445. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121446. };
  121447. static long _vq_quantmap__8c1_s_p5_0[] = {
  121448. 7, 5, 3, 1, 0, 2, 4, 6,
  121449. 8,
  121450. };
  121451. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  121452. _vq_quantthresh__8c1_s_p5_0,
  121453. _vq_quantmap__8c1_s_p5_0,
  121454. 9,
  121455. 9
  121456. };
  121457. static static_codebook _8c1_s_p5_0 = {
  121458. 2, 81,
  121459. _vq_lengthlist__8c1_s_p5_0,
  121460. 1, -531628032, 1611661312, 4, 0,
  121461. _vq_quantlist__8c1_s_p5_0,
  121462. NULL,
  121463. &_vq_auxt__8c1_s_p5_0,
  121464. NULL,
  121465. 0
  121466. };
  121467. static long _vq_quantlist__8c1_s_p6_0[] = {
  121468. 8,
  121469. 7,
  121470. 9,
  121471. 6,
  121472. 10,
  121473. 5,
  121474. 11,
  121475. 4,
  121476. 12,
  121477. 3,
  121478. 13,
  121479. 2,
  121480. 14,
  121481. 1,
  121482. 15,
  121483. 0,
  121484. 16,
  121485. };
  121486. static long _vq_lengthlist__8c1_s_p6_0[] = {
  121487. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  121488. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  121489. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  121490. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  121491. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  121492. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  121493. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  121494. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  121495. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  121496. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  121497. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  121498. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  121499. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  121500. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  121501. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  121502. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  121503. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  121504. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  121505. 14,
  121506. };
  121507. static float _vq_quantthresh__8c1_s_p6_0[] = {
  121508. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  121509. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  121510. };
  121511. static long _vq_quantmap__8c1_s_p6_0[] = {
  121512. 15, 13, 11, 9, 7, 5, 3, 1,
  121513. 0, 2, 4, 6, 8, 10, 12, 14,
  121514. 16,
  121515. };
  121516. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  121517. _vq_quantthresh__8c1_s_p6_0,
  121518. _vq_quantmap__8c1_s_p6_0,
  121519. 17,
  121520. 17
  121521. };
  121522. static static_codebook _8c1_s_p6_0 = {
  121523. 2, 289,
  121524. _vq_lengthlist__8c1_s_p6_0,
  121525. 1, -529530880, 1611661312, 5, 0,
  121526. _vq_quantlist__8c1_s_p6_0,
  121527. NULL,
  121528. &_vq_auxt__8c1_s_p6_0,
  121529. NULL,
  121530. 0
  121531. };
  121532. static long _vq_quantlist__8c1_s_p7_0[] = {
  121533. 1,
  121534. 0,
  121535. 2,
  121536. };
  121537. static long _vq_lengthlist__8c1_s_p7_0[] = {
  121538. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  121539. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  121540. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  121541. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  121542. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  121543. 9,
  121544. };
  121545. static float _vq_quantthresh__8c1_s_p7_0[] = {
  121546. -5.5, 5.5,
  121547. };
  121548. static long _vq_quantmap__8c1_s_p7_0[] = {
  121549. 1, 0, 2,
  121550. };
  121551. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  121552. _vq_quantthresh__8c1_s_p7_0,
  121553. _vq_quantmap__8c1_s_p7_0,
  121554. 3,
  121555. 3
  121556. };
  121557. static static_codebook _8c1_s_p7_0 = {
  121558. 4, 81,
  121559. _vq_lengthlist__8c1_s_p7_0,
  121560. 1, -529137664, 1618345984, 2, 0,
  121561. _vq_quantlist__8c1_s_p7_0,
  121562. NULL,
  121563. &_vq_auxt__8c1_s_p7_0,
  121564. NULL,
  121565. 0
  121566. };
  121567. static long _vq_quantlist__8c1_s_p7_1[] = {
  121568. 5,
  121569. 4,
  121570. 6,
  121571. 3,
  121572. 7,
  121573. 2,
  121574. 8,
  121575. 1,
  121576. 9,
  121577. 0,
  121578. 10,
  121579. };
  121580. static long _vq_lengthlist__8c1_s_p7_1[] = {
  121581. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  121582. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  121583. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  121584. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  121585. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  121586. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  121587. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  121588. 10,10,10, 8, 8, 8, 8, 8, 8,
  121589. };
  121590. static float _vq_quantthresh__8c1_s_p7_1[] = {
  121591. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  121592. 3.5, 4.5,
  121593. };
  121594. static long _vq_quantmap__8c1_s_p7_1[] = {
  121595. 9, 7, 5, 3, 1, 0, 2, 4,
  121596. 6, 8, 10,
  121597. };
  121598. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  121599. _vq_quantthresh__8c1_s_p7_1,
  121600. _vq_quantmap__8c1_s_p7_1,
  121601. 11,
  121602. 11
  121603. };
  121604. static static_codebook _8c1_s_p7_1 = {
  121605. 2, 121,
  121606. _vq_lengthlist__8c1_s_p7_1,
  121607. 1, -531365888, 1611661312, 4, 0,
  121608. _vq_quantlist__8c1_s_p7_1,
  121609. NULL,
  121610. &_vq_auxt__8c1_s_p7_1,
  121611. NULL,
  121612. 0
  121613. };
  121614. static long _vq_quantlist__8c1_s_p8_0[] = {
  121615. 6,
  121616. 5,
  121617. 7,
  121618. 4,
  121619. 8,
  121620. 3,
  121621. 9,
  121622. 2,
  121623. 10,
  121624. 1,
  121625. 11,
  121626. 0,
  121627. 12,
  121628. };
  121629. static long _vq_lengthlist__8c1_s_p8_0[] = {
  121630. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  121631. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  121632. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  121633. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  121634. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  121635. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  121636. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  121637. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  121638. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  121639. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  121640. 0,12,12,11,10,12,11,13,12,
  121641. };
  121642. static float _vq_quantthresh__8c1_s_p8_0[] = {
  121643. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  121644. 12.5, 17.5, 22.5, 27.5,
  121645. };
  121646. static long _vq_quantmap__8c1_s_p8_0[] = {
  121647. 11, 9, 7, 5, 3, 1, 0, 2,
  121648. 4, 6, 8, 10, 12,
  121649. };
  121650. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  121651. _vq_quantthresh__8c1_s_p8_0,
  121652. _vq_quantmap__8c1_s_p8_0,
  121653. 13,
  121654. 13
  121655. };
  121656. static static_codebook _8c1_s_p8_0 = {
  121657. 2, 169,
  121658. _vq_lengthlist__8c1_s_p8_0,
  121659. 1, -526516224, 1616117760, 4, 0,
  121660. _vq_quantlist__8c1_s_p8_0,
  121661. NULL,
  121662. &_vq_auxt__8c1_s_p8_0,
  121663. NULL,
  121664. 0
  121665. };
  121666. static long _vq_quantlist__8c1_s_p8_1[] = {
  121667. 2,
  121668. 1,
  121669. 3,
  121670. 0,
  121671. 4,
  121672. };
  121673. static long _vq_lengthlist__8c1_s_p8_1[] = {
  121674. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  121675. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  121676. };
  121677. static float _vq_quantthresh__8c1_s_p8_1[] = {
  121678. -1.5, -0.5, 0.5, 1.5,
  121679. };
  121680. static long _vq_quantmap__8c1_s_p8_1[] = {
  121681. 3, 1, 0, 2, 4,
  121682. };
  121683. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  121684. _vq_quantthresh__8c1_s_p8_1,
  121685. _vq_quantmap__8c1_s_p8_1,
  121686. 5,
  121687. 5
  121688. };
  121689. static static_codebook _8c1_s_p8_1 = {
  121690. 2, 25,
  121691. _vq_lengthlist__8c1_s_p8_1,
  121692. 1, -533725184, 1611661312, 3, 0,
  121693. _vq_quantlist__8c1_s_p8_1,
  121694. NULL,
  121695. &_vq_auxt__8c1_s_p8_1,
  121696. NULL,
  121697. 0
  121698. };
  121699. static long _vq_quantlist__8c1_s_p9_0[] = {
  121700. 6,
  121701. 5,
  121702. 7,
  121703. 4,
  121704. 8,
  121705. 3,
  121706. 9,
  121707. 2,
  121708. 10,
  121709. 1,
  121710. 11,
  121711. 0,
  121712. 12,
  121713. };
  121714. static long _vq_lengthlist__8c1_s_p9_0[] = {
  121715. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  121716. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  121717. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121718. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121719. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121720. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121721. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121722. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121723. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121724. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121725. 10,10,10,10,10, 9, 9, 9, 9,
  121726. };
  121727. static float _vq_quantthresh__8c1_s_p9_0[] = {
  121728. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  121729. 787.5, 1102.5, 1417.5, 1732.5,
  121730. };
  121731. static long _vq_quantmap__8c1_s_p9_0[] = {
  121732. 11, 9, 7, 5, 3, 1, 0, 2,
  121733. 4, 6, 8, 10, 12,
  121734. };
  121735. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  121736. _vq_quantthresh__8c1_s_p9_0,
  121737. _vq_quantmap__8c1_s_p9_0,
  121738. 13,
  121739. 13
  121740. };
  121741. static static_codebook _8c1_s_p9_0 = {
  121742. 2, 169,
  121743. _vq_lengthlist__8c1_s_p9_0,
  121744. 1, -513964032, 1628680192, 4, 0,
  121745. _vq_quantlist__8c1_s_p9_0,
  121746. NULL,
  121747. &_vq_auxt__8c1_s_p9_0,
  121748. NULL,
  121749. 0
  121750. };
  121751. static long _vq_quantlist__8c1_s_p9_1[] = {
  121752. 7,
  121753. 6,
  121754. 8,
  121755. 5,
  121756. 9,
  121757. 4,
  121758. 10,
  121759. 3,
  121760. 11,
  121761. 2,
  121762. 12,
  121763. 1,
  121764. 13,
  121765. 0,
  121766. 14,
  121767. };
  121768. static long _vq_lengthlist__8c1_s_p9_1[] = {
  121769. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  121770. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  121771. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  121772. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  121773. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  121774. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  121775. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  121776. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  121777. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  121778. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  121779. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  121780. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  121781. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  121782. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  121783. 15,
  121784. };
  121785. static float _vq_quantthresh__8c1_s_p9_1[] = {
  121786. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  121787. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  121788. };
  121789. static long _vq_quantmap__8c1_s_p9_1[] = {
  121790. 13, 11, 9, 7, 5, 3, 1, 0,
  121791. 2, 4, 6, 8, 10, 12, 14,
  121792. };
  121793. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  121794. _vq_quantthresh__8c1_s_p9_1,
  121795. _vq_quantmap__8c1_s_p9_1,
  121796. 15,
  121797. 15
  121798. };
  121799. static static_codebook _8c1_s_p9_1 = {
  121800. 2, 225,
  121801. _vq_lengthlist__8c1_s_p9_1,
  121802. 1, -520986624, 1620377600, 4, 0,
  121803. _vq_quantlist__8c1_s_p9_1,
  121804. NULL,
  121805. &_vq_auxt__8c1_s_p9_1,
  121806. NULL,
  121807. 0
  121808. };
  121809. static long _vq_quantlist__8c1_s_p9_2[] = {
  121810. 10,
  121811. 9,
  121812. 11,
  121813. 8,
  121814. 12,
  121815. 7,
  121816. 13,
  121817. 6,
  121818. 14,
  121819. 5,
  121820. 15,
  121821. 4,
  121822. 16,
  121823. 3,
  121824. 17,
  121825. 2,
  121826. 18,
  121827. 1,
  121828. 19,
  121829. 0,
  121830. 20,
  121831. };
  121832. static long _vq_lengthlist__8c1_s_p9_2[] = {
  121833. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  121834. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  121835. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  121836. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  121837. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  121838. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  121839. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  121840. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  121841. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  121842. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  121843. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  121844. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  121845. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  121846. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  121847. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  121848. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  121849. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121850. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  121851. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  121852. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  121853. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121854. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  121855. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  121856. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  121857. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  121858. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  121859. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  121860. 10,10,10,10,10,10,10,10,10,
  121861. };
  121862. static float _vq_quantthresh__8c1_s_p9_2[] = {
  121863. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  121864. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  121865. 6.5, 7.5, 8.5, 9.5,
  121866. };
  121867. static long _vq_quantmap__8c1_s_p9_2[] = {
  121868. 19, 17, 15, 13, 11, 9, 7, 5,
  121869. 3, 1, 0, 2, 4, 6, 8, 10,
  121870. 12, 14, 16, 18, 20,
  121871. };
  121872. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  121873. _vq_quantthresh__8c1_s_p9_2,
  121874. _vq_quantmap__8c1_s_p9_2,
  121875. 21,
  121876. 21
  121877. };
  121878. static static_codebook _8c1_s_p9_2 = {
  121879. 2, 441,
  121880. _vq_lengthlist__8c1_s_p9_2,
  121881. 1, -529268736, 1611661312, 5, 0,
  121882. _vq_quantlist__8c1_s_p9_2,
  121883. NULL,
  121884. &_vq_auxt__8c1_s_p9_2,
  121885. NULL,
  121886. 0
  121887. };
  121888. static long _huff_lengthlist__8c1_s_single[] = {
  121889. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  121890. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  121891. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  121892. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  121893. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  121894. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  121895. 9, 7, 7, 8,
  121896. };
  121897. static static_codebook _huff_book__8c1_s_single = {
  121898. 2, 100,
  121899. _huff_lengthlist__8c1_s_single,
  121900. 0, 0, 0, 0, 0,
  121901. NULL,
  121902. NULL,
  121903. NULL,
  121904. NULL,
  121905. 0
  121906. };
  121907. static long _huff_lengthlist__44c2_s_long[] = {
  121908. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  121909. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  121910. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  121911. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  121912. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  121913. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  121914. 10, 8, 8, 9,
  121915. };
  121916. static static_codebook _huff_book__44c2_s_long = {
  121917. 2, 100,
  121918. _huff_lengthlist__44c2_s_long,
  121919. 0, 0, 0, 0, 0,
  121920. NULL,
  121921. NULL,
  121922. NULL,
  121923. NULL,
  121924. 0
  121925. };
  121926. static long _vq_quantlist__44c2_s_p1_0[] = {
  121927. 1,
  121928. 0,
  121929. 2,
  121930. };
  121931. static long _vq_lengthlist__44c2_s_p1_0[] = {
  121932. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  121933. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121937. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  121938. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121942. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  121943. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  121978. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  121979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  121983. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  121984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  121988. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  121989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122023. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  122024. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122028. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  122029. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  122030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122033. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  122034. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  122035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122342. 0,
  122343. };
  122344. static float _vq_quantthresh__44c2_s_p1_0[] = {
  122345. -0.5, 0.5,
  122346. };
  122347. static long _vq_quantmap__44c2_s_p1_0[] = {
  122348. 1, 0, 2,
  122349. };
  122350. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  122351. _vq_quantthresh__44c2_s_p1_0,
  122352. _vq_quantmap__44c2_s_p1_0,
  122353. 3,
  122354. 3
  122355. };
  122356. static static_codebook _44c2_s_p1_0 = {
  122357. 8, 6561,
  122358. _vq_lengthlist__44c2_s_p1_0,
  122359. 1, -535822336, 1611661312, 2, 0,
  122360. _vq_quantlist__44c2_s_p1_0,
  122361. NULL,
  122362. &_vq_auxt__44c2_s_p1_0,
  122363. NULL,
  122364. 0
  122365. };
  122366. static long _vq_quantlist__44c2_s_p2_0[] = {
  122367. 2,
  122368. 1,
  122369. 3,
  122370. 0,
  122371. 4,
  122372. };
  122373. static long _vq_lengthlist__44c2_s_p2_0[] = {
  122374. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  122375. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  122376. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  122377. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  122378. 0, 0, 9, 9, 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, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  122384. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  122385. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  122386. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122391. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  122392. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  122393. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  122394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122399. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  122400. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  122401. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 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,
  122414. };
  122415. static float _vq_quantthresh__44c2_s_p2_0[] = {
  122416. -1.5, -0.5, 0.5, 1.5,
  122417. };
  122418. static long _vq_quantmap__44c2_s_p2_0[] = {
  122419. 3, 1, 0, 2, 4,
  122420. };
  122421. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  122422. _vq_quantthresh__44c2_s_p2_0,
  122423. _vq_quantmap__44c2_s_p2_0,
  122424. 5,
  122425. 5
  122426. };
  122427. static static_codebook _44c2_s_p2_0 = {
  122428. 4, 625,
  122429. _vq_lengthlist__44c2_s_p2_0,
  122430. 1, -533725184, 1611661312, 3, 0,
  122431. _vq_quantlist__44c2_s_p2_0,
  122432. NULL,
  122433. &_vq_auxt__44c2_s_p2_0,
  122434. NULL,
  122435. 0
  122436. };
  122437. static long _vq_quantlist__44c2_s_p3_0[] = {
  122438. 2,
  122439. 1,
  122440. 3,
  122441. 0,
  122442. 4,
  122443. };
  122444. static long _vq_lengthlist__44c2_s_p3_0[] = {
  122445. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  122447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122448. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  122450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122451. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  122485. };
  122486. static float _vq_quantthresh__44c2_s_p3_0[] = {
  122487. -1.5, -0.5, 0.5, 1.5,
  122488. };
  122489. static long _vq_quantmap__44c2_s_p3_0[] = {
  122490. 3, 1, 0, 2, 4,
  122491. };
  122492. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  122493. _vq_quantthresh__44c2_s_p3_0,
  122494. _vq_quantmap__44c2_s_p3_0,
  122495. 5,
  122496. 5
  122497. };
  122498. static static_codebook _44c2_s_p3_0 = {
  122499. 4, 625,
  122500. _vq_lengthlist__44c2_s_p3_0,
  122501. 1, -533725184, 1611661312, 3, 0,
  122502. _vq_quantlist__44c2_s_p3_0,
  122503. NULL,
  122504. &_vq_auxt__44c2_s_p3_0,
  122505. NULL,
  122506. 0
  122507. };
  122508. static long _vq_quantlist__44c2_s_p4_0[] = {
  122509. 4,
  122510. 3,
  122511. 5,
  122512. 2,
  122513. 6,
  122514. 1,
  122515. 7,
  122516. 0,
  122517. 8,
  122518. };
  122519. static long _vq_lengthlist__44c2_s_p4_0[] = {
  122520. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  122521. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  122522. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  122523. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  122524. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122525. 0,
  122526. };
  122527. static float _vq_quantthresh__44c2_s_p4_0[] = {
  122528. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122529. };
  122530. static long _vq_quantmap__44c2_s_p4_0[] = {
  122531. 7, 5, 3, 1, 0, 2, 4, 6,
  122532. 8,
  122533. };
  122534. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  122535. _vq_quantthresh__44c2_s_p4_0,
  122536. _vq_quantmap__44c2_s_p4_0,
  122537. 9,
  122538. 9
  122539. };
  122540. static static_codebook _44c2_s_p4_0 = {
  122541. 2, 81,
  122542. _vq_lengthlist__44c2_s_p4_0,
  122543. 1, -531628032, 1611661312, 4, 0,
  122544. _vq_quantlist__44c2_s_p4_0,
  122545. NULL,
  122546. &_vq_auxt__44c2_s_p4_0,
  122547. NULL,
  122548. 0
  122549. };
  122550. static long _vq_quantlist__44c2_s_p5_0[] = {
  122551. 4,
  122552. 3,
  122553. 5,
  122554. 2,
  122555. 6,
  122556. 1,
  122557. 7,
  122558. 0,
  122559. 8,
  122560. };
  122561. static long _vq_lengthlist__44c2_s_p5_0[] = {
  122562. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  122563. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  122564. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  122565. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  122566. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  122567. 11,
  122568. };
  122569. static float _vq_quantthresh__44c2_s_p5_0[] = {
  122570. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122571. };
  122572. static long _vq_quantmap__44c2_s_p5_0[] = {
  122573. 7, 5, 3, 1, 0, 2, 4, 6,
  122574. 8,
  122575. };
  122576. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  122577. _vq_quantthresh__44c2_s_p5_0,
  122578. _vq_quantmap__44c2_s_p5_0,
  122579. 9,
  122580. 9
  122581. };
  122582. static static_codebook _44c2_s_p5_0 = {
  122583. 2, 81,
  122584. _vq_lengthlist__44c2_s_p5_0,
  122585. 1, -531628032, 1611661312, 4, 0,
  122586. _vq_quantlist__44c2_s_p5_0,
  122587. NULL,
  122588. &_vq_auxt__44c2_s_p5_0,
  122589. NULL,
  122590. 0
  122591. };
  122592. static long _vq_quantlist__44c2_s_p6_0[] = {
  122593. 8,
  122594. 7,
  122595. 9,
  122596. 6,
  122597. 10,
  122598. 5,
  122599. 11,
  122600. 4,
  122601. 12,
  122602. 3,
  122603. 13,
  122604. 2,
  122605. 14,
  122606. 1,
  122607. 15,
  122608. 0,
  122609. 16,
  122610. };
  122611. static long _vq_lengthlist__44c2_s_p6_0[] = {
  122612. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  122613. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  122614. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  122615. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  122616. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  122617. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  122618. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  122619. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  122620. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  122621. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122622. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  122623. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  122624. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  122625. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  122626. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  122627. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  122628. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  122629. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  122630. 14,
  122631. };
  122632. static float _vq_quantthresh__44c2_s_p6_0[] = {
  122633. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122634. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122635. };
  122636. static long _vq_quantmap__44c2_s_p6_0[] = {
  122637. 15, 13, 11, 9, 7, 5, 3, 1,
  122638. 0, 2, 4, 6, 8, 10, 12, 14,
  122639. 16,
  122640. };
  122641. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  122642. _vq_quantthresh__44c2_s_p6_0,
  122643. _vq_quantmap__44c2_s_p6_0,
  122644. 17,
  122645. 17
  122646. };
  122647. static static_codebook _44c2_s_p6_0 = {
  122648. 2, 289,
  122649. _vq_lengthlist__44c2_s_p6_0,
  122650. 1, -529530880, 1611661312, 5, 0,
  122651. _vq_quantlist__44c2_s_p6_0,
  122652. NULL,
  122653. &_vq_auxt__44c2_s_p6_0,
  122654. NULL,
  122655. 0
  122656. };
  122657. static long _vq_quantlist__44c2_s_p7_0[] = {
  122658. 1,
  122659. 0,
  122660. 2,
  122661. };
  122662. static long _vq_lengthlist__44c2_s_p7_0[] = {
  122663. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  122664. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  122665. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  122666. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  122667. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  122668. 11,
  122669. };
  122670. static float _vq_quantthresh__44c2_s_p7_0[] = {
  122671. -5.5, 5.5,
  122672. };
  122673. static long _vq_quantmap__44c2_s_p7_0[] = {
  122674. 1, 0, 2,
  122675. };
  122676. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  122677. _vq_quantthresh__44c2_s_p7_0,
  122678. _vq_quantmap__44c2_s_p7_0,
  122679. 3,
  122680. 3
  122681. };
  122682. static static_codebook _44c2_s_p7_0 = {
  122683. 4, 81,
  122684. _vq_lengthlist__44c2_s_p7_0,
  122685. 1, -529137664, 1618345984, 2, 0,
  122686. _vq_quantlist__44c2_s_p7_0,
  122687. NULL,
  122688. &_vq_auxt__44c2_s_p7_0,
  122689. NULL,
  122690. 0
  122691. };
  122692. static long _vq_quantlist__44c2_s_p7_1[] = {
  122693. 5,
  122694. 4,
  122695. 6,
  122696. 3,
  122697. 7,
  122698. 2,
  122699. 8,
  122700. 1,
  122701. 9,
  122702. 0,
  122703. 10,
  122704. };
  122705. static long _vq_lengthlist__44c2_s_p7_1[] = {
  122706. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  122707. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  122708. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  122709. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  122710. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  122711. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  122712. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  122713. 10,10,10, 8, 8, 8, 8, 8, 8,
  122714. };
  122715. static float _vq_quantthresh__44c2_s_p7_1[] = {
  122716. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122717. 3.5, 4.5,
  122718. };
  122719. static long _vq_quantmap__44c2_s_p7_1[] = {
  122720. 9, 7, 5, 3, 1, 0, 2, 4,
  122721. 6, 8, 10,
  122722. };
  122723. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  122724. _vq_quantthresh__44c2_s_p7_1,
  122725. _vq_quantmap__44c2_s_p7_1,
  122726. 11,
  122727. 11
  122728. };
  122729. static static_codebook _44c2_s_p7_1 = {
  122730. 2, 121,
  122731. _vq_lengthlist__44c2_s_p7_1,
  122732. 1, -531365888, 1611661312, 4, 0,
  122733. _vq_quantlist__44c2_s_p7_1,
  122734. NULL,
  122735. &_vq_auxt__44c2_s_p7_1,
  122736. NULL,
  122737. 0
  122738. };
  122739. static long _vq_quantlist__44c2_s_p8_0[] = {
  122740. 6,
  122741. 5,
  122742. 7,
  122743. 4,
  122744. 8,
  122745. 3,
  122746. 9,
  122747. 2,
  122748. 10,
  122749. 1,
  122750. 11,
  122751. 0,
  122752. 12,
  122753. };
  122754. static long _vq_lengthlist__44c2_s_p8_0[] = {
  122755. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  122756. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  122757. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  122758. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  122759. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  122760. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  122761. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  122762. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  122763. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  122764. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  122765. 0,12,12,12,12,13,12,14,14,
  122766. };
  122767. static float _vq_quantthresh__44c2_s_p8_0[] = {
  122768. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122769. 12.5, 17.5, 22.5, 27.5,
  122770. };
  122771. static long _vq_quantmap__44c2_s_p8_0[] = {
  122772. 11, 9, 7, 5, 3, 1, 0, 2,
  122773. 4, 6, 8, 10, 12,
  122774. };
  122775. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  122776. _vq_quantthresh__44c2_s_p8_0,
  122777. _vq_quantmap__44c2_s_p8_0,
  122778. 13,
  122779. 13
  122780. };
  122781. static static_codebook _44c2_s_p8_0 = {
  122782. 2, 169,
  122783. _vq_lengthlist__44c2_s_p8_0,
  122784. 1, -526516224, 1616117760, 4, 0,
  122785. _vq_quantlist__44c2_s_p8_0,
  122786. NULL,
  122787. &_vq_auxt__44c2_s_p8_0,
  122788. NULL,
  122789. 0
  122790. };
  122791. static long _vq_quantlist__44c2_s_p8_1[] = {
  122792. 2,
  122793. 1,
  122794. 3,
  122795. 0,
  122796. 4,
  122797. };
  122798. static long _vq_lengthlist__44c2_s_p8_1[] = {
  122799. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  122800. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  122801. };
  122802. static float _vq_quantthresh__44c2_s_p8_1[] = {
  122803. -1.5, -0.5, 0.5, 1.5,
  122804. };
  122805. static long _vq_quantmap__44c2_s_p8_1[] = {
  122806. 3, 1, 0, 2, 4,
  122807. };
  122808. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  122809. _vq_quantthresh__44c2_s_p8_1,
  122810. _vq_quantmap__44c2_s_p8_1,
  122811. 5,
  122812. 5
  122813. };
  122814. static static_codebook _44c2_s_p8_1 = {
  122815. 2, 25,
  122816. _vq_lengthlist__44c2_s_p8_1,
  122817. 1, -533725184, 1611661312, 3, 0,
  122818. _vq_quantlist__44c2_s_p8_1,
  122819. NULL,
  122820. &_vq_auxt__44c2_s_p8_1,
  122821. NULL,
  122822. 0
  122823. };
  122824. static long _vq_quantlist__44c2_s_p9_0[] = {
  122825. 6,
  122826. 5,
  122827. 7,
  122828. 4,
  122829. 8,
  122830. 3,
  122831. 9,
  122832. 2,
  122833. 10,
  122834. 1,
  122835. 11,
  122836. 0,
  122837. 12,
  122838. };
  122839. static long _vq_lengthlist__44c2_s_p9_0[] = {
  122840. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  122841. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  122842. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122843. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  122844. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122845. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122846. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122847. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122848. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122849. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122850. 11,11,11,11,11,11,11,11,11,
  122851. };
  122852. static float _vq_quantthresh__44c2_s_p9_0[] = {
  122853. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  122854. 552.5, 773.5, 994.5, 1215.5,
  122855. };
  122856. static long _vq_quantmap__44c2_s_p9_0[] = {
  122857. 11, 9, 7, 5, 3, 1, 0, 2,
  122858. 4, 6, 8, 10, 12,
  122859. };
  122860. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  122861. _vq_quantthresh__44c2_s_p9_0,
  122862. _vq_quantmap__44c2_s_p9_0,
  122863. 13,
  122864. 13
  122865. };
  122866. static static_codebook _44c2_s_p9_0 = {
  122867. 2, 169,
  122868. _vq_lengthlist__44c2_s_p9_0,
  122869. 1, -514541568, 1627103232, 4, 0,
  122870. _vq_quantlist__44c2_s_p9_0,
  122871. NULL,
  122872. &_vq_auxt__44c2_s_p9_0,
  122873. NULL,
  122874. 0
  122875. };
  122876. static long _vq_quantlist__44c2_s_p9_1[] = {
  122877. 6,
  122878. 5,
  122879. 7,
  122880. 4,
  122881. 8,
  122882. 3,
  122883. 9,
  122884. 2,
  122885. 10,
  122886. 1,
  122887. 11,
  122888. 0,
  122889. 12,
  122890. };
  122891. static long _vq_lengthlist__44c2_s_p9_1[] = {
  122892. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  122893. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  122894. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  122895. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  122896. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  122897. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  122898. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  122899. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  122900. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  122901. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  122902. 17,13,12,12,10,13,11,14,14,
  122903. };
  122904. static float _vq_quantthresh__44c2_s_p9_1[] = {
  122905. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  122906. 42.5, 59.5, 76.5, 93.5,
  122907. };
  122908. static long _vq_quantmap__44c2_s_p9_1[] = {
  122909. 11, 9, 7, 5, 3, 1, 0, 2,
  122910. 4, 6, 8, 10, 12,
  122911. };
  122912. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  122913. _vq_quantthresh__44c2_s_p9_1,
  122914. _vq_quantmap__44c2_s_p9_1,
  122915. 13,
  122916. 13
  122917. };
  122918. static static_codebook _44c2_s_p9_1 = {
  122919. 2, 169,
  122920. _vq_lengthlist__44c2_s_p9_1,
  122921. 1, -522616832, 1620115456, 4, 0,
  122922. _vq_quantlist__44c2_s_p9_1,
  122923. NULL,
  122924. &_vq_auxt__44c2_s_p9_1,
  122925. NULL,
  122926. 0
  122927. };
  122928. static long _vq_quantlist__44c2_s_p9_2[] = {
  122929. 8,
  122930. 7,
  122931. 9,
  122932. 6,
  122933. 10,
  122934. 5,
  122935. 11,
  122936. 4,
  122937. 12,
  122938. 3,
  122939. 13,
  122940. 2,
  122941. 14,
  122942. 1,
  122943. 15,
  122944. 0,
  122945. 16,
  122946. };
  122947. static long _vq_lengthlist__44c2_s_p9_2[] = {
  122948. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  122949. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  122950. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  122951. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  122952. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  122953. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  122954. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  122955. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  122956. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  122957. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  122958. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  122959. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  122960. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  122961. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  122962. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  122963. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  122964. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  122965. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  122966. 10,
  122967. };
  122968. static float _vq_quantthresh__44c2_s_p9_2[] = {
  122969. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122970. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122971. };
  122972. static long _vq_quantmap__44c2_s_p9_2[] = {
  122973. 15, 13, 11, 9, 7, 5, 3, 1,
  122974. 0, 2, 4, 6, 8, 10, 12, 14,
  122975. 16,
  122976. };
  122977. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  122978. _vq_quantthresh__44c2_s_p9_2,
  122979. _vq_quantmap__44c2_s_p9_2,
  122980. 17,
  122981. 17
  122982. };
  122983. static static_codebook _44c2_s_p9_2 = {
  122984. 2, 289,
  122985. _vq_lengthlist__44c2_s_p9_2,
  122986. 1, -529530880, 1611661312, 5, 0,
  122987. _vq_quantlist__44c2_s_p9_2,
  122988. NULL,
  122989. &_vq_auxt__44c2_s_p9_2,
  122990. NULL,
  122991. 0
  122992. };
  122993. static long _huff_lengthlist__44c2_s_short[] = {
  122994. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  122995. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  122996. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  122997. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  122998. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  122999. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  123000. 6, 8, 9,12,
  123001. };
  123002. static static_codebook _huff_book__44c2_s_short = {
  123003. 2, 100,
  123004. _huff_lengthlist__44c2_s_short,
  123005. 0, 0, 0, 0, 0,
  123006. NULL,
  123007. NULL,
  123008. NULL,
  123009. NULL,
  123010. 0
  123011. };
  123012. static long _huff_lengthlist__44c3_s_long[] = {
  123013. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  123014. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  123015. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  123016. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  123017. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  123018. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  123019. 9, 8, 8, 8,
  123020. };
  123021. static static_codebook _huff_book__44c3_s_long = {
  123022. 2, 100,
  123023. _huff_lengthlist__44c3_s_long,
  123024. 0, 0, 0, 0, 0,
  123025. NULL,
  123026. NULL,
  123027. NULL,
  123028. NULL,
  123029. 0
  123030. };
  123031. static long _vq_quantlist__44c3_s_p1_0[] = {
  123032. 1,
  123033. 0,
  123034. 2,
  123035. };
  123036. static long _vq_lengthlist__44c3_s_p1_0[] = {
  123037. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  123038. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123042. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  123043. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123047. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  123048. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123083. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  123084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  123088. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  123089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  123093. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  123094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123128. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  123129. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123133. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  123134. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  123135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123138. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  123139. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  123140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123447. 0,
  123448. };
  123449. static float _vq_quantthresh__44c3_s_p1_0[] = {
  123450. -0.5, 0.5,
  123451. };
  123452. static long _vq_quantmap__44c3_s_p1_0[] = {
  123453. 1, 0, 2,
  123454. };
  123455. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  123456. _vq_quantthresh__44c3_s_p1_0,
  123457. _vq_quantmap__44c3_s_p1_0,
  123458. 3,
  123459. 3
  123460. };
  123461. static static_codebook _44c3_s_p1_0 = {
  123462. 8, 6561,
  123463. _vq_lengthlist__44c3_s_p1_0,
  123464. 1, -535822336, 1611661312, 2, 0,
  123465. _vq_quantlist__44c3_s_p1_0,
  123466. NULL,
  123467. &_vq_auxt__44c3_s_p1_0,
  123468. NULL,
  123469. 0
  123470. };
  123471. static long _vq_quantlist__44c3_s_p2_0[] = {
  123472. 2,
  123473. 1,
  123474. 3,
  123475. 0,
  123476. 4,
  123477. };
  123478. static long _vq_lengthlist__44c3_s_p2_0[] = {
  123479. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  123480. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  123481. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  123482. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  123483. 0, 0,10,10, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  123489. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  123490. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  123491. 9, 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, 0, 0, 0, 0, 0, 0, 0,
  123495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123496. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  123497. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  123498. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  123499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123504. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  123505. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  123506. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  123519. };
  123520. static float _vq_quantthresh__44c3_s_p2_0[] = {
  123521. -1.5, -0.5, 0.5, 1.5,
  123522. };
  123523. static long _vq_quantmap__44c3_s_p2_0[] = {
  123524. 3, 1, 0, 2, 4,
  123525. };
  123526. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  123527. _vq_quantthresh__44c3_s_p2_0,
  123528. _vq_quantmap__44c3_s_p2_0,
  123529. 5,
  123530. 5
  123531. };
  123532. static static_codebook _44c3_s_p2_0 = {
  123533. 4, 625,
  123534. _vq_lengthlist__44c3_s_p2_0,
  123535. 1, -533725184, 1611661312, 3, 0,
  123536. _vq_quantlist__44c3_s_p2_0,
  123537. NULL,
  123538. &_vq_auxt__44c3_s_p2_0,
  123539. NULL,
  123540. 0
  123541. };
  123542. static long _vq_quantlist__44c3_s_p3_0[] = {
  123543. 2,
  123544. 1,
  123545. 3,
  123546. 0,
  123547. 4,
  123548. };
  123549. static long _vq_lengthlist__44c3_s_p3_0[] = {
  123550. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  123552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123553. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123556. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  123590. };
  123591. static float _vq_quantthresh__44c3_s_p3_0[] = {
  123592. -1.5, -0.5, 0.5, 1.5,
  123593. };
  123594. static long _vq_quantmap__44c3_s_p3_0[] = {
  123595. 3, 1, 0, 2, 4,
  123596. };
  123597. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  123598. _vq_quantthresh__44c3_s_p3_0,
  123599. _vq_quantmap__44c3_s_p3_0,
  123600. 5,
  123601. 5
  123602. };
  123603. static static_codebook _44c3_s_p3_0 = {
  123604. 4, 625,
  123605. _vq_lengthlist__44c3_s_p3_0,
  123606. 1, -533725184, 1611661312, 3, 0,
  123607. _vq_quantlist__44c3_s_p3_0,
  123608. NULL,
  123609. &_vq_auxt__44c3_s_p3_0,
  123610. NULL,
  123611. 0
  123612. };
  123613. static long _vq_quantlist__44c3_s_p4_0[] = {
  123614. 4,
  123615. 3,
  123616. 5,
  123617. 2,
  123618. 6,
  123619. 1,
  123620. 7,
  123621. 0,
  123622. 8,
  123623. };
  123624. static long _vq_lengthlist__44c3_s_p4_0[] = {
  123625. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  123626. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  123627. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  123628. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  123629. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123630. 0,
  123631. };
  123632. static float _vq_quantthresh__44c3_s_p4_0[] = {
  123633. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123634. };
  123635. static long _vq_quantmap__44c3_s_p4_0[] = {
  123636. 7, 5, 3, 1, 0, 2, 4, 6,
  123637. 8,
  123638. };
  123639. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  123640. _vq_quantthresh__44c3_s_p4_0,
  123641. _vq_quantmap__44c3_s_p4_0,
  123642. 9,
  123643. 9
  123644. };
  123645. static static_codebook _44c3_s_p4_0 = {
  123646. 2, 81,
  123647. _vq_lengthlist__44c3_s_p4_0,
  123648. 1, -531628032, 1611661312, 4, 0,
  123649. _vq_quantlist__44c3_s_p4_0,
  123650. NULL,
  123651. &_vq_auxt__44c3_s_p4_0,
  123652. NULL,
  123653. 0
  123654. };
  123655. static long _vq_quantlist__44c3_s_p5_0[] = {
  123656. 4,
  123657. 3,
  123658. 5,
  123659. 2,
  123660. 6,
  123661. 1,
  123662. 7,
  123663. 0,
  123664. 8,
  123665. };
  123666. static long _vq_lengthlist__44c3_s_p5_0[] = {
  123667. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  123668. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  123669. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  123670. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  123671. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  123672. 11,
  123673. };
  123674. static float _vq_quantthresh__44c3_s_p5_0[] = {
  123675. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123676. };
  123677. static long _vq_quantmap__44c3_s_p5_0[] = {
  123678. 7, 5, 3, 1, 0, 2, 4, 6,
  123679. 8,
  123680. };
  123681. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  123682. _vq_quantthresh__44c3_s_p5_0,
  123683. _vq_quantmap__44c3_s_p5_0,
  123684. 9,
  123685. 9
  123686. };
  123687. static static_codebook _44c3_s_p5_0 = {
  123688. 2, 81,
  123689. _vq_lengthlist__44c3_s_p5_0,
  123690. 1, -531628032, 1611661312, 4, 0,
  123691. _vq_quantlist__44c3_s_p5_0,
  123692. NULL,
  123693. &_vq_auxt__44c3_s_p5_0,
  123694. NULL,
  123695. 0
  123696. };
  123697. static long _vq_quantlist__44c3_s_p6_0[] = {
  123698. 8,
  123699. 7,
  123700. 9,
  123701. 6,
  123702. 10,
  123703. 5,
  123704. 11,
  123705. 4,
  123706. 12,
  123707. 3,
  123708. 13,
  123709. 2,
  123710. 14,
  123711. 1,
  123712. 15,
  123713. 0,
  123714. 16,
  123715. };
  123716. static long _vq_lengthlist__44c3_s_p6_0[] = {
  123717. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123718. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  123719. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  123720. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123721. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123722. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  123723. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  123724. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  123725. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  123726. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  123727. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  123728. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  123729. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  123730. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  123731. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  123732. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  123733. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  123734. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  123735. 13,
  123736. };
  123737. static float _vq_quantthresh__44c3_s_p6_0[] = {
  123738. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123739. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123740. };
  123741. static long _vq_quantmap__44c3_s_p6_0[] = {
  123742. 15, 13, 11, 9, 7, 5, 3, 1,
  123743. 0, 2, 4, 6, 8, 10, 12, 14,
  123744. 16,
  123745. };
  123746. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  123747. _vq_quantthresh__44c3_s_p6_0,
  123748. _vq_quantmap__44c3_s_p6_0,
  123749. 17,
  123750. 17
  123751. };
  123752. static static_codebook _44c3_s_p6_0 = {
  123753. 2, 289,
  123754. _vq_lengthlist__44c3_s_p6_0,
  123755. 1, -529530880, 1611661312, 5, 0,
  123756. _vq_quantlist__44c3_s_p6_0,
  123757. NULL,
  123758. &_vq_auxt__44c3_s_p6_0,
  123759. NULL,
  123760. 0
  123761. };
  123762. static long _vq_quantlist__44c3_s_p7_0[] = {
  123763. 1,
  123764. 0,
  123765. 2,
  123766. };
  123767. static long _vq_lengthlist__44c3_s_p7_0[] = {
  123768. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  123769. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  123770. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  123771. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  123772. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  123773. 10,
  123774. };
  123775. static float _vq_quantthresh__44c3_s_p7_0[] = {
  123776. -5.5, 5.5,
  123777. };
  123778. static long _vq_quantmap__44c3_s_p7_0[] = {
  123779. 1, 0, 2,
  123780. };
  123781. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  123782. _vq_quantthresh__44c3_s_p7_0,
  123783. _vq_quantmap__44c3_s_p7_0,
  123784. 3,
  123785. 3
  123786. };
  123787. static static_codebook _44c3_s_p7_0 = {
  123788. 4, 81,
  123789. _vq_lengthlist__44c3_s_p7_0,
  123790. 1, -529137664, 1618345984, 2, 0,
  123791. _vq_quantlist__44c3_s_p7_0,
  123792. NULL,
  123793. &_vq_auxt__44c3_s_p7_0,
  123794. NULL,
  123795. 0
  123796. };
  123797. static long _vq_quantlist__44c3_s_p7_1[] = {
  123798. 5,
  123799. 4,
  123800. 6,
  123801. 3,
  123802. 7,
  123803. 2,
  123804. 8,
  123805. 1,
  123806. 9,
  123807. 0,
  123808. 10,
  123809. };
  123810. static long _vq_lengthlist__44c3_s_p7_1[] = {
  123811. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  123812. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  123813. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  123814. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  123815. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  123816. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  123817. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  123818. 10,10,10, 8, 8, 8, 8, 8, 8,
  123819. };
  123820. static float _vq_quantthresh__44c3_s_p7_1[] = {
  123821. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123822. 3.5, 4.5,
  123823. };
  123824. static long _vq_quantmap__44c3_s_p7_1[] = {
  123825. 9, 7, 5, 3, 1, 0, 2, 4,
  123826. 6, 8, 10,
  123827. };
  123828. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  123829. _vq_quantthresh__44c3_s_p7_1,
  123830. _vq_quantmap__44c3_s_p7_1,
  123831. 11,
  123832. 11
  123833. };
  123834. static static_codebook _44c3_s_p7_1 = {
  123835. 2, 121,
  123836. _vq_lengthlist__44c3_s_p7_1,
  123837. 1, -531365888, 1611661312, 4, 0,
  123838. _vq_quantlist__44c3_s_p7_1,
  123839. NULL,
  123840. &_vq_auxt__44c3_s_p7_1,
  123841. NULL,
  123842. 0
  123843. };
  123844. static long _vq_quantlist__44c3_s_p8_0[] = {
  123845. 6,
  123846. 5,
  123847. 7,
  123848. 4,
  123849. 8,
  123850. 3,
  123851. 9,
  123852. 2,
  123853. 10,
  123854. 1,
  123855. 11,
  123856. 0,
  123857. 12,
  123858. };
  123859. static long _vq_lengthlist__44c3_s_p8_0[] = {
  123860. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  123861. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  123862. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  123863. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  123864. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  123865. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  123866. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  123867. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  123868. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  123869. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  123870. 0,13,13,12,12,13,12,14,13,
  123871. };
  123872. static float _vq_quantthresh__44c3_s_p8_0[] = {
  123873. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123874. 12.5, 17.5, 22.5, 27.5,
  123875. };
  123876. static long _vq_quantmap__44c3_s_p8_0[] = {
  123877. 11, 9, 7, 5, 3, 1, 0, 2,
  123878. 4, 6, 8, 10, 12,
  123879. };
  123880. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  123881. _vq_quantthresh__44c3_s_p8_0,
  123882. _vq_quantmap__44c3_s_p8_0,
  123883. 13,
  123884. 13
  123885. };
  123886. static static_codebook _44c3_s_p8_0 = {
  123887. 2, 169,
  123888. _vq_lengthlist__44c3_s_p8_0,
  123889. 1, -526516224, 1616117760, 4, 0,
  123890. _vq_quantlist__44c3_s_p8_0,
  123891. NULL,
  123892. &_vq_auxt__44c3_s_p8_0,
  123893. NULL,
  123894. 0
  123895. };
  123896. static long _vq_quantlist__44c3_s_p8_1[] = {
  123897. 2,
  123898. 1,
  123899. 3,
  123900. 0,
  123901. 4,
  123902. };
  123903. static long _vq_lengthlist__44c3_s_p8_1[] = {
  123904. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  123905. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  123906. };
  123907. static float _vq_quantthresh__44c3_s_p8_1[] = {
  123908. -1.5, -0.5, 0.5, 1.5,
  123909. };
  123910. static long _vq_quantmap__44c3_s_p8_1[] = {
  123911. 3, 1, 0, 2, 4,
  123912. };
  123913. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  123914. _vq_quantthresh__44c3_s_p8_1,
  123915. _vq_quantmap__44c3_s_p8_1,
  123916. 5,
  123917. 5
  123918. };
  123919. static static_codebook _44c3_s_p8_1 = {
  123920. 2, 25,
  123921. _vq_lengthlist__44c3_s_p8_1,
  123922. 1, -533725184, 1611661312, 3, 0,
  123923. _vq_quantlist__44c3_s_p8_1,
  123924. NULL,
  123925. &_vq_auxt__44c3_s_p8_1,
  123926. NULL,
  123927. 0
  123928. };
  123929. static long _vq_quantlist__44c3_s_p9_0[] = {
  123930. 6,
  123931. 5,
  123932. 7,
  123933. 4,
  123934. 8,
  123935. 3,
  123936. 9,
  123937. 2,
  123938. 10,
  123939. 1,
  123940. 11,
  123941. 0,
  123942. 12,
  123943. };
  123944. static long _vq_lengthlist__44c3_s_p9_0[] = {
  123945. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  123946. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  123947. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123948. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  123949. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123950. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123951. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123952. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123953. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  123954. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123955. 11,11,11,11,11,11,11,11,11,
  123956. };
  123957. static float _vq_quantthresh__44c3_s_p9_0[] = {
  123958. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  123959. 637.5, 892.5, 1147.5, 1402.5,
  123960. };
  123961. static long _vq_quantmap__44c3_s_p9_0[] = {
  123962. 11, 9, 7, 5, 3, 1, 0, 2,
  123963. 4, 6, 8, 10, 12,
  123964. };
  123965. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  123966. _vq_quantthresh__44c3_s_p9_0,
  123967. _vq_quantmap__44c3_s_p9_0,
  123968. 13,
  123969. 13
  123970. };
  123971. static static_codebook _44c3_s_p9_0 = {
  123972. 2, 169,
  123973. _vq_lengthlist__44c3_s_p9_0,
  123974. 1, -514332672, 1627381760, 4, 0,
  123975. _vq_quantlist__44c3_s_p9_0,
  123976. NULL,
  123977. &_vq_auxt__44c3_s_p9_0,
  123978. NULL,
  123979. 0
  123980. };
  123981. static long _vq_quantlist__44c3_s_p9_1[] = {
  123982. 7,
  123983. 6,
  123984. 8,
  123985. 5,
  123986. 9,
  123987. 4,
  123988. 10,
  123989. 3,
  123990. 11,
  123991. 2,
  123992. 12,
  123993. 1,
  123994. 13,
  123995. 0,
  123996. 14,
  123997. };
  123998. static long _vq_lengthlist__44c3_s_p9_1[] = {
  123999. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  124000. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  124001. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  124002. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  124003. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  124004. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  124005. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  124006. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  124007. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  124008. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  124009. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  124010. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  124011. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  124012. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  124013. 15,
  124014. };
  124015. static float _vq_quantthresh__44c3_s_p9_1[] = {
  124016. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  124017. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  124018. };
  124019. static long _vq_quantmap__44c3_s_p9_1[] = {
  124020. 13, 11, 9, 7, 5, 3, 1, 0,
  124021. 2, 4, 6, 8, 10, 12, 14,
  124022. };
  124023. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  124024. _vq_quantthresh__44c3_s_p9_1,
  124025. _vq_quantmap__44c3_s_p9_1,
  124026. 15,
  124027. 15
  124028. };
  124029. static static_codebook _44c3_s_p9_1 = {
  124030. 2, 225,
  124031. _vq_lengthlist__44c3_s_p9_1,
  124032. 1, -522338304, 1620115456, 4, 0,
  124033. _vq_quantlist__44c3_s_p9_1,
  124034. NULL,
  124035. &_vq_auxt__44c3_s_p9_1,
  124036. NULL,
  124037. 0
  124038. };
  124039. static long _vq_quantlist__44c3_s_p9_2[] = {
  124040. 8,
  124041. 7,
  124042. 9,
  124043. 6,
  124044. 10,
  124045. 5,
  124046. 11,
  124047. 4,
  124048. 12,
  124049. 3,
  124050. 13,
  124051. 2,
  124052. 14,
  124053. 1,
  124054. 15,
  124055. 0,
  124056. 16,
  124057. };
  124058. static long _vq_lengthlist__44c3_s_p9_2[] = {
  124059. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  124060. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  124061. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  124062. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  124063. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  124064. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  124065. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  124066. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  124067. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  124068. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  124069. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  124070. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  124071. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  124072. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  124073. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  124074. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  124075. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  124076. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  124077. 10,
  124078. };
  124079. static float _vq_quantthresh__44c3_s_p9_2[] = {
  124080. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124081. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124082. };
  124083. static long _vq_quantmap__44c3_s_p9_2[] = {
  124084. 15, 13, 11, 9, 7, 5, 3, 1,
  124085. 0, 2, 4, 6, 8, 10, 12, 14,
  124086. 16,
  124087. };
  124088. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  124089. _vq_quantthresh__44c3_s_p9_2,
  124090. _vq_quantmap__44c3_s_p9_2,
  124091. 17,
  124092. 17
  124093. };
  124094. static static_codebook _44c3_s_p9_2 = {
  124095. 2, 289,
  124096. _vq_lengthlist__44c3_s_p9_2,
  124097. 1, -529530880, 1611661312, 5, 0,
  124098. _vq_quantlist__44c3_s_p9_2,
  124099. NULL,
  124100. &_vq_auxt__44c3_s_p9_2,
  124101. NULL,
  124102. 0
  124103. };
  124104. static long _huff_lengthlist__44c3_s_short[] = {
  124105. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  124106. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  124107. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  124108. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  124109. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  124110. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  124111. 6, 8, 9,11,
  124112. };
  124113. static static_codebook _huff_book__44c3_s_short = {
  124114. 2, 100,
  124115. _huff_lengthlist__44c3_s_short,
  124116. 0, 0, 0, 0, 0,
  124117. NULL,
  124118. NULL,
  124119. NULL,
  124120. NULL,
  124121. 0
  124122. };
  124123. static long _huff_lengthlist__44c4_s_long[] = {
  124124. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  124125. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  124126. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  124127. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  124128. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  124129. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  124130. 9, 8, 7, 7,
  124131. };
  124132. static static_codebook _huff_book__44c4_s_long = {
  124133. 2, 100,
  124134. _huff_lengthlist__44c4_s_long,
  124135. 0, 0, 0, 0, 0,
  124136. NULL,
  124137. NULL,
  124138. NULL,
  124139. NULL,
  124140. 0
  124141. };
  124142. static long _vq_quantlist__44c4_s_p1_0[] = {
  124143. 1,
  124144. 0,
  124145. 2,
  124146. };
  124147. static long _vq_lengthlist__44c4_s_p1_0[] = {
  124148. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  124149. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124153. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124154. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124158. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  124159. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  124194. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  124195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124199. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  124200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  124204. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  124205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124239. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  124240. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124244. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  124245. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  124246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124249. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  124250. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124558. 0,
  124559. };
  124560. static float _vq_quantthresh__44c4_s_p1_0[] = {
  124561. -0.5, 0.5,
  124562. };
  124563. static long _vq_quantmap__44c4_s_p1_0[] = {
  124564. 1, 0, 2,
  124565. };
  124566. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  124567. _vq_quantthresh__44c4_s_p1_0,
  124568. _vq_quantmap__44c4_s_p1_0,
  124569. 3,
  124570. 3
  124571. };
  124572. static static_codebook _44c4_s_p1_0 = {
  124573. 8, 6561,
  124574. _vq_lengthlist__44c4_s_p1_0,
  124575. 1, -535822336, 1611661312, 2, 0,
  124576. _vq_quantlist__44c4_s_p1_0,
  124577. NULL,
  124578. &_vq_auxt__44c4_s_p1_0,
  124579. NULL,
  124580. 0
  124581. };
  124582. static long _vq_quantlist__44c4_s_p2_0[] = {
  124583. 2,
  124584. 1,
  124585. 3,
  124586. 0,
  124587. 4,
  124588. };
  124589. static long _vq_lengthlist__44c4_s_p2_0[] = {
  124590. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  124591. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  124592. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  124593. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  124594. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  124600. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  124601. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  124602. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  124608. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  124609. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  124616. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  124617. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  124618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124629. 0,
  124630. };
  124631. static float _vq_quantthresh__44c4_s_p2_0[] = {
  124632. -1.5, -0.5, 0.5, 1.5,
  124633. };
  124634. static long _vq_quantmap__44c4_s_p2_0[] = {
  124635. 3, 1, 0, 2, 4,
  124636. };
  124637. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  124638. _vq_quantthresh__44c4_s_p2_0,
  124639. _vq_quantmap__44c4_s_p2_0,
  124640. 5,
  124641. 5
  124642. };
  124643. static static_codebook _44c4_s_p2_0 = {
  124644. 4, 625,
  124645. _vq_lengthlist__44c4_s_p2_0,
  124646. 1, -533725184, 1611661312, 3, 0,
  124647. _vq_quantlist__44c4_s_p2_0,
  124648. NULL,
  124649. &_vq_auxt__44c4_s_p2_0,
  124650. NULL,
  124651. 0
  124652. };
  124653. static long _vq_quantlist__44c4_s_p3_0[] = {
  124654. 2,
  124655. 1,
  124656. 3,
  124657. 0,
  124658. 4,
  124659. };
  124660. static long _vq_lengthlist__44c4_s_p3_0[] = {
  124661. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  124663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124664. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  124666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124667. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124700. 0,
  124701. };
  124702. static float _vq_quantthresh__44c4_s_p3_0[] = {
  124703. -1.5, -0.5, 0.5, 1.5,
  124704. };
  124705. static long _vq_quantmap__44c4_s_p3_0[] = {
  124706. 3, 1, 0, 2, 4,
  124707. };
  124708. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  124709. _vq_quantthresh__44c4_s_p3_0,
  124710. _vq_quantmap__44c4_s_p3_0,
  124711. 5,
  124712. 5
  124713. };
  124714. static static_codebook _44c4_s_p3_0 = {
  124715. 4, 625,
  124716. _vq_lengthlist__44c4_s_p3_0,
  124717. 1, -533725184, 1611661312, 3, 0,
  124718. _vq_quantlist__44c4_s_p3_0,
  124719. NULL,
  124720. &_vq_auxt__44c4_s_p3_0,
  124721. NULL,
  124722. 0
  124723. };
  124724. static long _vq_quantlist__44c4_s_p4_0[] = {
  124725. 4,
  124726. 3,
  124727. 5,
  124728. 2,
  124729. 6,
  124730. 1,
  124731. 7,
  124732. 0,
  124733. 8,
  124734. };
  124735. static long _vq_lengthlist__44c4_s_p4_0[] = {
  124736. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  124737. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  124738. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  124739. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  124740. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124741. 0,
  124742. };
  124743. static float _vq_quantthresh__44c4_s_p4_0[] = {
  124744. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124745. };
  124746. static long _vq_quantmap__44c4_s_p4_0[] = {
  124747. 7, 5, 3, 1, 0, 2, 4, 6,
  124748. 8,
  124749. };
  124750. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  124751. _vq_quantthresh__44c4_s_p4_0,
  124752. _vq_quantmap__44c4_s_p4_0,
  124753. 9,
  124754. 9
  124755. };
  124756. static static_codebook _44c4_s_p4_0 = {
  124757. 2, 81,
  124758. _vq_lengthlist__44c4_s_p4_0,
  124759. 1, -531628032, 1611661312, 4, 0,
  124760. _vq_quantlist__44c4_s_p4_0,
  124761. NULL,
  124762. &_vq_auxt__44c4_s_p4_0,
  124763. NULL,
  124764. 0
  124765. };
  124766. static long _vq_quantlist__44c4_s_p5_0[] = {
  124767. 4,
  124768. 3,
  124769. 5,
  124770. 2,
  124771. 6,
  124772. 1,
  124773. 7,
  124774. 0,
  124775. 8,
  124776. };
  124777. static long _vq_lengthlist__44c4_s_p5_0[] = {
  124778. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  124779. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  124780. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  124781. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  124782. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  124783. 10,
  124784. };
  124785. static float _vq_quantthresh__44c4_s_p5_0[] = {
  124786. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124787. };
  124788. static long _vq_quantmap__44c4_s_p5_0[] = {
  124789. 7, 5, 3, 1, 0, 2, 4, 6,
  124790. 8,
  124791. };
  124792. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  124793. _vq_quantthresh__44c4_s_p5_0,
  124794. _vq_quantmap__44c4_s_p5_0,
  124795. 9,
  124796. 9
  124797. };
  124798. static static_codebook _44c4_s_p5_0 = {
  124799. 2, 81,
  124800. _vq_lengthlist__44c4_s_p5_0,
  124801. 1, -531628032, 1611661312, 4, 0,
  124802. _vq_quantlist__44c4_s_p5_0,
  124803. NULL,
  124804. &_vq_auxt__44c4_s_p5_0,
  124805. NULL,
  124806. 0
  124807. };
  124808. static long _vq_quantlist__44c4_s_p6_0[] = {
  124809. 8,
  124810. 7,
  124811. 9,
  124812. 6,
  124813. 10,
  124814. 5,
  124815. 11,
  124816. 4,
  124817. 12,
  124818. 3,
  124819. 13,
  124820. 2,
  124821. 14,
  124822. 1,
  124823. 15,
  124824. 0,
  124825. 16,
  124826. };
  124827. static long _vq_lengthlist__44c4_s_p6_0[] = {
  124828. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  124829. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124830. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  124831. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  124832. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  124833. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124834. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  124835. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  124836. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  124837. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  124838. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  124839. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  124840. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  124841. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  124842. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  124843. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  124844. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  124845. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  124846. 13,
  124847. };
  124848. static float _vq_quantthresh__44c4_s_p6_0[] = {
  124849. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124850. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124851. };
  124852. static long _vq_quantmap__44c4_s_p6_0[] = {
  124853. 15, 13, 11, 9, 7, 5, 3, 1,
  124854. 0, 2, 4, 6, 8, 10, 12, 14,
  124855. 16,
  124856. };
  124857. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  124858. _vq_quantthresh__44c4_s_p6_0,
  124859. _vq_quantmap__44c4_s_p6_0,
  124860. 17,
  124861. 17
  124862. };
  124863. static static_codebook _44c4_s_p6_0 = {
  124864. 2, 289,
  124865. _vq_lengthlist__44c4_s_p6_0,
  124866. 1, -529530880, 1611661312, 5, 0,
  124867. _vq_quantlist__44c4_s_p6_0,
  124868. NULL,
  124869. &_vq_auxt__44c4_s_p6_0,
  124870. NULL,
  124871. 0
  124872. };
  124873. static long _vq_quantlist__44c4_s_p7_0[] = {
  124874. 1,
  124875. 0,
  124876. 2,
  124877. };
  124878. static long _vq_lengthlist__44c4_s_p7_0[] = {
  124879. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  124880. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  124881. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  124882. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  124883. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  124884. 10,
  124885. };
  124886. static float _vq_quantthresh__44c4_s_p7_0[] = {
  124887. -5.5, 5.5,
  124888. };
  124889. static long _vq_quantmap__44c4_s_p7_0[] = {
  124890. 1, 0, 2,
  124891. };
  124892. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  124893. _vq_quantthresh__44c4_s_p7_0,
  124894. _vq_quantmap__44c4_s_p7_0,
  124895. 3,
  124896. 3
  124897. };
  124898. static static_codebook _44c4_s_p7_0 = {
  124899. 4, 81,
  124900. _vq_lengthlist__44c4_s_p7_0,
  124901. 1, -529137664, 1618345984, 2, 0,
  124902. _vq_quantlist__44c4_s_p7_0,
  124903. NULL,
  124904. &_vq_auxt__44c4_s_p7_0,
  124905. NULL,
  124906. 0
  124907. };
  124908. static long _vq_quantlist__44c4_s_p7_1[] = {
  124909. 5,
  124910. 4,
  124911. 6,
  124912. 3,
  124913. 7,
  124914. 2,
  124915. 8,
  124916. 1,
  124917. 9,
  124918. 0,
  124919. 10,
  124920. };
  124921. static long _vq_lengthlist__44c4_s_p7_1[] = {
  124922. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  124923. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  124924. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  124925. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  124926. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124927. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  124928. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  124929. 10,10,10, 8, 8, 8, 8, 9, 9,
  124930. };
  124931. static float _vq_quantthresh__44c4_s_p7_1[] = {
  124932. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124933. 3.5, 4.5,
  124934. };
  124935. static long _vq_quantmap__44c4_s_p7_1[] = {
  124936. 9, 7, 5, 3, 1, 0, 2, 4,
  124937. 6, 8, 10,
  124938. };
  124939. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  124940. _vq_quantthresh__44c4_s_p7_1,
  124941. _vq_quantmap__44c4_s_p7_1,
  124942. 11,
  124943. 11
  124944. };
  124945. static static_codebook _44c4_s_p7_1 = {
  124946. 2, 121,
  124947. _vq_lengthlist__44c4_s_p7_1,
  124948. 1, -531365888, 1611661312, 4, 0,
  124949. _vq_quantlist__44c4_s_p7_1,
  124950. NULL,
  124951. &_vq_auxt__44c4_s_p7_1,
  124952. NULL,
  124953. 0
  124954. };
  124955. static long _vq_quantlist__44c4_s_p8_0[] = {
  124956. 6,
  124957. 5,
  124958. 7,
  124959. 4,
  124960. 8,
  124961. 3,
  124962. 9,
  124963. 2,
  124964. 10,
  124965. 1,
  124966. 11,
  124967. 0,
  124968. 12,
  124969. };
  124970. static long _vq_lengthlist__44c4_s_p8_0[] = {
  124971. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  124972. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  124973. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124974. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  124975. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  124976. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  124977. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  124978. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  124979. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  124980. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  124981. 0,13,12,12,12,12,12,13,13,
  124982. };
  124983. static float _vq_quantthresh__44c4_s_p8_0[] = {
  124984. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124985. 12.5, 17.5, 22.5, 27.5,
  124986. };
  124987. static long _vq_quantmap__44c4_s_p8_0[] = {
  124988. 11, 9, 7, 5, 3, 1, 0, 2,
  124989. 4, 6, 8, 10, 12,
  124990. };
  124991. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  124992. _vq_quantthresh__44c4_s_p8_0,
  124993. _vq_quantmap__44c4_s_p8_0,
  124994. 13,
  124995. 13
  124996. };
  124997. static static_codebook _44c4_s_p8_0 = {
  124998. 2, 169,
  124999. _vq_lengthlist__44c4_s_p8_0,
  125000. 1, -526516224, 1616117760, 4, 0,
  125001. _vq_quantlist__44c4_s_p8_0,
  125002. NULL,
  125003. &_vq_auxt__44c4_s_p8_0,
  125004. NULL,
  125005. 0
  125006. };
  125007. static long _vq_quantlist__44c4_s_p8_1[] = {
  125008. 2,
  125009. 1,
  125010. 3,
  125011. 0,
  125012. 4,
  125013. };
  125014. static long _vq_lengthlist__44c4_s_p8_1[] = {
  125015. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  125016. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  125017. };
  125018. static float _vq_quantthresh__44c4_s_p8_1[] = {
  125019. -1.5, -0.5, 0.5, 1.5,
  125020. };
  125021. static long _vq_quantmap__44c4_s_p8_1[] = {
  125022. 3, 1, 0, 2, 4,
  125023. };
  125024. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  125025. _vq_quantthresh__44c4_s_p8_1,
  125026. _vq_quantmap__44c4_s_p8_1,
  125027. 5,
  125028. 5
  125029. };
  125030. static static_codebook _44c4_s_p8_1 = {
  125031. 2, 25,
  125032. _vq_lengthlist__44c4_s_p8_1,
  125033. 1, -533725184, 1611661312, 3, 0,
  125034. _vq_quantlist__44c4_s_p8_1,
  125035. NULL,
  125036. &_vq_auxt__44c4_s_p8_1,
  125037. NULL,
  125038. 0
  125039. };
  125040. static long _vq_quantlist__44c4_s_p9_0[] = {
  125041. 6,
  125042. 5,
  125043. 7,
  125044. 4,
  125045. 8,
  125046. 3,
  125047. 9,
  125048. 2,
  125049. 10,
  125050. 1,
  125051. 11,
  125052. 0,
  125053. 12,
  125054. };
  125055. static long _vq_lengthlist__44c4_s_p9_0[] = {
  125056. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  125057. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  125058. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125059. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125060. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125061. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125062. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125063. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125064. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125065. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125066. 12,12,12,12,12,12,12,12,12,
  125067. };
  125068. static float _vq_quantthresh__44c4_s_p9_0[] = {
  125069. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  125070. 787.5, 1102.5, 1417.5, 1732.5,
  125071. };
  125072. static long _vq_quantmap__44c4_s_p9_0[] = {
  125073. 11, 9, 7, 5, 3, 1, 0, 2,
  125074. 4, 6, 8, 10, 12,
  125075. };
  125076. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  125077. _vq_quantthresh__44c4_s_p9_0,
  125078. _vq_quantmap__44c4_s_p9_0,
  125079. 13,
  125080. 13
  125081. };
  125082. static static_codebook _44c4_s_p9_0 = {
  125083. 2, 169,
  125084. _vq_lengthlist__44c4_s_p9_0,
  125085. 1, -513964032, 1628680192, 4, 0,
  125086. _vq_quantlist__44c4_s_p9_0,
  125087. NULL,
  125088. &_vq_auxt__44c4_s_p9_0,
  125089. NULL,
  125090. 0
  125091. };
  125092. static long _vq_quantlist__44c4_s_p9_1[] = {
  125093. 7,
  125094. 6,
  125095. 8,
  125096. 5,
  125097. 9,
  125098. 4,
  125099. 10,
  125100. 3,
  125101. 11,
  125102. 2,
  125103. 12,
  125104. 1,
  125105. 13,
  125106. 0,
  125107. 14,
  125108. };
  125109. static long _vq_lengthlist__44c4_s_p9_1[] = {
  125110. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  125111. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  125112. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  125113. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  125114. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  125115. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  125116. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  125117. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  125118. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  125119. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  125120. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  125121. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  125122. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  125123. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  125124. 15,
  125125. };
  125126. static float _vq_quantthresh__44c4_s_p9_1[] = {
  125127. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125128. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125129. };
  125130. static long _vq_quantmap__44c4_s_p9_1[] = {
  125131. 13, 11, 9, 7, 5, 3, 1, 0,
  125132. 2, 4, 6, 8, 10, 12, 14,
  125133. };
  125134. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  125135. _vq_quantthresh__44c4_s_p9_1,
  125136. _vq_quantmap__44c4_s_p9_1,
  125137. 15,
  125138. 15
  125139. };
  125140. static static_codebook _44c4_s_p9_1 = {
  125141. 2, 225,
  125142. _vq_lengthlist__44c4_s_p9_1,
  125143. 1, -520986624, 1620377600, 4, 0,
  125144. _vq_quantlist__44c4_s_p9_1,
  125145. NULL,
  125146. &_vq_auxt__44c4_s_p9_1,
  125147. NULL,
  125148. 0
  125149. };
  125150. static long _vq_quantlist__44c4_s_p9_2[] = {
  125151. 10,
  125152. 9,
  125153. 11,
  125154. 8,
  125155. 12,
  125156. 7,
  125157. 13,
  125158. 6,
  125159. 14,
  125160. 5,
  125161. 15,
  125162. 4,
  125163. 16,
  125164. 3,
  125165. 17,
  125166. 2,
  125167. 18,
  125168. 1,
  125169. 19,
  125170. 0,
  125171. 20,
  125172. };
  125173. static long _vq_lengthlist__44c4_s_p9_2[] = {
  125174. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  125175. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  125176. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  125177. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  125178. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  125179. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  125180. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  125181. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125182. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  125183. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  125184. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  125185. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  125186. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  125187. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  125188. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  125189. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  125190. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  125191. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  125192. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  125193. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  125194. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125195. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  125196. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  125197. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  125198. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  125199. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  125200. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  125201. 10,10,10,10,10,10,10,10,10,
  125202. };
  125203. static float _vq_quantthresh__44c4_s_p9_2[] = {
  125204. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125205. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125206. 6.5, 7.5, 8.5, 9.5,
  125207. };
  125208. static long _vq_quantmap__44c4_s_p9_2[] = {
  125209. 19, 17, 15, 13, 11, 9, 7, 5,
  125210. 3, 1, 0, 2, 4, 6, 8, 10,
  125211. 12, 14, 16, 18, 20,
  125212. };
  125213. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  125214. _vq_quantthresh__44c4_s_p9_2,
  125215. _vq_quantmap__44c4_s_p9_2,
  125216. 21,
  125217. 21
  125218. };
  125219. static static_codebook _44c4_s_p9_2 = {
  125220. 2, 441,
  125221. _vq_lengthlist__44c4_s_p9_2,
  125222. 1, -529268736, 1611661312, 5, 0,
  125223. _vq_quantlist__44c4_s_p9_2,
  125224. NULL,
  125225. &_vq_auxt__44c4_s_p9_2,
  125226. NULL,
  125227. 0
  125228. };
  125229. static long _huff_lengthlist__44c4_s_short[] = {
  125230. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  125231. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  125232. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  125233. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  125234. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  125235. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  125236. 7, 9,12,17,
  125237. };
  125238. static static_codebook _huff_book__44c4_s_short = {
  125239. 2, 100,
  125240. _huff_lengthlist__44c4_s_short,
  125241. 0, 0, 0, 0, 0,
  125242. NULL,
  125243. NULL,
  125244. NULL,
  125245. NULL,
  125246. 0
  125247. };
  125248. static long _huff_lengthlist__44c5_s_long[] = {
  125249. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  125250. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  125251. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  125252. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  125253. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  125254. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  125255. 9, 8, 7, 7,
  125256. };
  125257. static static_codebook _huff_book__44c5_s_long = {
  125258. 2, 100,
  125259. _huff_lengthlist__44c5_s_long,
  125260. 0, 0, 0, 0, 0,
  125261. NULL,
  125262. NULL,
  125263. NULL,
  125264. NULL,
  125265. 0
  125266. };
  125267. static long _vq_quantlist__44c5_s_p1_0[] = {
  125268. 1,
  125269. 0,
  125270. 2,
  125271. };
  125272. static long _vq_lengthlist__44c5_s_p1_0[] = {
  125273. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  125274. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125278. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  125279. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125283. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  125284. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  125319. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  125324. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  125325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125329. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  125330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125364. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125365. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125369. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  125370. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  125371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125374. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  125375. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  125376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125683. 0,
  125684. };
  125685. static float _vq_quantthresh__44c5_s_p1_0[] = {
  125686. -0.5, 0.5,
  125687. };
  125688. static long _vq_quantmap__44c5_s_p1_0[] = {
  125689. 1, 0, 2,
  125690. };
  125691. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  125692. _vq_quantthresh__44c5_s_p1_0,
  125693. _vq_quantmap__44c5_s_p1_0,
  125694. 3,
  125695. 3
  125696. };
  125697. static static_codebook _44c5_s_p1_0 = {
  125698. 8, 6561,
  125699. _vq_lengthlist__44c5_s_p1_0,
  125700. 1, -535822336, 1611661312, 2, 0,
  125701. _vq_quantlist__44c5_s_p1_0,
  125702. NULL,
  125703. &_vq_auxt__44c5_s_p1_0,
  125704. NULL,
  125705. 0
  125706. };
  125707. static long _vq_quantlist__44c5_s_p2_0[] = {
  125708. 2,
  125709. 1,
  125710. 3,
  125711. 0,
  125712. 4,
  125713. };
  125714. static long _vq_lengthlist__44c5_s_p2_0[] = {
  125715. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  125716. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  125717. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  125718. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  125719. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125724. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  125725. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  125726. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  125727. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125732. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  125733. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  125734. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  125735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125740. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  125741. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  125742. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  125743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125754. 0,
  125755. };
  125756. static float _vq_quantthresh__44c5_s_p2_0[] = {
  125757. -1.5, -0.5, 0.5, 1.5,
  125758. };
  125759. static long _vq_quantmap__44c5_s_p2_0[] = {
  125760. 3, 1, 0, 2, 4,
  125761. };
  125762. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  125763. _vq_quantthresh__44c5_s_p2_0,
  125764. _vq_quantmap__44c5_s_p2_0,
  125765. 5,
  125766. 5
  125767. };
  125768. static static_codebook _44c5_s_p2_0 = {
  125769. 4, 625,
  125770. _vq_lengthlist__44c5_s_p2_0,
  125771. 1, -533725184, 1611661312, 3, 0,
  125772. _vq_quantlist__44c5_s_p2_0,
  125773. NULL,
  125774. &_vq_auxt__44c5_s_p2_0,
  125775. NULL,
  125776. 0
  125777. };
  125778. static long _vq_quantlist__44c5_s_p3_0[] = {
  125779. 2,
  125780. 1,
  125781. 3,
  125782. 0,
  125783. 4,
  125784. };
  125785. static long _vq_lengthlist__44c5_s_p3_0[] = {
  125786. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125789. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  125791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125792. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125825. 0,
  125826. };
  125827. static float _vq_quantthresh__44c5_s_p3_0[] = {
  125828. -1.5, -0.5, 0.5, 1.5,
  125829. };
  125830. static long _vq_quantmap__44c5_s_p3_0[] = {
  125831. 3, 1, 0, 2, 4,
  125832. };
  125833. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  125834. _vq_quantthresh__44c5_s_p3_0,
  125835. _vq_quantmap__44c5_s_p3_0,
  125836. 5,
  125837. 5
  125838. };
  125839. static static_codebook _44c5_s_p3_0 = {
  125840. 4, 625,
  125841. _vq_lengthlist__44c5_s_p3_0,
  125842. 1, -533725184, 1611661312, 3, 0,
  125843. _vq_quantlist__44c5_s_p3_0,
  125844. NULL,
  125845. &_vq_auxt__44c5_s_p3_0,
  125846. NULL,
  125847. 0
  125848. };
  125849. static long _vq_quantlist__44c5_s_p4_0[] = {
  125850. 4,
  125851. 3,
  125852. 5,
  125853. 2,
  125854. 6,
  125855. 1,
  125856. 7,
  125857. 0,
  125858. 8,
  125859. };
  125860. static long _vq_lengthlist__44c5_s_p4_0[] = {
  125861. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  125862. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  125863. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  125864. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  125865. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0,
  125867. };
  125868. static float _vq_quantthresh__44c5_s_p4_0[] = {
  125869. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125870. };
  125871. static long _vq_quantmap__44c5_s_p4_0[] = {
  125872. 7, 5, 3, 1, 0, 2, 4, 6,
  125873. 8,
  125874. };
  125875. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  125876. _vq_quantthresh__44c5_s_p4_0,
  125877. _vq_quantmap__44c5_s_p4_0,
  125878. 9,
  125879. 9
  125880. };
  125881. static static_codebook _44c5_s_p4_0 = {
  125882. 2, 81,
  125883. _vq_lengthlist__44c5_s_p4_0,
  125884. 1, -531628032, 1611661312, 4, 0,
  125885. _vq_quantlist__44c5_s_p4_0,
  125886. NULL,
  125887. &_vq_auxt__44c5_s_p4_0,
  125888. NULL,
  125889. 0
  125890. };
  125891. static long _vq_quantlist__44c5_s_p5_0[] = {
  125892. 4,
  125893. 3,
  125894. 5,
  125895. 2,
  125896. 6,
  125897. 1,
  125898. 7,
  125899. 0,
  125900. 8,
  125901. };
  125902. static long _vq_lengthlist__44c5_s_p5_0[] = {
  125903. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  125904. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  125905. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  125906. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  125907. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  125908. 10,
  125909. };
  125910. static float _vq_quantthresh__44c5_s_p5_0[] = {
  125911. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125912. };
  125913. static long _vq_quantmap__44c5_s_p5_0[] = {
  125914. 7, 5, 3, 1, 0, 2, 4, 6,
  125915. 8,
  125916. };
  125917. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  125918. _vq_quantthresh__44c5_s_p5_0,
  125919. _vq_quantmap__44c5_s_p5_0,
  125920. 9,
  125921. 9
  125922. };
  125923. static static_codebook _44c5_s_p5_0 = {
  125924. 2, 81,
  125925. _vq_lengthlist__44c5_s_p5_0,
  125926. 1, -531628032, 1611661312, 4, 0,
  125927. _vq_quantlist__44c5_s_p5_0,
  125928. NULL,
  125929. &_vq_auxt__44c5_s_p5_0,
  125930. NULL,
  125931. 0
  125932. };
  125933. static long _vq_quantlist__44c5_s_p6_0[] = {
  125934. 8,
  125935. 7,
  125936. 9,
  125937. 6,
  125938. 10,
  125939. 5,
  125940. 11,
  125941. 4,
  125942. 12,
  125943. 3,
  125944. 13,
  125945. 2,
  125946. 14,
  125947. 1,
  125948. 15,
  125949. 0,
  125950. 16,
  125951. };
  125952. static long _vq_lengthlist__44c5_s_p6_0[] = {
  125953. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  125954. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125955. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  125956. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  125957. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  125958. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  125959. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  125960. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  125961. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  125962. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  125963. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  125964. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  125965. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  125966. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  125967. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  125968. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  125969. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  125971. 13,
  125972. };
  125973. static float _vq_quantthresh__44c5_s_p6_0[] = {
  125974. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125975. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125976. };
  125977. static long _vq_quantmap__44c5_s_p6_0[] = {
  125978. 15, 13, 11, 9, 7, 5, 3, 1,
  125979. 0, 2, 4, 6, 8, 10, 12, 14,
  125980. 16,
  125981. };
  125982. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  125983. _vq_quantthresh__44c5_s_p6_0,
  125984. _vq_quantmap__44c5_s_p6_0,
  125985. 17,
  125986. 17
  125987. };
  125988. static static_codebook _44c5_s_p6_0 = {
  125989. 2, 289,
  125990. _vq_lengthlist__44c5_s_p6_0,
  125991. 1, -529530880, 1611661312, 5, 0,
  125992. _vq_quantlist__44c5_s_p6_0,
  125993. NULL,
  125994. &_vq_auxt__44c5_s_p6_0,
  125995. NULL,
  125996. 0
  125997. };
  125998. static long _vq_quantlist__44c5_s_p7_0[] = {
  125999. 1,
  126000. 0,
  126001. 2,
  126002. };
  126003. static long _vq_lengthlist__44c5_s_p7_0[] = {
  126004. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  126005. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  126006. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  126007. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  126008. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  126009. 10,
  126010. };
  126011. static float _vq_quantthresh__44c5_s_p7_0[] = {
  126012. -5.5, 5.5,
  126013. };
  126014. static long _vq_quantmap__44c5_s_p7_0[] = {
  126015. 1, 0, 2,
  126016. };
  126017. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  126018. _vq_quantthresh__44c5_s_p7_0,
  126019. _vq_quantmap__44c5_s_p7_0,
  126020. 3,
  126021. 3
  126022. };
  126023. static static_codebook _44c5_s_p7_0 = {
  126024. 4, 81,
  126025. _vq_lengthlist__44c5_s_p7_0,
  126026. 1, -529137664, 1618345984, 2, 0,
  126027. _vq_quantlist__44c5_s_p7_0,
  126028. NULL,
  126029. &_vq_auxt__44c5_s_p7_0,
  126030. NULL,
  126031. 0
  126032. };
  126033. static long _vq_quantlist__44c5_s_p7_1[] = {
  126034. 5,
  126035. 4,
  126036. 6,
  126037. 3,
  126038. 7,
  126039. 2,
  126040. 8,
  126041. 1,
  126042. 9,
  126043. 0,
  126044. 10,
  126045. };
  126046. static long _vq_lengthlist__44c5_s_p7_1[] = {
  126047. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  126048. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  126049. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  126050. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  126051. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  126052. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  126053. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  126054. 10,10,10, 8, 8, 8, 8, 8, 8,
  126055. };
  126056. static float _vq_quantthresh__44c5_s_p7_1[] = {
  126057. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126058. 3.5, 4.5,
  126059. };
  126060. static long _vq_quantmap__44c5_s_p7_1[] = {
  126061. 9, 7, 5, 3, 1, 0, 2, 4,
  126062. 6, 8, 10,
  126063. };
  126064. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  126065. _vq_quantthresh__44c5_s_p7_1,
  126066. _vq_quantmap__44c5_s_p7_1,
  126067. 11,
  126068. 11
  126069. };
  126070. static static_codebook _44c5_s_p7_1 = {
  126071. 2, 121,
  126072. _vq_lengthlist__44c5_s_p7_1,
  126073. 1, -531365888, 1611661312, 4, 0,
  126074. _vq_quantlist__44c5_s_p7_1,
  126075. NULL,
  126076. &_vq_auxt__44c5_s_p7_1,
  126077. NULL,
  126078. 0
  126079. };
  126080. static long _vq_quantlist__44c5_s_p8_0[] = {
  126081. 6,
  126082. 5,
  126083. 7,
  126084. 4,
  126085. 8,
  126086. 3,
  126087. 9,
  126088. 2,
  126089. 10,
  126090. 1,
  126091. 11,
  126092. 0,
  126093. 12,
  126094. };
  126095. static long _vq_lengthlist__44c5_s_p8_0[] = {
  126096. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  126097. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  126098. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126099. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126100. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  126101. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  126102. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  126103. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  126104. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  126105. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  126106. 0,12,12,12,12,12,12,13,13,
  126107. };
  126108. static float _vq_quantthresh__44c5_s_p8_0[] = {
  126109. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126110. 12.5, 17.5, 22.5, 27.5,
  126111. };
  126112. static long _vq_quantmap__44c5_s_p8_0[] = {
  126113. 11, 9, 7, 5, 3, 1, 0, 2,
  126114. 4, 6, 8, 10, 12,
  126115. };
  126116. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  126117. _vq_quantthresh__44c5_s_p8_0,
  126118. _vq_quantmap__44c5_s_p8_0,
  126119. 13,
  126120. 13
  126121. };
  126122. static static_codebook _44c5_s_p8_0 = {
  126123. 2, 169,
  126124. _vq_lengthlist__44c5_s_p8_0,
  126125. 1, -526516224, 1616117760, 4, 0,
  126126. _vq_quantlist__44c5_s_p8_0,
  126127. NULL,
  126128. &_vq_auxt__44c5_s_p8_0,
  126129. NULL,
  126130. 0
  126131. };
  126132. static long _vq_quantlist__44c5_s_p8_1[] = {
  126133. 2,
  126134. 1,
  126135. 3,
  126136. 0,
  126137. 4,
  126138. };
  126139. static long _vq_lengthlist__44c5_s_p8_1[] = {
  126140. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  126141. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126142. };
  126143. static float _vq_quantthresh__44c5_s_p8_1[] = {
  126144. -1.5, -0.5, 0.5, 1.5,
  126145. };
  126146. static long _vq_quantmap__44c5_s_p8_1[] = {
  126147. 3, 1, 0, 2, 4,
  126148. };
  126149. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  126150. _vq_quantthresh__44c5_s_p8_1,
  126151. _vq_quantmap__44c5_s_p8_1,
  126152. 5,
  126153. 5
  126154. };
  126155. static static_codebook _44c5_s_p8_1 = {
  126156. 2, 25,
  126157. _vq_lengthlist__44c5_s_p8_1,
  126158. 1, -533725184, 1611661312, 3, 0,
  126159. _vq_quantlist__44c5_s_p8_1,
  126160. NULL,
  126161. &_vq_auxt__44c5_s_p8_1,
  126162. NULL,
  126163. 0
  126164. };
  126165. static long _vq_quantlist__44c5_s_p9_0[] = {
  126166. 7,
  126167. 6,
  126168. 8,
  126169. 5,
  126170. 9,
  126171. 4,
  126172. 10,
  126173. 3,
  126174. 11,
  126175. 2,
  126176. 12,
  126177. 1,
  126178. 13,
  126179. 0,
  126180. 14,
  126181. };
  126182. static long _vq_lengthlist__44c5_s_p9_0[] = {
  126183. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  126184. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  126185. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126186. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126187. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126188. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126189. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126190. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126191. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126192. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126193. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126194. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126195. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126196. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  126197. 12,
  126198. };
  126199. static float _vq_quantthresh__44c5_s_p9_0[] = {
  126200. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  126201. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  126202. };
  126203. static long _vq_quantmap__44c5_s_p9_0[] = {
  126204. 13, 11, 9, 7, 5, 3, 1, 0,
  126205. 2, 4, 6, 8, 10, 12, 14,
  126206. };
  126207. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  126208. _vq_quantthresh__44c5_s_p9_0,
  126209. _vq_quantmap__44c5_s_p9_0,
  126210. 15,
  126211. 15
  126212. };
  126213. static static_codebook _44c5_s_p9_0 = {
  126214. 2, 225,
  126215. _vq_lengthlist__44c5_s_p9_0,
  126216. 1, -512522752, 1628852224, 4, 0,
  126217. _vq_quantlist__44c5_s_p9_0,
  126218. NULL,
  126219. &_vq_auxt__44c5_s_p9_0,
  126220. NULL,
  126221. 0
  126222. };
  126223. static long _vq_quantlist__44c5_s_p9_1[] = {
  126224. 8,
  126225. 7,
  126226. 9,
  126227. 6,
  126228. 10,
  126229. 5,
  126230. 11,
  126231. 4,
  126232. 12,
  126233. 3,
  126234. 13,
  126235. 2,
  126236. 14,
  126237. 1,
  126238. 15,
  126239. 0,
  126240. 16,
  126241. };
  126242. static long _vq_lengthlist__44c5_s_p9_1[] = {
  126243. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  126244. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  126245. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  126246. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  126247. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  126248. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  126249. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  126250. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  126251. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  126252. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  126253. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  126254. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  126255. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  126256. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  126257. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  126258. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  126259. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  126260. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  126261. 15,
  126262. };
  126263. static float _vq_quantthresh__44c5_s_p9_1[] = {
  126264. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  126265. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  126266. };
  126267. static long _vq_quantmap__44c5_s_p9_1[] = {
  126268. 15, 13, 11, 9, 7, 5, 3, 1,
  126269. 0, 2, 4, 6, 8, 10, 12, 14,
  126270. 16,
  126271. };
  126272. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  126273. _vq_quantthresh__44c5_s_p9_1,
  126274. _vq_quantmap__44c5_s_p9_1,
  126275. 17,
  126276. 17
  126277. };
  126278. static static_codebook _44c5_s_p9_1 = {
  126279. 2, 289,
  126280. _vq_lengthlist__44c5_s_p9_1,
  126281. 1, -520814592, 1620377600, 5, 0,
  126282. _vq_quantlist__44c5_s_p9_1,
  126283. NULL,
  126284. &_vq_auxt__44c5_s_p9_1,
  126285. NULL,
  126286. 0
  126287. };
  126288. static long _vq_quantlist__44c5_s_p9_2[] = {
  126289. 10,
  126290. 9,
  126291. 11,
  126292. 8,
  126293. 12,
  126294. 7,
  126295. 13,
  126296. 6,
  126297. 14,
  126298. 5,
  126299. 15,
  126300. 4,
  126301. 16,
  126302. 3,
  126303. 17,
  126304. 2,
  126305. 18,
  126306. 1,
  126307. 19,
  126308. 0,
  126309. 20,
  126310. };
  126311. static long _vq_lengthlist__44c5_s_p9_2[] = {
  126312. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  126313. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  126314. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  126315. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  126316. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  126317. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  126318. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  126319. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  126320. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  126321. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126322. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  126323. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  126324. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  126325. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  126326. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  126327. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  126328. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  126329. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  126330. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  126331. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  126332. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126333. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  126334. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  126335. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  126336. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  126337. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  126338. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  126339. 10,10,10,10,10,10,10,10,10,
  126340. };
  126341. static float _vq_quantthresh__44c5_s_p9_2[] = {
  126342. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126343. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126344. 6.5, 7.5, 8.5, 9.5,
  126345. };
  126346. static long _vq_quantmap__44c5_s_p9_2[] = {
  126347. 19, 17, 15, 13, 11, 9, 7, 5,
  126348. 3, 1, 0, 2, 4, 6, 8, 10,
  126349. 12, 14, 16, 18, 20,
  126350. };
  126351. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  126352. _vq_quantthresh__44c5_s_p9_2,
  126353. _vq_quantmap__44c5_s_p9_2,
  126354. 21,
  126355. 21
  126356. };
  126357. static static_codebook _44c5_s_p9_2 = {
  126358. 2, 441,
  126359. _vq_lengthlist__44c5_s_p9_2,
  126360. 1, -529268736, 1611661312, 5, 0,
  126361. _vq_quantlist__44c5_s_p9_2,
  126362. NULL,
  126363. &_vq_auxt__44c5_s_p9_2,
  126364. NULL,
  126365. 0
  126366. };
  126367. static long _huff_lengthlist__44c5_s_short[] = {
  126368. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  126369. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  126370. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  126371. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  126372. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  126373. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  126374. 6, 8,11,16,
  126375. };
  126376. static static_codebook _huff_book__44c5_s_short = {
  126377. 2, 100,
  126378. _huff_lengthlist__44c5_s_short,
  126379. 0, 0, 0, 0, 0,
  126380. NULL,
  126381. NULL,
  126382. NULL,
  126383. NULL,
  126384. 0
  126385. };
  126386. static long _huff_lengthlist__44c6_s_long[] = {
  126387. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  126388. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  126389. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  126390. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  126391. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  126392. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  126393. 11,10,10,12,
  126394. };
  126395. static static_codebook _huff_book__44c6_s_long = {
  126396. 2, 100,
  126397. _huff_lengthlist__44c6_s_long,
  126398. 0, 0, 0, 0, 0,
  126399. NULL,
  126400. NULL,
  126401. NULL,
  126402. NULL,
  126403. 0
  126404. };
  126405. static long _vq_quantlist__44c6_s_p1_0[] = {
  126406. 1,
  126407. 0,
  126408. 2,
  126409. };
  126410. static long _vq_lengthlist__44c6_s_p1_0[] = {
  126411. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  126412. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  126413. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  126414. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  126415. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  126416. 8,
  126417. };
  126418. static float _vq_quantthresh__44c6_s_p1_0[] = {
  126419. -0.5, 0.5,
  126420. };
  126421. static long _vq_quantmap__44c6_s_p1_0[] = {
  126422. 1, 0, 2,
  126423. };
  126424. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  126425. _vq_quantthresh__44c6_s_p1_0,
  126426. _vq_quantmap__44c6_s_p1_0,
  126427. 3,
  126428. 3
  126429. };
  126430. static static_codebook _44c6_s_p1_0 = {
  126431. 4, 81,
  126432. _vq_lengthlist__44c6_s_p1_0,
  126433. 1, -535822336, 1611661312, 2, 0,
  126434. _vq_quantlist__44c6_s_p1_0,
  126435. NULL,
  126436. &_vq_auxt__44c6_s_p1_0,
  126437. NULL,
  126438. 0
  126439. };
  126440. static long _vq_quantlist__44c6_s_p2_0[] = {
  126441. 2,
  126442. 1,
  126443. 3,
  126444. 0,
  126445. 4,
  126446. };
  126447. static long _vq_lengthlist__44c6_s_p2_0[] = {
  126448. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  126449. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  126450. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  126451. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  126452. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  126453. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  126454. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  126455. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  126456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126457. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  126458. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  126459. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  126460. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  126461. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  126462. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  126463. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  126464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126465. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  126466. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  126467. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  126468. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  126469. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  126470. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  126471. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126473. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  126474. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  126475. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  126476. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  126477. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  126478. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  126479. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  126484. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  126485. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  126486. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  126487. 13,
  126488. };
  126489. static float _vq_quantthresh__44c6_s_p2_0[] = {
  126490. -1.5, -0.5, 0.5, 1.5,
  126491. };
  126492. static long _vq_quantmap__44c6_s_p2_0[] = {
  126493. 3, 1, 0, 2, 4,
  126494. };
  126495. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  126496. _vq_quantthresh__44c6_s_p2_0,
  126497. _vq_quantmap__44c6_s_p2_0,
  126498. 5,
  126499. 5
  126500. };
  126501. static static_codebook _44c6_s_p2_0 = {
  126502. 4, 625,
  126503. _vq_lengthlist__44c6_s_p2_0,
  126504. 1, -533725184, 1611661312, 3, 0,
  126505. _vq_quantlist__44c6_s_p2_0,
  126506. NULL,
  126507. &_vq_auxt__44c6_s_p2_0,
  126508. NULL,
  126509. 0
  126510. };
  126511. static long _vq_quantlist__44c6_s_p3_0[] = {
  126512. 4,
  126513. 3,
  126514. 5,
  126515. 2,
  126516. 6,
  126517. 1,
  126518. 7,
  126519. 0,
  126520. 8,
  126521. };
  126522. static long _vq_lengthlist__44c6_s_p3_0[] = {
  126523. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  126524. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  126525. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  126526. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  126527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126528. 0,
  126529. };
  126530. static float _vq_quantthresh__44c6_s_p3_0[] = {
  126531. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126532. };
  126533. static long _vq_quantmap__44c6_s_p3_0[] = {
  126534. 7, 5, 3, 1, 0, 2, 4, 6,
  126535. 8,
  126536. };
  126537. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  126538. _vq_quantthresh__44c6_s_p3_0,
  126539. _vq_quantmap__44c6_s_p3_0,
  126540. 9,
  126541. 9
  126542. };
  126543. static static_codebook _44c6_s_p3_0 = {
  126544. 2, 81,
  126545. _vq_lengthlist__44c6_s_p3_0,
  126546. 1, -531628032, 1611661312, 4, 0,
  126547. _vq_quantlist__44c6_s_p3_0,
  126548. NULL,
  126549. &_vq_auxt__44c6_s_p3_0,
  126550. NULL,
  126551. 0
  126552. };
  126553. static long _vq_quantlist__44c6_s_p4_0[] = {
  126554. 8,
  126555. 7,
  126556. 9,
  126557. 6,
  126558. 10,
  126559. 5,
  126560. 11,
  126561. 4,
  126562. 12,
  126563. 3,
  126564. 13,
  126565. 2,
  126566. 14,
  126567. 1,
  126568. 15,
  126569. 0,
  126570. 16,
  126571. };
  126572. static long _vq_lengthlist__44c6_s_p4_0[] = {
  126573. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  126574. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  126575. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  126576. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  126577. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  126578. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  126579. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  126580. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  126581. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  126582. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  126583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126591. 0,
  126592. };
  126593. static float _vq_quantthresh__44c6_s_p4_0[] = {
  126594. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126595. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126596. };
  126597. static long _vq_quantmap__44c6_s_p4_0[] = {
  126598. 15, 13, 11, 9, 7, 5, 3, 1,
  126599. 0, 2, 4, 6, 8, 10, 12, 14,
  126600. 16,
  126601. };
  126602. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  126603. _vq_quantthresh__44c6_s_p4_0,
  126604. _vq_quantmap__44c6_s_p4_0,
  126605. 17,
  126606. 17
  126607. };
  126608. static static_codebook _44c6_s_p4_0 = {
  126609. 2, 289,
  126610. _vq_lengthlist__44c6_s_p4_0,
  126611. 1, -529530880, 1611661312, 5, 0,
  126612. _vq_quantlist__44c6_s_p4_0,
  126613. NULL,
  126614. &_vq_auxt__44c6_s_p4_0,
  126615. NULL,
  126616. 0
  126617. };
  126618. static long _vq_quantlist__44c6_s_p5_0[] = {
  126619. 1,
  126620. 0,
  126621. 2,
  126622. };
  126623. static long _vq_lengthlist__44c6_s_p5_0[] = {
  126624. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  126625. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  126626. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  126627. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  126628. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  126629. 12,
  126630. };
  126631. static float _vq_quantthresh__44c6_s_p5_0[] = {
  126632. -5.5, 5.5,
  126633. };
  126634. static long _vq_quantmap__44c6_s_p5_0[] = {
  126635. 1, 0, 2,
  126636. };
  126637. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  126638. _vq_quantthresh__44c6_s_p5_0,
  126639. _vq_quantmap__44c6_s_p5_0,
  126640. 3,
  126641. 3
  126642. };
  126643. static static_codebook _44c6_s_p5_0 = {
  126644. 4, 81,
  126645. _vq_lengthlist__44c6_s_p5_0,
  126646. 1, -529137664, 1618345984, 2, 0,
  126647. _vq_quantlist__44c6_s_p5_0,
  126648. NULL,
  126649. &_vq_auxt__44c6_s_p5_0,
  126650. NULL,
  126651. 0
  126652. };
  126653. static long _vq_quantlist__44c6_s_p5_1[] = {
  126654. 5,
  126655. 4,
  126656. 6,
  126657. 3,
  126658. 7,
  126659. 2,
  126660. 8,
  126661. 1,
  126662. 9,
  126663. 0,
  126664. 10,
  126665. };
  126666. static long _vq_lengthlist__44c6_s_p5_1[] = {
  126667. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  126668. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  126669. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  126670. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  126671. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  126672. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  126673. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  126674. 11,10,10, 7, 7, 8, 8, 8, 8,
  126675. };
  126676. static float _vq_quantthresh__44c6_s_p5_1[] = {
  126677. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126678. 3.5, 4.5,
  126679. };
  126680. static long _vq_quantmap__44c6_s_p5_1[] = {
  126681. 9, 7, 5, 3, 1, 0, 2, 4,
  126682. 6, 8, 10,
  126683. };
  126684. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  126685. _vq_quantthresh__44c6_s_p5_1,
  126686. _vq_quantmap__44c6_s_p5_1,
  126687. 11,
  126688. 11
  126689. };
  126690. static static_codebook _44c6_s_p5_1 = {
  126691. 2, 121,
  126692. _vq_lengthlist__44c6_s_p5_1,
  126693. 1, -531365888, 1611661312, 4, 0,
  126694. _vq_quantlist__44c6_s_p5_1,
  126695. NULL,
  126696. &_vq_auxt__44c6_s_p5_1,
  126697. NULL,
  126698. 0
  126699. };
  126700. static long _vq_quantlist__44c6_s_p6_0[] = {
  126701. 6,
  126702. 5,
  126703. 7,
  126704. 4,
  126705. 8,
  126706. 3,
  126707. 9,
  126708. 2,
  126709. 10,
  126710. 1,
  126711. 11,
  126712. 0,
  126713. 12,
  126714. };
  126715. static long _vq_lengthlist__44c6_s_p6_0[] = {
  126716. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  126717. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  126718. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  126719. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  126720. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  126721. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  126722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126726. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126727. };
  126728. static float _vq_quantthresh__44c6_s_p6_0[] = {
  126729. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126730. 12.5, 17.5, 22.5, 27.5,
  126731. };
  126732. static long _vq_quantmap__44c6_s_p6_0[] = {
  126733. 11, 9, 7, 5, 3, 1, 0, 2,
  126734. 4, 6, 8, 10, 12,
  126735. };
  126736. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  126737. _vq_quantthresh__44c6_s_p6_0,
  126738. _vq_quantmap__44c6_s_p6_0,
  126739. 13,
  126740. 13
  126741. };
  126742. static static_codebook _44c6_s_p6_0 = {
  126743. 2, 169,
  126744. _vq_lengthlist__44c6_s_p6_0,
  126745. 1, -526516224, 1616117760, 4, 0,
  126746. _vq_quantlist__44c6_s_p6_0,
  126747. NULL,
  126748. &_vq_auxt__44c6_s_p6_0,
  126749. NULL,
  126750. 0
  126751. };
  126752. static long _vq_quantlist__44c6_s_p6_1[] = {
  126753. 2,
  126754. 1,
  126755. 3,
  126756. 0,
  126757. 4,
  126758. };
  126759. static long _vq_lengthlist__44c6_s_p6_1[] = {
  126760. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  126761. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126762. };
  126763. static float _vq_quantthresh__44c6_s_p6_1[] = {
  126764. -1.5, -0.5, 0.5, 1.5,
  126765. };
  126766. static long _vq_quantmap__44c6_s_p6_1[] = {
  126767. 3, 1, 0, 2, 4,
  126768. };
  126769. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  126770. _vq_quantthresh__44c6_s_p6_1,
  126771. _vq_quantmap__44c6_s_p6_1,
  126772. 5,
  126773. 5
  126774. };
  126775. static static_codebook _44c6_s_p6_1 = {
  126776. 2, 25,
  126777. _vq_lengthlist__44c6_s_p6_1,
  126778. 1, -533725184, 1611661312, 3, 0,
  126779. _vq_quantlist__44c6_s_p6_1,
  126780. NULL,
  126781. &_vq_auxt__44c6_s_p6_1,
  126782. NULL,
  126783. 0
  126784. };
  126785. static long _vq_quantlist__44c6_s_p7_0[] = {
  126786. 6,
  126787. 5,
  126788. 7,
  126789. 4,
  126790. 8,
  126791. 3,
  126792. 9,
  126793. 2,
  126794. 10,
  126795. 1,
  126796. 11,
  126797. 0,
  126798. 12,
  126799. };
  126800. static long _vq_lengthlist__44c6_s_p7_0[] = {
  126801. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  126802. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  126803. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  126804. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  126805. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  126806. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  126807. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  126808. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  126809. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  126810. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  126811. 20,13,13,13,13,13,13,14,14,
  126812. };
  126813. static float _vq_quantthresh__44c6_s_p7_0[] = {
  126814. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  126815. 27.5, 38.5, 49.5, 60.5,
  126816. };
  126817. static long _vq_quantmap__44c6_s_p7_0[] = {
  126818. 11, 9, 7, 5, 3, 1, 0, 2,
  126819. 4, 6, 8, 10, 12,
  126820. };
  126821. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  126822. _vq_quantthresh__44c6_s_p7_0,
  126823. _vq_quantmap__44c6_s_p7_0,
  126824. 13,
  126825. 13
  126826. };
  126827. static static_codebook _44c6_s_p7_0 = {
  126828. 2, 169,
  126829. _vq_lengthlist__44c6_s_p7_0,
  126830. 1, -523206656, 1618345984, 4, 0,
  126831. _vq_quantlist__44c6_s_p7_0,
  126832. NULL,
  126833. &_vq_auxt__44c6_s_p7_0,
  126834. NULL,
  126835. 0
  126836. };
  126837. static long _vq_quantlist__44c6_s_p7_1[] = {
  126838. 5,
  126839. 4,
  126840. 6,
  126841. 3,
  126842. 7,
  126843. 2,
  126844. 8,
  126845. 1,
  126846. 9,
  126847. 0,
  126848. 10,
  126849. };
  126850. static long _vq_lengthlist__44c6_s_p7_1[] = {
  126851. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  126852. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  126853. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  126854. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  126855. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  126856. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  126857. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  126858. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  126859. };
  126860. static float _vq_quantthresh__44c6_s_p7_1[] = {
  126861. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126862. 3.5, 4.5,
  126863. };
  126864. static long _vq_quantmap__44c6_s_p7_1[] = {
  126865. 9, 7, 5, 3, 1, 0, 2, 4,
  126866. 6, 8, 10,
  126867. };
  126868. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  126869. _vq_quantthresh__44c6_s_p7_1,
  126870. _vq_quantmap__44c6_s_p7_1,
  126871. 11,
  126872. 11
  126873. };
  126874. static static_codebook _44c6_s_p7_1 = {
  126875. 2, 121,
  126876. _vq_lengthlist__44c6_s_p7_1,
  126877. 1, -531365888, 1611661312, 4, 0,
  126878. _vq_quantlist__44c6_s_p7_1,
  126879. NULL,
  126880. &_vq_auxt__44c6_s_p7_1,
  126881. NULL,
  126882. 0
  126883. };
  126884. static long _vq_quantlist__44c6_s_p8_0[] = {
  126885. 7,
  126886. 6,
  126887. 8,
  126888. 5,
  126889. 9,
  126890. 4,
  126891. 10,
  126892. 3,
  126893. 11,
  126894. 2,
  126895. 12,
  126896. 1,
  126897. 13,
  126898. 0,
  126899. 14,
  126900. };
  126901. static long _vq_lengthlist__44c6_s_p8_0[] = {
  126902. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  126903. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  126904. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  126905. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  126906. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  126907. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  126908. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  126909. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  126910. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  126911. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  126912. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  126913. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  126914. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  126915. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  126916. 14,
  126917. };
  126918. static float _vq_quantthresh__44c6_s_p8_0[] = {
  126919. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126920. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126921. };
  126922. static long _vq_quantmap__44c6_s_p8_0[] = {
  126923. 13, 11, 9, 7, 5, 3, 1, 0,
  126924. 2, 4, 6, 8, 10, 12, 14,
  126925. };
  126926. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  126927. _vq_quantthresh__44c6_s_p8_0,
  126928. _vq_quantmap__44c6_s_p8_0,
  126929. 15,
  126930. 15
  126931. };
  126932. static static_codebook _44c6_s_p8_0 = {
  126933. 2, 225,
  126934. _vq_lengthlist__44c6_s_p8_0,
  126935. 1, -520986624, 1620377600, 4, 0,
  126936. _vq_quantlist__44c6_s_p8_0,
  126937. NULL,
  126938. &_vq_auxt__44c6_s_p8_0,
  126939. NULL,
  126940. 0
  126941. };
  126942. static long _vq_quantlist__44c6_s_p8_1[] = {
  126943. 10,
  126944. 9,
  126945. 11,
  126946. 8,
  126947. 12,
  126948. 7,
  126949. 13,
  126950. 6,
  126951. 14,
  126952. 5,
  126953. 15,
  126954. 4,
  126955. 16,
  126956. 3,
  126957. 17,
  126958. 2,
  126959. 18,
  126960. 1,
  126961. 19,
  126962. 0,
  126963. 20,
  126964. };
  126965. static long _vq_lengthlist__44c6_s_p8_1[] = {
  126966. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  126967. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  126968. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  126969. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  126970. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126971. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  126972. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  126973. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  126974. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126975. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126976. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  126977. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  126978. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  126979. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  126980. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  126981. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  126982. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  126983. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  126984. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  126985. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  126986. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  126987. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  126988. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  126989. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  126990. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  126991. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  126992. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  126993. 10,10,10,10,10,10,10,10,10,
  126994. };
  126995. static float _vq_quantthresh__44c6_s_p8_1[] = {
  126996. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126997. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126998. 6.5, 7.5, 8.5, 9.5,
  126999. };
  127000. static long _vq_quantmap__44c6_s_p8_1[] = {
  127001. 19, 17, 15, 13, 11, 9, 7, 5,
  127002. 3, 1, 0, 2, 4, 6, 8, 10,
  127003. 12, 14, 16, 18, 20,
  127004. };
  127005. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  127006. _vq_quantthresh__44c6_s_p8_1,
  127007. _vq_quantmap__44c6_s_p8_1,
  127008. 21,
  127009. 21
  127010. };
  127011. static static_codebook _44c6_s_p8_1 = {
  127012. 2, 441,
  127013. _vq_lengthlist__44c6_s_p8_1,
  127014. 1, -529268736, 1611661312, 5, 0,
  127015. _vq_quantlist__44c6_s_p8_1,
  127016. NULL,
  127017. &_vq_auxt__44c6_s_p8_1,
  127018. NULL,
  127019. 0
  127020. };
  127021. static long _vq_quantlist__44c6_s_p9_0[] = {
  127022. 6,
  127023. 5,
  127024. 7,
  127025. 4,
  127026. 8,
  127027. 3,
  127028. 9,
  127029. 2,
  127030. 10,
  127031. 1,
  127032. 11,
  127033. 0,
  127034. 12,
  127035. };
  127036. static long _vq_lengthlist__44c6_s_p9_0[] = {
  127037. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  127038. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  127039. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127040. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  127041. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127042. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127043. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127044. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127045. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127046. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127047. 10,10,10,10,10,10,10,10,10,
  127048. };
  127049. static float _vq_quantthresh__44c6_s_p9_0[] = {
  127050. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  127051. 1592.5, 2229.5, 2866.5, 3503.5,
  127052. };
  127053. static long _vq_quantmap__44c6_s_p9_0[] = {
  127054. 11, 9, 7, 5, 3, 1, 0, 2,
  127055. 4, 6, 8, 10, 12,
  127056. };
  127057. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  127058. _vq_quantthresh__44c6_s_p9_0,
  127059. _vq_quantmap__44c6_s_p9_0,
  127060. 13,
  127061. 13
  127062. };
  127063. static static_codebook _44c6_s_p9_0 = {
  127064. 2, 169,
  127065. _vq_lengthlist__44c6_s_p9_0,
  127066. 1, -511845376, 1630791680, 4, 0,
  127067. _vq_quantlist__44c6_s_p9_0,
  127068. NULL,
  127069. &_vq_auxt__44c6_s_p9_0,
  127070. NULL,
  127071. 0
  127072. };
  127073. static long _vq_quantlist__44c6_s_p9_1[] = {
  127074. 6,
  127075. 5,
  127076. 7,
  127077. 4,
  127078. 8,
  127079. 3,
  127080. 9,
  127081. 2,
  127082. 10,
  127083. 1,
  127084. 11,
  127085. 0,
  127086. 12,
  127087. };
  127088. static long _vq_lengthlist__44c6_s_p9_1[] = {
  127089. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  127090. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  127091. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  127092. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  127093. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  127094. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  127095. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  127096. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  127097. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  127098. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  127099. 15,12,10,11,11,13,11,12,13,
  127100. };
  127101. static float _vq_quantthresh__44c6_s_p9_1[] = {
  127102. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  127103. 122.5, 171.5, 220.5, 269.5,
  127104. };
  127105. static long _vq_quantmap__44c6_s_p9_1[] = {
  127106. 11, 9, 7, 5, 3, 1, 0, 2,
  127107. 4, 6, 8, 10, 12,
  127108. };
  127109. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  127110. _vq_quantthresh__44c6_s_p9_1,
  127111. _vq_quantmap__44c6_s_p9_1,
  127112. 13,
  127113. 13
  127114. };
  127115. static static_codebook _44c6_s_p9_1 = {
  127116. 2, 169,
  127117. _vq_lengthlist__44c6_s_p9_1,
  127118. 1, -518889472, 1622704128, 4, 0,
  127119. _vq_quantlist__44c6_s_p9_1,
  127120. NULL,
  127121. &_vq_auxt__44c6_s_p9_1,
  127122. NULL,
  127123. 0
  127124. };
  127125. static long _vq_quantlist__44c6_s_p9_2[] = {
  127126. 24,
  127127. 23,
  127128. 25,
  127129. 22,
  127130. 26,
  127131. 21,
  127132. 27,
  127133. 20,
  127134. 28,
  127135. 19,
  127136. 29,
  127137. 18,
  127138. 30,
  127139. 17,
  127140. 31,
  127141. 16,
  127142. 32,
  127143. 15,
  127144. 33,
  127145. 14,
  127146. 34,
  127147. 13,
  127148. 35,
  127149. 12,
  127150. 36,
  127151. 11,
  127152. 37,
  127153. 10,
  127154. 38,
  127155. 9,
  127156. 39,
  127157. 8,
  127158. 40,
  127159. 7,
  127160. 41,
  127161. 6,
  127162. 42,
  127163. 5,
  127164. 43,
  127165. 4,
  127166. 44,
  127167. 3,
  127168. 45,
  127169. 2,
  127170. 46,
  127171. 1,
  127172. 47,
  127173. 0,
  127174. 48,
  127175. };
  127176. static long _vq_lengthlist__44c6_s_p9_2[] = {
  127177. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  127178. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  127179. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  127180. 7,
  127181. };
  127182. static float _vq_quantthresh__44c6_s_p9_2[] = {
  127183. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  127184. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  127185. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127186. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127187. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  127188. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  127189. };
  127190. static long _vq_quantmap__44c6_s_p9_2[] = {
  127191. 47, 45, 43, 41, 39, 37, 35, 33,
  127192. 31, 29, 27, 25, 23, 21, 19, 17,
  127193. 15, 13, 11, 9, 7, 5, 3, 1,
  127194. 0, 2, 4, 6, 8, 10, 12, 14,
  127195. 16, 18, 20, 22, 24, 26, 28, 30,
  127196. 32, 34, 36, 38, 40, 42, 44, 46,
  127197. 48,
  127198. };
  127199. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  127200. _vq_quantthresh__44c6_s_p9_2,
  127201. _vq_quantmap__44c6_s_p9_2,
  127202. 49,
  127203. 49
  127204. };
  127205. static static_codebook _44c6_s_p9_2 = {
  127206. 1, 49,
  127207. _vq_lengthlist__44c6_s_p9_2,
  127208. 1, -526909440, 1611661312, 6, 0,
  127209. _vq_quantlist__44c6_s_p9_2,
  127210. NULL,
  127211. &_vq_auxt__44c6_s_p9_2,
  127212. NULL,
  127213. 0
  127214. };
  127215. static long _huff_lengthlist__44c6_s_short[] = {
  127216. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  127217. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  127218. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  127219. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  127220. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  127221. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  127222. 9,10,17,18,
  127223. };
  127224. static static_codebook _huff_book__44c6_s_short = {
  127225. 2, 100,
  127226. _huff_lengthlist__44c6_s_short,
  127227. 0, 0, 0, 0, 0,
  127228. NULL,
  127229. NULL,
  127230. NULL,
  127231. NULL,
  127232. 0
  127233. };
  127234. static long _huff_lengthlist__44c7_s_long[] = {
  127235. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  127236. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  127237. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  127238. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  127239. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  127240. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  127241. 11,10,10,12,
  127242. };
  127243. static static_codebook _huff_book__44c7_s_long = {
  127244. 2, 100,
  127245. _huff_lengthlist__44c7_s_long,
  127246. 0, 0, 0, 0, 0,
  127247. NULL,
  127248. NULL,
  127249. NULL,
  127250. NULL,
  127251. 0
  127252. };
  127253. static long _vq_quantlist__44c7_s_p1_0[] = {
  127254. 1,
  127255. 0,
  127256. 2,
  127257. };
  127258. static long _vq_lengthlist__44c7_s_p1_0[] = {
  127259. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  127260. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  127261. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  127262. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  127263. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  127264. 8,
  127265. };
  127266. static float _vq_quantthresh__44c7_s_p1_0[] = {
  127267. -0.5, 0.5,
  127268. };
  127269. static long _vq_quantmap__44c7_s_p1_0[] = {
  127270. 1, 0, 2,
  127271. };
  127272. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  127273. _vq_quantthresh__44c7_s_p1_0,
  127274. _vq_quantmap__44c7_s_p1_0,
  127275. 3,
  127276. 3
  127277. };
  127278. static static_codebook _44c7_s_p1_0 = {
  127279. 4, 81,
  127280. _vq_lengthlist__44c7_s_p1_0,
  127281. 1, -535822336, 1611661312, 2, 0,
  127282. _vq_quantlist__44c7_s_p1_0,
  127283. NULL,
  127284. &_vq_auxt__44c7_s_p1_0,
  127285. NULL,
  127286. 0
  127287. };
  127288. static long _vq_quantlist__44c7_s_p2_0[] = {
  127289. 2,
  127290. 1,
  127291. 3,
  127292. 0,
  127293. 4,
  127294. };
  127295. static long _vq_lengthlist__44c7_s_p2_0[] = {
  127296. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  127297. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  127298. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  127299. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  127300. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  127301. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  127302. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  127303. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  127304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127305. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  127306. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  127307. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  127308. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  127309. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  127310. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  127311. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  127312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127313. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  127314. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  127315. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  127316. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  127317. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  127318. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  127319. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127321. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  127322. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  127323. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  127324. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  127325. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  127326. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  127327. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  127332. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  127333. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  127334. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  127335. 13,
  127336. };
  127337. static float _vq_quantthresh__44c7_s_p2_0[] = {
  127338. -1.5, -0.5, 0.5, 1.5,
  127339. };
  127340. static long _vq_quantmap__44c7_s_p2_0[] = {
  127341. 3, 1, 0, 2, 4,
  127342. };
  127343. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  127344. _vq_quantthresh__44c7_s_p2_0,
  127345. _vq_quantmap__44c7_s_p2_0,
  127346. 5,
  127347. 5
  127348. };
  127349. static static_codebook _44c7_s_p2_0 = {
  127350. 4, 625,
  127351. _vq_lengthlist__44c7_s_p2_0,
  127352. 1, -533725184, 1611661312, 3, 0,
  127353. _vq_quantlist__44c7_s_p2_0,
  127354. NULL,
  127355. &_vq_auxt__44c7_s_p2_0,
  127356. NULL,
  127357. 0
  127358. };
  127359. static long _vq_quantlist__44c7_s_p3_0[] = {
  127360. 4,
  127361. 3,
  127362. 5,
  127363. 2,
  127364. 6,
  127365. 1,
  127366. 7,
  127367. 0,
  127368. 8,
  127369. };
  127370. static long _vq_lengthlist__44c7_s_p3_0[] = {
  127371. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  127372. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  127373. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  127374. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  127375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127376. 0,
  127377. };
  127378. static float _vq_quantthresh__44c7_s_p3_0[] = {
  127379. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127380. };
  127381. static long _vq_quantmap__44c7_s_p3_0[] = {
  127382. 7, 5, 3, 1, 0, 2, 4, 6,
  127383. 8,
  127384. };
  127385. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  127386. _vq_quantthresh__44c7_s_p3_0,
  127387. _vq_quantmap__44c7_s_p3_0,
  127388. 9,
  127389. 9
  127390. };
  127391. static static_codebook _44c7_s_p3_0 = {
  127392. 2, 81,
  127393. _vq_lengthlist__44c7_s_p3_0,
  127394. 1, -531628032, 1611661312, 4, 0,
  127395. _vq_quantlist__44c7_s_p3_0,
  127396. NULL,
  127397. &_vq_auxt__44c7_s_p3_0,
  127398. NULL,
  127399. 0
  127400. };
  127401. static long _vq_quantlist__44c7_s_p4_0[] = {
  127402. 8,
  127403. 7,
  127404. 9,
  127405. 6,
  127406. 10,
  127407. 5,
  127408. 11,
  127409. 4,
  127410. 12,
  127411. 3,
  127412. 13,
  127413. 2,
  127414. 14,
  127415. 1,
  127416. 15,
  127417. 0,
  127418. 16,
  127419. };
  127420. static long _vq_lengthlist__44c7_s_p4_0[] = {
  127421. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  127422. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  127423. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  127424. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  127425. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  127426. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  127427. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  127428. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  127429. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  127430. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  127431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127439. 0,
  127440. };
  127441. static float _vq_quantthresh__44c7_s_p4_0[] = {
  127442. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127443. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127444. };
  127445. static long _vq_quantmap__44c7_s_p4_0[] = {
  127446. 15, 13, 11, 9, 7, 5, 3, 1,
  127447. 0, 2, 4, 6, 8, 10, 12, 14,
  127448. 16,
  127449. };
  127450. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  127451. _vq_quantthresh__44c7_s_p4_0,
  127452. _vq_quantmap__44c7_s_p4_0,
  127453. 17,
  127454. 17
  127455. };
  127456. static static_codebook _44c7_s_p4_0 = {
  127457. 2, 289,
  127458. _vq_lengthlist__44c7_s_p4_0,
  127459. 1, -529530880, 1611661312, 5, 0,
  127460. _vq_quantlist__44c7_s_p4_0,
  127461. NULL,
  127462. &_vq_auxt__44c7_s_p4_0,
  127463. NULL,
  127464. 0
  127465. };
  127466. static long _vq_quantlist__44c7_s_p5_0[] = {
  127467. 1,
  127468. 0,
  127469. 2,
  127470. };
  127471. static long _vq_lengthlist__44c7_s_p5_0[] = {
  127472. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  127473. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  127474. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  127475. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  127476. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  127477. 12,
  127478. };
  127479. static float _vq_quantthresh__44c7_s_p5_0[] = {
  127480. -5.5, 5.5,
  127481. };
  127482. static long _vq_quantmap__44c7_s_p5_0[] = {
  127483. 1, 0, 2,
  127484. };
  127485. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  127486. _vq_quantthresh__44c7_s_p5_0,
  127487. _vq_quantmap__44c7_s_p5_0,
  127488. 3,
  127489. 3
  127490. };
  127491. static static_codebook _44c7_s_p5_0 = {
  127492. 4, 81,
  127493. _vq_lengthlist__44c7_s_p5_0,
  127494. 1, -529137664, 1618345984, 2, 0,
  127495. _vq_quantlist__44c7_s_p5_0,
  127496. NULL,
  127497. &_vq_auxt__44c7_s_p5_0,
  127498. NULL,
  127499. 0
  127500. };
  127501. static long _vq_quantlist__44c7_s_p5_1[] = {
  127502. 5,
  127503. 4,
  127504. 6,
  127505. 3,
  127506. 7,
  127507. 2,
  127508. 8,
  127509. 1,
  127510. 9,
  127511. 0,
  127512. 10,
  127513. };
  127514. static long _vq_lengthlist__44c7_s_p5_1[] = {
  127515. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  127516. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  127517. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  127518. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  127519. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  127520. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  127521. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  127522. 11,11,11, 7, 7, 8, 8, 8, 8,
  127523. };
  127524. static float _vq_quantthresh__44c7_s_p5_1[] = {
  127525. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127526. 3.5, 4.5,
  127527. };
  127528. static long _vq_quantmap__44c7_s_p5_1[] = {
  127529. 9, 7, 5, 3, 1, 0, 2, 4,
  127530. 6, 8, 10,
  127531. };
  127532. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  127533. _vq_quantthresh__44c7_s_p5_1,
  127534. _vq_quantmap__44c7_s_p5_1,
  127535. 11,
  127536. 11
  127537. };
  127538. static static_codebook _44c7_s_p5_1 = {
  127539. 2, 121,
  127540. _vq_lengthlist__44c7_s_p5_1,
  127541. 1, -531365888, 1611661312, 4, 0,
  127542. _vq_quantlist__44c7_s_p5_1,
  127543. NULL,
  127544. &_vq_auxt__44c7_s_p5_1,
  127545. NULL,
  127546. 0
  127547. };
  127548. static long _vq_quantlist__44c7_s_p6_0[] = {
  127549. 6,
  127550. 5,
  127551. 7,
  127552. 4,
  127553. 8,
  127554. 3,
  127555. 9,
  127556. 2,
  127557. 10,
  127558. 1,
  127559. 11,
  127560. 0,
  127561. 12,
  127562. };
  127563. static long _vq_lengthlist__44c7_s_p6_0[] = {
  127564. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  127565. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127566. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  127567. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  127568. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  127569. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  127570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127574. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127575. };
  127576. static float _vq_quantthresh__44c7_s_p6_0[] = {
  127577. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127578. 12.5, 17.5, 22.5, 27.5,
  127579. };
  127580. static long _vq_quantmap__44c7_s_p6_0[] = {
  127581. 11, 9, 7, 5, 3, 1, 0, 2,
  127582. 4, 6, 8, 10, 12,
  127583. };
  127584. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  127585. _vq_quantthresh__44c7_s_p6_0,
  127586. _vq_quantmap__44c7_s_p6_0,
  127587. 13,
  127588. 13
  127589. };
  127590. static static_codebook _44c7_s_p6_0 = {
  127591. 2, 169,
  127592. _vq_lengthlist__44c7_s_p6_0,
  127593. 1, -526516224, 1616117760, 4, 0,
  127594. _vq_quantlist__44c7_s_p6_0,
  127595. NULL,
  127596. &_vq_auxt__44c7_s_p6_0,
  127597. NULL,
  127598. 0
  127599. };
  127600. static long _vq_quantlist__44c7_s_p6_1[] = {
  127601. 2,
  127602. 1,
  127603. 3,
  127604. 0,
  127605. 4,
  127606. };
  127607. static long _vq_lengthlist__44c7_s_p6_1[] = {
  127608. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  127609. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127610. };
  127611. static float _vq_quantthresh__44c7_s_p6_1[] = {
  127612. -1.5, -0.5, 0.5, 1.5,
  127613. };
  127614. static long _vq_quantmap__44c7_s_p6_1[] = {
  127615. 3, 1, 0, 2, 4,
  127616. };
  127617. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  127618. _vq_quantthresh__44c7_s_p6_1,
  127619. _vq_quantmap__44c7_s_p6_1,
  127620. 5,
  127621. 5
  127622. };
  127623. static static_codebook _44c7_s_p6_1 = {
  127624. 2, 25,
  127625. _vq_lengthlist__44c7_s_p6_1,
  127626. 1, -533725184, 1611661312, 3, 0,
  127627. _vq_quantlist__44c7_s_p6_1,
  127628. NULL,
  127629. &_vq_auxt__44c7_s_p6_1,
  127630. NULL,
  127631. 0
  127632. };
  127633. static long _vq_quantlist__44c7_s_p7_0[] = {
  127634. 6,
  127635. 5,
  127636. 7,
  127637. 4,
  127638. 8,
  127639. 3,
  127640. 9,
  127641. 2,
  127642. 10,
  127643. 1,
  127644. 11,
  127645. 0,
  127646. 12,
  127647. };
  127648. static long _vq_lengthlist__44c7_s_p7_0[] = {
  127649. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  127650. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  127651. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  127652. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  127653. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  127654. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  127655. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  127656. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  127657. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  127658. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  127659. 19,13,13,13,13,14,14,15,15,
  127660. };
  127661. static float _vq_quantthresh__44c7_s_p7_0[] = {
  127662. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  127663. 27.5, 38.5, 49.5, 60.5,
  127664. };
  127665. static long _vq_quantmap__44c7_s_p7_0[] = {
  127666. 11, 9, 7, 5, 3, 1, 0, 2,
  127667. 4, 6, 8, 10, 12,
  127668. };
  127669. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  127670. _vq_quantthresh__44c7_s_p7_0,
  127671. _vq_quantmap__44c7_s_p7_0,
  127672. 13,
  127673. 13
  127674. };
  127675. static static_codebook _44c7_s_p7_0 = {
  127676. 2, 169,
  127677. _vq_lengthlist__44c7_s_p7_0,
  127678. 1, -523206656, 1618345984, 4, 0,
  127679. _vq_quantlist__44c7_s_p7_0,
  127680. NULL,
  127681. &_vq_auxt__44c7_s_p7_0,
  127682. NULL,
  127683. 0
  127684. };
  127685. static long _vq_quantlist__44c7_s_p7_1[] = {
  127686. 5,
  127687. 4,
  127688. 6,
  127689. 3,
  127690. 7,
  127691. 2,
  127692. 8,
  127693. 1,
  127694. 9,
  127695. 0,
  127696. 10,
  127697. };
  127698. static long _vq_lengthlist__44c7_s_p7_1[] = {
  127699. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  127700. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  127701. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  127702. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  127703. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  127704. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  127705. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  127706. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  127707. };
  127708. static float _vq_quantthresh__44c7_s_p7_1[] = {
  127709. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127710. 3.5, 4.5,
  127711. };
  127712. static long _vq_quantmap__44c7_s_p7_1[] = {
  127713. 9, 7, 5, 3, 1, 0, 2, 4,
  127714. 6, 8, 10,
  127715. };
  127716. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  127717. _vq_quantthresh__44c7_s_p7_1,
  127718. _vq_quantmap__44c7_s_p7_1,
  127719. 11,
  127720. 11
  127721. };
  127722. static static_codebook _44c7_s_p7_1 = {
  127723. 2, 121,
  127724. _vq_lengthlist__44c7_s_p7_1,
  127725. 1, -531365888, 1611661312, 4, 0,
  127726. _vq_quantlist__44c7_s_p7_1,
  127727. NULL,
  127728. &_vq_auxt__44c7_s_p7_1,
  127729. NULL,
  127730. 0
  127731. };
  127732. static long _vq_quantlist__44c7_s_p8_0[] = {
  127733. 7,
  127734. 6,
  127735. 8,
  127736. 5,
  127737. 9,
  127738. 4,
  127739. 10,
  127740. 3,
  127741. 11,
  127742. 2,
  127743. 12,
  127744. 1,
  127745. 13,
  127746. 0,
  127747. 14,
  127748. };
  127749. static long _vq_lengthlist__44c7_s_p8_0[] = {
  127750. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  127751. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  127752. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  127753. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  127754. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  127755. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  127756. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  127757. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  127758. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  127759. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  127760. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  127761. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  127762. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  127763. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  127764. 14,
  127765. };
  127766. static float _vq_quantthresh__44c7_s_p8_0[] = {
  127767. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127768. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127769. };
  127770. static long _vq_quantmap__44c7_s_p8_0[] = {
  127771. 13, 11, 9, 7, 5, 3, 1, 0,
  127772. 2, 4, 6, 8, 10, 12, 14,
  127773. };
  127774. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  127775. _vq_quantthresh__44c7_s_p8_0,
  127776. _vq_quantmap__44c7_s_p8_0,
  127777. 15,
  127778. 15
  127779. };
  127780. static static_codebook _44c7_s_p8_0 = {
  127781. 2, 225,
  127782. _vq_lengthlist__44c7_s_p8_0,
  127783. 1, -520986624, 1620377600, 4, 0,
  127784. _vq_quantlist__44c7_s_p8_0,
  127785. NULL,
  127786. &_vq_auxt__44c7_s_p8_0,
  127787. NULL,
  127788. 0
  127789. };
  127790. static long _vq_quantlist__44c7_s_p8_1[] = {
  127791. 10,
  127792. 9,
  127793. 11,
  127794. 8,
  127795. 12,
  127796. 7,
  127797. 13,
  127798. 6,
  127799. 14,
  127800. 5,
  127801. 15,
  127802. 4,
  127803. 16,
  127804. 3,
  127805. 17,
  127806. 2,
  127807. 18,
  127808. 1,
  127809. 19,
  127810. 0,
  127811. 20,
  127812. };
  127813. static long _vq_lengthlist__44c7_s_p8_1[] = {
  127814. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  127815. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  127816. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  127817. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  127818. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127819. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  127820. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  127821. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  127822. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127823. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127824. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  127825. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  127826. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  127827. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  127828. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  127829. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  127830. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  127831. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  127832. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  127833. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  127834. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  127835. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  127836. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  127837. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  127838. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  127839. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  127840. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  127841. 10,10,10,10,10,10,10,10,10,
  127842. };
  127843. static float _vq_quantthresh__44c7_s_p8_1[] = {
  127844. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127845. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127846. 6.5, 7.5, 8.5, 9.5,
  127847. };
  127848. static long _vq_quantmap__44c7_s_p8_1[] = {
  127849. 19, 17, 15, 13, 11, 9, 7, 5,
  127850. 3, 1, 0, 2, 4, 6, 8, 10,
  127851. 12, 14, 16, 18, 20,
  127852. };
  127853. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  127854. _vq_quantthresh__44c7_s_p8_1,
  127855. _vq_quantmap__44c7_s_p8_1,
  127856. 21,
  127857. 21
  127858. };
  127859. static static_codebook _44c7_s_p8_1 = {
  127860. 2, 441,
  127861. _vq_lengthlist__44c7_s_p8_1,
  127862. 1, -529268736, 1611661312, 5, 0,
  127863. _vq_quantlist__44c7_s_p8_1,
  127864. NULL,
  127865. &_vq_auxt__44c7_s_p8_1,
  127866. NULL,
  127867. 0
  127868. };
  127869. static long _vq_quantlist__44c7_s_p9_0[] = {
  127870. 6,
  127871. 5,
  127872. 7,
  127873. 4,
  127874. 8,
  127875. 3,
  127876. 9,
  127877. 2,
  127878. 10,
  127879. 1,
  127880. 11,
  127881. 0,
  127882. 12,
  127883. };
  127884. static long _vq_lengthlist__44c7_s_p9_0[] = {
  127885. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  127886. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  127887. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127888. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127889. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127890. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127891. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127892. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127893. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127894. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127895. 11,11,11,11,11,11,11,11,11,
  127896. };
  127897. static float _vq_quantthresh__44c7_s_p9_0[] = {
  127898. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  127899. 1592.5, 2229.5, 2866.5, 3503.5,
  127900. };
  127901. static long _vq_quantmap__44c7_s_p9_0[] = {
  127902. 11, 9, 7, 5, 3, 1, 0, 2,
  127903. 4, 6, 8, 10, 12,
  127904. };
  127905. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  127906. _vq_quantthresh__44c7_s_p9_0,
  127907. _vq_quantmap__44c7_s_p9_0,
  127908. 13,
  127909. 13
  127910. };
  127911. static static_codebook _44c7_s_p9_0 = {
  127912. 2, 169,
  127913. _vq_lengthlist__44c7_s_p9_0,
  127914. 1, -511845376, 1630791680, 4, 0,
  127915. _vq_quantlist__44c7_s_p9_0,
  127916. NULL,
  127917. &_vq_auxt__44c7_s_p9_0,
  127918. NULL,
  127919. 0
  127920. };
  127921. static long _vq_quantlist__44c7_s_p9_1[] = {
  127922. 6,
  127923. 5,
  127924. 7,
  127925. 4,
  127926. 8,
  127927. 3,
  127928. 9,
  127929. 2,
  127930. 10,
  127931. 1,
  127932. 11,
  127933. 0,
  127934. 12,
  127935. };
  127936. static long _vq_lengthlist__44c7_s_p9_1[] = {
  127937. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  127938. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  127939. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  127940. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  127941. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  127942. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  127943. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  127944. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  127945. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  127946. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  127947. 15,11,11,10,10,12,12,12,12,
  127948. };
  127949. static float _vq_quantthresh__44c7_s_p9_1[] = {
  127950. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  127951. 122.5, 171.5, 220.5, 269.5,
  127952. };
  127953. static long _vq_quantmap__44c7_s_p9_1[] = {
  127954. 11, 9, 7, 5, 3, 1, 0, 2,
  127955. 4, 6, 8, 10, 12,
  127956. };
  127957. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  127958. _vq_quantthresh__44c7_s_p9_1,
  127959. _vq_quantmap__44c7_s_p9_1,
  127960. 13,
  127961. 13
  127962. };
  127963. static static_codebook _44c7_s_p9_1 = {
  127964. 2, 169,
  127965. _vq_lengthlist__44c7_s_p9_1,
  127966. 1, -518889472, 1622704128, 4, 0,
  127967. _vq_quantlist__44c7_s_p9_1,
  127968. NULL,
  127969. &_vq_auxt__44c7_s_p9_1,
  127970. NULL,
  127971. 0
  127972. };
  127973. static long _vq_quantlist__44c7_s_p9_2[] = {
  127974. 24,
  127975. 23,
  127976. 25,
  127977. 22,
  127978. 26,
  127979. 21,
  127980. 27,
  127981. 20,
  127982. 28,
  127983. 19,
  127984. 29,
  127985. 18,
  127986. 30,
  127987. 17,
  127988. 31,
  127989. 16,
  127990. 32,
  127991. 15,
  127992. 33,
  127993. 14,
  127994. 34,
  127995. 13,
  127996. 35,
  127997. 12,
  127998. 36,
  127999. 11,
  128000. 37,
  128001. 10,
  128002. 38,
  128003. 9,
  128004. 39,
  128005. 8,
  128006. 40,
  128007. 7,
  128008. 41,
  128009. 6,
  128010. 42,
  128011. 5,
  128012. 43,
  128013. 4,
  128014. 44,
  128015. 3,
  128016. 45,
  128017. 2,
  128018. 46,
  128019. 1,
  128020. 47,
  128021. 0,
  128022. 48,
  128023. };
  128024. static long _vq_lengthlist__44c7_s_p9_2[] = {
  128025. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  128026. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128027. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128028. 7,
  128029. };
  128030. static float _vq_quantthresh__44c7_s_p9_2[] = {
  128031. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  128032. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  128033. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128034. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128035. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  128036. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  128037. };
  128038. static long _vq_quantmap__44c7_s_p9_2[] = {
  128039. 47, 45, 43, 41, 39, 37, 35, 33,
  128040. 31, 29, 27, 25, 23, 21, 19, 17,
  128041. 15, 13, 11, 9, 7, 5, 3, 1,
  128042. 0, 2, 4, 6, 8, 10, 12, 14,
  128043. 16, 18, 20, 22, 24, 26, 28, 30,
  128044. 32, 34, 36, 38, 40, 42, 44, 46,
  128045. 48,
  128046. };
  128047. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  128048. _vq_quantthresh__44c7_s_p9_2,
  128049. _vq_quantmap__44c7_s_p9_2,
  128050. 49,
  128051. 49
  128052. };
  128053. static static_codebook _44c7_s_p9_2 = {
  128054. 1, 49,
  128055. _vq_lengthlist__44c7_s_p9_2,
  128056. 1, -526909440, 1611661312, 6, 0,
  128057. _vq_quantlist__44c7_s_p9_2,
  128058. NULL,
  128059. &_vq_auxt__44c7_s_p9_2,
  128060. NULL,
  128061. 0
  128062. };
  128063. static long _huff_lengthlist__44c7_s_short[] = {
  128064. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  128065. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  128066. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  128067. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  128068. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  128069. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  128070. 10, 9,11,14,
  128071. };
  128072. static static_codebook _huff_book__44c7_s_short = {
  128073. 2, 100,
  128074. _huff_lengthlist__44c7_s_short,
  128075. 0, 0, 0, 0, 0,
  128076. NULL,
  128077. NULL,
  128078. NULL,
  128079. NULL,
  128080. 0
  128081. };
  128082. static long _huff_lengthlist__44c8_s_long[] = {
  128083. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  128084. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  128085. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  128086. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  128087. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  128088. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  128089. 11, 9, 9,10,
  128090. };
  128091. static static_codebook _huff_book__44c8_s_long = {
  128092. 2, 100,
  128093. _huff_lengthlist__44c8_s_long,
  128094. 0, 0, 0, 0, 0,
  128095. NULL,
  128096. NULL,
  128097. NULL,
  128098. NULL,
  128099. 0
  128100. };
  128101. static long _vq_quantlist__44c8_s_p1_0[] = {
  128102. 1,
  128103. 0,
  128104. 2,
  128105. };
  128106. static long _vq_lengthlist__44c8_s_p1_0[] = {
  128107. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  128108. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  128109. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  128110. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  128111. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  128112. 8,
  128113. };
  128114. static float _vq_quantthresh__44c8_s_p1_0[] = {
  128115. -0.5, 0.5,
  128116. };
  128117. static long _vq_quantmap__44c8_s_p1_0[] = {
  128118. 1, 0, 2,
  128119. };
  128120. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  128121. _vq_quantthresh__44c8_s_p1_0,
  128122. _vq_quantmap__44c8_s_p1_0,
  128123. 3,
  128124. 3
  128125. };
  128126. static static_codebook _44c8_s_p1_0 = {
  128127. 4, 81,
  128128. _vq_lengthlist__44c8_s_p1_0,
  128129. 1, -535822336, 1611661312, 2, 0,
  128130. _vq_quantlist__44c8_s_p1_0,
  128131. NULL,
  128132. &_vq_auxt__44c8_s_p1_0,
  128133. NULL,
  128134. 0
  128135. };
  128136. static long _vq_quantlist__44c8_s_p2_0[] = {
  128137. 2,
  128138. 1,
  128139. 3,
  128140. 0,
  128141. 4,
  128142. };
  128143. static long _vq_lengthlist__44c8_s_p2_0[] = {
  128144. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  128145. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  128146. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  128147. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  128148. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  128149. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  128150. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  128151. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  128152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128153. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  128154. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  128155. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  128156. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  128157. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  128158. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  128159. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  128160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128161. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  128162. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  128163. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  128164. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  128165. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  128166. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  128167. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128169. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  128170. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  128171. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  128172. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  128173. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  128174. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  128175. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  128180. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  128181. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  128182. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  128183. 13,
  128184. };
  128185. static float _vq_quantthresh__44c8_s_p2_0[] = {
  128186. -1.5, -0.5, 0.5, 1.5,
  128187. };
  128188. static long _vq_quantmap__44c8_s_p2_0[] = {
  128189. 3, 1, 0, 2, 4,
  128190. };
  128191. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  128192. _vq_quantthresh__44c8_s_p2_0,
  128193. _vq_quantmap__44c8_s_p2_0,
  128194. 5,
  128195. 5
  128196. };
  128197. static static_codebook _44c8_s_p2_0 = {
  128198. 4, 625,
  128199. _vq_lengthlist__44c8_s_p2_0,
  128200. 1, -533725184, 1611661312, 3, 0,
  128201. _vq_quantlist__44c8_s_p2_0,
  128202. NULL,
  128203. &_vq_auxt__44c8_s_p2_0,
  128204. NULL,
  128205. 0
  128206. };
  128207. static long _vq_quantlist__44c8_s_p3_0[] = {
  128208. 4,
  128209. 3,
  128210. 5,
  128211. 2,
  128212. 6,
  128213. 1,
  128214. 7,
  128215. 0,
  128216. 8,
  128217. };
  128218. static long _vq_lengthlist__44c8_s_p3_0[] = {
  128219. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  128220. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  128221. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  128222. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  128223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128224. 0,
  128225. };
  128226. static float _vq_quantthresh__44c8_s_p3_0[] = {
  128227. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128228. };
  128229. static long _vq_quantmap__44c8_s_p3_0[] = {
  128230. 7, 5, 3, 1, 0, 2, 4, 6,
  128231. 8,
  128232. };
  128233. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  128234. _vq_quantthresh__44c8_s_p3_0,
  128235. _vq_quantmap__44c8_s_p3_0,
  128236. 9,
  128237. 9
  128238. };
  128239. static static_codebook _44c8_s_p3_0 = {
  128240. 2, 81,
  128241. _vq_lengthlist__44c8_s_p3_0,
  128242. 1, -531628032, 1611661312, 4, 0,
  128243. _vq_quantlist__44c8_s_p3_0,
  128244. NULL,
  128245. &_vq_auxt__44c8_s_p3_0,
  128246. NULL,
  128247. 0
  128248. };
  128249. static long _vq_quantlist__44c8_s_p4_0[] = {
  128250. 8,
  128251. 7,
  128252. 9,
  128253. 6,
  128254. 10,
  128255. 5,
  128256. 11,
  128257. 4,
  128258. 12,
  128259. 3,
  128260. 13,
  128261. 2,
  128262. 14,
  128263. 1,
  128264. 15,
  128265. 0,
  128266. 16,
  128267. };
  128268. static long _vq_lengthlist__44c8_s_p4_0[] = {
  128269. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  128270. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  128271. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  128272. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  128273. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  128274. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  128275. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  128276. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  128277. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  128278. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  128279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128287. 0,
  128288. };
  128289. static float _vq_quantthresh__44c8_s_p4_0[] = {
  128290. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128291. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128292. };
  128293. static long _vq_quantmap__44c8_s_p4_0[] = {
  128294. 15, 13, 11, 9, 7, 5, 3, 1,
  128295. 0, 2, 4, 6, 8, 10, 12, 14,
  128296. 16,
  128297. };
  128298. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  128299. _vq_quantthresh__44c8_s_p4_0,
  128300. _vq_quantmap__44c8_s_p4_0,
  128301. 17,
  128302. 17
  128303. };
  128304. static static_codebook _44c8_s_p4_0 = {
  128305. 2, 289,
  128306. _vq_lengthlist__44c8_s_p4_0,
  128307. 1, -529530880, 1611661312, 5, 0,
  128308. _vq_quantlist__44c8_s_p4_0,
  128309. NULL,
  128310. &_vq_auxt__44c8_s_p4_0,
  128311. NULL,
  128312. 0
  128313. };
  128314. static long _vq_quantlist__44c8_s_p5_0[] = {
  128315. 1,
  128316. 0,
  128317. 2,
  128318. };
  128319. static long _vq_lengthlist__44c8_s_p5_0[] = {
  128320. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  128321. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  128322. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  128323. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  128324. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  128325. 12,
  128326. };
  128327. static float _vq_quantthresh__44c8_s_p5_0[] = {
  128328. -5.5, 5.5,
  128329. };
  128330. static long _vq_quantmap__44c8_s_p5_0[] = {
  128331. 1, 0, 2,
  128332. };
  128333. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  128334. _vq_quantthresh__44c8_s_p5_0,
  128335. _vq_quantmap__44c8_s_p5_0,
  128336. 3,
  128337. 3
  128338. };
  128339. static static_codebook _44c8_s_p5_0 = {
  128340. 4, 81,
  128341. _vq_lengthlist__44c8_s_p5_0,
  128342. 1, -529137664, 1618345984, 2, 0,
  128343. _vq_quantlist__44c8_s_p5_0,
  128344. NULL,
  128345. &_vq_auxt__44c8_s_p5_0,
  128346. NULL,
  128347. 0
  128348. };
  128349. static long _vq_quantlist__44c8_s_p5_1[] = {
  128350. 5,
  128351. 4,
  128352. 6,
  128353. 3,
  128354. 7,
  128355. 2,
  128356. 8,
  128357. 1,
  128358. 9,
  128359. 0,
  128360. 10,
  128361. };
  128362. static long _vq_lengthlist__44c8_s_p5_1[] = {
  128363. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  128364. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  128365. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  128366. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  128367. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  128368. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  128369. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  128370. 11,11,11, 7, 7, 7, 7, 8, 8,
  128371. };
  128372. static float _vq_quantthresh__44c8_s_p5_1[] = {
  128373. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128374. 3.5, 4.5,
  128375. };
  128376. static long _vq_quantmap__44c8_s_p5_1[] = {
  128377. 9, 7, 5, 3, 1, 0, 2, 4,
  128378. 6, 8, 10,
  128379. };
  128380. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  128381. _vq_quantthresh__44c8_s_p5_1,
  128382. _vq_quantmap__44c8_s_p5_1,
  128383. 11,
  128384. 11
  128385. };
  128386. static static_codebook _44c8_s_p5_1 = {
  128387. 2, 121,
  128388. _vq_lengthlist__44c8_s_p5_1,
  128389. 1, -531365888, 1611661312, 4, 0,
  128390. _vq_quantlist__44c8_s_p5_1,
  128391. NULL,
  128392. &_vq_auxt__44c8_s_p5_1,
  128393. NULL,
  128394. 0
  128395. };
  128396. static long _vq_quantlist__44c8_s_p6_0[] = {
  128397. 6,
  128398. 5,
  128399. 7,
  128400. 4,
  128401. 8,
  128402. 3,
  128403. 9,
  128404. 2,
  128405. 10,
  128406. 1,
  128407. 11,
  128408. 0,
  128409. 12,
  128410. };
  128411. static long _vq_lengthlist__44c8_s_p6_0[] = {
  128412. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  128413. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  128414. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  128415. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  128416. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  128417. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  128418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128422. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128423. };
  128424. static float _vq_quantthresh__44c8_s_p6_0[] = {
  128425. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128426. 12.5, 17.5, 22.5, 27.5,
  128427. };
  128428. static long _vq_quantmap__44c8_s_p6_0[] = {
  128429. 11, 9, 7, 5, 3, 1, 0, 2,
  128430. 4, 6, 8, 10, 12,
  128431. };
  128432. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  128433. _vq_quantthresh__44c8_s_p6_0,
  128434. _vq_quantmap__44c8_s_p6_0,
  128435. 13,
  128436. 13
  128437. };
  128438. static static_codebook _44c8_s_p6_0 = {
  128439. 2, 169,
  128440. _vq_lengthlist__44c8_s_p6_0,
  128441. 1, -526516224, 1616117760, 4, 0,
  128442. _vq_quantlist__44c8_s_p6_0,
  128443. NULL,
  128444. &_vq_auxt__44c8_s_p6_0,
  128445. NULL,
  128446. 0
  128447. };
  128448. static long _vq_quantlist__44c8_s_p6_1[] = {
  128449. 2,
  128450. 1,
  128451. 3,
  128452. 0,
  128453. 4,
  128454. };
  128455. static long _vq_lengthlist__44c8_s_p6_1[] = {
  128456. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  128457. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128458. };
  128459. static float _vq_quantthresh__44c8_s_p6_1[] = {
  128460. -1.5, -0.5, 0.5, 1.5,
  128461. };
  128462. static long _vq_quantmap__44c8_s_p6_1[] = {
  128463. 3, 1, 0, 2, 4,
  128464. };
  128465. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  128466. _vq_quantthresh__44c8_s_p6_1,
  128467. _vq_quantmap__44c8_s_p6_1,
  128468. 5,
  128469. 5
  128470. };
  128471. static static_codebook _44c8_s_p6_1 = {
  128472. 2, 25,
  128473. _vq_lengthlist__44c8_s_p6_1,
  128474. 1, -533725184, 1611661312, 3, 0,
  128475. _vq_quantlist__44c8_s_p6_1,
  128476. NULL,
  128477. &_vq_auxt__44c8_s_p6_1,
  128478. NULL,
  128479. 0
  128480. };
  128481. static long _vq_quantlist__44c8_s_p7_0[] = {
  128482. 6,
  128483. 5,
  128484. 7,
  128485. 4,
  128486. 8,
  128487. 3,
  128488. 9,
  128489. 2,
  128490. 10,
  128491. 1,
  128492. 11,
  128493. 0,
  128494. 12,
  128495. };
  128496. static long _vq_lengthlist__44c8_s_p7_0[] = {
  128497. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  128498. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  128499. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  128500. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  128501. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  128502. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  128503. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  128504. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  128505. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  128506. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  128507. 20,13,13,13,13,14,13,15,15,
  128508. };
  128509. static float _vq_quantthresh__44c8_s_p7_0[] = {
  128510. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  128511. 27.5, 38.5, 49.5, 60.5,
  128512. };
  128513. static long _vq_quantmap__44c8_s_p7_0[] = {
  128514. 11, 9, 7, 5, 3, 1, 0, 2,
  128515. 4, 6, 8, 10, 12,
  128516. };
  128517. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  128518. _vq_quantthresh__44c8_s_p7_0,
  128519. _vq_quantmap__44c8_s_p7_0,
  128520. 13,
  128521. 13
  128522. };
  128523. static static_codebook _44c8_s_p7_0 = {
  128524. 2, 169,
  128525. _vq_lengthlist__44c8_s_p7_0,
  128526. 1, -523206656, 1618345984, 4, 0,
  128527. _vq_quantlist__44c8_s_p7_0,
  128528. NULL,
  128529. &_vq_auxt__44c8_s_p7_0,
  128530. NULL,
  128531. 0
  128532. };
  128533. static long _vq_quantlist__44c8_s_p7_1[] = {
  128534. 5,
  128535. 4,
  128536. 6,
  128537. 3,
  128538. 7,
  128539. 2,
  128540. 8,
  128541. 1,
  128542. 9,
  128543. 0,
  128544. 10,
  128545. };
  128546. static long _vq_lengthlist__44c8_s_p7_1[] = {
  128547. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  128548. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  128549. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  128550. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  128551. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  128552. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  128553. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  128554. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  128555. };
  128556. static float _vq_quantthresh__44c8_s_p7_1[] = {
  128557. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128558. 3.5, 4.5,
  128559. };
  128560. static long _vq_quantmap__44c8_s_p7_1[] = {
  128561. 9, 7, 5, 3, 1, 0, 2, 4,
  128562. 6, 8, 10,
  128563. };
  128564. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  128565. _vq_quantthresh__44c8_s_p7_1,
  128566. _vq_quantmap__44c8_s_p7_1,
  128567. 11,
  128568. 11
  128569. };
  128570. static static_codebook _44c8_s_p7_1 = {
  128571. 2, 121,
  128572. _vq_lengthlist__44c8_s_p7_1,
  128573. 1, -531365888, 1611661312, 4, 0,
  128574. _vq_quantlist__44c8_s_p7_1,
  128575. NULL,
  128576. &_vq_auxt__44c8_s_p7_1,
  128577. NULL,
  128578. 0
  128579. };
  128580. static long _vq_quantlist__44c8_s_p8_0[] = {
  128581. 7,
  128582. 6,
  128583. 8,
  128584. 5,
  128585. 9,
  128586. 4,
  128587. 10,
  128588. 3,
  128589. 11,
  128590. 2,
  128591. 12,
  128592. 1,
  128593. 13,
  128594. 0,
  128595. 14,
  128596. };
  128597. static long _vq_lengthlist__44c8_s_p8_0[] = {
  128598. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  128599. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  128600. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  128601. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  128602. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  128603. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  128604. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  128605. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  128606. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  128607. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  128608. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  128609. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  128610. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  128611. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  128612. 15,
  128613. };
  128614. static float _vq_quantthresh__44c8_s_p8_0[] = {
  128615. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  128616. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  128617. };
  128618. static long _vq_quantmap__44c8_s_p8_0[] = {
  128619. 13, 11, 9, 7, 5, 3, 1, 0,
  128620. 2, 4, 6, 8, 10, 12, 14,
  128621. };
  128622. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  128623. _vq_quantthresh__44c8_s_p8_0,
  128624. _vq_quantmap__44c8_s_p8_0,
  128625. 15,
  128626. 15
  128627. };
  128628. static static_codebook _44c8_s_p8_0 = {
  128629. 2, 225,
  128630. _vq_lengthlist__44c8_s_p8_0,
  128631. 1, -520986624, 1620377600, 4, 0,
  128632. _vq_quantlist__44c8_s_p8_0,
  128633. NULL,
  128634. &_vq_auxt__44c8_s_p8_0,
  128635. NULL,
  128636. 0
  128637. };
  128638. static long _vq_quantlist__44c8_s_p8_1[] = {
  128639. 10,
  128640. 9,
  128641. 11,
  128642. 8,
  128643. 12,
  128644. 7,
  128645. 13,
  128646. 6,
  128647. 14,
  128648. 5,
  128649. 15,
  128650. 4,
  128651. 16,
  128652. 3,
  128653. 17,
  128654. 2,
  128655. 18,
  128656. 1,
  128657. 19,
  128658. 0,
  128659. 20,
  128660. };
  128661. static long _vq_lengthlist__44c8_s_p8_1[] = {
  128662. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  128663. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  128664. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  128665. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  128666. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128667. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  128668. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  128669. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  128670. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128671. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128672. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  128673. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  128674. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  128675. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128676. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  128677. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  128678. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  128679. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  128680. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  128681. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  128682. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  128683. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  128684. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  128685. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  128686. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  128687. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  128688. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  128689. 10, 9, 9,10,10, 9,10, 9, 9,
  128690. };
  128691. static float _vq_quantthresh__44c8_s_p8_1[] = {
  128692. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128693. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128694. 6.5, 7.5, 8.5, 9.5,
  128695. };
  128696. static long _vq_quantmap__44c8_s_p8_1[] = {
  128697. 19, 17, 15, 13, 11, 9, 7, 5,
  128698. 3, 1, 0, 2, 4, 6, 8, 10,
  128699. 12, 14, 16, 18, 20,
  128700. };
  128701. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  128702. _vq_quantthresh__44c8_s_p8_1,
  128703. _vq_quantmap__44c8_s_p8_1,
  128704. 21,
  128705. 21
  128706. };
  128707. static static_codebook _44c8_s_p8_1 = {
  128708. 2, 441,
  128709. _vq_lengthlist__44c8_s_p8_1,
  128710. 1, -529268736, 1611661312, 5, 0,
  128711. _vq_quantlist__44c8_s_p8_1,
  128712. NULL,
  128713. &_vq_auxt__44c8_s_p8_1,
  128714. NULL,
  128715. 0
  128716. };
  128717. static long _vq_quantlist__44c8_s_p9_0[] = {
  128718. 8,
  128719. 7,
  128720. 9,
  128721. 6,
  128722. 10,
  128723. 5,
  128724. 11,
  128725. 4,
  128726. 12,
  128727. 3,
  128728. 13,
  128729. 2,
  128730. 14,
  128731. 1,
  128732. 15,
  128733. 0,
  128734. 16,
  128735. };
  128736. static long _vq_lengthlist__44c8_s_p9_0[] = {
  128737. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128738. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  128739. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  128740. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128741. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128742. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128743. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128744. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128745. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128746. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128747. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128748. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128749. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128750. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128751. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128752. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128753. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128754. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128755. 10,
  128756. };
  128757. static float _vq_quantthresh__44c8_s_p9_0[] = {
  128758. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  128759. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  128760. };
  128761. static long _vq_quantmap__44c8_s_p9_0[] = {
  128762. 15, 13, 11, 9, 7, 5, 3, 1,
  128763. 0, 2, 4, 6, 8, 10, 12, 14,
  128764. 16,
  128765. };
  128766. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  128767. _vq_quantthresh__44c8_s_p9_0,
  128768. _vq_quantmap__44c8_s_p9_0,
  128769. 17,
  128770. 17
  128771. };
  128772. static static_codebook _44c8_s_p9_0 = {
  128773. 2, 289,
  128774. _vq_lengthlist__44c8_s_p9_0,
  128775. 1, -509798400, 1631393792, 5, 0,
  128776. _vq_quantlist__44c8_s_p9_0,
  128777. NULL,
  128778. &_vq_auxt__44c8_s_p9_0,
  128779. NULL,
  128780. 0
  128781. };
  128782. static long _vq_quantlist__44c8_s_p9_1[] = {
  128783. 9,
  128784. 8,
  128785. 10,
  128786. 7,
  128787. 11,
  128788. 6,
  128789. 12,
  128790. 5,
  128791. 13,
  128792. 4,
  128793. 14,
  128794. 3,
  128795. 15,
  128796. 2,
  128797. 16,
  128798. 1,
  128799. 17,
  128800. 0,
  128801. 18,
  128802. };
  128803. static long _vq_lengthlist__44c8_s_p9_1[] = {
  128804. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  128805. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  128806. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  128807. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  128808. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  128809. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  128810. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  128811. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  128812. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  128813. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  128814. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  128815. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  128816. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  128817. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  128818. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  128819. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  128820. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  128821. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  128822. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  128823. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  128824. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  128825. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  128826. 14,13,13,14,14,15,14,15,14,
  128827. };
  128828. static float _vq_quantthresh__44c8_s_p9_1[] = {
  128829. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  128830. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  128831. 367.5, 416.5,
  128832. };
  128833. static long _vq_quantmap__44c8_s_p9_1[] = {
  128834. 17, 15, 13, 11, 9, 7, 5, 3,
  128835. 1, 0, 2, 4, 6, 8, 10, 12,
  128836. 14, 16, 18,
  128837. };
  128838. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  128839. _vq_quantthresh__44c8_s_p9_1,
  128840. _vq_quantmap__44c8_s_p9_1,
  128841. 19,
  128842. 19
  128843. };
  128844. static static_codebook _44c8_s_p9_1 = {
  128845. 2, 361,
  128846. _vq_lengthlist__44c8_s_p9_1,
  128847. 1, -518287360, 1622704128, 5, 0,
  128848. _vq_quantlist__44c8_s_p9_1,
  128849. NULL,
  128850. &_vq_auxt__44c8_s_p9_1,
  128851. NULL,
  128852. 0
  128853. };
  128854. static long _vq_quantlist__44c8_s_p9_2[] = {
  128855. 24,
  128856. 23,
  128857. 25,
  128858. 22,
  128859. 26,
  128860. 21,
  128861. 27,
  128862. 20,
  128863. 28,
  128864. 19,
  128865. 29,
  128866. 18,
  128867. 30,
  128868. 17,
  128869. 31,
  128870. 16,
  128871. 32,
  128872. 15,
  128873. 33,
  128874. 14,
  128875. 34,
  128876. 13,
  128877. 35,
  128878. 12,
  128879. 36,
  128880. 11,
  128881. 37,
  128882. 10,
  128883. 38,
  128884. 9,
  128885. 39,
  128886. 8,
  128887. 40,
  128888. 7,
  128889. 41,
  128890. 6,
  128891. 42,
  128892. 5,
  128893. 43,
  128894. 4,
  128895. 44,
  128896. 3,
  128897. 45,
  128898. 2,
  128899. 46,
  128900. 1,
  128901. 47,
  128902. 0,
  128903. 48,
  128904. };
  128905. static long _vq_lengthlist__44c8_s_p9_2[] = {
  128906. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  128907. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128908. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128909. 7,
  128910. };
  128911. static float _vq_quantthresh__44c8_s_p9_2[] = {
  128912. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  128913. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  128914. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128915. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128916. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  128917. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  128918. };
  128919. static long _vq_quantmap__44c8_s_p9_2[] = {
  128920. 47, 45, 43, 41, 39, 37, 35, 33,
  128921. 31, 29, 27, 25, 23, 21, 19, 17,
  128922. 15, 13, 11, 9, 7, 5, 3, 1,
  128923. 0, 2, 4, 6, 8, 10, 12, 14,
  128924. 16, 18, 20, 22, 24, 26, 28, 30,
  128925. 32, 34, 36, 38, 40, 42, 44, 46,
  128926. 48,
  128927. };
  128928. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  128929. _vq_quantthresh__44c8_s_p9_2,
  128930. _vq_quantmap__44c8_s_p9_2,
  128931. 49,
  128932. 49
  128933. };
  128934. static static_codebook _44c8_s_p9_2 = {
  128935. 1, 49,
  128936. _vq_lengthlist__44c8_s_p9_2,
  128937. 1, -526909440, 1611661312, 6, 0,
  128938. _vq_quantlist__44c8_s_p9_2,
  128939. NULL,
  128940. &_vq_auxt__44c8_s_p9_2,
  128941. NULL,
  128942. 0
  128943. };
  128944. static long _huff_lengthlist__44c8_s_short[] = {
  128945. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  128946. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  128947. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  128948. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  128949. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  128950. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  128951. 10, 9,11,14,
  128952. };
  128953. static static_codebook _huff_book__44c8_s_short = {
  128954. 2, 100,
  128955. _huff_lengthlist__44c8_s_short,
  128956. 0, 0, 0, 0, 0,
  128957. NULL,
  128958. NULL,
  128959. NULL,
  128960. NULL,
  128961. 0
  128962. };
  128963. static long _huff_lengthlist__44c9_s_long[] = {
  128964. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  128965. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  128966. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  128967. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  128968. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  128969. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  128970. 10, 9, 8, 9,
  128971. };
  128972. static static_codebook _huff_book__44c9_s_long = {
  128973. 2, 100,
  128974. _huff_lengthlist__44c9_s_long,
  128975. 0, 0, 0, 0, 0,
  128976. NULL,
  128977. NULL,
  128978. NULL,
  128979. NULL,
  128980. 0
  128981. };
  128982. static long _vq_quantlist__44c9_s_p1_0[] = {
  128983. 1,
  128984. 0,
  128985. 2,
  128986. };
  128987. static long _vq_lengthlist__44c9_s_p1_0[] = {
  128988. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  128989. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  128990. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  128991. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  128992. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  128993. 7,
  128994. };
  128995. static float _vq_quantthresh__44c9_s_p1_0[] = {
  128996. -0.5, 0.5,
  128997. };
  128998. static long _vq_quantmap__44c9_s_p1_0[] = {
  128999. 1, 0, 2,
  129000. };
  129001. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  129002. _vq_quantthresh__44c9_s_p1_0,
  129003. _vq_quantmap__44c9_s_p1_0,
  129004. 3,
  129005. 3
  129006. };
  129007. static static_codebook _44c9_s_p1_0 = {
  129008. 4, 81,
  129009. _vq_lengthlist__44c9_s_p1_0,
  129010. 1, -535822336, 1611661312, 2, 0,
  129011. _vq_quantlist__44c9_s_p1_0,
  129012. NULL,
  129013. &_vq_auxt__44c9_s_p1_0,
  129014. NULL,
  129015. 0
  129016. };
  129017. static long _vq_quantlist__44c9_s_p2_0[] = {
  129018. 2,
  129019. 1,
  129020. 3,
  129021. 0,
  129022. 4,
  129023. };
  129024. static long _vq_lengthlist__44c9_s_p2_0[] = {
  129025. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  129026. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  129027. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  129028. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  129029. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  129030. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  129031. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  129032. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  129033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129034. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  129035. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  129036. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  129037. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  129038. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  129039. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  129040. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  129041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129042. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  129043. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  129044. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  129045. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  129046. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  129047. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  129048. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129050. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  129051. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  129052. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  129053. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  129054. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  129055. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  129056. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  129061. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  129062. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  129063. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  129064. 12,
  129065. };
  129066. static float _vq_quantthresh__44c9_s_p2_0[] = {
  129067. -1.5, -0.5, 0.5, 1.5,
  129068. };
  129069. static long _vq_quantmap__44c9_s_p2_0[] = {
  129070. 3, 1, 0, 2, 4,
  129071. };
  129072. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  129073. _vq_quantthresh__44c9_s_p2_0,
  129074. _vq_quantmap__44c9_s_p2_0,
  129075. 5,
  129076. 5
  129077. };
  129078. static static_codebook _44c9_s_p2_0 = {
  129079. 4, 625,
  129080. _vq_lengthlist__44c9_s_p2_0,
  129081. 1, -533725184, 1611661312, 3, 0,
  129082. _vq_quantlist__44c9_s_p2_0,
  129083. NULL,
  129084. &_vq_auxt__44c9_s_p2_0,
  129085. NULL,
  129086. 0
  129087. };
  129088. static long _vq_quantlist__44c9_s_p3_0[] = {
  129089. 4,
  129090. 3,
  129091. 5,
  129092. 2,
  129093. 6,
  129094. 1,
  129095. 7,
  129096. 0,
  129097. 8,
  129098. };
  129099. static long _vq_lengthlist__44c9_s_p3_0[] = {
  129100. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  129101. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  129102. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  129103. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  129104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129105. 0,
  129106. };
  129107. static float _vq_quantthresh__44c9_s_p3_0[] = {
  129108. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129109. };
  129110. static long _vq_quantmap__44c9_s_p3_0[] = {
  129111. 7, 5, 3, 1, 0, 2, 4, 6,
  129112. 8,
  129113. };
  129114. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  129115. _vq_quantthresh__44c9_s_p3_0,
  129116. _vq_quantmap__44c9_s_p3_0,
  129117. 9,
  129118. 9
  129119. };
  129120. static static_codebook _44c9_s_p3_0 = {
  129121. 2, 81,
  129122. _vq_lengthlist__44c9_s_p3_0,
  129123. 1, -531628032, 1611661312, 4, 0,
  129124. _vq_quantlist__44c9_s_p3_0,
  129125. NULL,
  129126. &_vq_auxt__44c9_s_p3_0,
  129127. NULL,
  129128. 0
  129129. };
  129130. static long _vq_quantlist__44c9_s_p4_0[] = {
  129131. 8,
  129132. 7,
  129133. 9,
  129134. 6,
  129135. 10,
  129136. 5,
  129137. 11,
  129138. 4,
  129139. 12,
  129140. 3,
  129141. 13,
  129142. 2,
  129143. 14,
  129144. 1,
  129145. 15,
  129146. 0,
  129147. 16,
  129148. };
  129149. static long _vq_lengthlist__44c9_s_p4_0[] = {
  129150. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  129151. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  129152. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  129153. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  129154. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  129155. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  129156. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  129157. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  129158. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  129159. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  129160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129168. 0,
  129169. };
  129170. static float _vq_quantthresh__44c9_s_p4_0[] = {
  129171. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129172. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129173. };
  129174. static long _vq_quantmap__44c9_s_p4_0[] = {
  129175. 15, 13, 11, 9, 7, 5, 3, 1,
  129176. 0, 2, 4, 6, 8, 10, 12, 14,
  129177. 16,
  129178. };
  129179. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  129180. _vq_quantthresh__44c9_s_p4_0,
  129181. _vq_quantmap__44c9_s_p4_0,
  129182. 17,
  129183. 17
  129184. };
  129185. static static_codebook _44c9_s_p4_0 = {
  129186. 2, 289,
  129187. _vq_lengthlist__44c9_s_p4_0,
  129188. 1, -529530880, 1611661312, 5, 0,
  129189. _vq_quantlist__44c9_s_p4_0,
  129190. NULL,
  129191. &_vq_auxt__44c9_s_p4_0,
  129192. NULL,
  129193. 0
  129194. };
  129195. static long _vq_quantlist__44c9_s_p5_0[] = {
  129196. 1,
  129197. 0,
  129198. 2,
  129199. };
  129200. static long _vq_lengthlist__44c9_s_p5_0[] = {
  129201. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  129202. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  129203. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  129204. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  129205. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  129206. 12,
  129207. };
  129208. static float _vq_quantthresh__44c9_s_p5_0[] = {
  129209. -5.5, 5.5,
  129210. };
  129211. static long _vq_quantmap__44c9_s_p5_0[] = {
  129212. 1, 0, 2,
  129213. };
  129214. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  129215. _vq_quantthresh__44c9_s_p5_0,
  129216. _vq_quantmap__44c9_s_p5_0,
  129217. 3,
  129218. 3
  129219. };
  129220. static static_codebook _44c9_s_p5_0 = {
  129221. 4, 81,
  129222. _vq_lengthlist__44c9_s_p5_0,
  129223. 1, -529137664, 1618345984, 2, 0,
  129224. _vq_quantlist__44c9_s_p5_0,
  129225. NULL,
  129226. &_vq_auxt__44c9_s_p5_0,
  129227. NULL,
  129228. 0
  129229. };
  129230. static long _vq_quantlist__44c9_s_p5_1[] = {
  129231. 5,
  129232. 4,
  129233. 6,
  129234. 3,
  129235. 7,
  129236. 2,
  129237. 8,
  129238. 1,
  129239. 9,
  129240. 0,
  129241. 10,
  129242. };
  129243. static long _vq_lengthlist__44c9_s_p5_1[] = {
  129244. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  129245. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  129246. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  129247. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  129248. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  129249. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  129250. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  129251. 11,11,11, 7, 7, 7, 7, 7, 7,
  129252. };
  129253. static float _vq_quantthresh__44c9_s_p5_1[] = {
  129254. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129255. 3.5, 4.5,
  129256. };
  129257. static long _vq_quantmap__44c9_s_p5_1[] = {
  129258. 9, 7, 5, 3, 1, 0, 2, 4,
  129259. 6, 8, 10,
  129260. };
  129261. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  129262. _vq_quantthresh__44c9_s_p5_1,
  129263. _vq_quantmap__44c9_s_p5_1,
  129264. 11,
  129265. 11
  129266. };
  129267. static static_codebook _44c9_s_p5_1 = {
  129268. 2, 121,
  129269. _vq_lengthlist__44c9_s_p5_1,
  129270. 1, -531365888, 1611661312, 4, 0,
  129271. _vq_quantlist__44c9_s_p5_1,
  129272. NULL,
  129273. &_vq_auxt__44c9_s_p5_1,
  129274. NULL,
  129275. 0
  129276. };
  129277. static long _vq_quantlist__44c9_s_p6_0[] = {
  129278. 6,
  129279. 5,
  129280. 7,
  129281. 4,
  129282. 8,
  129283. 3,
  129284. 9,
  129285. 2,
  129286. 10,
  129287. 1,
  129288. 11,
  129289. 0,
  129290. 12,
  129291. };
  129292. static long _vq_lengthlist__44c9_s_p6_0[] = {
  129293. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  129294. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  129295. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  129296. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  129297. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  129298. 11, 8, 8, 9, 9,10,10,11,11,12,12, 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,
  129304. };
  129305. static float _vq_quantthresh__44c9_s_p6_0[] = {
  129306. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129307. 12.5, 17.5, 22.5, 27.5,
  129308. };
  129309. static long _vq_quantmap__44c9_s_p6_0[] = {
  129310. 11, 9, 7, 5, 3, 1, 0, 2,
  129311. 4, 6, 8, 10, 12,
  129312. };
  129313. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  129314. _vq_quantthresh__44c9_s_p6_0,
  129315. _vq_quantmap__44c9_s_p6_0,
  129316. 13,
  129317. 13
  129318. };
  129319. static static_codebook _44c9_s_p6_0 = {
  129320. 2, 169,
  129321. _vq_lengthlist__44c9_s_p6_0,
  129322. 1, -526516224, 1616117760, 4, 0,
  129323. _vq_quantlist__44c9_s_p6_0,
  129324. NULL,
  129325. &_vq_auxt__44c9_s_p6_0,
  129326. NULL,
  129327. 0
  129328. };
  129329. static long _vq_quantlist__44c9_s_p6_1[] = {
  129330. 2,
  129331. 1,
  129332. 3,
  129333. 0,
  129334. 4,
  129335. };
  129336. static long _vq_lengthlist__44c9_s_p6_1[] = {
  129337. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  129338. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  129339. };
  129340. static float _vq_quantthresh__44c9_s_p6_1[] = {
  129341. -1.5, -0.5, 0.5, 1.5,
  129342. };
  129343. static long _vq_quantmap__44c9_s_p6_1[] = {
  129344. 3, 1, 0, 2, 4,
  129345. };
  129346. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  129347. _vq_quantthresh__44c9_s_p6_1,
  129348. _vq_quantmap__44c9_s_p6_1,
  129349. 5,
  129350. 5
  129351. };
  129352. static static_codebook _44c9_s_p6_1 = {
  129353. 2, 25,
  129354. _vq_lengthlist__44c9_s_p6_1,
  129355. 1, -533725184, 1611661312, 3, 0,
  129356. _vq_quantlist__44c9_s_p6_1,
  129357. NULL,
  129358. &_vq_auxt__44c9_s_p6_1,
  129359. NULL,
  129360. 0
  129361. };
  129362. static long _vq_quantlist__44c9_s_p7_0[] = {
  129363. 6,
  129364. 5,
  129365. 7,
  129366. 4,
  129367. 8,
  129368. 3,
  129369. 9,
  129370. 2,
  129371. 10,
  129372. 1,
  129373. 11,
  129374. 0,
  129375. 12,
  129376. };
  129377. static long _vq_lengthlist__44c9_s_p7_0[] = {
  129378. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  129379. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  129380. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  129381. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  129382. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  129383. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  129384. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  129385. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  129386. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  129387. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  129388. 19,12,12,12,12,13,13,14,14,
  129389. };
  129390. static float _vq_quantthresh__44c9_s_p7_0[] = {
  129391. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  129392. 27.5, 38.5, 49.5, 60.5,
  129393. };
  129394. static long _vq_quantmap__44c9_s_p7_0[] = {
  129395. 11, 9, 7, 5, 3, 1, 0, 2,
  129396. 4, 6, 8, 10, 12,
  129397. };
  129398. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  129399. _vq_quantthresh__44c9_s_p7_0,
  129400. _vq_quantmap__44c9_s_p7_0,
  129401. 13,
  129402. 13
  129403. };
  129404. static static_codebook _44c9_s_p7_0 = {
  129405. 2, 169,
  129406. _vq_lengthlist__44c9_s_p7_0,
  129407. 1, -523206656, 1618345984, 4, 0,
  129408. _vq_quantlist__44c9_s_p7_0,
  129409. NULL,
  129410. &_vq_auxt__44c9_s_p7_0,
  129411. NULL,
  129412. 0
  129413. };
  129414. static long _vq_quantlist__44c9_s_p7_1[] = {
  129415. 5,
  129416. 4,
  129417. 6,
  129418. 3,
  129419. 7,
  129420. 2,
  129421. 8,
  129422. 1,
  129423. 9,
  129424. 0,
  129425. 10,
  129426. };
  129427. static long _vq_lengthlist__44c9_s_p7_1[] = {
  129428. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  129429. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  129430. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  129431. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  129432. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  129433. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  129434. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  129435. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  129436. };
  129437. static float _vq_quantthresh__44c9_s_p7_1[] = {
  129438. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129439. 3.5, 4.5,
  129440. };
  129441. static long _vq_quantmap__44c9_s_p7_1[] = {
  129442. 9, 7, 5, 3, 1, 0, 2, 4,
  129443. 6, 8, 10,
  129444. };
  129445. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  129446. _vq_quantthresh__44c9_s_p7_1,
  129447. _vq_quantmap__44c9_s_p7_1,
  129448. 11,
  129449. 11
  129450. };
  129451. static static_codebook _44c9_s_p7_1 = {
  129452. 2, 121,
  129453. _vq_lengthlist__44c9_s_p7_1,
  129454. 1, -531365888, 1611661312, 4, 0,
  129455. _vq_quantlist__44c9_s_p7_1,
  129456. NULL,
  129457. &_vq_auxt__44c9_s_p7_1,
  129458. NULL,
  129459. 0
  129460. };
  129461. static long _vq_quantlist__44c9_s_p8_0[] = {
  129462. 7,
  129463. 6,
  129464. 8,
  129465. 5,
  129466. 9,
  129467. 4,
  129468. 10,
  129469. 3,
  129470. 11,
  129471. 2,
  129472. 12,
  129473. 1,
  129474. 13,
  129475. 0,
  129476. 14,
  129477. };
  129478. static long _vq_lengthlist__44c9_s_p8_0[] = {
  129479. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  129480. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  129481. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  129482. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  129483. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  129484. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  129485. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  129486. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  129487. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  129488. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  129489. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  129490. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  129491. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  129492. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  129493. 14,
  129494. };
  129495. static float _vq_quantthresh__44c9_s_p8_0[] = {
  129496. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  129497. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  129498. };
  129499. static long _vq_quantmap__44c9_s_p8_0[] = {
  129500. 13, 11, 9, 7, 5, 3, 1, 0,
  129501. 2, 4, 6, 8, 10, 12, 14,
  129502. };
  129503. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  129504. _vq_quantthresh__44c9_s_p8_0,
  129505. _vq_quantmap__44c9_s_p8_0,
  129506. 15,
  129507. 15
  129508. };
  129509. static static_codebook _44c9_s_p8_0 = {
  129510. 2, 225,
  129511. _vq_lengthlist__44c9_s_p8_0,
  129512. 1, -520986624, 1620377600, 4, 0,
  129513. _vq_quantlist__44c9_s_p8_0,
  129514. NULL,
  129515. &_vq_auxt__44c9_s_p8_0,
  129516. NULL,
  129517. 0
  129518. };
  129519. static long _vq_quantlist__44c9_s_p8_1[] = {
  129520. 10,
  129521. 9,
  129522. 11,
  129523. 8,
  129524. 12,
  129525. 7,
  129526. 13,
  129527. 6,
  129528. 14,
  129529. 5,
  129530. 15,
  129531. 4,
  129532. 16,
  129533. 3,
  129534. 17,
  129535. 2,
  129536. 18,
  129537. 1,
  129538. 19,
  129539. 0,
  129540. 20,
  129541. };
  129542. static long _vq_lengthlist__44c9_s_p8_1[] = {
  129543. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  129544. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  129545. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  129546. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  129547. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129548. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  129549. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  129550. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  129551. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129552. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129553. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  129554. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  129555. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129556. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129557. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  129558. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  129559. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  129560. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  129561. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  129562. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  129563. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  129564. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  129565. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  129566. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  129567. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  129568. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  129569. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  129570. 9, 9, 9,10, 9, 9, 9, 9, 9,
  129571. };
  129572. static float _vq_quantthresh__44c9_s_p8_1[] = {
  129573. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  129574. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  129575. 6.5, 7.5, 8.5, 9.5,
  129576. };
  129577. static long _vq_quantmap__44c9_s_p8_1[] = {
  129578. 19, 17, 15, 13, 11, 9, 7, 5,
  129579. 3, 1, 0, 2, 4, 6, 8, 10,
  129580. 12, 14, 16, 18, 20,
  129581. };
  129582. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  129583. _vq_quantthresh__44c9_s_p8_1,
  129584. _vq_quantmap__44c9_s_p8_1,
  129585. 21,
  129586. 21
  129587. };
  129588. static static_codebook _44c9_s_p8_1 = {
  129589. 2, 441,
  129590. _vq_lengthlist__44c9_s_p8_1,
  129591. 1, -529268736, 1611661312, 5, 0,
  129592. _vq_quantlist__44c9_s_p8_1,
  129593. NULL,
  129594. &_vq_auxt__44c9_s_p8_1,
  129595. NULL,
  129596. 0
  129597. };
  129598. static long _vq_quantlist__44c9_s_p9_0[] = {
  129599. 9,
  129600. 8,
  129601. 10,
  129602. 7,
  129603. 11,
  129604. 6,
  129605. 12,
  129606. 5,
  129607. 13,
  129608. 4,
  129609. 14,
  129610. 3,
  129611. 15,
  129612. 2,
  129613. 16,
  129614. 1,
  129615. 17,
  129616. 0,
  129617. 18,
  129618. };
  129619. static long _vq_lengthlist__44c9_s_p9_0[] = {
  129620. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129621. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  129622. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  129623. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  129624. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129625. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129626. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129627. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129628. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129629. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129630. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129631. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129632. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129633. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129634. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129635. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129636. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129637. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129638. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129639. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129640. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129641. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129642. 11,11,11,11,11,11,11,11,11,
  129643. };
  129644. static float _vq_quantthresh__44c9_s_p9_0[] = {
  129645. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  129646. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  129647. 6982.5, 7913.5,
  129648. };
  129649. static long _vq_quantmap__44c9_s_p9_0[] = {
  129650. 17, 15, 13, 11, 9, 7, 5, 3,
  129651. 1, 0, 2, 4, 6, 8, 10, 12,
  129652. 14, 16, 18,
  129653. };
  129654. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  129655. _vq_quantthresh__44c9_s_p9_0,
  129656. _vq_quantmap__44c9_s_p9_0,
  129657. 19,
  129658. 19
  129659. };
  129660. static static_codebook _44c9_s_p9_0 = {
  129661. 2, 361,
  129662. _vq_lengthlist__44c9_s_p9_0,
  129663. 1, -508535424, 1631393792, 5, 0,
  129664. _vq_quantlist__44c9_s_p9_0,
  129665. NULL,
  129666. &_vq_auxt__44c9_s_p9_0,
  129667. NULL,
  129668. 0
  129669. };
  129670. static long _vq_quantlist__44c9_s_p9_1[] = {
  129671. 9,
  129672. 8,
  129673. 10,
  129674. 7,
  129675. 11,
  129676. 6,
  129677. 12,
  129678. 5,
  129679. 13,
  129680. 4,
  129681. 14,
  129682. 3,
  129683. 15,
  129684. 2,
  129685. 16,
  129686. 1,
  129687. 17,
  129688. 0,
  129689. 18,
  129690. };
  129691. static long _vq_lengthlist__44c9_s_p9_1[] = {
  129692. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  129693. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  129694. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  129695. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  129696. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  129697. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  129698. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  129699. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  129700. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  129701. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  129702. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  129703. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  129704. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  129705. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  129706. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  129707. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  129708. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  129709. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  129710. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  129711. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  129712. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  129713. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  129714. 13,13,13,14,13,14,15,15,15,
  129715. };
  129716. static float _vq_quantthresh__44c9_s_p9_1[] = {
  129717. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  129718. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  129719. 367.5, 416.5,
  129720. };
  129721. static long _vq_quantmap__44c9_s_p9_1[] = {
  129722. 17, 15, 13, 11, 9, 7, 5, 3,
  129723. 1, 0, 2, 4, 6, 8, 10, 12,
  129724. 14, 16, 18,
  129725. };
  129726. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  129727. _vq_quantthresh__44c9_s_p9_1,
  129728. _vq_quantmap__44c9_s_p9_1,
  129729. 19,
  129730. 19
  129731. };
  129732. static static_codebook _44c9_s_p9_1 = {
  129733. 2, 361,
  129734. _vq_lengthlist__44c9_s_p9_1,
  129735. 1, -518287360, 1622704128, 5, 0,
  129736. _vq_quantlist__44c9_s_p9_1,
  129737. NULL,
  129738. &_vq_auxt__44c9_s_p9_1,
  129739. NULL,
  129740. 0
  129741. };
  129742. static long _vq_quantlist__44c9_s_p9_2[] = {
  129743. 24,
  129744. 23,
  129745. 25,
  129746. 22,
  129747. 26,
  129748. 21,
  129749. 27,
  129750. 20,
  129751. 28,
  129752. 19,
  129753. 29,
  129754. 18,
  129755. 30,
  129756. 17,
  129757. 31,
  129758. 16,
  129759. 32,
  129760. 15,
  129761. 33,
  129762. 14,
  129763. 34,
  129764. 13,
  129765. 35,
  129766. 12,
  129767. 36,
  129768. 11,
  129769. 37,
  129770. 10,
  129771. 38,
  129772. 9,
  129773. 39,
  129774. 8,
  129775. 40,
  129776. 7,
  129777. 41,
  129778. 6,
  129779. 42,
  129780. 5,
  129781. 43,
  129782. 4,
  129783. 44,
  129784. 3,
  129785. 45,
  129786. 2,
  129787. 46,
  129788. 1,
  129789. 47,
  129790. 0,
  129791. 48,
  129792. };
  129793. static long _vq_lengthlist__44c9_s_p9_2[] = {
  129794. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  129795. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  129796. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129797. 7,
  129798. };
  129799. static float _vq_quantthresh__44c9_s_p9_2[] = {
  129800. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  129801. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  129802. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129803. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129804. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  129805. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  129806. };
  129807. static long _vq_quantmap__44c9_s_p9_2[] = {
  129808. 47, 45, 43, 41, 39, 37, 35, 33,
  129809. 31, 29, 27, 25, 23, 21, 19, 17,
  129810. 15, 13, 11, 9, 7, 5, 3, 1,
  129811. 0, 2, 4, 6, 8, 10, 12, 14,
  129812. 16, 18, 20, 22, 24, 26, 28, 30,
  129813. 32, 34, 36, 38, 40, 42, 44, 46,
  129814. 48,
  129815. };
  129816. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  129817. _vq_quantthresh__44c9_s_p9_2,
  129818. _vq_quantmap__44c9_s_p9_2,
  129819. 49,
  129820. 49
  129821. };
  129822. static static_codebook _44c9_s_p9_2 = {
  129823. 1, 49,
  129824. _vq_lengthlist__44c9_s_p9_2,
  129825. 1, -526909440, 1611661312, 6, 0,
  129826. _vq_quantlist__44c9_s_p9_2,
  129827. NULL,
  129828. &_vq_auxt__44c9_s_p9_2,
  129829. NULL,
  129830. 0
  129831. };
  129832. static long _huff_lengthlist__44c9_s_short[] = {
  129833. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  129834. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  129835. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  129836. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  129837. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  129838. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  129839. 9, 8,10,13,
  129840. };
  129841. static static_codebook _huff_book__44c9_s_short = {
  129842. 2, 100,
  129843. _huff_lengthlist__44c9_s_short,
  129844. 0, 0, 0, 0, 0,
  129845. NULL,
  129846. NULL,
  129847. NULL,
  129848. NULL,
  129849. 0
  129850. };
  129851. static long _huff_lengthlist__44c0_s_long[] = {
  129852. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  129853. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  129854. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  129855. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  129856. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  129857. 12,
  129858. };
  129859. static static_codebook _huff_book__44c0_s_long = {
  129860. 2, 81,
  129861. _huff_lengthlist__44c0_s_long,
  129862. 0, 0, 0, 0, 0,
  129863. NULL,
  129864. NULL,
  129865. NULL,
  129866. NULL,
  129867. 0
  129868. };
  129869. static long _vq_quantlist__44c0_s_p1_0[] = {
  129870. 1,
  129871. 0,
  129872. 2,
  129873. };
  129874. static long _vq_lengthlist__44c0_s_p1_0[] = {
  129875. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129876. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129880. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  129881. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129885. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  129886. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129921. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  129922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  129926. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  129927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  129931. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  129932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129966. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  129967. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129971. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  129972. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  129973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129976. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  129977. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  129978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  130273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130285. 0,
  130286. };
  130287. static float _vq_quantthresh__44c0_s_p1_0[] = {
  130288. -0.5, 0.5,
  130289. };
  130290. static long _vq_quantmap__44c0_s_p1_0[] = {
  130291. 1, 0, 2,
  130292. };
  130293. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  130294. _vq_quantthresh__44c0_s_p1_0,
  130295. _vq_quantmap__44c0_s_p1_0,
  130296. 3,
  130297. 3
  130298. };
  130299. static static_codebook _44c0_s_p1_0 = {
  130300. 8, 6561,
  130301. _vq_lengthlist__44c0_s_p1_0,
  130302. 1, -535822336, 1611661312, 2, 0,
  130303. _vq_quantlist__44c0_s_p1_0,
  130304. NULL,
  130305. &_vq_auxt__44c0_s_p1_0,
  130306. NULL,
  130307. 0
  130308. };
  130309. static long _vq_quantlist__44c0_s_p2_0[] = {
  130310. 2,
  130311. 1,
  130312. 3,
  130313. 0,
  130314. 4,
  130315. };
  130316. static long _vq_lengthlist__44c0_s_p2_0[] = {
  130317. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  130319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130320. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  130322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130323. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130356. 0,
  130357. };
  130358. static float _vq_quantthresh__44c0_s_p2_0[] = {
  130359. -1.5, -0.5, 0.5, 1.5,
  130360. };
  130361. static long _vq_quantmap__44c0_s_p2_0[] = {
  130362. 3, 1, 0, 2, 4,
  130363. };
  130364. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  130365. _vq_quantthresh__44c0_s_p2_0,
  130366. _vq_quantmap__44c0_s_p2_0,
  130367. 5,
  130368. 5
  130369. };
  130370. static static_codebook _44c0_s_p2_0 = {
  130371. 4, 625,
  130372. _vq_lengthlist__44c0_s_p2_0,
  130373. 1, -533725184, 1611661312, 3, 0,
  130374. _vq_quantlist__44c0_s_p2_0,
  130375. NULL,
  130376. &_vq_auxt__44c0_s_p2_0,
  130377. NULL,
  130378. 0
  130379. };
  130380. static long _vq_quantlist__44c0_s_p3_0[] = {
  130381. 4,
  130382. 3,
  130383. 5,
  130384. 2,
  130385. 6,
  130386. 1,
  130387. 7,
  130388. 0,
  130389. 8,
  130390. };
  130391. static long _vq_lengthlist__44c0_s_p3_0[] = {
  130392. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  130393. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  130394. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  130395. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  130396. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130397. 0,
  130398. };
  130399. static float _vq_quantthresh__44c0_s_p3_0[] = {
  130400. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130401. };
  130402. static long _vq_quantmap__44c0_s_p3_0[] = {
  130403. 7, 5, 3, 1, 0, 2, 4, 6,
  130404. 8,
  130405. };
  130406. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  130407. _vq_quantthresh__44c0_s_p3_0,
  130408. _vq_quantmap__44c0_s_p3_0,
  130409. 9,
  130410. 9
  130411. };
  130412. static static_codebook _44c0_s_p3_0 = {
  130413. 2, 81,
  130414. _vq_lengthlist__44c0_s_p3_0,
  130415. 1, -531628032, 1611661312, 4, 0,
  130416. _vq_quantlist__44c0_s_p3_0,
  130417. NULL,
  130418. &_vq_auxt__44c0_s_p3_0,
  130419. NULL,
  130420. 0
  130421. };
  130422. static long _vq_quantlist__44c0_s_p4_0[] = {
  130423. 4,
  130424. 3,
  130425. 5,
  130426. 2,
  130427. 6,
  130428. 1,
  130429. 7,
  130430. 0,
  130431. 8,
  130432. };
  130433. static long _vq_lengthlist__44c0_s_p4_0[] = {
  130434. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  130435. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  130436. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  130437. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  130438. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  130439. 10,
  130440. };
  130441. static float _vq_quantthresh__44c0_s_p4_0[] = {
  130442. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130443. };
  130444. static long _vq_quantmap__44c0_s_p4_0[] = {
  130445. 7, 5, 3, 1, 0, 2, 4, 6,
  130446. 8,
  130447. };
  130448. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  130449. _vq_quantthresh__44c0_s_p4_0,
  130450. _vq_quantmap__44c0_s_p4_0,
  130451. 9,
  130452. 9
  130453. };
  130454. static static_codebook _44c0_s_p4_0 = {
  130455. 2, 81,
  130456. _vq_lengthlist__44c0_s_p4_0,
  130457. 1, -531628032, 1611661312, 4, 0,
  130458. _vq_quantlist__44c0_s_p4_0,
  130459. NULL,
  130460. &_vq_auxt__44c0_s_p4_0,
  130461. NULL,
  130462. 0
  130463. };
  130464. static long _vq_quantlist__44c0_s_p5_0[] = {
  130465. 8,
  130466. 7,
  130467. 9,
  130468. 6,
  130469. 10,
  130470. 5,
  130471. 11,
  130472. 4,
  130473. 12,
  130474. 3,
  130475. 13,
  130476. 2,
  130477. 14,
  130478. 1,
  130479. 15,
  130480. 0,
  130481. 16,
  130482. };
  130483. static long _vq_lengthlist__44c0_s_p5_0[] = {
  130484. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  130485. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  130486. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  130487. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130488. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130489. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  130490. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  130491. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130492. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130493. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130494. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  130495. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  130496. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  130497. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  130498. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  130499. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  130500. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  130501. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  130502. 14,
  130503. };
  130504. static float _vq_quantthresh__44c0_s_p5_0[] = {
  130505. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130506. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130507. };
  130508. static long _vq_quantmap__44c0_s_p5_0[] = {
  130509. 15, 13, 11, 9, 7, 5, 3, 1,
  130510. 0, 2, 4, 6, 8, 10, 12, 14,
  130511. 16,
  130512. };
  130513. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  130514. _vq_quantthresh__44c0_s_p5_0,
  130515. _vq_quantmap__44c0_s_p5_0,
  130516. 17,
  130517. 17
  130518. };
  130519. static static_codebook _44c0_s_p5_0 = {
  130520. 2, 289,
  130521. _vq_lengthlist__44c0_s_p5_0,
  130522. 1, -529530880, 1611661312, 5, 0,
  130523. _vq_quantlist__44c0_s_p5_0,
  130524. NULL,
  130525. &_vq_auxt__44c0_s_p5_0,
  130526. NULL,
  130527. 0
  130528. };
  130529. static long _vq_quantlist__44c0_s_p6_0[] = {
  130530. 1,
  130531. 0,
  130532. 2,
  130533. };
  130534. static long _vq_lengthlist__44c0_s_p6_0[] = {
  130535. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  130536. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130537. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  130538. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  130539. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  130540. 10,
  130541. };
  130542. static float _vq_quantthresh__44c0_s_p6_0[] = {
  130543. -5.5, 5.5,
  130544. };
  130545. static long _vq_quantmap__44c0_s_p6_0[] = {
  130546. 1, 0, 2,
  130547. };
  130548. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  130549. _vq_quantthresh__44c0_s_p6_0,
  130550. _vq_quantmap__44c0_s_p6_0,
  130551. 3,
  130552. 3
  130553. };
  130554. static static_codebook _44c0_s_p6_0 = {
  130555. 4, 81,
  130556. _vq_lengthlist__44c0_s_p6_0,
  130557. 1, -529137664, 1618345984, 2, 0,
  130558. _vq_quantlist__44c0_s_p6_0,
  130559. NULL,
  130560. &_vq_auxt__44c0_s_p6_0,
  130561. NULL,
  130562. 0
  130563. };
  130564. static long _vq_quantlist__44c0_s_p6_1[] = {
  130565. 5,
  130566. 4,
  130567. 6,
  130568. 3,
  130569. 7,
  130570. 2,
  130571. 8,
  130572. 1,
  130573. 9,
  130574. 0,
  130575. 10,
  130576. };
  130577. static long _vq_lengthlist__44c0_s_p6_1[] = {
  130578. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  130579. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  130580. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  130581. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130582. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130583. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130584. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  130585. 10,10,10, 8, 8, 8, 8, 8, 8,
  130586. };
  130587. static float _vq_quantthresh__44c0_s_p6_1[] = {
  130588. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130589. 3.5, 4.5,
  130590. };
  130591. static long _vq_quantmap__44c0_s_p6_1[] = {
  130592. 9, 7, 5, 3, 1, 0, 2, 4,
  130593. 6, 8, 10,
  130594. };
  130595. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  130596. _vq_quantthresh__44c0_s_p6_1,
  130597. _vq_quantmap__44c0_s_p6_1,
  130598. 11,
  130599. 11
  130600. };
  130601. static static_codebook _44c0_s_p6_1 = {
  130602. 2, 121,
  130603. _vq_lengthlist__44c0_s_p6_1,
  130604. 1, -531365888, 1611661312, 4, 0,
  130605. _vq_quantlist__44c0_s_p6_1,
  130606. NULL,
  130607. &_vq_auxt__44c0_s_p6_1,
  130608. NULL,
  130609. 0
  130610. };
  130611. static long _vq_quantlist__44c0_s_p7_0[] = {
  130612. 6,
  130613. 5,
  130614. 7,
  130615. 4,
  130616. 8,
  130617. 3,
  130618. 9,
  130619. 2,
  130620. 10,
  130621. 1,
  130622. 11,
  130623. 0,
  130624. 12,
  130625. };
  130626. static long _vq_lengthlist__44c0_s_p7_0[] = {
  130627. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  130628. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  130629. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130630. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130631. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  130632. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130633. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  130634. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  130635. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  130636. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  130637. 0,12,12,11,11,12,12,13,13,
  130638. };
  130639. static float _vq_quantthresh__44c0_s_p7_0[] = {
  130640. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130641. 12.5, 17.5, 22.5, 27.5,
  130642. };
  130643. static long _vq_quantmap__44c0_s_p7_0[] = {
  130644. 11, 9, 7, 5, 3, 1, 0, 2,
  130645. 4, 6, 8, 10, 12,
  130646. };
  130647. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  130648. _vq_quantthresh__44c0_s_p7_0,
  130649. _vq_quantmap__44c0_s_p7_0,
  130650. 13,
  130651. 13
  130652. };
  130653. static static_codebook _44c0_s_p7_0 = {
  130654. 2, 169,
  130655. _vq_lengthlist__44c0_s_p7_0,
  130656. 1, -526516224, 1616117760, 4, 0,
  130657. _vq_quantlist__44c0_s_p7_0,
  130658. NULL,
  130659. &_vq_auxt__44c0_s_p7_0,
  130660. NULL,
  130661. 0
  130662. };
  130663. static long _vq_quantlist__44c0_s_p7_1[] = {
  130664. 2,
  130665. 1,
  130666. 3,
  130667. 0,
  130668. 4,
  130669. };
  130670. static long _vq_lengthlist__44c0_s_p7_1[] = {
  130671. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  130672. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  130673. };
  130674. static float _vq_quantthresh__44c0_s_p7_1[] = {
  130675. -1.5, -0.5, 0.5, 1.5,
  130676. };
  130677. static long _vq_quantmap__44c0_s_p7_1[] = {
  130678. 3, 1, 0, 2, 4,
  130679. };
  130680. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  130681. _vq_quantthresh__44c0_s_p7_1,
  130682. _vq_quantmap__44c0_s_p7_1,
  130683. 5,
  130684. 5
  130685. };
  130686. static static_codebook _44c0_s_p7_1 = {
  130687. 2, 25,
  130688. _vq_lengthlist__44c0_s_p7_1,
  130689. 1, -533725184, 1611661312, 3, 0,
  130690. _vq_quantlist__44c0_s_p7_1,
  130691. NULL,
  130692. &_vq_auxt__44c0_s_p7_1,
  130693. NULL,
  130694. 0
  130695. };
  130696. static long _vq_quantlist__44c0_s_p8_0[] = {
  130697. 2,
  130698. 1,
  130699. 3,
  130700. 0,
  130701. 4,
  130702. };
  130703. static long _vq_lengthlist__44c0_s_p8_0[] = {
  130704. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  130705. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130706. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130707. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130708. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130709. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130710. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130711. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  130712. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130713. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130714. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130715. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130716. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  130717. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130718. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130719. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  130720. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130721. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130722. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130723. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130724. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130725. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130726. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130727. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130728. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130729. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130730. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130731. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130732. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130733. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130734. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130735. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130736. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130737. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130738. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130739. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130740. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130741. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130742. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130743. 11,
  130744. };
  130745. static float _vq_quantthresh__44c0_s_p8_0[] = {
  130746. -331.5, -110.5, 110.5, 331.5,
  130747. };
  130748. static long _vq_quantmap__44c0_s_p8_0[] = {
  130749. 3, 1, 0, 2, 4,
  130750. };
  130751. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  130752. _vq_quantthresh__44c0_s_p8_0,
  130753. _vq_quantmap__44c0_s_p8_0,
  130754. 5,
  130755. 5
  130756. };
  130757. static static_codebook _44c0_s_p8_0 = {
  130758. 4, 625,
  130759. _vq_lengthlist__44c0_s_p8_0,
  130760. 1, -518283264, 1627103232, 3, 0,
  130761. _vq_quantlist__44c0_s_p8_0,
  130762. NULL,
  130763. &_vq_auxt__44c0_s_p8_0,
  130764. NULL,
  130765. 0
  130766. };
  130767. static long _vq_quantlist__44c0_s_p8_1[] = {
  130768. 6,
  130769. 5,
  130770. 7,
  130771. 4,
  130772. 8,
  130773. 3,
  130774. 9,
  130775. 2,
  130776. 10,
  130777. 1,
  130778. 11,
  130779. 0,
  130780. 12,
  130781. };
  130782. static long _vq_lengthlist__44c0_s_p8_1[] = {
  130783. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  130784. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  130785. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  130786. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  130787. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  130788. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  130789. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  130790. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  130791. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  130792. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  130793. 16,13,13,12,12,14,14,15,13,
  130794. };
  130795. static float _vq_quantthresh__44c0_s_p8_1[] = {
  130796. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  130797. 42.5, 59.5, 76.5, 93.5,
  130798. };
  130799. static long _vq_quantmap__44c0_s_p8_1[] = {
  130800. 11, 9, 7, 5, 3, 1, 0, 2,
  130801. 4, 6, 8, 10, 12,
  130802. };
  130803. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  130804. _vq_quantthresh__44c0_s_p8_1,
  130805. _vq_quantmap__44c0_s_p8_1,
  130806. 13,
  130807. 13
  130808. };
  130809. static static_codebook _44c0_s_p8_1 = {
  130810. 2, 169,
  130811. _vq_lengthlist__44c0_s_p8_1,
  130812. 1, -522616832, 1620115456, 4, 0,
  130813. _vq_quantlist__44c0_s_p8_1,
  130814. NULL,
  130815. &_vq_auxt__44c0_s_p8_1,
  130816. NULL,
  130817. 0
  130818. };
  130819. static long _vq_quantlist__44c0_s_p8_2[] = {
  130820. 8,
  130821. 7,
  130822. 9,
  130823. 6,
  130824. 10,
  130825. 5,
  130826. 11,
  130827. 4,
  130828. 12,
  130829. 3,
  130830. 13,
  130831. 2,
  130832. 14,
  130833. 1,
  130834. 15,
  130835. 0,
  130836. 16,
  130837. };
  130838. static long _vq_lengthlist__44c0_s_p8_2[] = {
  130839. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  130840. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  130841. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  130842. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130843. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  130844. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  130845. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  130846. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  130847. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  130848. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  130849. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  130850. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  130851. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  130852. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130853. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  130854. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  130855. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  130856. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  130857. 10,
  130858. };
  130859. static float _vq_quantthresh__44c0_s_p8_2[] = {
  130860. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130861. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130862. };
  130863. static long _vq_quantmap__44c0_s_p8_2[] = {
  130864. 15, 13, 11, 9, 7, 5, 3, 1,
  130865. 0, 2, 4, 6, 8, 10, 12, 14,
  130866. 16,
  130867. };
  130868. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  130869. _vq_quantthresh__44c0_s_p8_2,
  130870. _vq_quantmap__44c0_s_p8_2,
  130871. 17,
  130872. 17
  130873. };
  130874. static static_codebook _44c0_s_p8_2 = {
  130875. 2, 289,
  130876. _vq_lengthlist__44c0_s_p8_2,
  130877. 1, -529530880, 1611661312, 5, 0,
  130878. _vq_quantlist__44c0_s_p8_2,
  130879. NULL,
  130880. &_vq_auxt__44c0_s_p8_2,
  130881. NULL,
  130882. 0
  130883. };
  130884. static long _huff_lengthlist__44c0_s_short[] = {
  130885. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  130886. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  130887. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  130888. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  130889. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  130890. 12,
  130891. };
  130892. static static_codebook _huff_book__44c0_s_short = {
  130893. 2, 81,
  130894. _huff_lengthlist__44c0_s_short,
  130895. 0, 0, 0, 0, 0,
  130896. NULL,
  130897. NULL,
  130898. NULL,
  130899. NULL,
  130900. 0
  130901. };
  130902. static long _huff_lengthlist__44c0_sm_long[] = {
  130903. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  130904. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  130905. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  130906. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  130907. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  130908. 13,
  130909. };
  130910. static static_codebook _huff_book__44c0_sm_long = {
  130911. 2, 81,
  130912. _huff_lengthlist__44c0_sm_long,
  130913. 0, 0, 0, 0, 0,
  130914. NULL,
  130915. NULL,
  130916. NULL,
  130917. NULL,
  130918. 0
  130919. };
  130920. static long _vq_quantlist__44c0_sm_p1_0[] = {
  130921. 1,
  130922. 0,
  130923. 2,
  130924. };
  130925. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  130926. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130927. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130931. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130932. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130936. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  130937. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  130972. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  130973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130977. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  130978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130982. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  130983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131017. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131018. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131022. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  131023. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  131024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131027. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131028. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  131029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  131295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131326. 0, 0, 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,
  131337. };
  131338. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  131339. -0.5, 0.5,
  131340. };
  131341. static long _vq_quantmap__44c0_sm_p1_0[] = {
  131342. 1, 0, 2,
  131343. };
  131344. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  131345. _vq_quantthresh__44c0_sm_p1_0,
  131346. _vq_quantmap__44c0_sm_p1_0,
  131347. 3,
  131348. 3
  131349. };
  131350. static static_codebook _44c0_sm_p1_0 = {
  131351. 8, 6561,
  131352. _vq_lengthlist__44c0_sm_p1_0,
  131353. 1, -535822336, 1611661312, 2, 0,
  131354. _vq_quantlist__44c0_sm_p1_0,
  131355. NULL,
  131356. &_vq_auxt__44c0_sm_p1_0,
  131357. NULL,
  131358. 0
  131359. };
  131360. static long _vq_quantlist__44c0_sm_p2_0[] = {
  131361. 2,
  131362. 1,
  131363. 3,
  131364. 0,
  131365. 4,
  131366. };
  131367. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  131368. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  131370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131371. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  131373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131374. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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,
  131408. };
  131409. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  131410. -1.5, -0.5, 0.5, 1.5,
  131411. };
  131412. static long _vq_quantmap__44c0_sm_p2_0[] = {
  131413. 3, 1, 0, 2, 4,
  131414. };
  131415. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  131416. _vq_quantthresh__44c0_sm_p2_0,
  131417. _vq_quantmap__44c0_sm_p2_0,
  131418. 5,
  131419. 5
  131420. };
  131421. static static_codebook _44c0_sm_p2_0 = {
  131422. 4, 625,
  131423. _vq_lengthlist__44c0_sm_p2_0,
  131424. 1, -533725184, 1611661312, 3, 0,
  131425. _vq_quantlist__44c0_sm_p2_0,
  131426. NULL,
  131427. &_vq_auxt__44c0_sm_p2_0,
  131428. NULL,
  131429. 0
  131430. };
  131431. static long _vq_quantlist__44c0_sm_p3_0[] = {
  131432. 4,
  131433. 3,
  131434. 5,
  131435. 2,
  131436. 6,
  131437. 1,
  131438. 7,
  131439. 0,
  131440. 8,
  131441. };
  131442. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  131443. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  131444. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  131445. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131446. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  131447. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131448. 0,
  131449. };
  131450. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  131451. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131452. };
  131453. static long _vq_quantmap__44c0_sm_p3_0[] = {
  131454. 7, 5, 3, 1, 0, 2, 4, 6,
  131455. 8,
  131456. };
  131457. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  131458. _vq_quantthresh__44c0_sm_p3_0,
  131459. _vq_quantmap__44c0_sm_p3_0,
  131460. 9,
  131461. 9
  131462. };
  131463. static static_codebook _44c0_sm_p3_0 = {
  131464. 2, 81,
  131465. _vq_lengthlist__44c0_sm_p3_0,
  131466. 1, -531628032, 1611661312, 4, 0,
  131467. _vq_quantlist__44c0_sm_p3_0,
  131468. NULL,
  131469. &_vq_auxt__44c0_sm_p3_0,
  131470. NULL,
  131471. 0
  131472. };
  131473. static long _vq_quantlist__44c0_sm_p4_0[] = {
  131474. 4,
  131475. 3,
  131476. 5,
  131477. 2,
  131478. 6,
  131479. 1,
  131480. 7,
  131481. 0,
  131482. 8,
  131483. };
  131484. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  131485. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  131486. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  131487. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  131488. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  131489. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  131490. 11,
  131491. };
  131492. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  131493. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131494. };
  131495. static long _vq_quantmap__44c0_sm_p4_0[] = {
  131496. 7, 5, 3, 1, 0, 2, 4, 6,
  131497. 8,
  131498. };
  131499. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  131500. _vq_quantthresh__44c0_sm_p4_0,
  131501. _vq_quantmap__44c0_sm_p4_0,
  131502. 9,
  131503. 9
  131504. };
  131505. static static_codebook _44c0_sm_p4_0 = {
  131506. 2, 81,
  131507. _vq_lengthlist__44c0_sm_p4_0,
  131508. 1, -531628032, 1611661312, 4, 0,
  131509. _vq_quantlist__44c0_sm_p4_0,
  131510. NULL,
  131511. &_vq_auxt__44c0_sm_p4_0,
  131512. NULL,
  131513. 0
  131514. };
  131515. static long _vq_quantlist__44c0_sm_p5_0[] = {
  131516. 8,
  131517. 7,
  131518. 9,
  131519. 6,
  131520. 10,
  131521. 5,
  131522. 11,
  131523. 4,
  131524. 12,
  131525. 3,
  131526. 13,
  131527. 2,
  131528. 14,
  131529. 1,
  131530. 15,
  131531. 0,
  131532. 16,
  131533. };
  131534. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  131535. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  131536. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  131537. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  131538. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  131539. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  131540. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  131541. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  131542. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  131543. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  131544. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  131545. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  131546. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  131547. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  131548. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  131549. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  131550. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  131551. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  131552. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  131553. 14,
  131554. };
  131555. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  131556. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131557. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131558. };
  131559. static long _vq_quantmap__44c0_sm_p5_0[] = {
  131560. 15, 13, 11, 9, 7, 5, 3, 1,
  131561. 0, 2, 4, 6, 8, 10, 12, 14,
  131562. 16,
  131563. };
  131564. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  131565. _vq_quantthresh__44c0_sm_p5_0,
  131566. _vq_quantmap__44c0_sm_p5_0,
  131567. 17,
  131568. 17
  131569. };
  131570. static static_codebook _44c0_sm_p5_0 = {
  131571. 2, 289,
  131572. _vq_lengthlist__44c0_sm_p5_0,
  131573. 1, -529530880, 1611661312, 5, 0,
  131574. _vq_quantlist__44c0_sm_p5_0,
  131575. NULL,
  131576. &_vq_auxt__44c0_sm_p5_0,
  131577. NULL,
  131578. 0
  131579. };
  131580. static long _vq_quantlist__44c0_sm_p6_0[] = {
  131581. 1,
  131582. 0,
  131583. 2,
  131584. };
  131585. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  131586. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131587. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  131588. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  131589. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  131590. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  131591. 11,
  131592. };
  131593. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  131594. -5.5, 5.5,
  131595. };
  131596. static long _vq_quantmap__44c0_sm_p6_0[] = {
  131597. 1, 0, 2,
  131598. };
  131599. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  131600. _vq_quantthresh__44c0_sm_p6_0,
  131601. _vq_quantmap__44c0_sm_p6_0,
  131602. 3,
  131603. 3
  131604. };
  131605. static static_codebook _44c0_sm_p6_0 = {
  131606. 4, 81,
  131607. _vq_lengthlist__44c0_sm_p6_0,
  131608. 1, -529137664, 1618345984, 2, 0,
  131609. _vq_quantlist__44c0_sm_p6_0,
  131610. NULL,
  131611. &_vq_auxt__44c0_sm_p6_0,
  131612. NULL,
  131613. 0
  131614. };
  131615. static long _vq_quantlist__44c0_sm_p6_1[] = {
  131616. 5,
  131617. 4,
  131618. 6,
  131619. 3,
  131620. 7,
  131621. 2,
  131622. 8,
  131623. 1,
  131624. 9,
  131625. 0,
  131626. 10,
  131627. };
  131628. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  131629. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  131630. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131631. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  131632. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  131633. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  131634. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  131635. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131636. 10,10,10, 8, 8, 8, 8, 8, 8,
  131637. };
  131638. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  131639. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131640. 3.5, 4.5,
  131641. };
  131642. static long _vq_quantmap__44c0_sm_p6_1[] = {
  131643. 9, 7, 5, 3, 1, 0, 2, 4,
  131644. 6, 8, 10,
  131645. };
  131646. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  131647. _vq_quantthresh__44c0_sm_p6_1,
  131648. _vq_quantmap__44c0_sm_p6_1,
  131649. 11,
  131650. 11
  131651. };
  131652. static static_codebook _44c0_sm_p6_1 = {
  131653. 2, 121,
  131654. _vq_lengthlist__44c0_sm_p6_1,
  131655. 1, -531365888, 1611661312, 4, 0,
  131656. _vq_quantlist__44c0_sm_p6_1,
  131657. NULL,
  131658. &_vq_auxt__44c0_sm_p6_1,
  131659. NULL,
  131660. 0
  131661. };
  131662. static long _vq_quantlist__44c0_sm_p7_0[] = {
  131663. 6,
  131664. 5,
  131665. 7,
  131666. 4,
  131667. 8,
  131668. 3,
  131669. 9,
  131670. 2,
  131671. 10,
  131672. 1,
  131673. 11,
  131674. 0,
  131675. 12,
  131676. };
  131677. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  131678. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  131679. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  131680. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131681. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131682. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  131683. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  131684. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  131685. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  131686. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  131687. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  131688. 0,12,12,11,11,13,12,14,14,
  131689. };
  131690. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  131691. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131692. 12.5, 17.5, 22.5, 27.5,
  131693. };
  131694. static long _vq_quantmap__44c0_sm_p7_0[] = {
  131695. 11, 9, 7, 5, 3, 1, 0, 2,
  131696. 4, 6, 8, 10, 12,
  131697. };
  131698. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  131699. _vq_quantthresh__44c0_sm_p7_0,
  131700. _vq_quantmap__44c0_sm_p7_0,
  131701. 13,
  131702. 13
  131703. };
  131704. static static_codebook _44c0_sm_p7_0 = {
  131705. 2, 169,
  131706. _vq_lengthlist__44c0_sm_p7_0,
  131707. 1, -526516224, 1616117760, 4, 0,
  131708. _vq_quantlist__44c0_sm_p7_0,
  131709. NULL,
  131710. &_vq_auxt__44c0_sm_p7_0,
  131711. NULL,
  131712. 0
  131713. };
  131714. static long _vq_quantlist__44c0_sm_p7_1[] = {
  131715. 2,
  131716. 1,
  131717. 3,
  131718. 0,
  131719. 4,
  131720. };
  131721. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  131722. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  131723. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  131724. };
  131725. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  131726. -1.5, -0.5, 0.5, 1.5,
  131727. };
  131728. static long _vq_quantmap__44c0_sm_p7_1[] = {
  131729. 3, 1, 0, 2, 4,
  131730. };
  131731. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  131732. _vq_quantthresh__44c0_sm_p7_1,
  131733. _vq_quantmap__44c0_sm_p7_1,
  131734. 5,
  131735. 5
  131736. };
  131737. static static_codebook _44c0_sm_p7_1 = {
  131738. 2, 25,
  131739. _vq_lengthlist__44c0_sm_p7_1,
  131740. 1, -533725184, 1611661312, 3, 0,
  131741. _vq_quantlist__44c0_sm_p7_1,
  131742. NULL,
  131743. &_vq_auxt__44c0_sm_p7_1,
  131744. NULL,
  131745. 0
  131746. };
  131747. static long _vq_quantlist__44c0_sm_p8_0[] = {
  131748. 4,
  131749. 3,
  131750. 5,
  131751. 2,
  131752. 6,
  131753. 1,
  131754. 7,
  131755. 0,
  131756. 8,
  131757. };
  131758. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  131759. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  131760. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  131761. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131762. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131763. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131764. 12,
  131765. };
  131766. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  131767. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  131768. };
  131769. static long _vq_quantmap__44c0_sm_p8_0[] = {
  131770. 7, 5, 3, 1, 0, 2, 4, 6,
  131771. 8,
  131772. };
  131773. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  131774. _vq_quantthresh__44c0_sm_p8_0,
  131775. _vq_quantmap__44c0_sm_p8_0,
  131776. 9,
  131777. 9
  131778. };
  131779. static static_codebook _44c0_sm_p8_0 = {
  131780. 2, 81,
  131781. _vq_lengthlist__44c0_sm_p8_0,
  131782. 1, -516186112, 1627103232, 4, 0,
  131783. _vq_quantlist__44c0_sm_p8_0,
  131784. NULL,
  131785. &_vq_auxt__44c0_sm_p8_0,
  131786. NULL,
  131787. 0
  131788. };
  131789. static long _vq_quantlist__44c0_sm_p8_1[] = {
  131790. 6,
  131791. 5,
  131792. 7,
  131793. 4,
  131794. 8,
  131795. 3,
  131796. 9,
  131797. 2,
  131798. 10,
  131799. 1,
  131800. 11,
  131801. 0,
  131802. 12,
  131803. };
  131804. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  131805. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  131806. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  131807. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  131808. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  131809. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  131810. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  131811. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  131812. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  131813. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  131814. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  131815. 20,13,13,12,12,16,13,15,13,
  131816. };
  131817. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  131818. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  131819. 42.5, 59.5, 76.5, 93.5,
  131820. };
  131821. static long _vq_quantmap__44c0_sm_p8_1[] = {
  131822. 11, 9, 7, 5, 3, 1, 0, 2,
  131823. 4, 6, 8, 10, 12,
  131824. };
  131825. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  131826. _vq_quantthresh__44c0_sm_p8_1,
  131827. _vq_quantmap__44c0_sm_p8_1,
  131828. 13,
  131829. 13
  131830. };
  131831. static static_codebook _44c0_sm_p8_1 = {
  131832. 2, 169,
  131833. _vq_lengthlist__44c0_sm_p8_1,
  131834. 1, -522616832, 1620115456, 4, 0,
  131835. _vq_quantlist__44c0_sm_p8_1,
  131836. NULL,
  131837. &_vq_auxt__44c0_sm_p8_1,
  131838. NULL,
  131839. 0
  131840. };
  131841. static long _vq_quantlist__44c0_sm_p8_2[] = {
  131842. 8,
  131843. 7,
  131844. 9,
  131845. 6,
  131846. 10,
  131847. 5,
  131848. 11,
  131849. 4,
  131850. 12,
  131851. 3,
  131852. 13,
  131853. 2,
  131854. 14,
  131855. 1,
  131856. 15,
  131857. 0,
  131858. 16,
  131859. };
  131860. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  131861. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131862. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  131863. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  131864. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  131865. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  131866. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  131867. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  131868. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  131869. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  131870. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  131871. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  131872. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  131873. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  131874. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  131875. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  131876. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  131877. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  131878. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  131879. 9,
  131880. };
  131881. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  131882. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131883. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131884. };
  131885. static long _vq_quantmap__44c0_sm_p8_2[] = {
  131886. 15, 13, 11, 9, 7, 5, 3, 1,
  131887. 0, 2, 4, 6, 8, 10, 12, 14,
  131888. 16,
  131889. };
  131890. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  131891. _vq_quantthresh__44c0_sm_p8_2,
  131892. _vq_quantmap__44c0_sm_p8_2,
  131893. 17,
  131894. 17
  131895. };
  131896. static static_codebook _44c0_sm_p8_2 = {
  131897. 2, 289,
  131898. _vq_lengthlist__44c0_sm_p8_2,
  131899. 1, -529530880, 1611661312, 5, 0,
  131900. _vq_quantlist__44c0_sm_p8_2,
  131901. NULL,
  131902. &_vq_auxt__44c0_sm_p8_2,
  131903. NULL,
  131904. 0
  131905. };
  131906. static long _huff_lengthlist__44c0_sm_short[] = {
  131907. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  131908. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  131909. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  131910. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  131911. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  131912. 12,
  131913. };
  131914. static static_codebook _huff_book__44c0_sm_short = {
  131915. 2, 81,
  131916. _huff_lengthlist__44c0_sm_short,
  131917. 0, 0, 0, 0, 0,
  131918. NULL,
  131919. NULL,
  131920. NULL,
  131921. NULL,
  131922. 0
  131923. };
  131924. static long _huff_lengthlist__44c1_s_long[] = {
  131925. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  131926. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  131927. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  131928. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  131929. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  131930. 11,
  131931. };
  131932. static static_codebook _huff_book__44c1_s_long = {
  131933. 2, 81,
  131934. _huff_lengthlist__44c1_s_long,
  131935. 0, 0, 0, 0, 0,
  131936. NULL,
  131937. NULL,
  131938. NULL,
  131939. NULL,
  131940. 0
  131941. };
  131942. static long _vq_quantlist__44c1_s_p1_0[] = {
  131943. 1,
  131944. 0,
  131945. 2,
  131946. };
  131947. static long _vq_lengthlist__44c1_s_p1_0[] = {
  131948. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  131949. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131953. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  131954. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131958. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  131959. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131994. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  131995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  131999. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  132000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  132004. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  132005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132039. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  132040. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132044. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  132045. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  132046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132049. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  132050. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  132051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  132327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132358. 0,
  132359. };
  132360. static float _vq_quantthresh__44c1_s_p1_0[] = {
  132361. -0.5, 0.5,
  132362. };
  132363. static long _vq_quantmap__44c1_s_p1_0[] = {
  132364. 1, 0, 2,
  132365. };
  132366. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  132367. _vq_quantthresh__44c1_s_p1_0,
  132368. _vq_quantmap__44c1_s_p1_0,
  132369. 3,
  132370. 3
  132371. };
  132372. static static_codebook _44c1_s_p1_0 = {
  132373. 8, 6561,
  132374. _vq_lengthlist__44c1_s_p1_0,
  132375. 1, -535822336, 1611661312, 2, 0,
  132376. _vq_quantlist__44c1_s_p1_0,
  132377. NULL,
  132378. &_vq_auxt__44c1_s_p1_0,
  132379. NULL,
  132380. 0
  132381. };
  132382. static long _vq_quantlist__44c1_s_p2_0[] = {
  132383. 2,
  132384. 1,
  132385. 3,
  132386. 0,
  132387. 4,
  132388. };
  132389. static long _vq_lengthlist__44c1_s_p2_0[] = {
  132390. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  132392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132393. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  132395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132396. 0, 0, 0, 0, 6, 6, 6, 8, 8, 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,
  132430. };
  132431. static float _vq_quantthresh__44c1_s_p2_0[] = {
  132432. -1.5, -0.5, 0.5, 1.5,
  132433. };
  132434. static long _vq_quantmap__44c1_s_p2_0[] = {
  132435. 3, 1, 0, 2, 4,
  132436. };
  132437. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  132438. _vq_quantthresh__44c1_s_p2_0,
  132439. _vq_quantmap__44c1_s_p2_0,
  132440. 5,
  132441. 5
  132442. };
  132443. static static_codebook _44c1_s_p2_0 = {
  132444. 4, 625,
  132445. _vq_lengthlist__44c1_s_p2_0,
  132446. 1, -533725184, 1611661312, 3, 0,
  132447. _vq_quantlist__44c1_s_p2_0,
  132448. NULL,
  132449. &_vq_auxt__44c1_s_p2_0,
  132450. NULL,
  132451. 0
  132452. };
  132453. static long _vq_quantlist__44c1_s_p3_0[] = {
  132454. 4,
  132455. 3,
  132456. 5,
  132457. 2,
  132458. 6,
  132459. 1,
  132460. 7,
  132461. 0,
  132462. 8,
  132463. };
  132464. static long _vq_lengthlist__44c1_s_p3_0[] = {
  132465. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  132466. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  132467. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  132468. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  132469. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132470. 0,
  132471. };
  132472. static float _vq_quantthresh__44c1_s_p3_0[] = {
  132473. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132474. };
  132475. static long _vq_quantmap__44c1_s_p3_0[] = {
  132476. 7, 5, 3, 1, 0, 2, 4, 6,
  132477. 8,
  132478. };
  132479. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  132480. _vq_quantthresh__44c1_s_p3_0,
  132481. _vq_quantmap__44c1_s_p3_0,
  132482. 9,
  132483. 9
  132484. };
  132485. static static_codebook _44c1_s_p3_0 = {
  132486. 2, 81,
  132487. _vq_lengthlist__44c1_s_p3_0,
  132488. 1, -531628032, 1611661312, 4, 0,
  132489. _vq_quantlist__44c1_s_p3_0,
  132490. NULL,
  132491. &_vq_auxt__44c1_s_p3_0,
  132492. NULL,
  132493. 0
  132494. };
  132495. static long _vq_quantlist__44c1_s_p4_0[] = {
  132496. 4,
  132497. 3,
  132498. 5,
  132499. 2,
  132500. 6,
  132501. 1,
  132502. 7,
  132503. 0,
  132504. 8,
  132505. };
  132506. static long _vq_lengthlist__44c1_s_p4_0[] = {
  132507. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  132508. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  132509. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  132510. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  132511. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  132512. 11,
  132513. };
  132514. static float _vq_quantthresh__44c1_s_p4_0[] = {
  132515. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132516. };
  132517. static long _vq_quantmap__44c1_s_p4_0[] = {
  132518. 7, 5, 3, 1, 0, 2, 4, 6,
  132519. 8,
  132520. };
  132521. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  132522. _vq_quantthresh__44c1_s_p4_0,
  132523. _vq_quantmap__44c1_s_p4_0,
  132524. 9,
  132525. 9
  132526. };
  132527. static static_codebook _44c1_s_p4_0 = {
  132528. 2, 81,
  132529. _vq_lengthlist__44c1_s_p4_0,
  132530. 1, -531628032, 1611661312, 4, 0,
  132531. _vq_quantlist__44c1_s_p4_0,
  132532. NULL,
  132533. &_vq_auxt__44c1_s_p4_0,
  132534. NULL,
  132535. 0
  132536. };
  132537. static long _vq_quantlist__44c1_s_p5_0[] = {
  132538. 8,
  132539. 7,
  132540. 9,
  132541. 6,
  132542. 10,
  132543. 5,
  132544. 11,
  132545. 4,
  132546. 12,
  132547. 3,
  132548. 13,
  132549. 2,
  132550. 14,
  132551. 1,
  132552. 15,
  132553. 0,
  132554. 16,
  132555. };
  132556. static long _vq_lengthlist__44c1_s_p5_0[] = {
  132557. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  132558. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132559. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  132560. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132561. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132562. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  132563. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  132564. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  132565. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132566. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  132567. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  132568. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132569. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  132570. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  132571. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  132572. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  132573. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  132574. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  132575. 14,
  132576. };
  132577. static float _vq_quantthresh__44c1_s_p5_0[] = {
  132578. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132579. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132580. };
  132581. static long _vq_quantmap__44c1_s_p5_0[] = {
  132582. 15, 13, 11, 9, 7, 5, 3, 1,
  132583. 0, 2, 4, 6, 8, 10, 12, 14,
  132584. 16,
  132585. };
  132586. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  132587. _vq_quantthresh__44c1_s_p5_0,
  132588. _vq_quantmap__44c1_s_p5_0,
  132589. 17,
  132590. 17
  132591. };
  132592. static static_codebook _44c1_s_p5_0 = {
  132593. 2, 289,
  132594. _vq_lengthlist__44c1_s_p5_0,
  132595. 1, -529530880, 1611661312, 5, 0,
  132596. _vq_quantlist__44c1_s_p5_0,
  132597. NULL,
  132598. &_vq_auxt__44c1_s_p5_0,
  132599. NULL,
  132600. 0
  132601. };
  132602. static long _vq_quantlist__44c1_s_p6_0[] = {
  132603. 1,
  132604. 0,
  132605. 2,
  132606. };
  132607. static long _vq_lengthlist__44c1_s_p6_0[] = {
  132608. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  132609. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  132610. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  132611. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  132612. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  132613. 11,
  132614. };
  132615. static float _vq_quantthresh__44c1_s_p6_0[] = {
  132616. -5.5, 5.5,
  132617. };
  132618. static long _vq_quantmap__44c1_s_p6_0[] = {
  132619. 1, 0, 2,
  132620. };
  132621. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  132622. _vq_quantthresh__44c1_s_p6_0,
  132623. _vq_quantmap__44c1_s_p6_0,
  132624. 3,
  132625. 3
  132626. };
  132627. static static_codebook _44c1_s_p6_0 = {
  132628. 4, 81,
  132629. _vq_lengthlist__44c1_s_p6_0,
  132630. 1, -529137664, 1618345984, 2, 0,
  132631. _vq_quantlist__44c1_s_p6_0,
  132632. NULL,
  132633. &_vq_auxt__44c1_s_p6_0,
  132634. NULL,
  132635. 0
  132636. };
  132637. static long _vq_quantlist__44c1_s_p6_1[] = {
  132638. 5,
  132639. 4,
  132640. 6,
  132641. 3,
  132642. 7,
  132643. 2,
  132644. 8,
  132645. 1,
  132646. 9,
  132647. 0,
  132648. 10,
  132649. };
  132650. static long _vq_lengthlist__44c1_s_p6_1[] = {
  132651. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  132652. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  132653. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  132654. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  132655. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132656. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  132657. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132658. 10,10,10, 8, 8, 8, 8, 8, 8,
  132659. };
  132660. static float _vq_quantthresh__44c1_s_p6_1[] = {
  132661. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132662. 3.5, 4.5,
  132663. };
  132664. static long _vq_quantmap__44c1_s_p6_1[] = {
  132665. 9, 7, 5, 3, 1, 0, 2, 4,
  132666. 6, 8, 10,
  132667. };
  132668. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  132669. _vq_quantthresh__44c1_s_p6_1,
  132670. _vq_quantmap__44c1_s_p6_1,
  132671. 11,
  132672. 11
  132673. };
  132674. static static_codebook _44c1_s_p6_1 = {
  132675. 2, 121,
  132676. _vq_lengthlist__44c1_s_p6_1,
  132677. 1, -531365888, 1611661312, 4, 0,
  132678. _vq_quantlist__44c1_s_p6_1,
  132679. NULL,
  132680. &_vq_auxt__44c1_s_p6_1,
  132681. NULL,
  132682. 0
  132683. };
  132684. static long _vq_quantlist__44c1_s_p7_0[] = {
  132685. 6,
  132686. 5,
  132687. 7,
  132688. 4,
  132689. 8,
  132690. 3,
  132691. 9,
  132692. 2,
  132693. 10,
  132694. 1,
  132695. 11,
  132696. 0,
  132697. 12,
  132698. };
  132699. static long _vq_lengthlist__44c1_s_p7_0[] = {
  132700. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  132701. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  132702. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132703. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132704. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  132705. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132706. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  132707. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  132708. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  132709. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  132710. 0,12,11,11,11,13,10,14,13,
  132711. };
  132712. static float _vq_quantthresh__44c1_s_p7_0[] = {
  132713. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132714. 12.5, 17.5, 22.5, 27.5,
  132715. };
  132716. static long _vq_quantmap__44c1_s_p7_0[] = {
  132717. 11, 9, 7, 5, 3, 1, 0, 2,
  132718. 4, 6, 8, 10, 12,
  132719. };
  132720. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  132721. _vq_quantthresh__44c1_s_p7_0,
  132722. _vq_quantmap__44c1_s_p7_0,
  132723. 13,
  132724. 13
  132725. };
  132726. static static_codebook _44c1_s_p7_0 = {
  132727. 2, 169,
  132728. _vq_lengthlist__44c1_s_p7_0,
  132729. 1, -526516224, 1616117760, 4, 0,
  132730. _vq_quantlist__44c1_s_p7_0,
  132731. NULL,
  132732. &_vq_auxt__44c1_s_p7_0,
  132733. NULL,
  132734. 0
  132735. };
  132736. static long _vq_quantlist__44c1_s_p7_1[] = {
  132737. 2,
  132738. 1,
  132739. 3,
  132740. 0,
  132741. 4,
  132742. };
  132743. static long _vq_lengthlist__44c1_s_p7_1[] = {
  132744. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  132745. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  132746. };
  132747. static float _vq_quantthresh__44c1_s_p7_1[] = {
  132748. -1.5, -0.5, 0.5, 1.5,
  132749. };
  132750. static long _vq_quantmap__44c1_s_p7_1[] = {
  132751. 3, 1, 0, 2, 4,
  132752. };
  132753. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  132754. _vq_quantthresh__44c1_s_p7_1,
  132755. _vq_quantmap__44c1_s_p7_1,
  132756. 5,
  132757. 5
  132758. };
  132759. static static_codebook _44c1_s_p7_1 = {
  132760. 2, 25,
  132761. _vq_lengthlist__44c1_s_p7_1,
  132762. 1, -533725184, 1611661312, 3, 0,
  132763. _vq_quantlist__44c1_s_p7_1,
  132764. NULL,
  132765. &_vq_auxt__44c1_s_p7_1,
  132766. NULL,
  132767. 0
  132768. };
  132769. static long _vq_quantlist__44c1_s_p8_0[] = {
  132770. 6,
  132771. 5,
  132772. 7,
  132773. 4,
  132774. 8,
  132775. 3,
  132776. 9,
  132777. 2,
  132778. 10,
  132779. 1,
  132780. 11,
  132781. 0,
  132782. 12,
  132783. };
  132784. static long _vq_lengthlist__44c1_s_p8_0[] = {
  132785. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  132786. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  132787. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132788. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132789. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132790. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132791. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132792. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132793. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132794. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132795. 10,10,10,10,10,10,10,10,10,
  132796. };
  132797. static float _vq_quantthresh__44c1_s_p8_0[] = {
  132798. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  132799. 552.5, 773.5, 994.5, 1215.5,
  132800. };
  132801. static long _vq_quantmap__44c1_s_p8_0[] = {
  132802. 11, 9, 7, 5, 3, 1, 0, 2,
  132803. 4, 6, 8, 10, 12,
  132804. };
  132805. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  132806. _vq_quantthresh__44c1_s_p8_0,
  132807. _vq_quantmap__44c1_s_p8_0,
  132808. 13,
  132809. 13
  132810. };
  132811. static static_codebook _44c1_s_p8_0 = {
  132812. 2, 169,
  132813. _vq_lengthlist__44c1_s_p8_0,
  132814. 1, -514541568, 1627103232, 4, 0,
  132815. _vq_quantlist__44c1_s_p8_0,
  132816. NULL,
  132817. &_vq_auxt__44c1_s_p8_0,
  132818. NULL,
  132819. 0
  132820. };
  132821. static long _vq_quantlist__44c1_s_p8_1[] = {
  132822. 6,
  132823. 5,
  132824. 7,
  132825. 4,
  132826. 8,
  132827. 3,
  132828. 9,
  132829. 2,
  132830. 10,
  132831. 1,
  132832. 11,
  132833. 0,
  132834. 12,
  132835. };
  132836. static long _vq_lengthlist__44c1_s_p8_1[] = {
  132837. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  132838. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  132839. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  132840. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  132841. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  132842. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  132843. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  132844. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  132845. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  132846. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  132847. 16,13,12,12,11,14,12,15,13,
  132848. };
  132849. static float _vq_quantthresh__44c1_s_p8_1[] = {
  132850. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  132851. 42.5, 59.5, 76.5, 93.5,
  132852. };
  132853. static long _vq_quantmap__44c1_s_p8_1[] = {
  132854. 11, 9, 7, 5, 3, 1, 0, 2,
  132855. 4, 6, 8, 10, 12,
  132856. };
  132857. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  132858. _vq_quantthresh__44c1_s_p8_1,
  132859. _vq_quantmap__44c1_s_p8_1,
  132860. 13,
  132861. 13
  132862. };
  132863. static static_codebook _44c1_s_p8_1 = {
  132864. 2, 169,
  132865. _vq_lengthlist__44c1_s_p8_1,
  132866. 1, -522616832, 1620115456, 4, 0,
  132867. _vq_quantlist__44c1_s_p8_1,
  132868. NULL,
  132869. &_vq_auxt__44c1_s_p8_1,
  132870. NULL,
  132871. 0
  132872. };
  132873. static long _vq_quantlist__44c1_s_p8_2[] = {
  132874. 8,
  132875. 7,
  132876. 9,
  132877. 6,
  132878. 10,
  132879. 5,
  132880. 11,
  132881. 4,
  132882. 12,
  132883. 3,
  132884. 13,
  132885. 2,
  132886. 14,
  132887. 1,
  132888. 15,
  132889. 0,
  132890. 16,
  132891. };
  132892. static long _vq_lengthlist__44c1_s_p8_2[] = {
  132893. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132894. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  132895. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  132896. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  132897. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  132898. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  132899. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  132900. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  132901. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  132902. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  132903. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  132904. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  132905. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  132906. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  132907. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  132908. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  132909. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  132910. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  132911. 9,
  132912. };
  132913. static float _vq_quantthresh__44c1_s_p8_2[] = {
  132914. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132915. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132916. };
  132917. static long _vq_quantmap__44c1_s_p8_2[] = {
  132918. 15, 13, 11, 9, 7, 5, 3, 1,
  132919. 0, 2, 4, 6, 8, 10, 12, 14,
  132920. 16,
  132921. };
  132922. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  132923. _vq_quantthresh__44c1_s_p8_2,
  132924. _vq_quantmap__44c1_s_p8_2,
  132925. 17,
  132926. 17
  132927. };
  132928. static static_codebook _44c1_s_p8_2 = {
  132929. 2, 289,
  132930. _vq_lengthlist__44c1_s_p8_2,
  132931. 1, -529530880, 1611661312, 5, 0,
  132932. _vq_quantlist__44c1_s_p8_2,
  132933. NULL,
  132934. &_vq_auxt__44c1_s_p8_2,
  132935. NULL,
  132936. 0
  132937. };
  132938. static long _huff_lengthlist__44c1_s_short[] = {
  132939. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  132940. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  132941. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  132942. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  132943. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  132944. 11,
  132945. };
  132946. static static_codebook _huff_book__44c1_s_short = {
  132947. 2, 81,
  132948. _huff_lengthlist__44c1_s_short,
  132949. 0, 0, 0, 0, 0,
  132950. NULL,
  132951. NULL,
  132952. NULL,
  132953. NULL,
  132954. 0
  132955. };
  132956. static long _huff_lengthlist__44c1_sm_long[] = {
  132957. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  132958. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  132959. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  132960. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  132961. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  132962. 11,
  132963. };
  132964. static static_codebook _huff_book__44c1_sm_long = {
  132965. 2, 81,
  132966. _huff_lengthlist__44c1_sm_long,
  132967. 0, 0, 0, 0, 0,
  132968. NULL,
  132969. NULL,
  132970. NULL,
  132971. NULL,
  132972. 0
  132973. };
  132974. static long _vq_quantlist__44c1_sm_p1_0[] = {
  132975. 1,
  132976. 0,
  132977. 2,
  132978. };
  132979. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  132980. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  132981. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132985. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  132986. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132990. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  132991. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  133026. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  133027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  133031. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  133032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  133036. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  133037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133071. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  133072. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133076. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  133077. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  133078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133081. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  133082. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  133083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  133359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133390. 0,
  133391. };
  133392. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  133393. -0.5, 0.5,
  133394. };
  133395. static long _vq_quantmap__44c1_sm_p1_0[] = {
  133396. 1, 0, 2,
  133397. };
  133398. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  133399. _vq_quantthresh__44c1_sm_p1_0,
  133400. _vq_quantmap__44c1_sm_p1_0,
  133401. 3,
  133402. 3
  133403. };
  133404. static static_codebook _44c1_sm_p1_0 = {
  133405. 8, 6561,
  133406. _vq_lengthlist__44c1_sm_p1_0,
  133407. 1, -535822336, 1611661312, 2, 0,
  133408. _vq_quantlist__44c1_sm_p1_0,
  133409. NULL,
  133410. &_vq_auxt__44c1_sm_p1_0,
  133411. NULL,
  133412. 0
  133413. };
  133414. static long _vq_quantlist__44c1_sm_p2_0[] = {
  133415. 2,
  133416. 1,
  133417. 3,
  133418. 0,
  133419. 4,
  133420. };
  133421. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  133422. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  133424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133425. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  133427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133428. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  133462. };
  133463. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  133464. -1.5, -0.5, 0.5, 1.5,
  133465. };
  133466. static long _vq_quantmap__44c1_sm_p2_0[] = {
  133467. 3, 1, 0, 2, 4,
  133468. };
  133469. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  133470. _vq_quantthresh__44c1_sm_p2_0,
  133471. _vq_quantmap__44c1_sm_p2_0,
  133472. 5,
  133473. 5
  133474. };
  133475. static static_codebook _44c1_sm_p2_0 = {
  133476. 4, 625,
  133477. _vq_lengthlist__44c1_sm_p2_0,
  133478. 1, -533725184, 1611661312, 3, 0,
  133479. _vq_quantlist__44c1_sm_p2_0,
  133480. NULL,
  133481. &_vq_auxt__44c1_sm_p2_0,
  133482. NULL,
  133483. 0
  133484. };
  133485. static long _vq_quantlist__44c1_sm_p3_0[] = {
  133486. 4,
  133487. 3,
  133488. 5,
  133489. 2,
  133490. 6,
  133491. 1,
  133492. 7,
  133493. 0,
  133494. 8,
  133495. };
  133496. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  133497. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  133498. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  133499. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  133500. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  133501. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133502. 0,
  133503. };
  133504. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  133505. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133506. };
  133507. static long _vq_quantmap__44c1_sm_p3_0[] = {
  133508. 7, 5, 3, 1, 0, 2, 4, 6,
  133509. 8,
  133510. };
  133511. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  133512. _vq_quantthresh__44c1_sm_p3_0,
  133513. _vq_quantmap__44c1_sm_p3_0,
  133514. 9,
  133515. 9
  133516. };
  133517. static static_codebook _44c1_sm_p3_0 = {
  133518. 2, 81,
  133519. _vq_lengthlist__44c1_sm_p3_0,
  133520. 1, -531628032, 1611661312, 4, 0,
  133521. _vq_quantlist__44c1_sm_p3_0,
  133522. NULL,
  133523. &_vq_auxt__44c1_sm_p3_0,
  133524. NULL,
  133525. 0
  133526. };
  133527. static long _vq_quantlist__44c1_sm_p4_0[] = {
  133528. 4,
  133529. 3,
  133530. 5,
  133531. 2,
  133532. 6,
  133533. 1,
  133534. 7,
  133535. 0,
  133536. 8,
  133537. };
  133538. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  133539. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  133540. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  133541. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  133542. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  133543. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  133544. 11,
  133545. };
  133546. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  133547. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133548. };
  133549. static long _vq_quantmap__44c1_sm_p4_0[] = {
  133550. 7, 5, 3, 1, 0, 2, 4, 6,
  133551. 8,
  133552. };
  133553. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  133554. _vq_quantthresh__44c1_sm_p4_0,
  133555. _vq_quantmap__44c1_sm_p4_0,
  133556. 9,
  133557. 9
  133558. };
  133559. static static_codebook _44c1_sm_p4_0 = {
  133560. 2, 81,
  133561. _vq_lengthlist__44c1_sm_p4_0,
  133562. 1, -531628032, 1611661312, 4, 0,
  133563. _vq_quantlist__44c1_sm_p4_0,
  133564. NULL,
  133565. &_vq_auxt__44c1_sm_p4_0,
  133566. NULL,
  133567. 0
  133568. };
  133569. static long _vq_quantlist__44c1_sm_p5_0[] = {
  133570. 8,
  133571. 7,
  133572. 9,
  133573. 6,
  133574. 10,
  133575. 5,
  133576. 11,
  133577. 4,
  133578. 12,
  133579. 3,
  133580. 13,
  133581. 2,
  133582. 14,
  133583. 1,
  133584. 15,
  133585. 0,
  133586. 16,
  133587. };
  133588. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  133589. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133590. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  133591. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  133592. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  133593. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  133594. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  133595. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  133596. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  133597. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  133598. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  133599. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  133600. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  133601. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  133602. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  133603. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  133604. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  133605. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  133606. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  133607. 14,
  133608. };
  133609. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  133610. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133611. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133612. };
  133613. static long _vq_quantmap__44c1_sm_p5_0[] = {
  133614. 15, 13, 11, 9, 7, 5, 3, 1,
  133615. 0, 2, 4, 6, 8, 10, 12, 14,
  133616. 16,
  133617. };
  133618. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  133619. _vq_quantthresh__44c1_sm_p5_0,
  133620. _vq_quantmap__44c1_sm_p5_0,
  133621. 17,
  133622. 17
  133623. };
  133624. static static_codebook _44c1_sm_p5_0 = {
  133625. 2, 289,
  133626. _vq_lengthlist__44c1_sm_p5_0,
  133627. 1, -529530880, 1611661312, 5, 0,
  133628. _vq_quantlist__44c1_sm_p5_0,
  133629. NULL,
  133630. &_vq_auxt__44c1_sm_p5_0,
  133631. NULL,
  133632. 0
  133633. };
  133634. static long _vq_quantlist__44c1_sm_p6_0[] = {
  133635. 1,
  133636. 0,
  133637. 2,
  133638. };
  133639. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  133640. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  133641. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  133642. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  133643. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  133644. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  133645. 11,
  133646. };
  133647. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  133648. -5.5, 5.5,
  133649. };
  133650. static long _vq_quantmap__44c1_sm_p6_0[] = {
  133651. 1, 0, 2,
  133652. };
  133653. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  133654. _vq_quantthresh__44c1_sm_p6_0,
  133655. _vq_quantmap__44c1_sm_p6_0,
  133656. 3,
  133657. 3
  133658. };
  133659. static static_codebook _44c1_sm_p6_0 = {
  133660. 4, 81,
  133661. _vq_lengthlist__44c1_sm_p6_0,
  133662. 1, -529137664, 1618345984, 2, 0,
  133663. _vq_quantlist__44c1_sm_p6_0,
  133664. NULL,
  133665. &_vq_auxt__44c1_sm_p6_0,
  133666. NULL,
  133667. 0
  133668. };
  133669. static long _vq_quantlist__44c1_sm_p6_1[] = {
  133670. 5,
  133671. 4,
  133672. 6,
  133673. 3,
  133674. 7,
  133675. 2,
  133676. 8,
  133677. 1,
  133678. 9,
  133679. 0,
  133680. 10,
  133681. };
  133682. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  133683. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  133684. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  133685. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  133686. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  133687. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  133688. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  133689. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  133690. 10,10,10, 8, 8, 8, 8, 8, 8,
  133691. };
  133692. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  133693. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133694. 3.5, 4.5,
  133695. };
  133696. static long _vq_quantmap__44c1_sm_p6_1[] = {
  133697. 9, 7, 5, 3, 1, 0, 2, 4,
  133698. 6, 8, 10,
  133699. };
  133700. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  133701. _vq_quantthresh__44c1_sm_p6_1,
  133702. _vq_quantmap__44c1_sm_p6_1,
  133703. 11,
  133704. 11
  133705. };
  133706. static static_codebook _44c1_sm_p6_1 = {
  133707. 2, 121,
  133708. _vq_lengthlist__44c1_sm_p6_1,
  133709. 1, -531365888, 1611661312, 4, 0,
  133710. _vq_quantlist__44c1_sm_p6_1,
  133711. NULL,
  133712. &_vq_auxt__44c1_sm_p6_1,
  133713. NULL,
  133714. 0
  133715. };
  133716. static long _vq_quantlist__44c1_sm_p7_0[] = {
  133717. 6,
  133718. 5,
  133719. 7,
  133720. 4,
  133721. 8,
  133722. 3,
  133723. 9,
  133724. 2,
  133725. 10,
  133726. 1,
  133727. 11,
  133728. 0,
  133729. 12,
  133730. };
  133731. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  133732. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  133733. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  133734. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  133735. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  133736. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  133737. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  133738. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  133739. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  133740. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  133741. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  133742. 0,12,12,11,11,13,12,14,13,
  133743. };
  133744. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  133745. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133746. 12.5, 17.5, 22.5, 27.5,
  133747. };
  133748. static long _vq_quantmap__44c1_sm_p7_0[] = {
  133749. 11, 9, 7, 5, 3, 1, 0, 2,
  133750. 4, 6, 8, 10, 12,
  133751. };
  133752. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  133753. _vq_quantthresh__44c1_sm_p7_0,
  133754. _vq_quantmap__44c1_sm_p7_0,
  133755. 13,
  133756. 13
  133757. };
  133758. static static_codebook _44c1_sm_p7_0 = {
  133759. 2, 169,
  133760. _vq_lengthlist__44c1_sm_p7_0,
  133761. 1, -526516224, 1616117760, 4, 0,
  133762. _vq_quantlist__44c1_sm_p7_0,
  133763. NULL,
  133764. &_vq_auxt__44c1_sm_p7_0,
  133765. NULL,
  133766. 0
  133767. };
  133768. static long _vq_quantlist__44c1_sm_p7_1[] = {
  133769. 2,
  133770. 1,
  133771. 3,
  133772. 0,
  133773. 4,
  133774. };
  133775. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  133776. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  133777. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133778. };
  133779. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  133780. -1.5, -0.5, 0.5, 1.5,
  133781. };
  133782. static long _vq_quantmap__44c1_sm_p7_1[] = {
  133783. 3, 1, 0, 2, 4,
  133784. };
  133785. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  133786. _vq_quantthresh__44c1_sm_p7_1,
  133787. _vq_quantmap__44c1_sm_p7_1,
  133788. 5,
  133789. 5
  133790. };
  133791. static static_codebook _44c1_sm_p7_1 = {
  133792. 2, 25,
  133793. _vq_lengthlist__44c1_sm_p7_1,
  133794. 1, -533725184, 1611661312, 3, 0,
  133795. _vq_quantlist__44c1_sm_p7_1,
  133796. NULL,
  133797. &_vq_auxt__44c1_sm_p7_1,
  133798. NULL,
  133799. 0
  133800. };
  133801. static long _vq_quantlist__44c1_sm_p8_0[] = {
  133802. 6,
  133803. 5,
  133804. 7,
  133805. 4,
  133806. 8,
  133807. 3,
  133808. 9,
  133809. 2,
  133810. 10,
  133811. 1,
  133812. 11,
  133813. 0,
  133814. 12,
  133815. };
  133816. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  133817. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  133818. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  133819. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133820. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133821. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133822. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133823. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133824. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133825. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133826. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133827. 13,13,13,13,13,13,13,13,13,
  133828. };
  133829. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  133830. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  133831. 552.5, 773.5, 994.5, 1215.5,
  133832. };
  133833. static long _vq_quantmap__44c1_sm_p8_0[] = {
  133834. 11, 9, 7, 5, 3, 1, 0, 2,
  133835. 4, 6, 8, 10, 12,
  133836. };
  133837. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  133838. _vq_quantthresh__44c1_sm_p8_0,
  133839. _vq_quantmap__44c1_sm_p8_0,
  133840. 13,
  133841. 13
  133842. };
  133843. static static_codebook _44c1_sm_p8_0 = {
  133844. 2, 169,
  133845. _vq_lengthlist__44c1_sm_p8_0,
  133846. 1, -514541568, 1627103232, 4, 0,
  133847. _vq_quantlist__44c1_sm_p8_0,
  133848. NULL,
  133849. &_vq_auxt__44c1_sm_p8_0,
  133850. NULL,
  133851. 0
  133852. };
  133853. static long _vq_quantlist__44c1_sm_p8_1[] = {
  133854. 6,
  133855. 5,
  133856. 7,
  133857. 4,
  133858. 8,
  133859. 3,
  133860. 9,
  133861. 2,
  133862. 10,
  133863. 1,
  133864. 11,
  133865. 0,
  133866. 12,
  133867. };
  133868. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  133869. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  133870. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  133871. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  133872. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  133873. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  133874. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  133875. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  133876. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  133877. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  133878. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  133879. 20,13,12,12,12,14,12,14,13,
  133880. };
  133881. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  133882. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  133883. 42.5, 59.5, 76.5, 93.5,
  133884. };
  133885. static long _vq_quantmap__44c1_sm_p8_1[] = {
  133886. 11, 9, 7, 5, 3, 1, 0, 2,
  133887. 4, 6, 8, 10, 12,
  133888. };
  133889. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  133890. _vq_quantthresh__44c1_sm_p8_1,
  133891. _vq_quantmap__44c1_sm_p8_1,
  133892. 13,
  133893. 13
  133894. };
  133895. static static_codebook _44c1_sm_p8_1 = {
  133896. 2, 169,
  133897. _vq_lengthlist__44c1_sm_p8_1,
  133898. 1, -522616832, 1620115456, 4, 0,
  133899. _vq_quantlist__44c1_sm_p8_1,
  133900. NULL,
  133901. &_vq_auxt__44c1_sm_p8_1,
  133902. NULL,
  133903. 0
  133904. };
  133905. static long _vq_quantlist__44c1_sm_p8_2[] = {
  133906. 8,
  133907. 7,
  133908. 9,
  133909. 6,
  133910. 10,
  133911. 5,
  133912. 11,
  133913. 4,
  133914. 12,
  133915. 3,
  133916. 13,
  133917. 2,
  133918. 14,
  133919. 1,
  133920. 15,
  133921. 0,
  133922. 16,
  133923. };
  133924. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  133925. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  133926. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  133927. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133928. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  133929. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  133930. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  133931. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  133932. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  133933. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  133934. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  133935. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  133936. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  133937. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  133938. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  133939. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  133940. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  133941. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  133942. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  133943. 9,
  133944. };
  133945. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  133946. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133947. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133948. };
  133949. static long _vq_quantmap__44c1_sm_p8_2[] = {
  133950. 15, 13, 11, 9, 7, 5, 3, 1,
  133951. 0, 2, 4, 6, 8, 10, 12, 14,
  133952. 16,
  133953. };
  133954. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  133955. _vq_quantthresh__44c1_sm_p8_2,
  133956. _vq_quantmap__44c1_sm_p8_2,
  133957. 17,
  133958. 17
  133959. };
  133960. static static_codebook _44c1_sm_p8_2 = {
  133961. 2, 289,
  133962. _vq_lengthlist__44c1_sm_p8_2,
  133963. 1, -529530880, 1611661312, 5, 0,
  133964. _vq_quantlist__44c1_sm_p8_2,
  133965. NULL,
  133966. &_vq_auxt__44c1_sm_p8_2,
  133967. NULL,
  133968. 0
  133969. };
  133970. static long _huff_lengthlist__44c1_sm_short[] = {
  133971. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  133972. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  133973. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  133974. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  133975. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  133976. 11,
  133977. };
  133978. static static_codebook _huff_book__44c1_sm_short = {
  133979. 2, 81,
  133980. _huff_lengthlist__44c1_sm_short,
  133981. 0, 0, 0, 0, 0,
  133982. NULL,
  133983. NULL,
  133984. NULL,
  133985. NULL,
  133986. 0
  133987. };
  133988. static long _huff_lengthlist__44cn1_s_long[] = {
  133989. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  133990. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  133991. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  133992. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  133993. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  133994. 20,
  133995. };
  133996. static static_codebook _huff_book__44cn1_s_long = {
  133997. 2, 81,
  133998. _huff_lengthlist__44cn1_s_long,
  133999. 0, 0, 0, 0, 0,
  134000. NULL,
  134001. NULL,
  134002. NULL,
  134003. NULL,
  134004. 0
  134005. };
  134006. static long _vq_quantlist__44cn1_s_p1_0[] = {
  134007. 1,
  134008. 0,
  134009. 2,
  134010. };
  134011. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  134012. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  134013. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134017. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  134018. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134022. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  134023. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  134058. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  134059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  134063. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  134064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  134068. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  134069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134103. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  134104. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134108. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  134109. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  134110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134113. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  134114. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  134115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  134410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134422. 0,
  134423. };
  134424. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  134425. -0.5, 0.5,
  134426. };
  134427. static long _vq_quantmap__44cn1_s_p1_0[] = {
  134428. 1, 0, 2,
  134429. };
  134430. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  134431. _vq_quantthresh__44cn1_s_p1_0,
  134432. _vq_quantmap__44cn1_s_p1_0,
  134433. 3,
  134434. 3
  134435. };
  134436. static static_codebook _44cn1_s_p1_0 = {
  134437. 8, 6561,
  134438. _vq_lengthlist__44cn1_s_p1_0,
  134439. 1, -535822336, 1611661312, 2, 0,
  134440. _vq_quantlist__44cn1_s_p1_0,
  134441. NULL,
  134442. &_vq_auxt__44cn1_s_p1_0,
  134443. NULL,
  134444. 0
  134445. };
  134446. static long _vq_quantlist__44cn1_s_p2_0[] = {
  134447. 2,
  134448. 1,
  134449. 3,
  134450. 0,
  134451. 4,
  134452. };
  134453. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  134454. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  134456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134457. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  134459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134460. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  134461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134493. 0,
  134494. };
  134495. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  134496. -1.5, -0.5, 0.5, 1.5,
  134497. };
  134498. static long _vq_quantmap__44cn1_s_p2_0[] = {
  134499. 3, 1, 0, 2, 4,
  134500. };
  134501. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  134502. _vq_quantthresh__44cn1_s_p2_0,
  134503. _vq_quantmap__44cn1_s_p2_0,
  134504. 5,
  134505. 5
  134506. };
  134507. static static_codebook _44cn1_s_p2_0 = {
  134508. 4, 625,
  134509. _vq_lengthlist__44cn1_s_p2_0,
  134510. 1, -533725184, 1611661312, 3, 0,
  134511. _vq_quantlist__44cn1_s_p2_0,
  134512. NULL,
  134513. &_vq_auxt__44cn1_s_p2_0,
  134514. NULL,
  134515. 0
  134516. };
  134517. static long _vq_quantlist__44cn1_s_p3_0[] = {
  134518. 4,
  134519. 3,
  134520. 5,
  134521. 2,
  134522. 6,
  134523. 1,
  134524. 7,
  134525. 0,
  134526. 8,
  134527. };
  134528. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  134529. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  134530. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  134531. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  134532. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  134533. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134534. 0,
  134535. };
  134536. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  134537. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134538. };
  134539. static long _vq_quantmap__44cn1_s_p3_0[] = {
  134540. 7, 5, 3, 1, 0, 2, 4, 6,
  134541. 8,
  134542. };
  134543. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  134544. _vq_quantthresh__44cn1_s_p3_0,
  134545. _vq_quantmap__44cn1_s_p3_0,
  134546. 9,
  134547. 9
  134548. };
  134549. static static_codebook _44cn1_s_p3_0 = {
  134550. 2, 81,
  134551. _vq_lengthlist__44cn1_s_p3_0,
  134552. 1, -531628032, 1611661312, 4, 0,
  134553. _vq_quantlist__44cn1_s_p3_0,
  134554. NULL,
  134555. &_vq_auxt__44cn1_s_p3_0,
  134556. NULL,
  134557. 0
  134558. };
  134559. static long _vq_quantlist__44cn1_s_p4_0[] = {
  134560. 4,
  134561. 3,
  134562. 5,
  134563. 2,
  134564. 6,
  134565. 1,
  134566. 7,
  134567. 0,
  134568. 8,
  134569. };
  134570. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  134571. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  134572. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  134573. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  134574. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  134575. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  134576. 11,
  134577. };
  134578. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  134579. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134580. };
  134581. static long _vq_quantmap__44cn1_s_p4_0[] = {
  134582. 7, 5, 3, 1, 0, 2, 4, 6,
  134583. 8,
  134584. };
  134585. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  134586. _vq_quantthresh__44cn1_s_p4_0,
  134587. _vq_quantmap__44cn1_s_p4_0,
  134588. 9,
  134589. 9
  134590. };
  134591. static static_codebook _44cn1_s_p4_0 = {
  134592. 2, 81,
  134593. _vq_lengthlist__44cn1_s_p4_0,
  134594. 1, -531628032, 1611661312, 4, 0,
  134595. _vq_quantlist__44cn1_s_p4_0,
  134596. NULL,
  134597. &_vq_auxt__44cn1_s_p4_0,
  134598. NULL,
  134599. 0
  134600. };
  134601. static long _vq_quantlist__44cn1_s_p5_0[] = {
  134602. 8,
  134603. 7,
  134604. 9,
  134605. 6,
  134606. 10,
  134607. 5,
  134608. 11,
  134609. 4,
  134610. 12,
  134611. 3,
  134612. 13,
  134613. 2,
  134614. 14,
  134615. 1,
  134616. 15,
  134617. 0,
  134618. 16,
  134619. };
  134620. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  134621. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  134622. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  134623. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  134624. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  134625. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  134626. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  134627. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  134628. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  134629. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  134630. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  134631. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  134632. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  134633. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  134634. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  134635. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  134636. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  134637. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  134638. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  134639. 14,
  134640. };
  134641. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  134642. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134643. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134644. };
  134645. static long _vq_quantmap__44cn1_s_p5_0[] = {
  134646. 15, 13, 11, 9, 7, 5, 3, 1,
  134647. 0, 2, 4, 6, 8, 10, 12, 14,
  134648. 16,
  134649. };
  134650. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  134651. _vq_quantthresh__44cn1_s_p5_0,
  134652. _vq_quantmap__44cn1_s_p5_0,
  134653. 17,
  134654. 17
  134655. };
  134656. static static_codebook _44cn1_s_p5_0 = {
  134657. 2, 289,
  134658. _vq_lengthlist__44cn1_s_p5_0,
  134659. 1, -529530880, 1611661312, 5, 0,
  134660. _vq_quantlist__44cn1_s_p5_0,
  134661. NULL,
  134662. &_vq_auxt__44cn1_s_p5_0,
  134663. NULL,
  134664. 0
  134665. };
  134666. static long _vq_quantlist__44cn1_s_p6_0[] = {
  134667. 1,
  134668. 0,
  134669. 2,
  134670. };
  134671. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  134672. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  134673. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  134674. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  134675. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  134676. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  134677. 10,
  134678. };
  134679. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  134680. -5.5, 5.5,
  134681. };
  134682. static long _vq_quantmap__44cn1_s_p6_0[] = {
  134683. 1, 0, 2,
  134684. };
  134685. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  134686. _vq_quantthresh__44cn1_s_p6_0,
  134687. _vq_quantmap__44cn1_s_p6_0,
  134688. 3,
  134689. 3
  134690. };
  134691. static static_codebook _44cn1_s_p6_0 = {
  134692. 4, 81,
  134693. _vq_lengthlist__44cn1_s_p6_0,
  134694. 1, -529137664, 1618345984, 2, 0,
  134695. _vq_quantlist__44cn1_s_p6_0,
  134696. NULL,
  134697. &_vq_auxt__44cn1_s_p6_0,
  134698. NULL,
  134699. 0
  134700. };
  134701. static long _vq_quantlist__44cn1_s_p6_1[] = {
  134702. 5,
  134703. 4,
  134704. 6,
  134705. 3,
  134706. 7,
  134707. 2,
  134708. 8,
  134709. 1,
  134710. 9,
  134711. 0,
  134712. 10,
  134713. };
  134714. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  134715. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  134716. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  134717. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  134718. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  134719. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  134720. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134721. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  134722. 10,10,10, 9, 9, 9, 9, 9, 9,
  134723. };
  134724. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  134725. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134726. 3.5, 4.5,
  134727. };
  134728. static long _vq_quantmap__44cn1_s_p6_1[] = {
  134729. 9, 7, 5, 3, 1, 0, 2, 4,
  134730. 6, 8, 10,
  134731. };
  134732. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  134733. _vq_quantthresh__44cn1_s_p6_1,
  134734. _vq_quantmap__44cn1_s_p6_1,
  134735. 11,
  134736. 11
  134737. };
  134738. static static_codebook _44cn1_s_p6_1 = {
  134739. 2, 121,
  134740. _vq_lengthlist__44cn1_s_p6_1,
  134741. 1, -531365888, 1611661312, 4, 0,
  134742. _vq_quantlist__44cn1_s_p6_1,
  134743. NULL,
  134744. &_vq_auxt__44cn1_s_p6_1,
  134745. NULL,
  134746. 0
  134747. };
  134748. static long _vq_quantlist__44cn1_s_p7_0[] = {
  134749. 6,
  134750. 5,
  134751. 7,
  134752. 4,
  134753. 8,
  134754. 3,
  134755. 9,
  134756. 2,
  134757. 10,
  134758. 1,
  134759. 11,
  134760. 0,
  134761. 12,
  134762. };
  134763. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  134764. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134765. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  134766. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  134767. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  134768. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  134769. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  134770. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  134771. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  134772. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  134773. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  134774. 0,13,13,12,12,13,13,13,14,
  134775. };
  134776. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  134777. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134778. 12.5, 17.5, 22.5, 27.5,
  134779. };
  134780. static long _vq_quantmap__44cn1_s_p7_0[] = {
  134781. 11, 9, 7, 5, 3, 1, 0, 2,
  134782. 4, 6, 8, 10, 12,
  134783. };
  134784. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  134785. _vq_quantthresh__44cn1_s_p7_0,
  134786. _vq_quantmap__44cn1_s_p7_0,
  134787. 13,
  134788. 13
  134789. };
  134790. static static_codebook _44cn1_s_p7_0 = {
  134791. 2, 169,
  134792. _vq_lengthlist__44cn1_s_p7_0,
  134793. 1, -526516224, 1616117760, 4, 0,
  134794. _vq_quantlist__44cn1_s_p7_0,
  134795. NULL,
  134796. &_vq_auxt__44cn1_s_p7_0,
  134797. NULL,
  134798. 0
  134799. };
  134800. static long _vq_quantlist__44cn1_s_p7_1[] = {
  134801. 2,
  134802. 1,
  134803. 3,
  134804. 0,
  134805. 4,
  134806. };
  134807. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  134808. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  134809. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  134810. };
  134811. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  134812. -1.5, -0.5, 0.5, 1.5,
  134813. };
  134814. static long _vq_quantmap__44cn1_s_p7_1[] = {
  134815. 3, 1, 0, 2, 4,
  134816. };
  134817. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  134818. _vq_quantthresh__44cn1_s_p7_1,
  134819. _vq_quantmap__44cn1_s_p7_1,
  134820. 5,
  134821. 5
  134822. };
  134823. static static_codebook _44cn1_s_p7_1 = {
  134824. 2, 25,
  134825. _vq_lengthlist__44cn1_s_p7_1,
  134826. 1, -533725184, 1611661312, 3, 0,
  134827. _vq_quantlist__44cn1_s_p7_1,
  134828. NULL,
  134829. &_vq_auxt__44cn1_s_p7_1,
  134830. NULL,
  134831. 0
  134832. };
  134833. static long _vq_quantlist__44cn1_s_p8_0[] = {
  134834. 2,
  134835. 1,
  134836. 3,
  134837. 0,
  134838. 4,
  134839. };
  134840. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  134841. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  134842. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  134843. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134844. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  134845. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134846. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134847. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134848. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  134849. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134850. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  134851. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  134852. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134853. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134854. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134855. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134856. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  134857. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134858. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134859. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134860. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134861. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134862. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134863. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134864. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134865. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134866. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134867. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134868. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134869. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134870. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134871. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134872. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134873. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134874. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  134875. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134876. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134877. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134878. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134879. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134880. 12,
  134881. };
  134882. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  134883. -331.5, -110.5, 110.5, 331.5,
  134884. };
  134885. static long _vq_quantmap__44cn1_s_p8_0[] = {
  134886. 3, 1, 0, 2, 4,
  134887. };
  134888. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  134889. _vq_quantthresh__44cn1_s_p8_0,
  134890. _vq_quantmap__44cn1_s_p8_0,
  134891. 5,
  134892. 5
  134893. };
  134894. static static_codebook _44cn1_s_p8_0 = {
  134895. 4, 625,
  134896. _vq_lengthlist__44cn1_s_p8_0,
  134897. 1, -518283264, 1627103232, 3, 0,
  134898. _vq_quantlist__44cn1_s_p8_0,
  134899. NULL,
  134900. &_vq_auxt__44cn1_s_p8_0,
  134901. NULL,
  134902. 0
  134903. };
  134904. static long _vq_quantlist__44cn1_s_p8_1[] = {
  134905. 6,
  134906. 5,
  134907. 7,
  134908. 4,
  134909. 8,
  134910. 3,
  134911. 9,
  134912. 2,
  134913. 10,
  134914. 1,
  134915. 11,
  134916. 0,
  134917. 12,
  134918. };
  134919. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  134920. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  134921. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  134922. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  134923. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  134924. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  134925. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  134926. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  134927. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  134928. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  134929. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  134930. 15,12,12,11,11,14,12,13,14,
  134931. };
  134932. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  134933. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  134934. 42.5, 59.5, 76.5, 93.5,
  134935. };
  134936. static long _vq_quantmap__44cn1_s_p8_1[] = {
  134937. 11, 9, 7, 5, 3, 1, 0, 2,
  134938. 4, 6, 8, 10, 12,
  134939. };
  134940. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  134941. _vq_quantthresh__44cn1_s_p8_1,
  134942. _vq_quantmap__44cn1_s_p8_1,
  134943. 13,
  134944. 13
  134945. };
  134946. static static_codebook _44cn1_s_p8_1 = {
  134947. 2, 169,
  134948. _vq_lengthlist__44cn1_s_p8_1,
  134949. 1, -522616832, 1620115456, 4, 0,
  134950. _vq_quantlist__44cn1_s_p8_1,
  134951. NULL,
  134952. &_vq_auxt__44cn1_s_p8_1,
  134953. NULL,
  134954. 0
  134955. };
  134956. static long _vq_quantlist__44cn1_s_p8_2[] = {
  134957. 8,
  134958. 7,
  134959. 9,
  134960. 6,
  134961. 10,
  134962. 5,
  134963. 11,
  134964. 4,
  134965. 12,
  134966. 3,
  134967. 13,
  134968. 2,
  134969. 14,
  134970. 1,
  134971. 15,
  134972. 0,
  134973. 16,
  134974. };
  134975. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  134976. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  134977. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  134978. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  134979. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  134980. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  134981. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  134982. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  134983. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  134984. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  134985. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  134986. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  134987. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  134988. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  134989. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  134990. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  134991. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  134992. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  134993. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  134994. 9,
  134995. };
  134996. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  134997. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134998. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134999. };
  135000. static long _vq_quantmap__44cn1_s_p8_2[] = {
  135001. 15, 13, 11, 9, 7, 5, 3, 1,
  135002. 0, 2, 4, 6, 8, 10, 12, 14,
  135003. 16,
  135004. };
  135005. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  135006. _vq_quantthresh__44cn1_s_p8_2,
  135007. _vq_quantmap__44cn1_s_p8_2,
  135008. 17,
  135009. 17
  135010. };
  135011. static static_codebook _44cn1_s_p8_2 = {
  135012. 2, 289,
  135013. _vq_lengthlist__44cn1_s_p8_2,
  135014. 1, -529530880, 1611661312, 5, 0,
  135015. _vq_quantlist__44cn1_s_p8_2,
  135016. NULL,
  135017. &_vq_auxt__44cn1_s_p8_2,
  135018. NULL,
  135019. 0
  135020. };
  135021. static long _huff_lengthlist__44cn1_s_short[] = {
  135022. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  135023. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  135024. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  135025. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  135026. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  135027. 10,
  135028. };
  135029. static static_codebook _huff_book__44cn1_s_short = {
  135030. 2, 81,
  135031. _huff_lengthlist__44cn1_s_short,
  135032. 0, 0, 0, 0, 0,
  135033. NULL,
  135034. NULL,
  135035. NULL,
  135036. NULL,
  135037. 0
  135038. };
  135039. static long _huff_lengthlist__44cn1_sm_long[] = {
  135040. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  135041. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  135042. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  135043. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  135044. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  135045. 17,
  135046. };
  135047. static static_codebook _huff_book__44cn1_sm_long = {
  135048. 2, 81,
  135049. _huff_lengthlist__44cn1_sm_long,
  135050. 0, 0, 0, 0, 0,
  135051. NULL,
  135052. NULL,
  135053. NULL,
  135054. NULL,
  135055. 0
  135056. };
  135057. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  135058. 1,
  135059. 0,
  135060. 2,
  135061. };
  135062. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  135063. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135064. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135068. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  135069. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135073. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  135074. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  135109. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  135110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  135114. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  135115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135119. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  135120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135154. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  135155. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135159. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  135160. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  135161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135164. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  135165. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  135166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135473. 0,
  135474. };
  135475. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  135476. -0.5, 0.5,
  135477. };
  135478. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  135479. 1, 0, 2,
  135480. };
  135481. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  135482. _vq_quantthresh__44cn1_sm_p1_0,
  135483. _vq_quantmap__44cn1_sm_p1_0,
  135484. 3,
  135485. 3
  135486. };
  135487. static static_codebook _44cn1_sm_p1_0 = {
  135488. 8, 6561,
  135489. _vq_lengthlist__44cn1_sm_p1_0,
  135490. 1, -535822336, 1611661312, 2, 0,
  135491. _vq_quantlist__44cn1_sm_p1_0,
  135492. NULL,
  135493. &_vq_auxt__44cn1_sm_p1_0,
  135494. NULL,
  135495. 0
  135496. };
  135497. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  135498. 2,
  135499. 1,
  135500. 3,
  135501. 0,
  135502. 4,
  135503. };
  135504. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  135505. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  135507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135508. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  135510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135511. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  135512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135544. 0,
  135545. };
  135546. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  135547. -1.5, -0.5, 0.5, 1.5,
  135548. };
  135549. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  135550. 3, 1, 0, 2, 4,
  135551. };
  135552. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  135553. _vq_quantthresh__44cn1_sm_p2_0,
  135554. _vq_quantmap__44cn1_sm_p2_0,
  135555. 5,
  135556. 5
  135557. };
  135558. static static_codebook _44cn1_sm_p2_0 = {
  135559. 4, 625,
  135560. _vq_lengthlist__44cn1_sm_p2_0,
  135561. 1, -533725184, 1611661312, 3, 0,
  135562. _vq_quantlist__44cn1_sm_p2_0,
  135563. NULL,
  135564. &_vq_auxt__44cn1_sm_p2_0,
  135565. NULL,
  135566. 0
  135567. };
  135568. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  135569. 4,
  135570. 3,
  135571. 5,
  135572. 2,
  135573. 6,
  135574. 1,
  135575. 7,
  135576. 0,
  135577. 8,
  135578. };
  135579. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  135580. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  135581. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  135582. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  135583. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  135584. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135585. 0,
  135586. };
  135587. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  135588. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135589. };
  135590. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  135591. 7, 5, 3, 1, 0, 2, 4, 6,
  135592. 8,
  135593. };
  135594. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  135595. _vq_quantthresh__44cn1_sm_p3_0,
  135596. _vq_quantmap__44cn1_sm_p3_0,
  135597. 9,
  135598. 9
  135599. };
  135600. static static_codebook _44cn1_sm_p3_0 = {
  135601. 2, 81,
  135602. _vq_lengthlist__44cn1_sm_p3_0,
  135603. 1, -531628032, 1611661312, 4, 0,
  135604. _vq_quantlist__44cn1_sm_p3_0,
  135605. NULL,
  135606. &_vq_auxt__44cn1_sm_p3_0,
  135607. NULL,
  135608. 0
  135609. };
  135610. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  135611. 4,
  135612. 3,
  135613. 5,
  135614. 2,
  135615. 6,
  135616. 1,
  135617. 7,
  135618. 0,
  135619. 8,
  135620. };
  135621. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  135622. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  135623. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  135624. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  135625. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  135626. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  135627. 11,
  135628. };
  135629. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  135630. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135631. };
  135632. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  135633. 7, 5, 3, 1, 0, 2, 4, 6,
  135634. 8,
  135635. };
  135636. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  135637. _vq_quantthresh__44cn1_sm_p4_0,
  135638. _vq_quantmap__44cn1_sm_p4_0,
  135639. 9,
  135640. 9
  135641. };
  135642. static static_codebook _44cn1_sm_p4_0 = {
  135643. 2, 81,
  135644. _vq_lengthlist__44cn1_sm_p4_0,
  135645. 1, -531628032, 1611661312, 4, 0,
  135646. _vq_quantlist__44cn1_sm_p4_0,
  135647. NULL,
  135648. &_vq_auxt__44cn1_sm_p4_0,
  135649. NULL,
  135650. 0
  135651. };
  135652. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  135653. 8,
  135654. 7,
  135655. 9,
  135656. 6,
  135657. 10,
  135658. 5,
  135659. 11,
  135660. 4,
  135661. 12,
  135662. 3,
  135663. 13,
  135664. 2,
  135665. 14,
  135666. 1,
  135667. 15,
  135668. 0,
  135669. 16,
  135670. };
  135671. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  135672. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  135673. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  135674. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  135675. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135676. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  135677. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  135678. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  135679. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  135680. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  135681. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  135682. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  135683. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  135684. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  135685. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  135686. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  135687. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  135688. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  135689. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  135690. 14,
  135691. };
  135692. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  135693. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135694. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135695. };
  135696. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  135697. 15, 13, 11, 9, 7, 5, 3, 1,
  135698. 0, 2, 4, 6, 8, 10, 12, 14,
  135699. 16,
  135700. };
  135701. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  135702. _vq_quantthresh__44cn1_sm_p5_0,
  135703. _vq_quantmap__44cn1_sm_p5_0,
  135704. 17,
  135705. 17
  135706. };
  135707. static static_codebook _44cn1_sm_p5_0 = {
  135708. 2, 289,
  135709. _vq_lengthlist__44cn1_sm_p5_0,
  135710. 1, -529530880, 1611661312, 5, 0,
  135711. _vq_quantlist__44cn1_sm_p5_0,
  135712. NULL,
  135713. &_vq_auxt__44cn1_sm_p5_0,
  135714. NULL,
  135715. 0
  135716. };
  135717. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  135718. 1,
  135719. 0,
  135720. 2,
  135721. };
  135722. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  135723. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  135724. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  135725. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  135726. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  135727. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  135728. 10,
  135729. };
  135730. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  135731. -5.5, 5.5,
  135732. };
  135733. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  135734. 1, 0, 2,
  135735. };
  135736. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  135737. _vq_quantthresh__44cn1_sm_p6_0,
  135738. _vq_quantmap__44cn1_sm_p6_0,
  135739. 3,
  135740. 3
  135741. };
  135742. static static_codebook _44cn1_sm_p6_0 = {
  135743. 4, 81,
  135744. _vq_lengthlist__44cn1_sm_p6_0,
  135745. 1, -529137664, 1618345984, 2, 0,
  135746. _vq_quantlist__44cn1_sm_p6_0,
  135747. NULL,
  135748. &_vq_auxt__44cn1_sm_p6_0,
  135749. NULL,
  135750. 0
  135751. };
  135752. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  135753. 5,
  135754. 4,
  135755. 6,
  135756. 3,
  135757. 7,
  135758. 2,
  135759. 8,
  135760. 1,
  135761. 9,
  135762. 0,
  135763. 10,
  135764. };
  135765. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  135766. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  135767. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  135768. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  135769. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  135770. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  135771. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  135772. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  135773. 10,10,10, 8, 9, 8, 8, 9, 8,
  135774. };
  135775. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  135776. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135777. 3.5, 4.5,
  135778. };
  135779. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  135780. 9, 7, 5, 3, 1, 0, 2, 4,
  135781. 6, 8, 10,
  135782. };
  135783. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  135784. _vq_quantthresh__44cn1_sm_p6_1,
  135785. _vq_quantmap__44cn1_sm_p6_1,
  135786. 11,
  135787. 11
  135788. };
  135789. static static_codebook _44cn1_sm_p6_1 = {
  135790. 2, 121,
  135791. _vq_lengthlist__44cn1_sm_p6_1,
  135792. 1, -531365888, 1611661312, 4, 0,
  135793. _vq_quantlist__44cn1_sm_p6_1,
  135794. NULL,
  135795. &_vq_auxt__44cn1_sm_p6_1,
  135796. NULL,
  135797. 0
  135798. };
  135799. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  135800. 6,
  135801. 5,
  135802. 7,
  135803. 4,
  135804. 8,
  135805. 3,
  135806. 9,
  135807. 2,
  135808. 10,
  135809. 1,
  135810. 11,
  135811. 0,
  135812. 12,
  135813. };
  135814. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  135815. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  135816. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  135817. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135818. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135819. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  135820. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  135821. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  135822. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  135823. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  135824. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  135825. 0,13,12,12,12,13,13,13,14,
  135826. };
  135827. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  135828. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135829. 12.5, 17.5, 22.5, 27.5,
  135830. };
  135831. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  135832. 11, 9, 7, 5, 3, 1, 0, 2,
  135833. 4, 6, 8, 10, 12,
  135834. };
  135835. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  135836. _vq_quantthresh__44cn1_sm_p7_0,
  135837. _vq_quantmap__44cn1_sm_p7_0,
  135838. 13,
  135839. 13
  135840. };
  135841. static static_codebook _44cn1_sm_p7_0 = {
  135842. 2, 169,
  135843. _vq_lengthlist__44cn1_sm_p7_0,
  135844. 1, -526516224, 1616117760, 4, 0,
  135845. _vq_quantlist__44cn1_sm_p7_0,
  135846. NULL,
  135847. &_vq_auxt__44cn1_sm_p7_0,
  135848. NULL,
  135849. 0
  135850. };
  135851. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  135852. 2,
  135853. 1,
  135854. 3,
  135855. 0,
  135856. 4,
  135857. };
  135858. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  135859. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  135860. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  135861. };
  135862. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  135863. -1.5, -0.5, 0.5, 1.5,
  135864. };
  135865. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  135866. 3, 1, 0, 2, 4,
  135867. };
  135868. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  135869. _vq_quantthresh__44cn1_sm_p7_1,
  135870. _vq_quantmap__44cn1_sm_p7_1,
  135871. 5,
  135872. 5
  135873. };
  135874. static static_codebook _44cn1_sm_p7_1 = {
  135875. 2, 25,
  135876. _vq_lengthlist__44cn1_sm_p7_1,
  135877. 1, -533725184, 1611661312, 3, 0,
  135878. _vq_quantlist__44cn1_sm_p7_1,
  135879. NULL,
  135880. &_vq_auxt__44cn1_sm_p7_1,
  135881. NULL,
  135882. 0
  135883. };
  135884. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  135885. 4,
  135886. 3,
  135887. 5,
  135888. 2,
  135889. 6,
  135890. 1,
  135891. 7,
  135892. 0,
  135893. 8,
  135894. };
  135895. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  135896. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  135897. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  135898. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  135899. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  135900. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  135901. 14,
  135902. };
  135903. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  135904. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  135905. };
  135906. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  135907. 7, 5, 3, 1, 0, 2, 4, 6,
  135908. 8,
  135909. };
  135910. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  135911. _vq_quantthresh__44cn1_sm_p8_0,
  135912. _vq_quantmap__44cn1_sm_p8_0,
  135913. 9,
  135914. 9
  135915. };
  135916. static static_codebook _44cn1_sm_p8_0 = {
  135917. 2, 81,
  135918. _vq_lengthlist__44cn1_sm_p8_0,
  135919. 1, -516186112, 1627103232, 4, 0,
  135920. _vq_quantlist__44cn1_sm_p8_0,
  135921. NULL,
  135922. &_vq_auxt__44cn1_sm_p8_0,
  135923. NULL,
  135924. 0
  135925. };
  135926. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  135927. 6,
  135928. 5,
  135929. 7,
  135930. 4,
  135931. 8,
  135932. 3,
  135933. 9,
  135934. 2,
  135935. 10,
  135936. 1,
  135937. 11,
  135938. 0,
  135939. 12,
  135940. };
  135941. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  135942. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  135943. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  135944. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  135945. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  135946. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  135947. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  135948. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  135949. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  135950. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  135951. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  135952. 17,12,12,11,10,13,11,13,13,
  135953. };
  135954. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  135955. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135956. 42.5, 59.5, 76.5, 93.5,
  135957. };
  135958. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  135959. 11, 9, 7, 5, 3, 1, 0, 2,
  135960. 4, 6, 8, 10, 12,
  135961. };
  135962. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  135963. _vq_quantthresh__44cn1_sm_p8_1,
  135964. _vq_quantmap__44cn1_sm_p8_1,
  135965. 13,
  135966. 13
  135967. };
  135968. static static_codebook _44cn1_sm_p8_1 = {
  135969. 2, 169,
  135970. _vq_lengthlist__44cn1_sm_p8_1,
  135971. 1, -522616832, 1620115456, 4, 0,
  135972. _vq_quantlist__44cn1_sm_p8_1,
  135973. NULL,
  135974. &_vq_auxt__44cn1_sm_p8_1,
  135975. NULL,
  135976. 0
  135977. };
  135978. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  135979. 8,
  135980. 7,
  135981. 9,
  135982. 6,
  135983. 10,
  135984. 5,
  135985. 11,
  135986. 4,
  135987. 12,
  135988. 3,
  135989. 13,
  135990. 2,
  135991. 14,
  135992. 1,
  135993. 15,
  135994. 0,
  135995. 16,
  135996. };
  135997. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  135998. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135999. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  136000. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  136001. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136002. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  136003. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  136004. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  136005. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  136006. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  136007. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  136008. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  136009. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  136010. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  136011. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  136012. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  136013. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  136014. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  136015. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  136016. 9,
  136017. };
  136018. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  136019. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136020. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136021. };
  136022. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  136023. 15, 13, 11, 9, 7, 5, 3, 1,
  136024. 0, 2, 4, 6, 8, 10, 12, 14,
  136025. 16,
  136026. };
  136027. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  136028. _vq_quantthresh__44cn1_sm_p8_2,
  136029. _vq_quantmap__44cn1_sm_p8_2,
  136030. 17,
  136031. 17
  136032. };
  136033. static static_codebook _44cn1_sm_p8_2 = {
  136034. 2, 289,
  136035. _vq_lengthlist__44cn1_sm_p8_2,
  136036. 1, -529530880, 1611661312, 5, 0,
  136037. _vq_quantlist__44cn1_sm_p8_2,
  136038. NULL,
  136039. &_vq_auxt__44cn1_sm_p8_2,
  136040. NULL,
  136041. 0
  136042. };
  136043. static long _huff_lengthlist__44cn1_sm_short[] = {
  136044. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  136045. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  136046. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  136047. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  136048. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  136049. 9,
  136050. };
  136051. static static_codebook _huff_book__44cn1_sm_short = {
  136052. 2, 81,
  136053. _huff_lengthlist__44cn1_sm_short,
  136054. 0, 0, 0, 0, 0,
  136055. NULL,
  136056. NULL,
  136057. NULL,
  136058. NULL,
  136059. 0
  136060. };
  136061. /********* End of inlined file: res_books_stereo.h *********/
  136062. /***** residue backends *********************************************/
  136063. static vorbis_info_residue0 _residue_44_low={
  136064. 0,-1, -1, 9,-1,
  136065. /* 0 1 2 3 4 5 6 7 */
  136066. {0},
  136067. {-1},
  136068. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  136069. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  136070. };
  136071. static vorbis_info_residue0 _residue_44_mid={
  136072. 0,-1, -1, 10,-1,
  136073. /* 0 1 2 3 4 5 6 7 8 */
  136074. {0},
  136075. {-1},
  136076. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  136077. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  136078. };
  136079. static vorbis_info_residue0 _residue_44_high={
  136080. 0,-1, -1, 10,-1,
  136081. /* 0 1 2 3 4 5 6 7 8 */
  136082. {0},
  136083. {-1},
  136084. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  136085. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  136086. };
  136087. static static_bookblock _resbook_44s_n1={
  136088. {
  136089. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  136090. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  136091. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  136092. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  136093. }
  136094. };
  136095. static static_bookblock _resbook_44sm_n1={
  136096. {
  136097. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  136098. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  136099. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  136100. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  136101. }
  136102. };
  136103. static static_bookblock _resbook_44s_0={
  136104. {
  136105. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  136106. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  136107. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  136108. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  136109. }
  136110. };
  136111. static static_bookblock _resbook_44sm_0={
  136112. {
  136113. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  136114. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  136115. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  136116. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  136117. }
  136118. };
  136119. static static_bookblock _resbook_44s_1={
  136120. {
  136121. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  136122. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  136123. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  136124. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  136125. }
  136126. };
  136127. static static_bookblock _resbook_44sm_1={
  136128. {
  136129. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  136130. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  136131. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  136132. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  136133. }
  136134. };
  136135. static static_bookblock _resbook_44s_2={
  136136. {
  136137. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  136138. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  136139. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  136140. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  136141. }
  136142. };
  136143. static static_bookblock _resbook_44s_3={
  136144. {
  136145. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  136146. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  136147. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  136148. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  136149. }
  136150. };
  136151. static static_bookblock _resbook_44s_4={
  136152. {
  136153. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  136154. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  136155. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  136156. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  136157. }
  136158. };
  136159. static static_bookblock _resbook_44s_5={
  136160. {
  136161. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  136162. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  136163. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  136164. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  136165. }
  136166. };
  136167. static static_bookblock _resbook_44s_6={
  136168. {
  136169. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  136170. {0,0,&_44c6_s_p4_0},
  136171. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  136172. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  136173. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  136174. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  136175. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  136176. }
  136177. };
  136178. static static_bookblock _resbook_44s_7={
  136179. {
  136180. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  136181. {0,0,&_44c7_s_p4_0},
  136182. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  136183. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  136184. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  136185. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  136186. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  136187. }
  136188. };
  136189. static static_bookblock _resbook_44s_8={
  136190. {
  136191. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  136192. {0,0,&_44c8_s_p4_0},
  136193. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  136194. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  136195. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  136196. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  136197. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  136198. }
  136199. };
  136200. static static_bookblock _resbook_44s_9={
  136201. {
  136202. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  136203. {0,0,&_44c9_s_p4_0},
  136204. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  136205. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  136206. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  136207. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  136208. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  136209. }
  136210. };
  136211. static vorbis_residue_template _res_44s_n1[]={
  136212. {2,0, &_residue_44_low,
  136213. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  136214. &_resbook_44s_n1,&_resbook_44sm_n1},
  136215. {2,0, &_residue_44_low,
  136216. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  136217. &_resbook_44s_n1,&_resbook_44sm_n1}
  136218. };
  136219. static vorbis_residue_template _res_44s_0[]={
  136220. {2,0, &_residue_44_low,
  136221. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  136222. &_resbook_44s_0,&_resbook_44sm_0},
  136223. {2,0, &_residue_44_low,
  136224. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  136225. &_resbook_44s_0,&_resbook_44sm_0}
  136226. };
  136227. static vorbis_residue_template _res_44s_1[]={
  136228. {2,0, &_residue_44_low,
  136229. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  136230. &_resbook_44s_1,&_resbook_44sm_1},
  136231. {2,0, &_residue_44_low,
  136232. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  136233. &_resbook_44s_1,&_resbook_44sm_1}
  136234. };
  136235. static vorbis_residue_template _res_44s_2[]={
  136236. {2,0, &_residue_44_mid,
  136237. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  136238. &_resbook_44s_2,&_resbook_44s_2},
  136239. {2,0, &_residue_44_mid,
  136240. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  136241. &_resbook_44s_2,&_resbook_44s_2}
  136242. };
  136243. static vorbis_residue_template _res_44s_3[]={
  136244. {2,0, &_residue_44_mid,
  136245. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  136246. &_resbook_44s_3,&_resbook_44s_3},
  136247. {2,0, &_residue_44_mid,
  136248. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  136249. &_resbook_44s_3,&_resbook_44s_3}
  136250. };
  136251. static vorbis_residue_template _res_44s_4[]={
  136252. {2,0, &_residue_44_mid,
  136253. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  136254. &_resbook_44s_4,&_resbook_44s_4},
  136255. {2,0, &_residue_44_mid,
  136256. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  136257. &_resbook_44s_4,&_resbook_44s_4}
  136258. };
  136259. static vorbis_residue_template _res_44s_5[]={
  136260. {2,0, &_residue_44_mid,
  136261. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  136262. &_resbook_44s_5,&_resbook_44s_5},
  136263. {2,0, &_residue_44_mid,
  136264. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  136265. &_resbook_44s_5,&_resbook_44s_5}
  136266. };
  136267. static vorbis_residue_template _res_44s_6[]={
  136268. {2,0, &_residue_44_high,
  136269. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  136270. &_resbook_44s_6,&_resbook_44s_6},
  136271. {2,0, &_residue_44_high,
  136272. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  136273. &_resbook_44s_6,&_resbook_44s_6}
  136274. };
  136275. static vorbis_residue_template _res_44s_7[]={
  136276. {2,0, &_residue_44_high,
  136277. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  136278. &_resbook_44s_7,&_resbook_44s_7},
  136279. {2,0, &_residue_44_high,
  136280. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  136281. &_resbook_44s_7,&_resbook_44s_7}
  136282. };
  136283. static vorbis_residue_template _res_44s_8[]={
  136284. {2,0, &_residue_44_high,
  136285. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  136286. &_resbook_44s_8,&_resbook_44s_8},
  136287. {2,0, &_residue_44_high,
  136288. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  136289. &_resbook_44s_8,&_resbook_44s_8}
  136290. };
  136291. static vorbis_residue_template _res_44s_9[]={
  136292. {2,0, &_residue_44_high,
  136293. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  136294. &_resbook_44s_9,&_resbook_44s_9},
  136295. {2,0, &_residue_44_high,
  136296. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  136297. &_resbook_44s_9,&_resbook_44s_9}
  136298. };
  136299. static vorbis_mapping_template _mapres_template_44_stereo[]={
  136300. { _map_nominal, _res_44s_n1 }, /* -1 */
  136301. { _map_nominal, _res_44s_0 }, /* 0 */
  136302. { _map_nominal, _res_44s_1 }, /* 1 */
  136303. { _map_nominal, _res_44s_2 }, /* 2 */
  136304. { _map_nominal, _res_44s_3 }, /* 3 */
  136305. { _map_nominal, _res_44s_4 }, /* 4 */
  136306. { _map_nominal, _res_44s_5 }, /* 5 */
  136307. { _map_nominal, _res_44s_6 }, /* 6 */
  136308. { _map_nominal, _res_44s_7 }, /* 7 */
  136309. { _map_nominal, _res_44s_8 }, /* 8 */
  136310. { _map_nominal, _res_44s_9 }, /* 9 */
  136311. };
  136312. /********* End of inlined file: residue_44.h *********/
  136313. /********* Start of inlined file: psych_44.h *********/
  136314. /* preecho trigger settings *****************************************/
  136315. static vorbis_info_psy_global _psy_global_44[5]={
  136316. {8, /* lines per eighth octave */
  136317. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  136318. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  136319. -6.f,
  136320. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  136321. },
  136322. {8, /* lines per eighth octave */
  136323. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  136324. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  136325. -6.f,
  136326. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  136327. },
  136328. {8, /* lines per eighth octave */
  136329. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  136330. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  136331. -6.f,
  136332. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  136333. },
  136334. {8, /* lines per eighth octave */
  136335. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  136336. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  136337. -6.f,
  136338. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  136339. },
  136340. {8, /* lines per eighth octave */
  136341. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  136342. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  136343. -6.f,
  136344. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  136345. },
  136346. };
  136347. /* noise compander lookups * low, mid, high quality ****************/
  136348. static compandblock _psy_compand_44[6]={
  136349. /* sub-mode Z short */
  136350. {{
  136351. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  136352. 8, 9,10,11,12,13,14, 15, /* 15dB */
  136353. 16,17,18,19,20,21,22, 23, /* 23dB */
  136354. 24,25,26,27,28,29,30, 31, /* 31dB */
  136355. 32,33,34,35,36,37,38, 39, /* 39dB */
  136356. }},
  136357. /* mode_Z nominal short */
  136358. {{
  136359. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  136360. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  136361. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  136362. 15,16,17,17,17,18,18, 19, /* 31dB */
  136363. 19,19,20,21,22,23,24, 25, /* 39dB */
  136364. }},
  136365. /* mode A short */
  136366. {{
  136367. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  136368. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  136369. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  136370. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  136371. 11,12,13,14,15,16,17, 18, /* 39dB */
  136372. }},
  136373. /* sub-mode Z long */
  136374. {{
  136375. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  136376. 8, 9,10,11,12,13,14, 15, /* 15dB */
  136377. 16,17,18,19,20,21,22, 23, /* 23dB */
  136378. 24,25,26,27,28,29,30, 31, /* 31dB */
  136379. 32,33,34,35,36,37,38, 39, /* 39dB */
  136380. }},
  136381. /* mode_Z nominal long */
  136382. {{
  136383. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  136384. 8, 9,10,11,12,12,13, 13, /* 15dB */
  136385. 13,14,14,14,15,15,15, 15, /* 23dB */
  136386. 16,16,17,17,17,18,18, 19, /* 31dB */
  136387. 19,19,20,21,22,23,24, 25, /* 39dB */
  136388. }},
  136389. /* mode A long */
  136390. {{
  136391. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  136392. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  136393. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  136394. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  136395. 11,12,13,14,15,16,17, 18, /* 39dB */
  136396. }}
  136397. };
  136398. /* tonal masking curve level adjustments *************************/
  136399. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  136400. /* 63 125 250 500 1 2 4 8 16 */
  136401. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  136402. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  136403. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  136404. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  136405. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  136406. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  136407. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  136408. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  136409. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  136410. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  136411. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  136412. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  136413. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  136414. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  136415. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  136416. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  136417. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  136418. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  136419. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  136420. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  136421. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  136422. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  136423. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  136424. };
  136425. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  136426. /* 63 125 250 500 1 2 4 8 16 */
  136427. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  136428. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  136429. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  136430. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  136431. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  136432. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  136433. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  136434. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  136435. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  136436. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  136437. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  136438. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  136439. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  136440. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  136441. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  136442. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  136443. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  136444. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  136445. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  136446. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  136447. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  136448. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  136449. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  136450. };
  136451. /* noise bias (transition block) */
  136452. static noise3 _psy_noisebias_trans[12]={
  136453. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  136454. /* -1 */
  136455. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  136456. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  136457. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  136458. /* 0
  136459. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  136460. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  136461. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  136462. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  136463. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  136464. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  136465. /* 1
  136466. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  136467. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  136468. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  136469. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  136470. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  136471. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  136472. /* 2
  136473. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  136474. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  136475. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  136476. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  136477. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  136478. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  136479. /* 3
  136480. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  136481. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  136482. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  136483. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  136484. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  136485. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  136486. /* 4
  136487. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136488. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  136489. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  136490. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136491. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  136492. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  136493. /* 5
  136494. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136495. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  136496. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  136497. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136498. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  136499. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  136500. /* 6
  136501. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136502. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  136503. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  136504. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136505. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  136506. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  136507. /* 7
  136508. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136509. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  136510. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  136511. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136512. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  136513. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  136514. /* 8
  136515. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  136516. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  136517. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  136518. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  136519. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  136520. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  136521. /* 9
  136522. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  136523. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  136524. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  136525. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  136526. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  136527. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  136528. /* 10 */
  136529. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  136530. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  136531. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  136532. };
  136533. /* noise bias (long block) */
  136534. static noise3 _psy_noisebias_long[12]={
  136535. /*63 125 250 500 1k 2k 4k 8k 16k*/
  136536. /* -1 */
  136537. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  136538. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  136539. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  136540. /* 0 */
  136541. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  136542. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  136543. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  136544. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  136545. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  136546. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  136547. /* 1 */
  136548. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  136549. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  136550. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  136551. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  136552. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  136553. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  136554. /* 2 */
  136555. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  136556. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  136557. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  136558. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  136559. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  136560. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  136561. /* 3 */
  136562. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  136563. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  136564. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  136565. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  136566. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  136567. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  136568. /* 4 */
  136569. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136570. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  136571. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  136572. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136573. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  136574. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  136575. /* 5 */
  136576. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136577. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  136578. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  136579. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136580. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  136581. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  136582. /* 6 */
  136583. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136584. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  136585. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  136586. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136587. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  136588. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  136589. /* 7 */
  136590. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136591. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  136592. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  136593. /* 8 */
  136594. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  136595. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  136596. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  136597. /* 9 */
  136598. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  136599. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  136600. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  136601. /* 10 */
  136602. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  136603. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  136604. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  136605. };
  136606. /* noise bias (impulse block) */
  136607. static noise3 _psy_noisebias_impulse[12]={
  136608. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  136609. /* -1 */
  136610. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  136611. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  136612. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  136613. /* 0 */
  136614. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  136615. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  136616. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  136617. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  136618. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  136619. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  136620. /* 1 */
  136621. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  136622. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  136623. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  136624. /* 2 */
  136625. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  136626. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  136627. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  136628. /* 3 */
  136629. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  136630. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  136631. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  136632. /* 4 */
  136633. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  136634. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  136635. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  136636. /* 5 */
  136637. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  136638. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  136639. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  136640. /* 6
  136641. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  136642. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  136643. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  136644. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  136645. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  136646. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  136647. /* 7 */
  136648. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  136649. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  136650. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  136651. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  136652. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  136653. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  136654. /* 8 */
  136655. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  136656. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  136657. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  136658. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  136659. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  136660. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  136661. /* 9 */
  136662. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  136663. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  136664. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  136665. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  136666. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  136667. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  136668. /* 10 */
  136669. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  136670. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  136671. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  136672. };
  136673. /* noise bias (padding block) */
  136674. static noise3 _psy_noisebias_padding[12]={
  136675. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  136676. /* -1 */
  136677. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  136678. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  136679. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  136680. /* 0 */
  136681. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  136682. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  136683. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  136684. /* 1 */
  136685. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  136686. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  136687. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  136688. /* 2 */
  136689. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  136690. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  136691. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  136692. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  136693. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  136694. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  136695. /* 3 */
  136696. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  136697. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  136698. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  136699. /* 4 */
  136700. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  136701. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  136702. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  136703. /* 5 */
  136704. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  136705. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  136706. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  136707. /* 6 */
  136708. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  136709. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  136710. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  136711. /* 7 */
  136712. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  136713. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  136714. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  136715. /* 8 */
  136716. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  136717. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  136718. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  136719. /* 9 */
  136720. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  136721. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  136722. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  136723. /* 10 */
  136724. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  136725. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  136726. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  136727. };
  136728. static noiseguard _psy_noiseguards_44[4]={
  136729. {3,3,15},
  136730. {3,3,15},
  136731. {10,10,100},
  136732. {10,10,100},
  136733. };
  136734. static int _psy_tone_suppress[12]={
  136735. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  136736. };
  136737. static int _psy_tone_0dB[12]={
  136738. 90,90,95,95,95,95,105,105,105,105,105,105,
  136739. };
  136740. static int _psy_noise_suppress[12]={
  136741. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  136742. };
  136743. static vorbis_info_psy _psy_info_template={
  136744. /* blockflag */
  136745. -1,
  136746. /* ath_adjatt, ath_maxatt */
  136747. -140.,-140.,
  136748. /* tonemask att boost/decay,suppr,curves */
  136749. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  136750. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  136751. 1, -0.f, .5f, .5f, 0,0,0,
  136752. /* noiseoffset*3, noisecompand, max_curve_dB */
  136753. {{-1},{-1},{-1}},{-1},105.f,
  136754. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  136755. 0,0,-1,-1,0.,
  136756. };
  136757. /* ath ****************/
  136758. static int _psy_ath_floater[12]={
  136759. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  136760. };
  136761. static int _psy_ath_abs[12]={
  136762. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  136763. };
  136764. /* stereo setup. These don't map directly to quality level, there's
  136765. an additional indirection as several of the below may be used in a
  136766. single bitmanaged stream
  136767. ****************/
  136768. /* various stereo possibilities */
  136769. /* stereo mode by base quality level */
  136770. static adj_stereo _psy_stereo_modes_44[12]={
  136771. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  136772. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  136773. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  136774. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  136775. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  136776. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  136777. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  136778. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  136779. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  136780. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136781. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  136782. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  136783. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  136784. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  136785. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  136786. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  136787. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  136788. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  136789. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136790. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  136791. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  136792. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  136793. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  136794. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  136795. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  136796. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  136797. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  136798. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136799. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  136800. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  136801. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  136802. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  136803. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136804. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  136805. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136806. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  136807. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  136808. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136809. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  136810. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136811. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  136812. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136813. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136814. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136815. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  136816. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  136817. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136818. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  136819. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136820. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136821. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136822. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  136823. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136824. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136825. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  136826. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136827. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  136828. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136829. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136830. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136831. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136832. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136833. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136834. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  136835. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136836. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  136837. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136838. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136839. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136840. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136841. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136842. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136843. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  136844. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136845. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  136846. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136847. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136848. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  136849. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136850. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  136851. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136852. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136853. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  136854. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136855. };
  136856. /* tone master attenuation by base quality mode and bitrate tweak */
  136857. static att3 _psy_tone_masteratt_44[12]={
  136858. {{ 35, 21, 9}, 0, 0}, /* -1 */
  136859. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  136860. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  136861. {{ 25, 12, 2}, 0, 0}, /* 1 */
  136862. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  136863. {{ 20, 9, -3}, 0, 0}, /* 2 */
  136864. {{ 20, 9, -4}, 0, 0}, /* 3 */
  136865. {{ 20, 9, -4}, 0, 0}, /* 4 */
  136866. {{ 20, 6, -6}, 0, 0}, /* 5 */
  136867. {{ 20, 3, -10}, 0, 0}, /* 6 */
  136868. {{ 18, 1, -14}, 0, 0}, /* 7 */
  136869. {{ 18, 0, -16}, 0, 0}, /* 8 */
  136870. {{ 18, -2, -16}, 0, 0}, /* 9 */
  136871. {{ 12, -2, -20}, 0, 0}, /* 10 */
  136872. };
  136873. /* lowpass by mode **************/
  136874. static double _psy_lowpass_44[12]={
  136875. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  136876. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  136877. };
  136878. /* noise normalization **********/
  136879. static int _noise_start_short_44[11]={
  136880. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  136881. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  136882. };
  136883. static int _noise_start_long_44[11]={
  136884. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  136885. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  136886. };
  136887. static int _noise_part_short_44[11]={
  136888. 8,8,8,8,8,8,8,8,8,8,8
  136889. };
  136890. static int _noise_part_long_44[11]={
  136891. 32,32,32,32,32,32,32,32,32,32,32
  136892. };
  136893. static double _noise_thresh_44[11]={
  136894. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  136895. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  136896. };
  136897. static double _noise_thresh_5only[2]={
  136898. .5,.5,
  136899. };
  136900. /********* End of inlined file: psych_44.h *********/
  136901. static double rate_mapping_44_stereo[12]={
  136902. 22500.,32000.,40000.,48000.,56000.,64000.,
  136903. 80000.,96000.,112000.,128000.,160000.,250001.
  136904. };
  136905. static double quality_mapping_44[12]={
  136906. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  136907. };
  136908. static int blocksize_short_44[11]={
  136909. 512,256,256,256,256,256,256,256,256,256,256
  136910. };
  136911. static int blocksize_long_44[11]={
  136912. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  136913. };
  136914. static double _psy_compand_short_mapping[12]={
  136915. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  136916. };
  136917. static double _psy_compand_long_mapping[12]={
  136918. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  136919. };
  136920. static double _global_mapping_44[12]={
  136921. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  136922. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  136923. };
  136924. static int _floor_short_mapping_44[11]={
  136925. 1,0,0,2,2,4,5,5,5,5,5
  136926. };
  136927. static int _floor_long_mapping_44[11]={
  136928. 8,7,7,7,7,7,7,7,7,7,7
  136929. };
  136930. ve_setup_data_template ve_setup_44_stereo={
  136931. 11,
  136932. rate_mapping_44_stereo,
  136933. quality_mapping_44,
  136934. 2,
  136935. 40000,
  136936. 50000,
  136937. blocksize_short_44,
  136938. blocksize_long_44,
  136939. _psy_tone_masteratt_44,
  136940. _psy_tone_0dB,
  136941. _psy_tone_suppress,
  136942. _vp_tonemask_adj_otherblock,
  136943. _vp_tonemask_adj_longblock,
  136944. _vp_tonemask_adj_otherblock,
  136945. _psy_noiseguards_44,
  136946. _psy_noisebias_impulse,
  136947. _psy_noisebias_padding,
  136948. _psy_noisebias_trans,
  136949. _psy_noisebias_long,
  136950. _psy_noise_suppress,
  136951. _psy_compand_44,
  136952. _psy_compand_short_mapping,
  136953. _psy_compand_long_mapping,
  136954. {_noise_start_short_44,_noise_start_long_44},
  136955. {_noise_part_short_44,_noise_part_long_44},
  136956. _noise_thresh_44,
  136957. _psy_ath_floater,
  136958. _psy_ath_abs,
  136959. _psy_lowpass_44,
  136960. _psy_global_44,
  136961. _global_mapping_44,
  136962. _psy_stereo_modes_44,
  136963. _floor_books,
  136964. _floor,
  136965. _floor_short_mapping_44,
  136966. _floor_long_mapping_44,
  136967. _mapres_template_44_stereo
  136968. };
  136969. /********* End of inlined file: setup_44.h *********/
  136970. /********* Start of inlined file: setup_44u.h *********/
  136971. /********* Start of inlined file: residue_44u.h *********/
  136972. /********* Start of inlined file: res_books_uncoupled.h *********/
  136973. static long _vq_quantlist__16u0__p1_0[] = {
  136974. 1,
  136975. 0,
  136976. 2,
  136977. };
  136978. static long _vq_lengthlist__16u0__p1_0[] = {
  136979. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  136980. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  136981. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  136982. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  136983. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  136984. 12,
  136985. };
  136986. static float _vq_quantthresh__16u0__p1_0[] = {
  136987. -0.5, 0.5,
  136988. };
  136989. static long _vq_quantmap__16u0__p1_0[] = {
  136990. 1, 0, 2,
  136991. };
  136992. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  136993. _vq_quantthresh__16u0__p1_0,
  136994. _vq_quantmap__16u0__p1_0,
  136995. 3,
  136996. 3
  136997. };
  136998. static static_codebook _16u0__p1_0 = {
  136999. 4, 81,
  137000. _vq_lengthlist__16u0__p1_0,
  137001. 1, -535822336, 1611661312, 2, 0,
  137002. _vq_quantlist__16u0__p1_0,
  137003. NULL,
  137004. &_vq_auxt__16u0__p1_0,
  137005. NULL,
  137006. 0
  137007. };
  137008. static long _vq_quantlist__16u0__p2_0[] = {
  137009. 1,
  137010. 0,
  137011. 2,
  137012. };
  137013. static long _vq_lengthlist__16u0__p2_0[] = {
  137014. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  137015. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  137016. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  137017. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  137018. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  137019. 8,
  137020. };
  137021. static float _vq_quantthresh__16u0__p2_0[] = {
  137022. -0.5, 0.5,
  137023. };
  137024. static long _vq_quantmap__16u0__p2_0[] = {
  137025. 1, 0, 2,
  137026. };
  137027. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  137028. _vq_quantthresh__16u0__p2_0,
  137029. _vq_quantmap__16u0__p2_0,
  137030. 3,
  137031. 3
  137032. };
  137033. static static_codebook _16u0__p2_0 = {
  137034. 4, 81,
  137035. _vq_lengthlist__16u0__p2_0,
  137036. 1, -535822336, 1611661312, 2, 0,
  137037. _vq_quantlist__16u0__p2_0,
  137038. NULL,
  137039. &_vq_auxt__16u0__p2_0,
  137040. NULL,
  137041. 0
  137042. };
  137043. static long _vq_quantlist__16u0__p3_0[] = {
  137044. 2,
  137045. 1,
  137046. 3,
  137047. 0,
  137048. 4,
  137049. };
  137050. static long _vq_lengthlist__16u0__p3_0[] = {
  137051. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  137052. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  137053. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  137054. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  137055. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  137056. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  137057. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  137058. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  137059. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  137060. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  137061. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  137062. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  137063. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  137064. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  137065. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  137066. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  137067. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  137068. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  137069. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  137070. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  137071. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  137072. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  137073. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  137074. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  137075. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  137076. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  137077. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  137078. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  137079. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  137080. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  137081. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  137082. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  137083. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  137084. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  137085. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  137086. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  137087. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  137088. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  137089. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  137090. 18,
  137091. };
  137092. static float _vq_quantthresh__16u0__p3_0[] = {
  137093. -1.5, -0.5, 0.5, 1.5,
  137094. };
  137095. static long _vq_quantmap__16u0__p3_0[] = {
  137096. 3, 1, 0, 2, 4,
  137097. };
  137098. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  137099. _vq_quantthresh__16u0__p3_0,
  137100. _vq_quantmap__16u0__p3_0,
  137101. 5,
  137102. 5
  137103. };
  137104. static static_codebook _16u0__p3_0 = {
  137105. 4, 625,
  137106. _vq_lengthlist__16u0__p3_0,
  137107. 1, -533725184, 1611661312, 3, 0,
  137108. _vq_quantlist__16u0__p3_0,
  137109. NULL,
  137110. &_vq_auxt__16u0__p3_0,
  137111. NULL,
  137112. 0
  137113. };
  137114. static long _vq_quantlist__16u0__p4_0[] = {
  137115. 2,
  137116. 1,
  137117. 3,
  137118. 0,
  137119. 4,
  137120. };
  137121. static long _vq_lengthlist__16u0__p4_0[] = {
  137122. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  137123. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  137124. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  137125. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  137126. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  137127. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  137128. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  137129. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  137130. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  137131. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  137132. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  137133. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  137134. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  137135. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  137136. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  137137. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  137138. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  137139. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  137140. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  137141. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  137142. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  137143. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  137144. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  137145. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  137146. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  137147. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  137148. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  137149. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  137150. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  137151. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  137152. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  137153. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  137154. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  137155. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  137156. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  137157. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  137158. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  137159. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  137160. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  137161. 11,
  137162. };
  137163. static float _vq_quantthresh__16u0__p4_0[] = {
  137164. -1.5, -0.5, 0.5, 1.5,
  137165. };
  137166. static long _vq_quantmap__16u0__p4_0[] = {
  137167. 3, 1, 0, 2, 4,
  137168. };
  137169. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  137170. _vq_quantthresh__16u0__p4_0,
  137171. _vq_quantmap__16u0__p4_0,
  137172. 5,
  137173. 5
  137174. };
  137175. static static_codebook _16u0__p4_0 = {
  137176. 4, 625,
  137177. _vq_lengthlist__16u0__p4_0,
  137178. 1, -533725184, 1611661312, 3, 0,
  137179. _vq_quantlist__16u0__p4_0,
  137180. NULL,
  137181. &_vq_auxt__16u0__p4_0,
  137182. NULL,
  137183. 0
  137184. };
  137185. static long _vq_quantlist__16u0__p5_0[] = {
  137186. 4,
  137187. 3,
  137188. 5,
  137189. 2,
  137190. 6,
  137191. 1,
  137192. 7,
  137193. 0,
  137194. 8,
  137195. };
  137196. static long _vq_lengthlist__16u0__p5_0[] = {
  137197. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  137198. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  137199. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  137200. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  137201. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  137202. 12,
  137203. };
  137204. static float _vq_quantthresh__16u0__p5_0[] = {
  137205. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137206. };
  137207. static long _vq_quantmap__16u0__p5_0[] = {
  137208. 7, 5, 3, 1, 0, 2, 4, 6,
  137209. 8,
  137210. };
  137211. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  137212. _vq_quantthresh__16u0__p5_0,
  137213. _vq_quantmap__16u0__p5_0,
  137214. 9,
  137215. 9
  137216. };
  137217. static static_codebook _16u0__p5_0 = {
  137218. 2, 81,
  137219. _vq_lengthlist__16u0__p5_0,
  137220. 1, -531628032, 1611661312, 4, 0,
  137221. _vq_quantlist__16u0__p5_0,
  137222. NULL,
  137223. &_vq_auxt__16u0__p5_0,
  137224. NULL,
  137225. 0
  137226. };
  137227. static long _vq_quantlist__16u0__p6_0[] = {
  137228. 6,
  137229. 5,
  137230. 7,
  137231. 4,
  137232. 8,
  137233. 3,
  137234. 9,
  137235. 2,
  137236. 10,
  137237. 1,
  137238. 11,
  137239. 0,
  137240. 12,
  137241. };
  137242. static long _vq_lengthlist__16u0__p6_0[] = {
  137243. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  137244. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  137245. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  137246. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  137247. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  137248. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  137249. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  137250. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  137251. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  137252. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  137253. 18, 0,19, 0, 0, 0, 0, 0, 0,
  137254. };
  137255. static float _vq_quantthresh__16u0__p6_0[] = {
  137256. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137257. 12.5, 17.5, 22.5, 27.5,
  137258. };
  137259. static long _vq_quantmap__16u0__p6_0[] = {
  137260. 11, 9, 7, 5, 3, 1, 0, 2,
  137261. 4, 6, 8, 10, 12,
  137262. };
  137263. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  137264. _vq_quantthresh__16u0__p6_0,
  137265. _vq_quantmap__16u0__p6_0,
  137266. 13,
  137267. 13
  137268. };
  137269. static static_codebook _16u0__p6_0 = {
  137270. 2, 169,
  137271. _vq_lengthlist__16u0__p6_0,
  137272. 1, -526516224, 1616117760, 4, 0,
  137273. _vq_quantlist__16u0__p6_0,
  137274. NULL,
  137275. &_vq_auxt__16u0__p6_0,
  137276. NULL,
  137277. 0
  137278. };
  137279. static long _vq_quantlist__16u0__p6_1[] = {
  137280. 2,
  137281. 1,
  137282. 3,
  137283. 0,
  137284. 4,
  137285. };
  137286. static long _vq_lengthlist__16u0__p6_1[] = {
  137287. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  137288. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  137289. };
  137290. static float _vq_quantthresh__16u0__p6_1[] = {
  137291. -1.5, -0.5, 0.5, 1.5,
  137292. };
  137293. static long _vq_quantmap__16u0__p6_1[] = {
  137294. 3, 1, 0, 2, 4,
  137295. };
  137296. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  137297. _vq_quantthresh__16u0__p6_1,
  137298. _vq_quantmap__16u0__p6_1,
  137299. 5,
  137300. 5
  137301. };
  137302. static static_codebook _16u0__p6_1 = {
  137303. 2, 25,
  137304. _vq_lengthlist__16u0__p6_1,
  137305. 1, -533725184, 1611661312, 3, 0,
  137306. _vq_quantlist__16u0__p6_1,
  137307. NULL,
  137308. &_vq_auxt__16u0__p6_1,
  137309. NULL,
  137310. 0
  137311. };
  137312. static long _vq_quantlist__16u0__p7_0[] = {
  137313. 1,
  137314. 0,
  137315. 2,
  137316. };
  137317. static long _vq_lengthlist__16u0__p7_0[] = {
  137318. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  137319. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  137320. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  137321. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  137322. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  137323. 7,
  137324. };
  137325. static float _vq_quantthresh__16u0__p7_0[] = {
  137326. -157.5, 157.5,
  137327. };
  137328. static long _vq_quantmap__16u0__p7_0[] = {
  137329. 1, 0, 2,
  137330. };
  137331. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  137332. _vq_quantthresh__16u0__p7_0,
  137333. _vq_quantmap__16u0__p7_0,
  137334. 3,
  137335. 3
  137336. };
  137337. static static_codebook _16u0__p7_0 = {
  137338. 4, 81,
  137339. _vq_lengthlist__16u0__p7_0,
  137340. 1, -518803456, 1628680192, 2, 0,
  137341. _vq_quantlist__16u0__p7_0,
  137342. NULL,
  137343. &_vq_auxt__16u0__p7_0,
  137344. NULL,
  137345. 0
  137346. };
  137347. static long _vq_quantlist__16u0__p7_1[] = {
  137348. 7,
  137349. 6,
  137350. 8,
  137351. 5,
  137352. 9,
  137353. 4,
  137354. 10,
  137355. 3,
  137356. 11,
  137357. 2,
  137358. 12,
  137359. 1,
  137360. 13,
  137361. 0,
  137362. 14,
  137363. };
  137364. static long _vq_lengthlist__16u0__p7_1[] = {
  137365. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  137366. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  137367. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  137368. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  137369. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  137370. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  137371. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137372. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137373. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137374. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137375. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137376. 10,10,10,10,10,10,10,10,10,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,10,10,10,10,10,10,10,10,
  137379. 10,
  137380. };
  137381. static float _vq_quantthresh__16u0__p7_1[] = {
  137382. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  137383. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  137384. };
  137385. static long _vq_quantmap__16u0__p7_1[] = {
  137386. 13, 11, 9, 7, 5, 3, 1, 0,
  137387. 2, 4, 6, 8, 10, 12, 14,
  137388. };
  137389. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  137390. _vq_quantthresh__16u0__p7_1,
  137391. _vq_quantmap__16u0__p7_1,
  137392. 15,
  137393. 15
  137394. };
  137395. static static_codebook _16u0__p7_1 = {
  137396. 2, 225,
  137397. _vq_lengthlist__16u0__p7_1,
  137398. 1, -520986624, 1620377600, 4, 0,
  137399. _vq_quantlist__16u0__p7_1,
  137400. NULL,
  137401. &_vq_auxt__16u0__p7_1,
  137402. NULL,
  137403. 0
  137404. };
  137405. static long _vq_quantlist__16u0__p7_2[] = {
  137406. 10,
  137407. 9,
  137408. 11,
  137409. 8,
  137410. 12,
  137411. 7,
  137412. 13,
  137413. 6,
  137414. 14,
  137415. 5,
  137416. 15,
  137417. 4,
  137418. 16,
  137419. 3,
  137420. 17,
  137421. 2,
  137422. 18,
  137423. 1,
  137424. 19,
  137425. 0,
  137426. 20,
  137427. };
  137428. static long _vq_lengthlist__16u0__p7_2[] = {
  137429. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  137430. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  137431. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  137432. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  137433. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  137434. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  137435. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  137436. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  137437. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  137438. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  137439. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  137440. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  137441. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  137442. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  137443. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  137444. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  137445. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  137446. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  137447. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  137448. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  137449. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  137450. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  137451. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  137452. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  137453. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  137454. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  137455. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  137456. 10,10,12,11,10,11,11,11,10,
  137457. };
  137458. static float _vq_quantthresh__16u0__p7_2[] = {
  137459. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  137460. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  137461. 6.5, 7.5, 8.5, 9.5,
  137462. };
  137463. static long _vq_quantmap__16u0__p7_2[] = {
  137464. 19, 17, 15, 13, 11, 9, 7, 5,
  137465. 3, 1, 0, 2, 4, 6, 8, 10,
  137466. 12, 14, 16, 18, 20,
  137467. };
  137468. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  137469. _vq_quantthresh__16u0__p7_2,
  137470. _vq_quantmap__16u0__p7_2,
  137471. 21,
  137472. 21
  137473. };
  137474. static static_codebook _16u0__p7_2 = {
  137475. 2, 441,
  137476. _vq_lengthlist__16u0__p7_2,
  137477. 1, -529268736, 1611661312, 5, 0,
  137478. _vq_quantlist__16u0__p7_2,
  137479. NULL,
  137480. &_vq_auxt__16u0__p7_2,
  137481. NULL,
  137482. 0
  137483. };
  137484. static long _huff_lengthlist__16u0__single[] = {
  137485. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  137486. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  137487. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  137488. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  137489. };
  137490. static static_codebook _huff_book__16u0__single = {
  137491. 2, 64,
  137492. _huff_lengthlist__16u0__single,
  137493. 0, 0, 0, 0, 0,
  137494. NULL,
  137495. NULL,
  137496. NULL,
  137497. NULL,
  137498. 0
  137499. };
  137500. static long _huff_lengthlist__16u1__long[] = {
  137501. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  137502. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  137503. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  137504. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  137505. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  137506. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  137507. 16,13,16,18,
  137508. };
  137509. static static_codebook _huff_book__16u1__long = {
  137510. 2, 100,
  137511. _huff_lengthlist__16u1__long,
  137512. 0, 0, 0, 0, 0,
  137513. NULL,
  137514. NULL,
  137515. NULL,
  137516. NULL,
  137517. 0
  137518. };
  137519. static long _vq_quantlist__16u1__p1_0[] = {
  137520. 1,
  137521. 0,
  137522. 2,
  137523. };
  137524. static long _vq_lengthlist__16u1__p1_0[] = {
  137525. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  137526. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  137527. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  137528. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  137529. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  137530. 11,
  137531. };
  137532. static float _vq_quantthresh__16u1__p1_0[] = {
  137533. -0.5, 0.5,
  137534. };
  137535. static long _vq_quantmap__16u1__p1_0[] = {
  137536. 1, 0, 2,
  137537. };
  137538. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  137539. _vq_quantthresh__16u1__p1_0,
  137540. _vq_quantmap__16u1__p1_0,
  137541. 3,
  137542. 3
  137543. };
  137544. static static_codebook _16u1__p1_0 = {
  137545. 4, 81,
  137546. _vq_lengthlist__16u1__p1_0,
  137547. 1, -535822336, 1611661312, 2, 0,
  137548. _vq_quantlist__16u1__p1_0,
  137549. NULL,
  137550. &_vq_auxt__16u1__p1_0,
  137551. NULL,
  137552. 0
  137553. };
  137554. static long _vq_quantlist__16u1__p2_0[] = {
  137555. 1,
  137556. 0,
  137557. 2,
  137558. };
  137559. static long _vq_lengthlist__16u1__p2_0[] = {
  137560. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  137561. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  137562. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  137563. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  137564. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  137565. 8,
  137566. };
  137567. static float _vq_quantthresh__16u1__p2_0[] = {
  137568. -0.5, 0.5,
  137569. };
  137570. static long _vq_quantmap__16u1__p2_0[] = {
  137571. 1, 0, 2,
  137572. };
  137573. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  137574. _vq_quantthresh__16u1__p2_0,
  137575. _vq_quantmap__16u1__p2_0,
  137576. 3,
  137577. 3
  137578. };
  137579. static static_codebook _16u1__p2_0 = {
  137580. 4, 81,
  137581. _vq_lengthlist__16u1__p2_0,
  137582. 1, -535822336, 1611661312, 2, 0,
  137583. _vq_quantlist__16u1__p2_0,
  137584. NULL,
  137585. &_vq_auxt__16u1__p2_0,
  137586. NULL,
  137587. 0
  137588. };
  137589. static long _vq_quantlist__16u1__p3_0[] = {
  137590. 2,
  137591. 1,
  137592. 3,
  137593. 0,
  137594. 4,
  137595. };
  137596. static long _vq_lengthlist__16u1__p3_0[] = {
  137597. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  137598. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  137599. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  137600. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  137601. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  137602. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  137603. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  137604. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  137605. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  137606. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  137607. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  137608. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  137609. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  137610. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  137611. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  137612. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  137613. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  137614. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  137615. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  137616. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  137617. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  137618. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  137619. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  137620. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  137621. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  137622. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  137623. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  137624. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  137625. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  137626. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  137627. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  137628. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  137629. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  137630. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  137631. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  137632. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  137633. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  137634. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  137635. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  137636. 16,
  137637. };
  137638. static float _vq_quantthresh__16u1__p3_0[] = {
  137639. -1.5, -0.5, 0.5, 1.5,
  137640. };
  137641. static long _vq_quantmap__16u1__p3_0[] = {
  137642. 3, 1, 0, 2, 4,
  137643. };
  137644. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  137645. _vq_quantthresh__16u1__p3_0,
  137646. _vq_quantmap__16u1__p3_0,
  137647. 5,
  137648. 5
  137649. };
  137650. static static_codebook _16u1__p3_0 = {
  137651. 4, 625,
  137652. _vq_lengthlist__16u1__p3_0,
  137653. 1, -533725184, 1611661312, 3, 0,
  137654. _vq_quantlist__16u1__p3_0,
  137655. NULL,
  137656. &_vq_auxt__16u1__p3_0,
  137657. NULL,
  137658. 0
  137659. };
  137660. static long _vq_quantlist__16u1__p4_0[] = {
  137661. 2,
  137662. 1,
  137663. 3,
  137664. 0,
  137665. 4,
  137666. };
  137667. static long _vq_lengthlist__16u1__p4_0[] = {
  137668. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  137669. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  137670. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  137671. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  137672. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  137673. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  137674. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  137675. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  137676. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  137677. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  137678. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  137679. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  137680. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  137681. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  137682. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  137683. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  137684. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  137685. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  137686. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  137687. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  137688. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  137689. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  137690. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  137691. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  137692. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  137693. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  137694. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  137695. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  137696. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  137697. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  137698. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  137699. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  137700. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  137701. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  137702. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  137703. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  137704. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  137705. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  137706. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  137707. 11,
  137708. };
  137709. static float _vq_quantthresh__16u1__p4_0[] = {
  137710. -1.5, -0.5, 0.5, 1.5,
  137711. };
  137712. static long _vq_quantmap__16u1__p4_0[] = {
  137713. 3, 1, 0, 2, 4,
  137714. };
  137715. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  137716. _vq_quantthresh__16u1__p4_0,
  137717. _vq_quantmap__16u1__p4_0,
  137718. 5,
  137719. 5
  137720. };
  137721. static static_codebook _16u1__p4_0 = {
  137722. 4, 625,
  137723. _vq_lengthlist__16u1__p4_0,
  137724. 1, -533725184, 1611661312, 3, 0,
  137725. _vq_quantlist__16u1__p4_0,
  137726. NULL,
  137727. &_vq_auxt__16u1__p4_0,
  137728. NULL,
  137729. 0
  137730. };
  137731. static long _vq_quantlist__16u1__p5_0[] = {
  137732. 4,
  137733. 3,
  137734. 5,
  137735. 2,
  137736. 6,
  137737. 1,
  137738. 7,
  137739. 0,
  137740. 8,
  137741. };
  137742. static long _vq_lengthlist__16u1__p5_0[] = {
  137743. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  137744. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  137745. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  137746. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  137747. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  137748. 13,
  137749. };
  137750. static float _vq_quantthresh__16u1__p5_0[] = {
  137751. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137752. };
  137753. static long _vq_quantmap__16u1__p5_0[] = {
  137754. 7, 5, 3, 1, 0, 2, 4, 6,
  137755. 8,
  137756. };
  137757. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  137758. _vq_quantthresh__16u1__p5_0,
  137759. _vq_quantmap__16u1__p5_0,
  137760. 9,
  137761. 9
  137762. };
  137763. static static_codebook _16u1__p5_0 = {
  137764. 2, 81,
  137765. _vq_lengthlist__16u1__p5_0,
  137766. 1, -531628032, 1611661312, 4, 0,
  137767. _vq_quantlist__16u1__p5_0,
  137768. NULL,
  137769. &_vq_auxt__16u1__p5_0,
  137770. NULL,
  137771. 0
  137772. };
  137773. static long _vq_quantlist__16u1__p6_0[] = {
  137774. 4,
  137775. 3,
  137776. 5,
  137777. 2,
  137778. 6,
  137779. 1,
  137780. 7,
  137781. 0,
  137782. 8,
  137783. };
  137784. static long _vq_lengthlist__16u1__p6_0[] = {
  137785. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  137786. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  137787. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  137788. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  137789. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  137790. 11,
  137791. };
  137792. static float _vq_quantthresh__16u1__p6_0[] = {
  137793. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137794. };
  137795. static long _vq_quantmap__16u1__p6_0[] = {
  137796. 7, 5, 3, 1, 0, 2, 4, 6,
  137797. 8,
  137798. };
  137799. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  137800. _vq_quantthresh__16u1__p6_0,
  137801. _vq_quantmap__16u1__p6_0,
  137802. 9,
  137803. 9
  137804. };
  137805. static static_codebook _16u1__p6_0 = {
  137806. 2, 81,
  137807. _vq_lengthlist__16u1__p6_0,
  137808. 1, -531628032, 1611661312, 4, 0,
  137809. _vq_quantlist__16u1__p6_0,
  137810. NULL,
  137811. &_vq_auxt__16u1__p6_0,
  137812. NULL,
  137813. 0
  137814. };
  137815. static long _vq_quantlist__16u1__p7_0[] = {
  137816. 1,
  137817. 0,
  137818. 2,
  137819. };
  137820. static long _vq_lengthlist__16u1__p7_0[] = {
  137821. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  137822. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  137823. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  137824. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  137825. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  137826. 13,
  137827. };
  137828. static float _vq_quantthresh__16u1__p7_0[] = {
  137829. -5.5, 5.5,
  137830. };
  137831. static long _vq_quantmap__16u1__p7_0[] = {
  137832. 1, 0, 2,
  137833. };
  137834. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  137835. _vq_quantthresh__16u1__p7_0,
  137836. _vq_quantmap__16u1__p7_0,
  137837. 3,
  137838. 3
  137839. };
  137840. static static_codebook _16u1__p7_0 = {
  137841. 4, 81,
  137842. _vq_lengthlist__16u1__p7_0,
  137843. 1, -529137664, 1618345984, 2, 0,
  137844. _vq_quantlist__16u1__p7_0,
  137845. NULL,
  137846. &_vq_auxt__16u1__p7_0,
  137847. NULL,
  137848. 0
  137849. };
  137850. static long _vq_quantlist__16u1__p7_1[] = {
  137851. 5,
  137852. 4,
  137853. 6,
  137854. 3,
  137855. 7,
  137856. 2,
  137857. 8,
  137858. 1,
  137859. 9,
  137860. 0,
  137861. 10,
  137862. };
  137863. static long _vq_lengthlist__16u1__p7_1[] = {
  137864. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  137865. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  137866. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  137867. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  137868. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  137869. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  137870. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  137871. 8, 9, 9,10,10,10,10,10,10,
  137872. };
  137873. static float _vq_quantthresh__16u1__p7_1[] = {
  137874. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137875. 3.5, 4.5,
  137876. };
  137877. static long _vq_quantmap__16u1__p7_1[] = {
  137878. 9, 7, 5, 3, 1, 0, 2, 4,
  137879. 6, 8, 10,
  137880. };
  137881. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  137882. _vq_quantthresh__16u1__p7_1,
  137883. _vq_quantmap__16u1__p7_1,
  137884. 11,
  137885. 11
  137886. };
  137887. static static_codebook _16u1__p7_1 = {
  137888. 2, 121,
  137889. _vq_lengthlist__16u1__p7_1,
  137890. 1, -531365888, 1611661312, 4, 0,
  137891. _vq_quantlist__16u1__p7_1,
  137892. NULL,
  137893. &_vq_auxt__16u1__p7_1,
  137894. NULL,
  137895. 0
  137896. };
  137897. static long _vq_quantlist__16u1__p8_0[] = {
  137898. 5,
  137899. 4,
  137900. 6,
  137901. 3,
  137902. 7,
  137903. 2,
  137904. 8,
  137905. 1,
  137906. 9,
  137907. 0,
  137908. 10,
  137909. };
  137910. static long _vq_lengthlist__16u1__p8_0[] = {
  137911. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  137912. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  137913. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  137914. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  137915. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  137916. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  137917. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  137918. 13,14,14,15,15,16,16,15,16,
  137919. };
  137920. static float _vq_quantthresh__16u1__p8_0[] = {
  137921. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  137922. 38.5, 49.5,
  137923. };
  137924. static long _vq_quantmap__16u1__p8_0[] = {
  137925. 9, 7, 5, 3, 1, 0, 2, 4,
  137926. 6, 8, 10,
  137927. };
  137928. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  137929. _vq_quantthresh__16u1__p8_0,
  137930. _vq_quantmap__16u1__p8_0,
  137931. 11,
  137932. 11
  137933. };
  137934. static static_codebook _16u1__p8_0 = {
  137935. 2, 121,
  137936. _vq_lengthlist__16u1__p8_0,
  137937. 1, -524582912, 1618345984, 4, 0,
  137938. _vq_quantlist__16u1__p8_0,
  137939. NULL,
  137940. &_vq_auxt__16u1__p8_0,
  137941. NULL,
  137942. 0
  137943. };
  137944. static long _vq_quantlist__16u1__p8_1[] = {
  137945. 5,
  137946. 4,
  137947. 6,
  137948. 3,
  137949. 7,
  137950. 2,
  137951. 8,
  137952. 1,
  137953. 9,
  137954. 0,
  137955. 10,
  137956. };
  137957. static long _vq_lengthlist__16u1__p8_1[] = {
  137958. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  137959. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  137960. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  137961. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  137962. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  137963. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  137964. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  137965. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  137966. };
  137967. static float _vq_quantthresh__16u1__p8_1[] = {
  137968. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137969. 3.5, 4.5,
  137970. };
  137971. static long _vq_quantmap__16u1__p8_1[] = {
  137972. 9, 7, 5, 3, 1, 0, 2, 4,
  137973. 6, 8, 10,
  137974. };
  137975. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  137976. _vq_quantthresh__16u1__p8_1,
  137977. _vq_quantmap__16u1__p8_1,
  137978. 11,
  137979. 11
  137980. };
  137981. static static_codebook _16u1__p8_1 = {
  137982. 2, 121,
  137983. _vq_lengthlist__16u1__p8_1,
  137984. 1, -531365888, 1611661312, 4, 0,
  137985. _vq_quantlist__16u1__p8_1,
  137986. NULL,
  137987. &_vq_auxt__16u1__p8_1,
  137988. NULL,
  137989. 0
  137990. };
  137991. static long _vq_quantlist__16u1__p9_0[] = {
  137992. 7,
  137993. 6,
  137994. 8,
  137995. 5,
  137996. 9,
  137997. 4,
  137998. 10,
  137999. 3,
  138000. 11,
  138001. 2,
  138002. 12,
  138003. 1,
  138004. 13,
  138005. 0,
  138006. 14,
  138007. };
  138008. static long _vq_lengthlist__16u1__p9_0[] = {
  138009. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138010. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138011. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138012. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138013. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138014. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138015. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138016. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138017. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138018. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138019. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138020. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138021. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138022. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138023. 8,
  138024. };
  138025. static float _vq_quantthresh__16u1__p9_0[] = {
  138026. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  138027. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  138028. };
  138029. static long _vq_quantmap__16u1__p9_0[] = {
  138030. 13, 11, 9, 7, 5, 3, 1, 0,
  138031. 2, 4, 6, 8, 10, 12, 14,
  138032. };
  138033. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  138034. _vq_quantthresh__16u1__p9_0,
  138035. _vq_quantmap__16u1__p9_0,
  138036. 15,
  138037. 15
  138038. };
  138039. static static_codebook _16u1__p9_0 = {
  138040. 2, 225,
  138041. _vq_lengthlist__16u1__p9_0,
  138042. 1, -514071552, 1627381760, 4, 0,
  138043. _vq_quantlist__16u1__p9_0,
  138044. NULL,
  138045. &_vq_auxt__16u1__p9_0,
  138046. NULL,
  138047. 0
  138048. };
  138049. static long _vq_quantlist__16u1__p9_1[] = {
  138050. 7,
  138051. 6,
  138052. 8,
  138053. 5,
  138054. 9,
  138055. 4,
  138056. 10,
  138057. 3,
  138058. 11,
  138059. 2,
  138060. 12,
  138061. 1,
  138062. 13,
  138063. 0,
  138064. 14,
  138065. };
  138066. static long _vq_lengthlist__16u1__p9_1[] = {
  138067. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  138068. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  138069. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  138070. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  138071. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  138072. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  138073. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  138074. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  138075. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  138076. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138077. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  138078. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138079. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138080. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138081. 9,
  138082. };
  138083. static float _vq_quantthresh__16u1__p9_1[] = {
  138084. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  138085. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  138086. };
  138087. static long _vq_quantmap__16u1__p9_1[] = {
  138088. 13, 11, 9, 7, 5, 3, 1, 0,
  138089. 2, 4, 6, 8, 10, 12, 14,
  138090. };
  138091. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  138092. _vq_quantthresh__16u1__p9_1,
  138093. _vq_quantmap__16u1__p9_1,
  138094. 15,
  138095. 15
  138096. };
  138097. static static_codebook _16u1__p9_1 = {
  138098. 2, 225,
  138099. _vq_lengthlist__16u1__p9_1,
  138100. 1, -522338304, 1620115456, 4, 0,
  138101. _vq_quantlist__16u1__p9_1,
  138102. NULL,
  138103. &_vq_auxt__16u1__p9_1,
  138104. NULL,
  138105. 0
  138106. };
  138107. static long _vq_quantlist__16u1__p9_2[] = {
  138108. 8,
  138109. 7,
  138110. 9,
  138111. 6,
  138112. 10,
  138113. 5,
  138114. 11,
  138115. 4,
  138116. 12,
  138117. 3,
  138118. 13,
  138119. 2,
  138120. 14,
  138121. 1,
  138122. 15,
  138123. 0,
  138124. 16,
  138125. };
  138126. static long _vq_lengthlist__16u1__p9_2[] = {
  138127. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  138128. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  138129. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  138130. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  138131. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  138132. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  138133. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  138134. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  138135. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  138136. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  138137. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  138138. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  138139. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  138140. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  138141. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  138142. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  138143. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  138144. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  138145. 10,
  138146. };
  138147. static float _vq_quantthresh__16u1__p9_2[] = {
  138148. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138149. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138150. };
  138151. static long _vq_quantmap__16u1__p9_2[] = {
  138152. 15, 13, 11, 9, 7, 5, 3, 1,
  138153. 0, 2, 4, 6, 8, 10, 12, 14,
  138154. 16,
  138155. };
  138156. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  138157. _vq_quantthresh__16u1__p9_2,
  138158. _vq_quantmap__16u1__p9_2,
  138159. 17,
  138160. 17
  138161. };
  138162. static static_codebook _16u1__p9_2 = {
  138163. 2, 289,
  138164. _vq_lengthlist__16u1__p9_2,
  138165. 1, -529530880, 1611661312, 5, 0,
  138166. _vq_quantlist__16u1__p9_2,
  138167. NULL,
  138168. &_vq_auxt__16u1__p9_2,
  138169. NULL,
  138170. 0
  138171. };
  138172. static long _huff_lengthlist__16u1__short[] = {
  138173. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  138174. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  138175. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  138176. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  138177. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  138178. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  138179. 16,16,16,16,
  138180. };
  138181. static static_codebook _huff_book__16u1__short = {
  138182. 2, 100,
  138183. _huff_lengthlist__16u1__short,
  138184. 0, 0, 0, 0, 0,
  138185. NULL,
  138186. NULL,
  138187. NULL,
  138188. NULL,
  138189. 0
  138190. };
  138191. static long _huff_lengthlist__16u2__long[] = {
  138192. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  138193. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  138194. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  138195. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  138196. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  138197. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  138198. 13,14,18,18,
  138199. };
  138200. static static_codebook _huff_book__16u2__long = {
  138201. 2, 100,
  138202. _huff_lengthlist__16u2__long,
  138203. 0, 0, 0, 0, 0,
  138204. NULL,
  138205. NULL,
  138206. NULL,
  138207. NULL,
  138208. 0
  138209. };
  138210. static long _huff_lengthlist__16u2__short[] = {
  138211. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  138212. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  138213. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  138214. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  138215. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  138216. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  138217. 16,16,16,16,
  138218. };
  138219. static static_codebook _huff_book__16u2__short = {
  138220. 2, 100,
  138221. _huff_lengthlist__16u2__short,
  138222. 0, 0, 0, 0, 0,
  138223. NULL,
  138224. NULL,
  138225. NULL,
  138226. NULL,
  138227. 0
  138228. };
  138229. static long _vq_quantlist__16u2_p1_0[] = {
  138230. 1,
  138231. 0,
  138232. 2,
  138233. };
  138234. static long _vq_lengthlist__16u2_p1_0[] = {
  138235. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  138236. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  138237. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  138238. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  138239. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  138240. 10,
  138241. };
  138242. static float _vq_quantthresh__16u2_p1_0[] = {
  138243. -0.5, 0.5,
  138244. };
  138245. static long _vq_quantmap__16u2_p1_0[] = {
  138246. 1, 0, 2,
  138247. };
  138248. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  138249. _vq_quantthresh__16u2_p1_0,
  138250. _vq_quantmap__16u2_p1_0,
  138251. 3,
  138252. 3
  138253. };
  138254. static static_codebook _16u2_p1_0 = {
  138255. 4, 81,
  138256. _vq_lengthlist__16u2_p1_0,
  138257. 1, -535822336, 1611661312, 2, 0,
  138258. _vq_quantlist__16u2_p1_0,
  138259. NULL,
  138260. &_vq_auxt__16u2_p1_0,
  138261. NULL,
  138262. 0
  138263. };
  138264. static long _vq_quantlist__16u2_p2_0[] = {
  138265. 2,
  138266. 1,
  138267. 3,
  138268. 0,
  138269. 4,
  138270. };
  138271. static long _vq_lengthlist__16u2_p2_0[] = {
  138272. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  138273. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  138274. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  138275. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  138276. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  138277. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  138278. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  138279. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  138280. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  138281. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  138282. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  138283. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  138284. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  138285. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  138286. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  138287. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  138288. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  138289. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  138290. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  138291. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  138292. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  138293. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  138294. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  138295. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  138296. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  138297. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  138298. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  138299. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  138300. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  138301. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  138302. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  138303. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  138304. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  138305. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  138306. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  138307. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  138308. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  138309. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  138310. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  138311. 13,
  138312. };
  138313. static float _vq_quantthresh__16u2_p2_0[] = {
  138314. -1.5, -0.5, 0.5, 1.5,
  138315. };
  138316. static long _vq_quantmap__16u2_p2_0[] = {
  138317. 3, 1, 0, 2, 4,
  138318. };
  138319. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  138320. _vq_quantthresh__16u2_p2_0,
  138321. _vq_quantmap__16u2_p2_0,
  138322. 5,
  138323. 5
  138324. };
  138325. static static_codebook _16u2_p2_0 = {
  138326. 4, 625,
  138327. _vq_lengthlist__16u2_p2_0,
  138328. 1, -533725184, 1611661312, 3, 0,
  138329. _vq_quantlist__16u2_p2_0,
  138330. NULL,
  138331. &_vq_auxt__16u2_p2_0,
  138332. NULL,
  138333. 0
  138334. };
  138335. static long _vq_quantlist__16u2_p3_0[] = {
  138336. 4,
  138337. 3,
  138338. 5,
  138339. 2,
  138340. 6,
  138341. 1,
  138342. 7,
  138343. 0,
  138344. 8,
  138345. };
  138346. static long _vq_lengthlist__16u2_p3_0[] = {
  138347. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  138348. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  138349. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  138350. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  138351. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  138352. 11,
  138353. };
  138354. static float _vq_quantthresh__16u2_p3_0[] = {
  138355. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138356. };
  138357. static long _vq_quantmap__16u2_p3_0[] = {
  138358. 7, 5, 3, 1, 0, 2, 4, 6,
  138359. 8,
  138360. };
  138361. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  138362. _vq_quantthresh__16u2_p3_0,
  138363. _vq_quantmap__16u2_p3_0,
  138364. 9,
  138365. 9
  138366. };
  138367. static static_codebook _16u2_p3_0 = {
  138368. 2, 81,
  138369. _vq_lengthlist__16u2_p3_0,
  138370. 1, -531628032, 1611661312, 4, 0,
  138371. _vq_quantlist__16u2_p3_0,
  138372. NULL,
  138373. &_vq_auxt__16u2_p3_0,
  138374. NULL,
  138375. 0
  138376. };
  138377. static long _vq_quantlist__16u2_p4_0[] = {
  138378. 8,
  138379. 7,
  138380. 9,
  138381. 6,
  138382. 10,
  138383. 5,
  138384. 11,
  138385. 4,
  138386. 12,
  138387. 3,
  138388. 13,
  138389. 2,
  138390. 14,
  138391. 1,
  138392. 15,
  138393. 0,
  138394. 16,
  138395. };
  138396. static long _vq_lengthlist__16u2_p4_0[] = {
  138397. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  138398. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  138399. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  138400. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138401. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138402. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  138403. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  138404. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  138405. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  138406. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  138407. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  138408. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  138409. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  138410. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  138411. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  138412. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  138413. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  138414. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  138415. 14,
  138416. };
  138417. static float _vq_quantthresh__16u2_p4_0[] = {
  138418. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138419. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138420. };
  138421. static long _vq_quantmap__16u2_p4_0[] = {
  138422. 15, 13, 11, 9, 7, 5, 3, 1,
  138423. 0, 2, 4, 6, 8, 10, 12, 14,
  138424. 16,
  138425. };
  138426. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  138427. _vq_quantthresh__16u2_p4_0,
  138428. _vq_quantmap__16u2_p4_0,
  138429. 17,
  138430. 17
  138431. };
  138432. static static_codebook _16u2_p4_0 = {
  138433. 2, 289,
  138434. _vq_lengthlist__16u2_p4_0,
  138435. 1, -529530880, 1611661312, 5, 0,
  138436. _vq_quantlist__16u2_p4_0,
  138437. NULL,
  138438. &_vq_auxt__16u2_p4_0,
  138439. NULL,
  138440. 0
  138441. };
  138442. static long _vq_quantlist__16u2_p5_0[] = {
  138443. 1,
  138444. 0,
  138445. 2,
  138446. };
  138447. static long _vq_lengthlist__16u2_p5_0[] = {
  138448. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  138449. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  138450. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  138451. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  138452. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  138453. 10,
  138454. };
  138455. static float _vq_quantthresh__16u2_p5_0[] = {
  138456. -5.5, 5.5,
  138457. };
  138458. static long _vq_quantmap__16u2_p5_0[] = {
  138459. 1, 0, 2,
  138460. };
  138461. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  138462. _vq_quantthresh__16u2_p5_0,
  138463. _vq_quantmap__16u2_p5_0,
  138464. 3,
  138465. 3
  138466. };
  138467. static static_codebook _16u2_p5_0 = {
  138468. 4, 81,
  138469. _vq_lengthlist__16u2_p5_0,
  138470. 1, -529137664, 1618345984, 2, 0,
  138471. _vq_quantlist__16u2_p5_0,
  138472. NULL,
  138473. &_vq_auxt__16u2_p5_0,
  138474. NULL,
  138475. 0
  138476. };
  138477. static long _vq_quantlist__16u2_p5_1[] = {
  138478. 5,
  138479. 4,
  138480. 6,
  138481. 3,
  138482. 7,
  138483. 2,
  138484. 8,
  138485. 1,
  138486. 9,
  138487. 0,
  138488. 10,
  138489. };
  138490. static long _vq_lengthlist__16u2_p5_1[] = {
  138491. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  138492. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  138493. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  138494. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  138495. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  138496. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  138497. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  138498. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  138499. };
  138500. static float _vq_quantthresh__16u2_p5_1[] = {
  138501. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138502. 3.5, 4.5,
  138503. };
  138504. static long _vq_quantmap__16u2_p5_1[] = {
  138505. 9, 7, 5, 3, 1, 0, 2, 4,
  138506. 6, 8, 10,
  138507. };
  138508. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  138509. _vq_quantthresh__16u2_p5_1,
  138510. _vq_quantmap__16u2_p5_1,
  138511. 11,
  138512. 11
  138513. };
  138514. static static_codebook _16u2_p5_1 = {
  138515. 2, 121,
  138516. _vq_lengthlist__16u2_p5_1,
  138517. 1, -531365888, 1611661312, 4, 0,
  138518. _vq_quantlist__16u2_p5_1,
  138519. NULL,
  138520. &_vq_auxt__16u2_p5_1,
  138521. NULL,
  138522. 0
  138523. };
  138524. static long _vq_quantlist__16u2_p6_0[] = {
  138525. 6,
  138526. 5,
  138527. 7,
  138528. 4,
  138529. 8,
  138530. 3,
  138531. 9,
  138532. 2,
  138533. 10,
  138534. 1,
  138535. 11,
  138536. 0,
  138537. 12,
  138538. };
  138539. static long _vq_lengthlist__16u2_p6_0[] = {
  138540. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  138541. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  138542. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  138543. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  138544. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  138545. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  138546. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  138547. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  138548. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  138549. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  138550. 12,13,13,14,14,14,14,15,15,
  138551. };
  138552. static float _vq_quantthresh__16u2_p6_0[] = {
  138553. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138554. 12.5, 17.5, 22.5, 27.5,
  138555. };
  138556. static long _vq_quantmap__16u2_p6_0[] = {
  138557. 11, 9, 7, 5, 3, 1, 0, 2,
  138558. 4, 6, 8, 10, 12,
  138559. };
  138560. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  138561. _vq_quantthresh__16u2_p6_0,
  138562. _vq_quantmap__16u2_p6_0,
  138563. 13,
  138564. 13
  138565. };
  138566. static static_codebook _16u2_p6_0 = {
  138567. 2, 169,
  138568. _vq_lengthlist__16u2_p6_0,
  138569. 1, -526516224, 1616117760, 4, 0,
  138570. _vq_quantlist__16u2_p6_0,
  138571. NULL,
  138572. &_vq_auxt__16u2_p6_0,
  138573. NULL,
  138574. 0
  138575. };
  138576. static long _vq_quantlist__16u2_p6_1[] = {
  138577. 2,
  138578. 1,
  138579. 3,
  138580. 0,
  138581. 4,
  138582. };
  138583. static long _vq_lengthlist__16u2_p6_1[] = {
  138584. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  138585. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  138586. };
  138587. static float _vq_quantthresh__16u2_p6_1[] = {
  138588. -1.5, -0.5, 0.5, 1.5,
  138589. };
  138590. static long _vq_quantmap__16u2_p6_1[] = {
  138591. 3, 1, 0, 2, 4,
  138592. };
  138593. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  138594. _vq_quantthresh__16u2_p6_1,
  138595. _vq_quantmap__16u2_p6_1,
  138596. 5,
  138597. 5
  138598. };
  138599. static static_codebook _16u2_p6_1 = {
  138600. 2, 25,
  138601. _vq_lengthlist__16u2_p6_1,
  138602. 1, -533725184, 1611661312, 3, 0,
  138603. _vq_quantlist__16u2_p6_1,
  138604. NULL,
  138605. &_vq_auxt__16u2_p6_1,
  138606. NULL,
  138607. 0
  138608. };
  138609. static long _vq_quantlist__16u2_p7_0[] = {
  138610. 6,
  138611. 5,
  138612. 7,
  138613. 4,
  138614. 8,
  138615. 3,
  138616. 9,
  138617. 2,
  138618. 10,
  138619. 1,
  138620. 11,
  138621. 0,
  138622. 12,
  138623. };
  138624. static long _vq_lengthlist__16u2_p7_0[] = {
  138625. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  138626. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  138627. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  138628. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  138629. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  138630. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  138631. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  138632. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  138633. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  138634. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  138635. 12,13,13,13,14,14,14,15,14,
  138636. };
  138637. static float _vq_quantthresh__16u2_p7_0[] = {
  138638. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  138639. 27.5, 38.5, 49.5, 60.5,
  138640. };
  138641. static long _vq_quantmap__16u2_p7_0[] = {
  138642. 11, 9, 7, 5, 3, 1, 0, 2,
  138643. 4, 6, 8, 10, 12,
  138644. };
  138645. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  138646. _vq_quantthresh__16u2_p7_0,
  138647. _vq_quantmap__16u2_p7_0,
  138648. 13,
  138649. 13
  138650. };
  138651. static static_codebook _16u2_p7_0 = {
  138652. 2, 169,
  138653. _vq_lengthlist__16u2_p7_0,
  138654. 1, -523206656, 1618345984, 4, 0,
  138655. _vq_quantlist__16u2_p7_0,
  138656. NULL,
  138657. &_vq_auxt__16u2_p7_0,
  138658. NULL,
  138659. 0
  138660. };
  138661. static long _vq_quantlist__16u2_p7_1[] = {
  138662. 5,
  138663. 4,
  138664. 6,
  138665. 3,
  138666. 7,
  138667. 2,
  138668. 8,
  138669. 1,
  138670. 9,
  138671. 0,
  138672. 10,
  138673. };
  138674. static long _vq_lengthlist__16u2_p7_1[] = {
  138675. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  138676. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  138677. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  138678. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  138679. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  138680. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  138681. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  138682. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138683. };
  138684. static float _vq_quantthresh__16u2_p7_1[] = {
  138685. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138686. 3.5, 4.5,
  138687. };
  138688. static long _vq_quantmap__16u2_p7_1[] = {
  138689. 9, 7, 5, 3, 1, 0, 2, 4,
  138690. 6, 8, 10,
  138691. };
  138692. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  138693. _vq_quantthresh__16u2_p7_1,
  138694. _vq_quantmap__16u2_p7_1,
  138695. 11,
  138696. 11
  138697. };
  138698. static static_codebook _16u2_p7_1 = {
  138699. 2, 121,
  138700. _vq_lengthlist__16u2_p7_1,
  138701. 1, -531365888, 1611661312, 4, 0,
  138702. _vq_quantlist__16u2_p7_1,
  138703. NULL,
  138704. &_vq_auxt__16u2_p7_1,
  138705. NULL,
  138706. 0
  138707. };
  138708. static long _vq_quantlist__16u2_p8_0[] = {
  138709. 7,
  138710. 6,
  138711. 8,
  138712. 5,
  138713. 9,
  138714. 4,
  138715. 10,
  138716. 3,
  138717. 11,
  138718. 2,
  138719. 12,
  138720. 1,
  138721. 13,
  138722. 0,
  138723. 14,
  138724. };
  138725. static long _vq_lengthlist__16u2_p8_0[] = {
  138726. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  138727. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  138728. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  138729. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  138730. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  138731. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  138732. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  138733. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  138734. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  138735. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  138736. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  138737. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  138738. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  138739. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  138740. 14,
  138741. };
  138742. static float _vq_quantthresh__16u2_p8_0[] = {
  138743. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  138744. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  138745. };
  138746. static long _vq_quantmap__16u2_p8_0[] = {
  138747. 13, 11, 9, 7, 5, 3, 1, 0,
  138748. 2, 4, 6, 8, 10, 12, 14,
  138749. };
  138750. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  138751. _vq_quantthresh__16u2_p8_0,
  138752. _vq_quantmap__16u2_p8_0,
  138753. 15,
  138754. 15
  138755. };
  138756. static static_codebook _16u2_p8_0 = {
  138757. 2, 225,
  138758. _vq_lengthlist__16u2_p8_0,
  138759. 1, -520986624, 1620377600, 4, 0,
  138760. _vq_quantlist__16u2_p8_0,
  138761. NULL,
  138762. &_vq_auxt__16u2_p8_0,
  138763. NULL,
  138764. 0
  138765. };
  138766. static long _vq_quantlist__16u2_p8_1[] = {
  138767. 10,
  138768. 9,
  138769. 11,
  138770. 8,
  138771. 12,
  138772. 7,
  138773. 13,
  138774. 6,
  138775. 14,
  138776. 5,
  138777. 15,
  138778. 4,
  138779. 16,
  138780. 3,
  138781. 17,
  138782. 2,
  138783. 18,
  138784. 1,
  138785. 19,
  138786. 0,
  138787. 20,
  138788. };
  138789. static long _vq_lengthlist__16u2_p8_1[] = {
  138790. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  138791. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  138792. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  138793. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  138794. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  138795. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  138796. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  138797. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  138798. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  138799. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  138800. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  138801. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  138802. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  138803. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  138804. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  138805. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  138806. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  138807. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  138808. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  138809. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  138810. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  138811. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  138812. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  138813. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  138814. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  138815. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  138816. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  138817. 11,11,10,11,11,11,10,11,11,
  138818. };
  138819. static float _vq_quantthresh__16u2_p8_1[] = {
  138820. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  138821. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  138822. 6.5, 7.5, 8.5, 9.5,
  138823. };
  138824. static long _vq_quantmap__16u2_p8_1[] = {
  138825. 19, 17, 15, 13, 11, 9, 7, 5,
  138826. 3, 1, 0, 2, 4, 6, 8, 10,
  138827. 12, 14, 16, 18, 20,
  138828. };
  138829. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  138830. _vq_quantthresh__16u2_p8_1,
  138831. _vq_quantmap__16u2_p8_1,
  138832. 21,
  138833. 21
  138834. };
  138835. static static_codebook _16u2_p8_1 = {
  138836. 2, 441,
  138837. _vq_lengthlist__16u2_p8_1,
  138838. 1, -529268736, 1611661312, 5, 0,
  138839. _vq_quantlist__16u2_p8_1,
  138840. NULL,
  138841. &_vq_auxt__16u2_p8_1,
  138842. NULL,
  138843. 0
  138844. };
  138845. static long _vq_quantlist__16u2_p9_0[] = {
  138846. 5586,
  138847. 4655,
  138848. 6517,
  138849. 3724,
  138850. 7448,
  138851. 2793,
  138852. 8379,
  138853. 1862,
  138854. 9310,
  138855. 931,
  138856. 10241,
  138857. 0,
  138858. 11172,
  138859. 5521,
  138860. 5651,
  138861. };
  138862. static long _vq_lengthlist__16u2_p9_0[] = {
  138863. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  138864. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138865. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138866. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138867. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138868. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138869. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138870. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138871. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138872. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138873. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138874. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138875. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  138876. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  138877. 5,
  138878. };
  138879. static float _vq_quantthresh__16u2_p9_0[] = {
  138880. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  138881. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  138882. };
  138883. static long _vq_quantmap__16u2_p9_0[] = {
  138884. 11, 9, 7, 5, 3, 1, 13, 0,
  138885. 14, 2, 4, 6, 8, 10, 12,
  138886. };
  138887. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  138888. _vq_quantthresh__16u2_p9_0,
  138889. _vq_quantmap__16u2_p9_0,
  138890. 15,
  138891. 15
  138892. };
  138893. static static_codebook _16u2_p9_0 = {
  138894. 2, 225,
  138895. _vq_lengthlist__16u2_p9_0,
  138896. 1, -510275072, 1611661312, 14, 0,
  138897. _vq_quantlist__16u2_p9_0,
  138898. NULL,
  138899. &_vq_auxt__16u2_p9_0,
  138900. NULL,
  138901. 0
  138902. };
  138903. static long _vq_quantlist__16u2_p9_1[] = {
  138904. 392,
  138905. 343,
  138906. 441,
  138907. 294,
  138908. 490,
  138909. 245,
  138910. 539,
  138911. 196,
  138912. 588,
  138913. 147,
  138914. 637,
  138915. 98,
  138916. 686,
  138917. 49,
  138918. 735,
  138919. 0,
  138920. 784,
  138921. 388,
  138922. 396,
  138923. };
  138924. static long _vq_lengthlist__16u2_p9_1[] = {
  138925. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  138926. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  138927. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  138928. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  138929. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  138930. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  138931. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138932. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  138933. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  138934. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138935. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138936. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138937. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138938. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138939. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  138940. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138941. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138942. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138943. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138944. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138945. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  138946. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  138947. 11,11,11,11,11,11,11, 5, 4,
  138948. };
  138949. static float _vq_quantthresh__16u2_p9_1[] = {
  138950. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  138951. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  138952. 318.5, 367.5,
  138953. };
  138954. static long _vq_quantmap__16u2_p9_1[] = {
  138955. 15, 13, 11, 9, 7, 5, 3, 1,
  138956. 17, 0, 18, 2, 4, 6, 8, 10,
  138957. 12, 14, 16,
  138958. };
  138959. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  138960. _vq_quantthresh__16u2_p9_1,
  138961. _vq_quantmap__16u2_p9_1,
  138962. 19,
  138963. 19
  138964. };
  138965. static static_codebook _16u2_p9_1 = {
  138966. 2, 361,
  138967. _vq_lengthlist__16u2_p9_1,
  138968. 1, -518488064, 1611661312, 10, 0,
  138969. _vq_quantlist__16u2_p9_1,
  138970. NULL,
  138971. &_vq_auxt__16u2_p9_1,
  138972. NULL,
  138973. 0
  138974. };
  138975. static long _vq_quantlist__16u2_p9_2[] = {
  138976. 24,
  138977. 23,
  138978. 25,
  138979. 22,
  138980. 26,
  138981. 21,
  138982. 27,
  138983. 20,
  138984. 28,
  138985. 19,
  138986. 29,
  138987. 18,
  138988. 30,
  138989. 17,
  138990. 31,
  138991. 16,
  138992. 32,
  138993. 15,
  138994. 33,
  138995. 14,
  138996. 34,
  138997. 13,
  138998. 35,
  138999. 12,
  139000. 36,
  139001. 11,
  139002. 37,
  139003. 10,
  139004. 38,
  139005. 9,
  139006. 39,
  139007. 8,
  139008. 40,
  139009. 7,
  139010. 41,
  139011. 6,
  139012. 42,
  139013. 5,
  139014. 43,
  139015. 4,
  139016. 44,
  139017. 3,
  139018. 45,
  139019. 2,
  139020. 46,
  139021. 1,
  139022. 47,
  139023. 0,
  139024. 48,
  139025. };
  139026. static long _vq_lengthlist__16u2_p9_2[] = {
  139027. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  139028. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  139029. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  139030. 11,
  139031. };
  139032. static float _vq_quantthresh__16u2_p9_2[] = {
  139033. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  139034. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  139035. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139036. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139037. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  139038. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  139039. };
  139040. static long _vq_quantmap__16u2_p9_2[] = {
  139041. 47, 45, 43, 41, 39, 37, 35, 33,
  139042. 31, 29, 27, 25, 23, 21, 19, 17,
  139043. 15, 13, 11, 9, 7, 5, 3, 1,
  139044. 0, 2, 4, 6, 8, 10, 12, 14,
  139045. 16, 18, 20, 22, 24, 26, 28, 30,
  139046. 32, 34, 36, 38, 40, 42, 44, 46,
  139047. 48,
  139048. };
  139049. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  139050. _vq_quantthresh__16u2_p9_2,
  139051. _vq_quantmap__16u2_p9_2,
  139052. 49,
  139053. 49
  139054. };
  139055. static static_codebook _16u2_p9_2 = {
  139056. 1, 49,
  139057. _vq_lengthlist__16u2_p9_2,
  139058. 1, -526909440, 1611661312, 6, 0,
  139059. _vq_quantlist__16u2_p9_2,
  139060. NULL,
  139061. &_vq_auxt__16u2_p9_2,
  139062. NULL,
  139063. 0
  139064. };
  139065. static long _vq_quantlist__8u0__p1_0[] = {
  139066. 1,
  139067. 0,
  139068. 2,
  139069. };
  139070. static long _vq_lengthlist__8u0__p1_0[] = {
  139071. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  139072. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  139073. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  139074. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  139075. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  139076. 11,
  139077. };
  139078. static float _vq_quantthresh__8u0__p1_0[] = {
  139079. -0.5, 0.5,
  139080. };
  139081. static long _vq_quantmap__8u0__p1_0[] = {
  139082. 1, 0, 2,
  139083. };
  139084. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  139085. _vq_quantthresh__8u0__p1_0,
  139086. _vq_quantmap__8u0__p1_0,
  139087. 3,
  139088. 3
  139089. };
  139090. static static_codebook _8u0__p1_0 = {
  139091. 4, 81,
  139092. _vq_lengthlist__8u0__p1_0,
  139093. 1, -535822336, 1611661312, 2, 0,
  139094. _vq_quantlist__8u0__p1_0,
  139095. NULL,
  139096. &_vq_auxt__8u0__p1_0,
  139097. NULL,
  139098. 0
  139099. };
  139100. static long _vq_quantlist__8u0__p2_0[] = {
  139101. 1,
  139102. 0,
  139103. 2,
  139104. };
  139105. static long _vq_lengthlist__8u0__p2_0[] = {
  139106. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  139107. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  139108. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  139109. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  139110. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  139111. 8,
  139112. };
  139113. static float _vq_quantthresh__8u0__p2_0[] = {
  139114. -0.5, 0.5,
  139115. };
  139116. static long _vq_quantmap__8u0__p2_0[] = {
  139117. 1, 0, 2,
  139118. };
  139119. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  139120. _vq_quantthresh__8u0__p2_0,
  139121. _vq_quantmap__8u0__p2_0,
  139122. 3,
  139123. 3
  139124. };
  139125. static static_codebook _8u0__p2_0 = {
  139126. 4, 81,
  139127. _vq_lengthlist__8u0__p2_0,
  139128. 1, -535822336, 1611661312, 2, 0,
  139129. _vq_quantlist__8u0__p2_0,
  139130. NULL,
  139131. &_vq_auxt__8u0__p2_0,
  139132. NULL,
  139133. 0
  139134. };
  139135. static long _vq_quantlist__8u0__p3_0[] = {
  139136. 2,
  139137. 1,
  139138. 3,
  139139. 0,
  139140. 4,
  139141. };
  139142. static long _vq_lengthlist__8u0__p3_0[] = {
  139143. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  139144. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  139145. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  139146. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  139147. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  139148. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  139149. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  139150. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  139151. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  139152. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  139153. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  139154. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  139155. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  139156. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  139157. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  139158. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  139159. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  139160. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  139161. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  139162. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  139163. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  139164. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  139165. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  139166. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  139167. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  139168. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  139169. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  139170. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  139171. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  139172. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  139173. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  139174. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  139175. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  139176. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  139177. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  139178. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  139179. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  139180. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  139181. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  139182. 16,
  139183. };
  139184. static float _vq_quantthresh__8u0__p3_0[] = {
  139185. -1.5, -0.5, 0.5, 1.5,
  139186. };
  139187. static long _vq_quantmap__8u0__p3_0[] = {
  139188. 3, 1, 0, 2, 4,
  139189. };
  139190. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  139191. _vq_quantthresh__8u0__p3_0,
  139192. _vq_quantmap__8u0__p3_0,
  139193. 5,
  139194. 5
  139195. };
  139196. static static_codebook _8u0__p3_0 = {
  139197. 4, 625,
  139198. _vq_lengthlist__8u0__p3_0,
  139199. 1, -533725184, 1611661312, 3, 0,
  139200. _vq_quantlist__8u0__p3_0,
  139201. NULL,
  139202. &_vq_auxt__8u0__p3_0,
  139203. NULL,
  139204. 0
  139205. };
  139206. static long _vq_quantlist__8u0__p4_0[] = {
  139207. 2,
  139208. 1,
  139209. 3,
  139210. 0,
  139211. 4,
  139212. };
  139213. static long _vq_lengthlist__8u0__p4_0[] = {
  139214. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  139215. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  139216. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  139217. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  139218. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  139219. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  139220. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  139221. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  139222. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  139223. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  139224. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  139225. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  139226. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  139227. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  139228. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  139229. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  139230. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  139231. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  139232. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  139233. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  139234. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  139235. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  139236. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  139237. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  139238. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  139239. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  139240. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  139241. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  139242. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  139243. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  139244. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  139245. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  139246. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  139247. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  139248. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  139249. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  139250. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  139251. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  139252. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  139253. 12,
  139254. };
  139255. static float _vq_quantthresh__8u0__p4_0[] = {
  139256. -1.5, -0.5, 0.5, 1.5,
  139257. };
  139258. static long _vq_quantmap__8u0__p4_0[] = {
  139259. 3, 1, 0, 2, 4,
  139260. };
  139261. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  139262. _vq_quantthresh__8u0__p4_0,
  139263. _vq_quantmap__8u0__p4_0,
  139264. 5,
  139265. 5
  139266. };
  139267. static static_codebook _8u0__p4_0 = {
  139268. 4, 625,
  139269. _vq_lengthlist__8u0__p4_0,
  139270. 1, -533725184, 1611661312, 3, 0,
  139271. _vq_quantlist__8u0__p4_0,
  139272. NULL,
  139273. &_vq_auxt__8u0__p4_0,
  139274. NULL,
  139275. 0
  139276. };
  139277. static long _vq_quantlist__8u0__p5_0[] = {
  139278. 4,
  139279. 3,
  139280. 5,
  139281. 2,
  139282. 6,
  139283. 1,
  139284. 7,
  139285. 0,
  139286. 8,
  139287. };
  139288. static long _vq_lengthlist__8u0__p5_0[] = {
  139289. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  139290. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  139291. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  139292. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  139293. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  139294. 12,
  139295. };
  139296. static float _vq_quantthresh__8u0__p5_0[] = {
  139297. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139298. };
  139299. static long _vq_quantmap__8u0__p5_0[] = {
  139300. 7, 5, 3, 1, 0, 2, 4, 6,
  139301. 8,
  139302. };
  139303. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  139304. _vq_quantthresh__8u0__p5_0,
  139305. _vq_quantmap__8u0__p5_0,
  139306. 9,
  139307. 9
  139308. };
  139309. static static_codebook _8u0__p5_0 = {
  139310. 2, 81,
  139311. _vq_lengthlist__8u0__p5_0,
  139312. 1, -531628032, 1611661312, 4, 0,
  139313. _vq_quantlist__8u0__p5_0,
  139314. NULL,
  139315. &_vq_auxt__8u0__p5_0,
  139316. NULL,
  139317. 0
  139318. };
  139319. static long _vq_quantlist__8u0__p6_0[] = {
  139320. 6,
  139321. 5,
  139322. 7,
  139323. 4,
  139324. 8,
  139325. 3,
  139326. 9,
  139327. 2,
  139328. 10,
  139329. 1,
  139330. 11,
  139331. 0,
  139332. 12,
  139333. };
  139334. static long _vq_lengthlist__8u0__p6_0[] = {
  139335. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  139336. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  139337. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  139338. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  139339. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  139340. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  139341. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  139342. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  139343. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  139344. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  139345. 16, 0,15, 0,17, 0, 0, 0, 0,
  139346. };
  139347. static float _vq_quantthresh__8u0__p6_0[] = {
  139348. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139349. 12.5, 17.5, 22.5, 27.5,
  139350. };
  139351. static long _vq_quantmap__8u0__p6_0[] = {
  139352. 11, 9, 7, 5, 3, 1, 0, 2,
  139353. 4, 6, 8, 10, 12,
  139354. };
  139355. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  139356. _vq_quantthresh__8u0__p6_0,
  139357. _vq_quantmap__8u0__p6_0,
  139358. 13,
  139359. 13
  139360. };
  139361. static static_codebook _8u0__p6_0 = {
  139362. 2, 169,
  139363. _vq_lengthlist__8u0__p6_0,
  139364. 1, -526516224, 1616117760, 4, 0,
  139365. _vq_quantlist__8u0__p6_0,
  139366. NULL,
  139367. &_vq_auxt__8u0__p6_0,
  139368. NULL,
  139369. 0
  139370. };
  139371. static long _vq_quantlist__8u0__p6_1[] = {
  139372. 2,
  139373. 1,
  139374. 3,
  139375. 0,
  139376. 4,
  139377. };
  139378. static long _vq_lengthlist__8u0__p6_1[] = {
  139379. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  139380. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  139381. };
  139382. static float _vq_quantthresh__8u0__p6_1[] = {
  139383. -1.5, -0.5, 0.5, 1.5,
  139384. };
  139385. static long _vq_quantmap__8u0__p6_1[] = {
  139386. 3, 1, 0, 2, 4,
  139387. };
  139388. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  139389. _vq_quantthresh__8u0__p6_1,
  139390. _vq_quantmap__8u0__p6_1,
  139391. 5,
  139392. 5
  139393. };
  139394. static static_codebook _8u0__p6_1 = {
  139395. 2, 25,
  139396. _vq_lengthlist__8u0__p6_1,
  139397. 1, -533725184, 1611661312, 3, 0,
  139398. _vq_quantlist__8u0__p6_1,
  139399. NULL,
  139400. &_vq_auxt__8u0__p6_1,
  139401. NULL,
  139402. 0
  139403. };
  139404. static long _vq_quantlist__8u0__p7_0[] = {
  139405. 1,
  139406. 0,
  139407. 2,
  139408. };
  139409. static long _vq_lengthlist__8u0__p7_0[] = {
  139410. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139411. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139412. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  139413. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  139414. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  139415. 7,
  139416. };
  139417. static float _vq_quantthresh__8u0__p7_0[] = {
  139418. -157.5, 157.5,
  139419. };
  139420. static long _vq_quantmap__8u0__p7_0[] = {
  139421. 1, 0, 2,
  139422. };
  139423. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  139424. _vq_quantthresh__8u0__p7_0,
  139425. _vq_quantmap__8u0__p7_0,
  139426. 3,
  139427. 3
  139428. };
  139429. static static_codebook _8u0__p7_0 = {
  139430. 4, 81,
  139431. _vq_lengthlist__8u0__p7_0,
  139432. 1, -518803456, 1628680192, 2, 0,
  139433. _vq_quantlist__8u0__p7_0,
  139434. NULL,
  139435. &_vq_auxt__8u0__p7_0,
  139436. NULL,
  139437. 0
  139438. };
  139439. static long _vq_quantlist__8u0__p7_1[] = {
  139440. 7,
  139441. 6,
  139442. 8,
  139443. 5,
  139444. 9,
  139445. 4,
  139446. 10,
  139447. 3,
  139448. 11,
  139449. 2,
  139450. 12,
  139451. 1,
  139452. 13,
  139453. 0,
  139454. 14,
  139455. };
  139456. static long _vq_lengthlist__8u0__p7_1[] = {
  139457. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  139458. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  139459. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  139460. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  139461. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  139462. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  139463. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139464. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139465. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139466. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139467. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139468. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139469. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  139470. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139471. 10,
  139472. };
  139473. static float _vq_quantthresh__8u0__p7_1[] = {
  139474. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  139475. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  139476. };
  139477. static long _vq_quantmap__8u0__p7_1[] = {
  139478. 13, 11, 9, 7, 5, 3, 1, 0,
  139479. 2, 4, 6, 8, 10, 12, 14,
  139480. };
  139481. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  139482. _vq_quantthresh__8u0__p7_1,
  139483. _vq_quantmap__8u0__p7_1,
  139484. 15,
  139485. 15
  139486. };
  139487. static static_codebook _8u0__p7_1 = {
  139488. 2, 225,
  139489. _vq_lengthlist__8u0__p7_1,
  139490. 1, -520986624, 1620377600, 4, 0,
  139491. _vq_quantlist__8u0__p7_1,
  139492. NULL,
  139493. &_vq_auxt__8u0__p7_1,
  139494. NULL,
  139495. 0
  139496. };
  139497. static long _vq_quantlist__8u0__p7_2[] = {
  139498. 10,
  139499. 9,
  139500. 11,
  139501. 8,
  139502. 12,
  139503. 7,
  139504. 13,
  139505. 6,
  139506. 14,
  139507. 5,
  139508. 15,
  139509. 4,
  139510. 16,
  139511. 3,
  139512. 17,
  139513. 2,
  139514. 18,
  139515. 1,
  139516. 19,
  139517. 0,
  139518. 20,
  139519. };
  139520. static long _vq_lengthlist__8u0__p7_2[] = {
  139521. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  139522. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  139523. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  139524. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  139525. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  139526. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  139527. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  139528. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  139529. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  139530. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  139531. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  139532. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  139533. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  139534. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  139535. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  139536. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  139537. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  139538. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  139539. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  139540. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  139541. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  139542. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  139543. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  139544. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  139545. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  139546. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  139547. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  139548. 11,12,11,11,11,10,10,11,11,
  139549. };
  139550. static float _vq_quantthresh__8u0__p7_2[] = {
  139551. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  139552. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  139553. 6.5, 7.5, 8.5, 9.5,
  139554. };
  139555. static long _vq_quantmap__8u0__p7_2[] = {
  139556. 19, 17, 15, 13, 11, 9, 7, 5,
  139557. 3, 1, 0, 2, 4, 6, 8, 10,
  139558. 12, 14, 16, 18, 20,
  139559. };
  139560. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  139561. _vq_quantthresh__8u0__p7_2,
  139562. _vq_quantmap__8u0__p7_2,
  139563. 21,
  139564. 21
  139565. };
  139566. static static_codebook _8u0__p7_2 = {
  139567. 2, 441,
  139568. _vq_lengthlist__8u0__p7_2,
  139569. 1, -529268736, 1611661312, 5, 0,
  139570. _vq_quantlist__8u0__p7_2,
  139571. NULL,
  139572. &_vq_auxt__8u0__p7_2,
  139573. NULL,
  139574. 0
  139575. };
  139576. static long _huff_lengthlist__8u0__single[] = {
  139577. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  139578. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  139579. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  139580. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  139581. };
  139582. static static_codebook _huff_book__8u0__single = {
  139583. 2, 64,
  139584. _huff_lengthlist__8u0__single,
  139585. 0, 0, 0, 0, 0,
  139586. NULL,
  139587. NULL,
  139588. NULL,
  139589. NULL,
  139590. 0
  139591. };
  139592. static long _vq_quantlist__8u1__p1_0[] = {
  139593. 1,
  139594. 0,
  139595. 2,
  139596. };
  139597. static long _vq_lengthlist__8u1__p1_0[] = {
  139598. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  139599. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  139600. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  139601. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  139602. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  139603. 10,
  139604. };
  139605. static float _vq_quantthresh__8u1__p1_0[] = {
  139606. -0.5, 0.5,
  139607. };
  139608. static long _vq_quantmap__8u1__p1_0[] = {
  139609. 1, 0, 2,
  139610. };
  139611. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  139612. _vq_quantthresh__8u1__p1_0,
  139613. _vq_quantmap__8u1__p1_0,
  139614. 3,
  139615. 3
  139616. };
  139617. static static_codebook _8u1__p1_0 = {
  139618. 4, 81,
  139619. _vq_lengthlist__8u1__p1_0,
  139620. 1, -535822336, 1611661312, 2, 0,
  139621. _vq_quantlist__8u1__p1_0,
  139622. NULL,
  139623. &_vq_auxt__8u1__p1_0,
  139624. NULL,
  139625. 0
  139626. };
  139627. static long _vq_quantlist__8u1__p2_0[] = {
  139628. 1,
  139629. 0,
  139630. 2,
  139631. };
  139632. static long _vq_lengthlist__8u1__p2_0[] = {
  139633. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  139634. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  139635. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  139636. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  139637. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  139638. 7,
  139639. };
  139640. static float _vq_quantthresh__8u1__p2_0[] = {
  139641. -0.5, 0.5,
  139642. };
  139643. static long _vq_quantmap__8u1__p2_0[] = {
  139644. 1, 0, 2,
  139645. };
  139646. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  139647. _vq_quantthresh__8u1__p2_0,
  139648. _vq_quantmap__8u1__p2_0,
  139649. 3,
  139650. 3
  139651. };
  139652. static static_codebook _8u1__p2_0 = {
  139653. 4, 81,
  139654. _vq_lengthlist__8u1__p2_0,
  139655. 1, -535822336, 1611661312, 2, 0,
  139656. _vq_quantlist__8u1__p2_0,
  139657. NULL,
  139658. &_vq_auxt__8u1__p2_0,
  139659. NULL,
  139660. 0
  139661. };
  139662. static long _vq_quantlist__8u1__p3_0[] = {
  139663. 2,
  139664. 1,
  139665. 3,
  139666. 0,
  139667. 4,
  139668. };
  139669. static long _vq_lengthlist__8u1__p3_0[] = {
  139670. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  139671. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  139672. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  139673. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  139674. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  139675. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  139676. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  139677. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  139678. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  139679. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  139680. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  139681. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  139682. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  139683. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  139684. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  139685. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  139686. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  139687. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  139688. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  139689. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  139690. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  139691. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  139692. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  139693. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  139694. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  139695. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  139696. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  139697. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  139698. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  139699. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  139700. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  139701. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  139702. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  139703. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  139704. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  139705. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  139706. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  139707. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  139708. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  139709. 16,
  139710. };
  139711. static float _vq_quantthresh__8u1__p3_0[] = {
  139712. -1.5, -0.5, 0.5, 1.5,
  139713. };
  139714. static long _vq_quantmap__8u1__p3_0[] = {
  139715. 3, 1, 0, 2, 4,
  139716. };
  139717. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  139718. _vq_quantthresh__8u1__p3_0,
  139719. _vq_quantmap__8u1__p3_0,
  139720. 5,
  139721. 5
  139722. };
  139723. static static_codebook _8u1__p3_0 = {
  139724. 4, 625,
  139725. _vq_lengthlist__8u1__p3_0,
  139726. 1, -533725184, 1611661312, 3, 0,
  139727. _vq_quantlist__8u1__p3_0,
  139728. NULL,
  139729. &_vq_auxt__8u1__p3_0,
  139730. NULL,
  139731. 0
  139732. };
  139733. static long _vq_quantlist__8u1__p4_0[] = {
  139734. 2,
  139735. 1,
  139736. 3,
  139737. 0,
  139738. 4,
  139739. };
  139740. static long _vq_lengthlist__8u1__p4_0[] = {
  139741. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  139742. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  139743. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  139744. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  139745. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  139746. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  139747. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  139748. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  139749. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  139750. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  139751. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  139752. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  139753. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  139754. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  139755. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  139756. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  139757. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  139758. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  139759. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  139760. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  139761. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  139762. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  139763. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  139764. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  139765. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  139766. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  139767. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  139768. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  139769. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  139770. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  139771. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  139772. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  139773. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  139774. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  139775. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  139776. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  139777. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  139778. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  139779. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  139780. 10,
  139781. };
  139782. static float _vq_quantthresh__8u1__p4_0[] = {
  139783. -1.5, -0.5, 0.5, 1.5,
  139784. };
  139785. static long _vq_quantmap__8u1__p4_0[] = {
  139786. 3, 1, 0, 2, 4,
  139787. };
  139788. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  139789. _vq_quantthresh__8u1__p4_0,
  139790. _vq_quantmap__8u1__p4_0,
  139791. 5,
  139792. 5
  139793. };
  139794. static static_codebook _8u1__p4_0 = {
  139795. 4, 625,
  139796. _vq_lengthlist__8u1__p4_0,
  139797. 1, -533725184, 1611661312, 3, 0,
  139798. _vq_quantlist__8u1__p4_0,
  139799. NULL,
  139800. &_vq_auxt__8u1__p4_0,
  139801. NULL,
  139802. 0
  139803. };
  139804. static long _vq_quantlist__8u1__p5_0[] = {
  139805. 4,
  139806. 3,
  139807. 5,
  139808. 2,
  139809. 6,
  139810. 1,
  139811. 7,
  139812. 0,
  139813. 8,
  139814. };
  139815. static long _vq_lengthlist__8u1__p5_0[] = {
  139816. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  139817. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  139818. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  139819. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  139820. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  139821. 13,
  139822. };
  139823. static float _vq_quantthresh__8u1__p5_0[] = {
  139824. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139825. };
  139826. static long _vq_quantmap__8u1__p5_0[] = {
  139827. 7, 5, 3, 1, 0, 2, 4, 6,
  139828. 8,
  139829. };
  139830. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  139831. _vq_quantthresh__8u1__p5_0,
  139832. _vq_quantmap__8u1__p5_0,
  139833. 9,
  139834. 9
  139835. };
  139836. static static_codebook _8u1__p5_0 = {
  139837. 2, 81,
  139838. _vq_lengthlist__8u1__p5_0,
  139839. 1, -531628032, 1611661312, 4, 0,
  139840. _vq_quantlist__8u1__p5_0,
  139841. NULL,
  139842. &_vq_auxt__8u1__p5_0,
  139843. NULL,
  139844. 0
  139845. };
  139846. static long _vq_quantlist__8u1__p6_0[] = {
  139847. 4,
  139848. 3,
  139849. 5,
  139850. 2,
  139851. 6,
  139852. 1,
  139853. 7,
  139854. 0,
  139855. 8,
  139856. };
  139857. static long _vq_lengthlist__8u1__p6_0[] = {
  139858. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  139859. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  139860. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  139861. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  139862. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  139863. 10,
  139864. };
  139865. static float _vq_quantthresh__8u1__p6_0[] = {
  139866. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139867. };
  139868. static long _vq_quantmap__8u1__p6_0[] = {
  139869. 7, 5, 3, 1, 0, 2, 4, 6,
  139870. 8,
  139871. };
  139872. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  139873. _vq_quantthresh__8u1__p6_0,
  139874. _vq_quantmap__8u1__p6_0,
  139875. 9,
  139876. 9
  139877. };
  139878. static static_codebook _8u1__p6_0 = {
  139879. 2, 81,
  139880. _vq_lengthlist__8u1__p6_0,
  139881. 1, -531628032, 1611661312, 4, 0,
  139882. _vq_quantlist__8u1__p6_0,
  139883. NULL,
  139884. &_vq_auxt__8u1__p6_0,
  139885. NULL,
  139886. 0
  139887. };
  139888. static long _vq_quantlist__8u1__p7_0[] = {
  139889. 1,
  139890. 0,
  139891. 2,
  139892. };
  139893. static long _vq_lengthlist__8u1__p7_0[] = {
  139894. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  139895. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  139896. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  139897. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  139898. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  139899. 11,
  139900. };
  139901. static float _vq_quantthresh__8u1__p7_0[] = {
  139902. -5.5, 5.5,
  139903. };
  139904. static long _vq_quantmap__8u1__p7_0[] = {
  139905. 1, 0, 2,
  139906. };
  139907. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  139908. _vq_quantthresh__8u1__p7_0,
  139909. _vq_quantmap__8u1__p7_0,
  139910. 3,
  139911. 3
  139912. };
  139913. static static_codebook _8u1__p7_0 = {
  139914. 4, 81,
  139915. _vq_lengthlist__8u1__p7_0,
  139916. 1, -529137664, 1618345984, 2, 0,
  139917. _vq_quantlist__8u1__p7_0,
  139918. NULL,
  139919. &_vq_auxt__8u1__p7_0,
  139920. NULL,
  139921. 0
  139922. };
  139923. static long _vq_quantlist__8u1__p7_1[] = {
  139924. 5,
  139925. 4,
  139926. 6,
  139927. 3,
  139928. 7,
  139929. 2,
  139930. 8,
  139931. 1,
  139932. 9,
  139933. 0,
  139934. 10,
  139935. };
  139936. static long _vq_lengthlist__8u1__p7_1[] = {
  139937. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  139938. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  139939. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  139940. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  139941. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  139942. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  139943. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  139944. 9, 9, 9, 9, 9,10,10,10,10,
  139945. };
  139946. static float _vq_quantthresh__8u1__p7_1[] = {
  139947. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139948. 3.5, 4.5,
  139949. };
  139950. static long _vq_quantmap__8u1__p7_1[] = {
  139951. 9, 7, 5, 3, 1, 0, 2, 4,
  139952. 6, 8, 10,
  139953. };
  139954. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  139955. _vq_quantthresh__8u1__p7_1,
  139956. _vq_quantmap__8u1__p7_1,
  139957. 11,
  139958. 11
  139959. };
  139960. static static_codebook _8u1__p7_1 = {
  139961. 2, 121,
  139962. _vq_lengthlist__8u1__p7_1,
  139963. 1, -531365888, 1611661312, 4, 0,
  139964. _vq_quantlist__8u1__p7_1,
  139965. NULL,
  139966. &_vq_auxt__8u1__p7_1,
  139967. NULL,
  139968. 0
  139969. };
  139970. static long _vq_quantlist__8u1__p8_0[] = {
  139971. 5,
  139972. 4,
  139973. 6,
  139974. 3,
  139975. 7,
  139976. 2,
  139977. 8,
  139978. 1,
  139979. 9,
  139980. 0,
  139981. 10,
  139982. };
  139983. static long _vq_lengthlist__8u1__p8_0[] = {
  139984. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  139985. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  139986. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  139987. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  139988. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  139989. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  139990. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  139991. 12,13,13,14,14,15,15,15,15,
  139992. };
  139993. static float _vq_quantthresh__8u1__p8_0[] = {
  139994. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  139995. 38.5, 49.5,
  139996. };
  139997. static long _vq_quantmap__8u1__p8_0[] = {
  139998. 9, 7, 5, 3, 1, 0, 2, 4,
  139999. 6, 8, 10,
  140000. };
  140001. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  140002. _vq_quantthresh__8u1__p8_0,
  140003. _vq_quantmap__8u1__p8_0,
  140004. 11,
  140005. 11
  140006. };
  140007. static static_codebook _8u1__p8_0 = {
  140008. 2, 121,
  140009. _vq_lengthlist__8u1__p8_0,
  140010. 1, -524582912, 1618345984, 4, 0,
  140011. _vq_quantlist__8u1__p8_0,
  140012. NULL,
  140013. &_vq_auxt__8u1__p8_0,
  140014. NULL,
  140015. 0
  140016. };
  140017. static long _vq_quantlist__8u1__p8_1[] = {
  140018. 5,
  140019. 4,
  140020. 6,
  140021. 3,
  140022. 7,
  140023. 2,
  140024. 8,
  140025. 1,
  140026. 9,
  140027. 0,
  140028. 10,
  140029. };
  140030. static long _vq_lengthlist__8u1__p8_1[] = {
  140031. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  140032. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  140033. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  140034. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  140035. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140036. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  140037. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  140038. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  140039. };
  140040. static float _vq_quantthresh__8u1__p8_1[] = {
  140041. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140042. 3.5, 4.5,
  140043. };
  140044. static long _vq_quantmap__8u1__p8_1[] = {
  140045. 9, 7, 5, 3, 1, 0, 2, 4,
  140046. 6, 8, 10,
  140047. };
  140048. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  140049. _vq_quantthresh__8u1__p8_1,
  140050. _vq_quantmap__8u1__p8_1,
  140051. 11,
  140052. 11
  140053. };
  140054. static static_codebook _8u1__p8_1 = {
  140055. 2, 121,
  140056. _vq_lengthlist__8u1__p8_1,
  140057. 1, -531365888, 1611661312, 4, 0,
  140058. _vq_quantlist__8u1__p8_1,
  140059. NULL,
  140060. &_vq_auxt__8u1__p8_1,
  140061. NULL,
  140062. 0
  140063. };
  140064. static long _vq_quantlist__8u1__p9_0[] = {
  140065. 7,
  140066. 6,
  140067. 8,
  140068. 5,
  140069. 9,
  140070. 4,
  140071. 10,
  140072. 3,
  140073. 11,
  140074. 2,
  140075. 12,
  140076. 1,
  140077. 13,
  140078. 0,
  140079. 14,
  140080. };
  140081. static long _vq_lengthlist__8u1__p9_0[] = {
  140082. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  140083. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  140084. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140085. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140086. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140087. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140088. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140089. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140090. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140091. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140092. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140093. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140094. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  140095. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140096. 10,
  140097. };
  140098. static float _vq_quantthresh__8u1__p9_0[] = {
  140099. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  140100. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  140101. };
  140102. static long _vq_quantmap__8u1__p9_0[] = {
  140103. 13, 11, 9, 7, 5, 3, 1, 0,
  140104. 2, 4, 6, 8, 10, 12, 14,
  140105. };
  140106. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  140107. _vq_quantthresh__8u1__p9_0,
  140108. _vq_quantmap__8u1__p9_0,
  140109. 15,
  140110. 15
  140111. };
  140112. static static_codebook _8u1__p9_0 = {
  140113. 2, 225,
  140114. _vq_lengthlist__8u1__p9_0,
  140115. 1, -514071552, 1627381760, 4, 0,
  140116. _vq_quantlist__8u1__p9_0,
  140117. NULL,
  140118. &_vq_auxt__8u1__p9_0,
  140119. NULL,
  140120. 0
  140121. };
  140122. static long _vq_quantlist__8u1__p9_1[] = {
  140123. 7,
  140124. 6,
  140125. 8,
  140126. 5,
  140127. 9,
  140128. 4,
  140129. 10,
  140130. 3,
  140131. 11,
  140132. 2,
  140133. 12,
  140134. 1,
  140135. 13,
  140136. 0,
  140137. 14,
  140138. };
  140139. static long _vq_lengthlist__8u1__p9_1[] = {
  140140. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  140141. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  140142. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  140143. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  140144. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  140145. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  140146. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  140147. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  140148. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  140149. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  140150. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  140151. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  140152. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  140153. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  140154. 13,
  140155. };
  140156. static float _vq_quantthresh__8u1__p9_1[] = {
  140157. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  140158. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  140159. };
  140160. static long _vq_quantmap__8u1__p9_1[] = {
  140161. 13, 11, 9, 7, 5, 3, 1, 0,
  140162. 2, 4, 6, 8, 10, 12, 14,
  140163. };
  140164. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  140165. _vq_quantthresh__8u1__p9_1,
  140166. _vq_quantmap__8u1__p9_1,
  140167. 15,
  140168. 15
  140169. };
  140170. static static_codebook _8u1__p9_1 = {
  140171. 2, 225,
  140172. _vq_lengthlist__8u1__p9_1,
  140173. 1, -522338304, 1620115456, 4, 0,
  140174. _vq_quantlist__8u1__p9_1,
  140175. NULL,
  140176. &_vq_auxt__8u1__p9_1,
  140177. NULL,
  140178. 0
  140179. };
  140180. static long _vq_quantlist__8u1__p9_2[] = {
  140181. 8,
  140182. 7,
  140183. 9,
  140184. 6,
  140185. 10,
  140186. 5,
  140187. 11,
  140188. 4,
  140189. 12,
  140190. 3,
  140191. 13,
  140192. 2,
  140193. 14,
  140194. 1,
  140195. 15,
  140196. 0,
  140197. 16,
  140198. };
  140199. static long _vq_lengthlist__8u1__p9_2[] = {
  140200. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  140201. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  140202. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  140203. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  140204. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140205. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  140206. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140207. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  140208. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  140209. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  140210. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  140211. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  140212. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  140213. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  140214. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  140215. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  140216. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140217. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140218. 10,
  140219. };
  140220. static float _vq_quantthresh__8u1__p9_2[] = {
  140221. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140222. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140223. };
  140224. static long _vq_quantmap__8u1__p9_2[] = {
  140225. 15, 13, 11, 9, 7, 5, 3, 1,
  140226. 0, 2, 4, 6, 8, 10, 12, 14,
  140227. 16,
  140228. };
  140229. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  140230. _vq_quantthresh__8u1__p9_2,
  140231. _vq_quantmap__8u1__p9_2,
  140232. 17,
  140233. 17
  140234. };
  140235. static static_codebook _8u1__p9_2 = {
  140236. 2, 289,
  140237. _vq_lengthlist__8u1__p9_2,
  140238. 1, -529530880, 1611661312, 5, 0,
  140239. _vq_quantlist__8u1__p9_2,
  140240. NULL,
  140241. &_vq_auxt__8u1__p9_2,
  140242. NULL,
  140243. 0
  140244. };
  140245. static long _huff_lengthlist__8u1__single[] = {
  140246. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  140247. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  140248. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  140249. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  140250. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  140251. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  140252. 13, 8, 8,15,
  140253. };
  140254. static static_codebook _huff_book__8u1__single = {
  140255. 2, 100,
  140256. _huff_lengthlist__8u1__single,
  140257. 0, 0, 0, 0, 0,
  140258. NULL,
  140259. NULL,
  140260. NULL,
  140261. NULL,
  140262. 0
  140263. };
  140264. static long _huff_lengthlist__44u0__long[] = {
  140265. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  140266. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  140267. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  140268. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  140269. };
  140270. static static_codebook _huff_book__44u0__long = {
  140271. 2, 64,
  140272. _huff_lengthlist__44u0__long,
  140273. 0, 0, 0, 0, 0,
  140274. NULL,
  140275. NULL,
  140276. NULL,
  140277. NULL,
  140278. 0
  140279. };
  140280. static long _vq_quantlist__44u0__p1_0[] = {
  140281. 1,
  140282. 0,
  140283. 2,
  140284. };
  140285. static long _vq_lengthlist__44u0__p1_0[] = {
  140286. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  140287. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  140288. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  140289. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  140290. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  140291. 13,
  140292. };
  140293. static float _vq_quantthresh__44u0__p1_0[] = {
  140294. -0.5, 0.5,
  140295. };
  140296. static long _vq_quantmap__44u0__p1_0[] = {
  140297. 1, 0, 2,
  140298. };
  140299. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  140300. _vq_quantthresh__44u0__p1_0,
  140301. _vq_quantmap__44u0__p1_0,
  140302. 3,
  140303. 3
  140304. };
  140305. static static_codebook _44u0__p1_0 = {
  140306. 4, 81,
  140307. _vq_lengthlist__44u0__p1_0,
  140308. 1, -535822336, 1611661312, 2, 0,
  140309. _vq_quantlist__44u0__p1_0,
  140310. NULL,
  140311. &_vq_auxt__44u0__p1_0,
  140312. NULL,
  140313. 0
  140314. };
  140315. static long _vq_quantlist__44u0__p2_0[] = {
  140316. 1,
  140317. 0,
  140318. 2,
  140319. };
  140320. static long _vq_lengthlist__44u0__p2_0[] = {
  140321. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  140322. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  140323. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  140324. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  140325. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  140326. 9,
  140327. };
  140328. static float _vq_quantthresh__44u0__p2_0[] = {
  140329. -0.5, 0.5,
  140330. };
  140331. static long _vq_quantmap__44u0__p2_0[] = {
  140332. 1, 0, 2,
  140333. };
  140334. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  140335. _vq_quantthresh__44u0__p2_0,
  140336. _vq_quantmap__44u0__p2_0,
  140337. 3,
  140338. 3
  140339. };
  140340. static static_codebook _44u0__p2_0 = {
  140341. 4, 81,
  140342. _vq_lengthlist__44u0__p2_0,
  140343. 1, -535822336, 1611661312, 2, 0,
  140344. _vq_quantlist__44u0__p2_0,
  140345. NULL,
  140346. &_vq_auxt__44u0__p2_0,
  140347. NULL,
  140348. 0
  140349. };
  140350. static long _vq_quantlist__44u0__p3_0[] = {
  140351. 2,
  140352. 1,
  140353. 3,
  140354. 0,
  140355. 4,
  140356. };
  140357. static long _vq_lengthlist__44u0__p3_0[] = {
  140358. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  140359. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  140360. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  140361. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  140362. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  140363. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  140364. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  140365. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  140366. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  140367. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  140368. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  140369. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  140370. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  140371. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  140372. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  140373. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  140374. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  140375. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  140376. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  140377. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  140378. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  140379. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  140380. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  140381. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  140382. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  140383. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  140384. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  140385. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  140386. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  140387. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  140388. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  140389. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  140390. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  140391. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  140392. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  140393. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  140394. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  140395. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  140396. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  140397. 19,
  140398. };
  140399. static float _vq_quantthresh__44u0__p3_0[] = {
  140400. -1.5, -0.5, 0.5, 1.5,
  140401. };
  140402. static long _vq_quantmap__44u0__p3_0[] = {
  140403. 3, 1, 0, 2, 4,
  140404. };
  140405. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  140406. _vq_quantthresh__44u0__p3_0,
  140407. _vq_quantmap__44u0__p3_0,
  140408. 5,
  140409. 5
  140410. };
  140411. static static_codebook _44u0__p3_0 = {
  140412. 4, 625,
  140413. _vq_lengthlist__44u0__p3_0,
  140414. 1, -533725184, 1611661312, 3, 0,
  140415. _vq_quantlist__44u0__p3_0,
  140416. NULL,
  140417. &_vq_auxt__44u0__p3_0,
  140418. NULL,
  140419. 0
  140420. };
  140421. static long _vq_quantlist__44u0__p4_0[] = {
  140422. 2,
  140423. 1,
  140424. 3,
  140425. 0,
  140426. 4,
  140427. };
  140428. static long _vq_lengthlist__44u0__p4_0[] = {
  140429. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  140430. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  140431. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  140432. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  140433. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  140434. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  140435. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  140436. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  140437. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  140438. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  140439. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  140440. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  140441. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  140442. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  140443. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  140444. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  140445. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  140446. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  140447. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  140448. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  140449. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  140450. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  140451. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  140452. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  140453. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  140454. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  140455. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  140456. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  140457. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  140458. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  140459. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  140460. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  140461. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  140462. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  140463. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  140464. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  140465. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  140466. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  140467. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  140468. 12,
  140469. };
  140470. static float _vq_quantthresh__44u0__p4_0[] = {
  140471. -1.5, -0.5, 0.5, 1.5,
  140472. };
  140473. static long _vq_quantmap__44u0__p4_0[] = {
  140474. 3, 1, 0, 2, 4,
  140475. };
  140476. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  140477. _vq_quantthresh__44u0__p4_0,
  140478. _vq_quantmap__44u0__p4_0,
  140479. 5,
  140480. 5
  140481. };
  140482. static static_codebook _44u0__p4_0 = {
  140483. 4, 625,
  140484. _vq_lengthlist__44u0__p4_0,
  140485. 1, -533725184, 1611661312, 3, 0,
  140486. _vq_quantlist__44u0__p4_0,
  140487. NULL,
  140488. &_vq_auxt__44u0__p4_0,
  140489. NULL,
  140490. 0
  140491. };
  140492. static long _vq_quantlist__44u0__p5_0[] = {
  140493. 4,
  140494. 3,
  140495. 5,
  140496. 2,
  140497. 6,
  140498. 1,
  140499. 7,
  140500. 0,
  140501. 8,
  140502. };
  140503. static long _vq_lengthlist__44u0__p5_0[] = {
  140504. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  140505. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  140506. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  140507. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  140508. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  140509. 12,
  140510. };
  140511. static float _vq_quantthresh__44u0__p5_0[] = {
  140512. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140513. };
  140514. static long _vq_quantmap__44u0__p5_0[] = {
  140515. 7, 5, 3, 1, 0, 2, 4, 6,
  140516. 8,
  140517. };
  140518. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  140519. _vq_quantthresh__44u0__p5_0,
  140520. _vq_quantmap__44u0__p5_0,
  140521. 9,
  140522. 9
  140523. };
  140524. static static_codebook _44u0__p5_0 = {
  140525. 2, 81,
  140526. _vq_lengthlist__44u0__p5_0,
  140527. 1, -531628032, 1611661312, 4, 0,
  140528. _vq_quantlist__44u0__p5_0,
  140529. NULL,
  140530. &_vq_auxt__44u0__p5_0,
  140531. NULL,
  140532. 0
  140533. };
  140534. static long _vq_quantlist__44u0__p6_0[] = {
  140535. 6,
  140536. 5,
  140537. 7,
  140538. 4,
  140539. 8,
  140540. 3,
  140541. 9,
  140542. 2,
  140543. 10,
  140544. 1,
  140545. 11,
  140546. 0,
  140547. 12,
  140548. };
  140549. static long _vq_lengthlist__44u0__p6_0[] = {
  140550. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  140551. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  140552. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  140553. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  140554. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  140555. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  140556. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  140557. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  140558. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  140559. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  140560. 15,17,16,17,18,17,17,18, 0,
  140561. };
  140562. static float _vq_quantthresh__44u0__p6_0[] = {
  140563. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140564. 12.5, 17.5, 22.5, 27.5,
  140565. };
  140566. static long _vq_quantmap__44u0__p6_0[] = {
  140567. 11, 9, 7, 5, 3, 1, 0, 2,
  140568. 4, 6, 8, 10, 12,
  140569. };
  140570. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  140571. _vq_quantthresh__44u0__p6_0,
  140572. _vq_quantmap__44u0__p6_0,
  140573. 13,
  140574. 13
  140575. };
  140576. static static_codebook _44u0__p6_0 = {
  140577. 2, 169,
  140578. _vq_lengthlist__44u0__p6_0,
  140579. 1, -526516224, 1616117760, 4, 0,
  140580. _vq_quantlist__44u0__p6_0,
  140581. NULL,
  140582. &_vq_auxt__44u0__p6_0,
  140583. NULL,
  140584. 0
  140585. };
  140586. static long _vq_quantlist__44u0__p6_1[] = {
  140587. 2,
  140588. 1,
  140589. 3,
  140590. 0,
  140591. 4,
  140592. };
  140593. static long _vq_lengthlist__44u0__p6_1[] = {
  140594. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  140595. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  140596. };
  140597. static float _vq_quantthresh__44u0__p6_1[] = {
  140598. -1.5, -0.5, 0.5, 1.5,
  140599. };
  140600. static long _vq_quantmap__44u0__p6_1[] = {
  140601. 3, 1, 0, 2, 4,
  140602. };
  140603. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  140604. _vq_quantthresh__44u0__p6_1,
  140605. _vq_quantmap__44u0__p6_1,
  140606. 5,
  140607. 5
  140608. };
  140609. static static_codebook _44u0__p6_1 = {
  140610. 2, 25,
  140611. _vq_lengthlist__44u0__p6_1,
  140612. 1, -533725184, 1611661312, 3, 0,
  140613. _vq_quantlist__44u0__p6_1,
  140614. NULL,
  140615. &_vq_auxt__44u0__p6_1,
  140616. NULL,
  140617. 0
  140618. };
  140619. static long _vq_quantlist__44u0__p7_0[] = {
  140620. 2,
  140621. 1,
  140622. 3,
  140623. 0,
  140624. 4,
  140625. };
  140626. static long _vq_lengthlist__44u0__p7_0[] = {
  140627. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  140628. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140629. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140630. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140631. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140632. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140633. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140634. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  140635. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140636. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140637. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140638. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140639. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140640. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140641. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140642. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140643. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140644. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140645. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140646. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140647. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140648. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140649. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140650. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140651. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140652. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140653. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140654. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140655. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140656. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140657. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  140658. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140659. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140660. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140661. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140662. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140663. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140664. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140665. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140666. 10,
  140667. };
  140668. static float _vq_quantthresh__44u0__p7_0[] = {
  140669. -253.5, -84.5, 84.5, 253.5,
  140670. };
  140671. static long _vq_quantmap__44u0__p7_0[] = {
  140672. 3, 1, 0, 2, 4,
  140673. };
  140674. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  140675. _vq_quantthresh__44u0__p7_0,
  140676. _vq_quantmap__44u0__p7_0,
  140677. 5,
  140678. 5
  140679. };
  140680. static static_codebook _44u0__p7_0 = {
  140681. 4, 625,
  140682. _vq_lengthlist__44u0__p7_0,
  140683. 1, -518709248, 1626677248, 3, 0,
  140684. _vq_quantlist__44u0__p7_0,
  140685. NULL,
  140686. &_vq_auxt__44u0__p7_0,
  140687. NULL,
  140688. 0
  140689. };
  140690. static long _vq_quantlist__44u0__p7_1[] = {
  140691. 6,
  140692. 5,
  140693. 7,
  140694. 4,
  140695. 8,
  140696. 3,
  140697. 9,
  140698. 2,
  140699. 10,
  140700. 1,
  140701. 11,
  140702. 0,
  140703. 12,
  140704. };
  140705. static long _vq_lengthlist__44u0__p7_1[] = {
  140706. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  140707. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  140708. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  140709. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  140710. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  140711. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  140712. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  140713. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  140714. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  140715. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  140716. 15,15,15,15,15,15,15,15,15,
  140717. };
  140718. static float _vq_quantthresh__44u0__p7_1[] = {
  140719. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  140720. 32.5, 45.5, 58.5, 71.5,
  140721. };
  140722. static long _vq_quantmap__44u0__p7_1[] = {
  140723. 11, 9, 7, 5, 3, 1, 0, 2,
  140724. 4, 6, 8, 10, 12,
  140725. };
  140726. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  140727. _vq_quantthresh__44u0__p7_1,
  140728. _vq_quantmap__44u0__p7_1,
  140729. 13,
  140730. 13
  140731. };
  140732. static static_codebook _44u0__p7_1 = {
  140733. 2, 169,
  140734. _vq_lengthlist__44u0__p7_1,
  140735. 1, -523010048, 1618608128, 4, 0,
  140736. _vq_quantlist__44u0__p7_1,
  140737. NULL,
  140738. &_vq_auxt__44u0__p7_1,
  140739. NULL,
  140740. 0
  140741. };
  140742. static long _vq_quantlist__44u0__p7_2[] = {
  140743. 6,
  140744. 5,
  140745. 7,
  140746. 4,
  140747. 8,
  140748. 3,
  140749. 9,
  140750. 2,
  140751. 10,
  140752. 1,
  140753. 11,
  140754. 0,
  140755. 12,
  140756. };
  140757. static long _vq_lengthlist__44u0__p7_2[] = {
  140758. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  140759. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  140760. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  140761. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  140762. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  140763. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  140764. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  140765. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140766. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140767. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  140768. 9, 9, 9,10, 9, 9,10,10, 9,
  140769. };
  140770. static float _vq_quantthresh__44u0__p7_2[] = {
  140771. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  140772. 2.5, 3.5, 4.5, 5.5,
  140773. };
  140774. static long _vq_quantmap__44u0__p7_2[] = {
  140775. 11, 9, 7, 5, 3, 1, 0, 2,
  140776. 4, 6, 8, 10, 12,
  140777. };
  140778. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  140779. _vq_quantthresh__44u0__p7_2,
  140780. _vq_quantmap__44u0__p7_2,
  140781. 13,
  140782. 13
  140783. };
  140784. static static_codebook _44u0__p7_2 = {
  140785. 2, 169,
  140786. _vq_lengthlist__44u0__p7_2,
  140787. 1, -531103744, 1611661312, 4, 0,
  140788. _vq_quantlist__44u0__p7_2,
  140789. NULL,
  140790. &_vq_auxt__44u0__p7_2,
  140791. NULL,
  140792. 0
  140793. };
  140794. static long _huff_lengthlist__44u0__short[] = {
  140795. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  140796. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  140797. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  140798. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  140799. };
  140800. static static_codebook _huff_book__44u0__short = {
  140801. 2, 64,
  140802. _huff_lengthlist__44u0__short,
  140803. 0, 0, 0, 0, 0,
  140804. NULL,
  140805. NULL,
  140806. NULL,
  140807. NULL,
  140808. 0
  140809. };
  140810. static long _huff_lengthlist__44u1__long[] = {
  140811. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  140812. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  140813. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  140814. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  140815. };
  140816. static static_codebook _huff_book__44u1__long = {
  140817. 2, 64,
  140818. _huff_lengthlist__44u1__long,
  140819. 0, 0, 0, 0, 0,
  140820. NULL,
  140821. NULL,
  140822. NULL,
  140823. NULL,
  140824. 0
  140825. };
  140826. static long _vq_quantlist__44u1__p1_0[] = {
  140827. 1,
  140828. 0,
  140829. 2,
  140830. };
  140831. static long _vq_lengthlist__44u1__p1_0[] = {
  140832. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  140833. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  140834. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  140835. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  140836. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  140837. 13,
  140838. };
  140839. static float _vq_quantthresh__44u1__p1_0[] = {
  140840. -0.5, 0.5,
  140841. };
  140842. static long _vq_quantmap__44u1__p1_0[] = {
  140843. 1, 0, 2,
  140844. };
  140845. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  140846. _vq_quantthresh__44u1__p1_0,
  140847. _vq_quantmap__44u1__p1_0,
  140848. 3,
  140849. 3
  140850. };
  140851. static static_codebook _44u1__p1_0 = {
  140852. 4, 81,
  140853. _vq_lengthlist__44u1__p1_0,
  140854. 1, -535822336, 1611661312, 2, 0,
  140855. _vq_quantlist__44u1__p1_0,
  140856. NULL,
  140857. &_vq_auxt__44u1__p1_0,
  140858. NULL,
  140859. 0
  140860. };
  140861. static long _vq_quantlist__44u1__p2_0[] = {
  140862. 1,
  140863. 0,
  140864. 2,
  140865. };
  140866. static long _vq_lengthlist__44u1__p2_0[] = {
  140867. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  140868. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  140869. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  140870. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  140871. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  140872. 9,
  140873. };
  140874. static float _vq_quantthresh__44u1__p2_0[] = {
  140875. -0.5, 0.5,
  140876. };
  140877. static long _vq_quantmap__44u1__p2_0[] = {
  140878. 1, 0, 2,
  140879. };
  140880. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  140881. _vq_quantthresh__44u1__p2_0,
  140882. _vq_quantmap__44u1__p2_0,
  140883. 3,
  140884. 3
  140885. };
  140886. static static_codebook _44u1__p2_0 = {
  140887. 4, 81,
  140888. _vq_lengthlist__44u1__p2_0,
  140889. 1, -535822336, 1611661312, 2, 0,
  140890. _vq_quantlist__44u1__p2_0,
  140891. NULL,
  140892. &_vq_auxt__44u1__p2_0,
  140893. NULL,
  140894. 0
  140895. };
  140896. static long _vq_quantlist__44u1__p3_0[] = {
  140897. 2,
  140898. 1,
  140899. 3,
  140900. 0,
  140901. 4,
  140902. };
  140903. static long _vq_lengthlist__44u1__p3_0[] = {
  140904. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  140905. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  140906. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  140907. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  140908. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  140909. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  140910. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  140911. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  140912. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  140913. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  140914. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  140915. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  140916. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  140917. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  140918. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  140919. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  140920. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  140921. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  140922. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  140923. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  140924. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  140925. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  140926. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  140927. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  140928. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  140929. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  140930. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  140931. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  140932. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  140933. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  140934. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  140935. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  140936. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  140937. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  140938. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  140939. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  140940. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  140941. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  140942. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  140943. 19,
  140944. };
  140945. static float _vq_quantthresh__44u1__p3_0[] = {
  140946. -1.5, -0.5, 0.5, 1.5,
  140947. };
  140948. static long _vq_quantmap__44u1__p3_0[] = {
  140949. 3, 1, 0, 2, 4,
  140950. };
  140951. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  140952. _vq_quantthresh__44u1__p3_0,
  140953. _vq_quantmap__44u1__p3_0,
  140954. 5,
  140955. 5
  140956. };
  140957. static static_codebook _44u1__p3_0 = {
  140958. 4, 625,
  140959. _vq_lengthlist__44u1__p3_0,
  140960. 1, -533725184, 1611661312, 3, 0,
  140961. _vq_quantlist__44u1__p3_0,
  140962. NULL,
  140963. &_vq_auxt__44u1__p3_0,
  140964. NULL,
  140965. 0
  140966. };
  140967. static long _vq_quantlist__44u1__p4_0[] = {
  140968. 2,
  140969. 1,
  140970. 3,
  140971. 0,
  140972. 4,
  140973. };
  140974. static long _vq_lengthlist__44u1__p4_0[] = {
  140975. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  140976. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  140977. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  140978. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  140979. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  140980. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  140981. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  140982. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  140983. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  140984. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  140985. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  140986. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  140987. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  140988. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  140989. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  140990. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  140991. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  140992. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  140993. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  140994. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  140995. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  140996. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  140997. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  140998. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  140999. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  141000. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  141001. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  141002. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  141003. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  141004. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  141005. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  141006. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  141007. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  141008. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  141009. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  141010. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  141011. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  141012. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  141013. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  141014. 12,
  141015. };
  141016. static float _vq_quantthresh__44u1__p4_0[] = {
  141017. -1.5, -0.5, 0.5, 1.5,
  141018. };
  141019. static long _vq_quantmap__44u1__p4_0[] = {
  141020. 3, 1, 0, 2, 4,
  141021. };
  141022. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  141023. _vq_quantthresh__44u1__p4_0,
  141024. _vq_quantmap__44u1__p4_0,
  141025. 5,
  141026. 5
  141027. };
  141028. static static_codebook _44u1__p4_0 = {
  141029. 4, 625,
  141030. _vq_lengthlist__44u1__p4_0,
  141031. 1, -533725184, 1611661312, 3, 0,
  141032. _vq_quantlist__44u1__p4_0,
  141033. NULL,
  141034. &_vq_auxt__44u1__p4_0,
  141035. NULL,
  141036. 0
  141037. };
  141038. static long _vq_quantlist__44u1__p5_0[] = {
  141039. 4,
  141040. 3,
  141041. 5,
  141042. 2,
  141043. 6,
  141044. 1,
  141045. 7,
  141046. 0,
  141047. 8,
  141048. };
  141049. static long _vq_lengthlist__44u1__p5_0[] = {
  141050. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  141051. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  141052. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  141053. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  141054. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  141055. 12,
  141056. };
  141057. static float _vq_quantthresh__44u1__p5_0[] = {
  141058. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141059. };
  141060. static long _vq_quantmap__44u1__p5_0[] = {
  141061. 7, 5, 3, 1, 0, 2, 4, 6,
  141062. 8,
  141063. };
  141064. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  141065. _vq_quantthresh__44u1__p5_0,
  141066. _vq_quantmap__44u1__p5_0,
  141067. 9,
  141068. 9
  141069. };
  141070. static static_codebook _44u1__p5_0 = {
  141071. 2, 81,
  141072. _vq_lengthlist__44u1__p5_0,
  141073. 1, -531628032, 1611661312, 4, 0,
  141074. _vq_quantlist__44u1__p5_0,
  141075. NULL,
  141076. &_vq_auxt__44u1__p5_0,
  141077. NULL,
  141078. 0
  141079. };
  141080. static long _vq_quantlist__44u1__p6_0[] = {
  141081. 6,
  141082. 5,
  141083. 7,
  141084. 4,
  141085. 8,
  141086. 3,
  141087. 9,
  141088. 2,
  141089. 10,
  141090. 1,
  141091. 11,
  141092. 0,
  141093. 12,
  141094. };
  141095. static long _vq_lengthlist__44u1__p6_0[] = {
  141096. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  141097. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  141098. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  141099. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  141100. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  141101. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  141102. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  141103. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  141104. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  141105. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  141106. 15,17,16,17,18,17,17,18, 0,
  141107. };
  141108. static float _vq_quantthresh__44u1__p6_0[] = {
  141109. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141110. 12.5, 17.5, 22.5, 27.5,
  141111. };
  141112. static long _vq_quantmap__44u1__p6_0[] = {
  141113. 11, 9, 7, 5, 3, 1, 0, 2,
  141114. 4, 6, 8, 10, 12,
  141115. };
  141116. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  141117. _vq_quantthresh__44u1__p6_0,
  141118. _vq_quantmap__44u1__p6_0,
  141119. 13,
  141120. 13
  141121. };
  141122. static static_codebook _44u1__p6_0 = {
  141123. 2, 169,
  141124. _vq_lengthlist__44u1__p6_0,
  141125. 1, -526516224, 1616117760, 4, 0,
  141126. _vq_quantlist__44u1__p6_0,
  141127. NULL,
  141128. &_vq_auxt__44u1__p6_0,
  141129. NULL,
  141130. 0
  141131. };
  141132. static long _vq_quantlist__44u1__p6_1[] = {
  141133. 2,
  141134. 1,
  141135. 3,
  141136. 0,
  141137. 4,
  141138. };
  141139. static long _vq_lengthlist__44u1__p6_1[] = {
  141140. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  141141. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  141142. };
  141143. static float _vq_quantthresh__44u1__p6_1[] = {
  141144. -1.5, -0.5, 0.5, 1.5,
  141145. };
  141146. static long _vq_quantmap__44u1__p6_1[] = {
  141147. 3, 1, 0, 2, 4,
  141148. };
  141149. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  141150. _vq_quantthresh__44u1__p6_1,
  141151. _vq_quantmap__44u1__p6_1,
  141152. 5,
  141153. 5
  141154. };
  141155. static static_codebook _44u1__p6_1 = {
  141156. 2, 25,
  141157. _vq_lengthlist__44u1__p6_1,
  141158. 1, -533725184, 1611661312, 3, 0,
  141159. _vq_quantlist__44u1__p6_1,
  141160. NULL,
  141161. &_vq_auxt__44u1__p6_1,
  141162. NULL,
  141163. 0
  141164. };
  141165. static long _vq_quantlist__44u1__p7_0[] = {
  141166. 3,
  141167. 2,
  141168. 4,
  141169. 1,
  141170. 5,
  141171. 0,
  141172. 6,
  141173. };
  141174. static long _vq_lengthlist__44u1__p7_0[] = {
  141175. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141176. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141177. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141178. 8,
  141179. };
  141180. static float _vq_quantthresh__44u1__p7_0[] = {
  141181. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  141182. };
  141183. static long _vq_quantmap__44u1__p7_0[] = {
  141184. 5, 3, 1, 0, 2, 4, 6,
  141185. };
  141186. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  141187. _vq_quantthresh__44u1__p7_0,
  141188. _vq_quantmap__44u1__p7_0,
  141189. 7,
  141190. 7
  141191. };
  141192. static static_codebook _44u1__p7_0 = {
  141193. 2, 49,
  141194. _vq_lengthlist__44u1__p7_0,
  141195. 1, -518017024, 1626677248, 3, 0,
  141196. _vq_quantlist__44u1__p7_0,
  141197. NULL,
  141198. &_vq_auxt__44u1__p7_0,
  141199. NULL,
  141200. 0
  141201. };
  141202. static long _vq_quantlist__44u1__p7_1[] = {
  141203. 6,
  141204. 5,
  141205. 7,
  141206. 4,
  141207. 8,
  141208. 3,
  141209. 9,
  141210. 2,
  141211. 10,
  141212. 1,
  141213. 11,
  141214. 0,
  141215. 12,
  141216. };
  141217. static long _vq_lengthlist__44u1__p7_1[] = {
  141218. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  141219. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  141220. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  141221. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  141222. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  141223. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  141224. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  141225. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  141226. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  141227. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  141228. 15,15,15,15,15,15,15,15,15,
  141229. };
  141230. static float _vq_quantthresh__44u1__p7_1[] = {
  141231. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  141232. 32.5, 45.5, 58.5, 71.5,
  141233. };
  141234. static long _vq_quantmap__44u1__p7_1[] = {
  141235. 11, 9, 7, 5, 3, 1, 0, 2,
  141236. 4, 6, 8, 10, 12,
  141237. };
  141238. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  141239. _vq_quantthresh__44u1__p7_1,
  141240. _vq_quantmap__44u1__p7_1,
  141241. 13,
  141242. 13
  141243. };
  141244. static static_codebook _44u1__p7_1 = {
  141245. 2, 169,
  141246. _vq_lengthlist__44u1__p7_1,
  141247. 1, -523010048, 1618608128, 4, 0,
  141248. _vq_quantlist__44u1__p7_1,
  141249. NULL,
  141250. &_vq_auxt__44u1__p7_1,
  141251. NULL,
  141252. 0
  141253. };
  141254. static long _vq_quantlist__44u1__p7_2[] = {
  141255. 6,
  141256. 5,
  141257. 7,
  141258. 4,
  141259. 8,
  141260. 3,
  141261. 9,
  141262. 2,
  141263. 10,
  141264. 1,
  141265. 11,
  141266. 0,
  141267. 12,
  141268. };
  141269. static long _vq_lengthlist__44u1__p7_2[] = {
  141270. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  141271. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  141272. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  141273. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  141274. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  141275. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  141276. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  141277. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141278. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141279. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  141280. 9, 9, 9,10, 9, 9,10,10, 9,
  141281. };
  141282. static float _vq_quantthresh__44u1__p7_2[] = {
  141283. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  141284. 2.5, 3.5, 4.5, 5.5,
  141285. };
  141286. static long _vq_quantmap__44u1__p7_2[] = {
  141287. 11, 9, 7, 5, 3, 1, 0, 2,
  141288. 4, 6, 8, 10, 12,
  141289. };
  141290. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  141291. _vq_quantthresh__44u1__p7_2,
  141292. _vq_quantmap__44u1__p7_2,
  141293. 13,
  141294. 13
  141295. };
  141296. static static_codebook _44u1__p7_2 = {
  141297. 2, 169,
  141298. _vq_lengthlist__44u1__p7_2,
  141299. 1, -531103744, 1611661312, 4, 0,
  141300. _vq_quantlist__44u1__p7_2,
  141301. NULL,
  141302. &_vq_auxt__44u1__p7_2,
  141303. NULL,
  141304. 0
  141305. };
  141306. static long _huff_lengthlist__44u1__short[] = {
  141307. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  141308. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  141309. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  141310. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  141311. };
  141312. static static_codebook _huff_book__44u1__short = {
  141313. 2, 64,
  141314. _huff_lengthlist__44u1__short,
  141315. 0, 0, 0, 0, 0,
  141316. NULL,
  141317. NULL,
  141318. NULL,
  141319. NULL,
  141320. 0
  141321. };
  141322. static long _huff_lengthlist__44u2__long[] = {
  141323. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  141324. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  141325. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  141326. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  141327. };
  141328. static static_codebook _huff_book__44u2__long = {
  141329. 2, 64,
  141330. _huff_lengthlist__44u2__long,
  141331. 0, 0, 0, 0, 0,
  141332. NULL,
  141333. NULL,
  141334. NULL,
  141335. NULL,
  141336. 0
  141337. };
  141338. static long _vq_quantlist__44u2__p1_0[] = {
  141339. 1,
  141340. 0,
  141341. 2,
  141342. };
  141343. static long _vq_lengthlist__44u2__p1_0[] = {
  141344. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  141345. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  141346. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  141347. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  141348. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  141349. 13,
  141350. };
  141351. static float _vq_quantthresh__44u2__p1_0[] = {
  141352. -0.5, 0.5,
  141353. };
  141354. static long _vq_quantmap__44u2__p1_0[] = {
  141355. 1, 0, 2,
  141356. };
  141357. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  141358. _vq_quantthresh__44u2__p1_0,
  141359. _vq_quantmap__44u2__p1_0,
  141360. 3,
  141361. 3
  141362. };
  141363. static static_codebook _44u2__p1_0 = {
  141364. 4, 81,
  141365. _vq_lengthlist__44u2__p1_0,
  141366. 1, -535822336, 1611661312, 2, 0,
  141367. _vq_quantlist__44u2__p1_0,
  141368. NULL,
  141369. &_vq_auxt__44u2__p1_0,
  141370. NULL,
  141371. 0
  141372. };
  141373. static long _vq_quantlist__44u2__p2_0[] = {
  141374. 1,
  141375. 0,
  141376. 2,
  141377. };
  141378. static long _vq_lengthlist__44u2__p2_0[] = {
  141379. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  141380. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  141381. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  141382. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  141383. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  141384. 9,
  141385. };
  141386. static float _vq_quantthresh__44u2__p2_0[] = {
  141387. -0.5, 0.5,
  141388. };
  141389. static long _vq_quantmap__44u2__p2_0[] = {
  141390. 1, 0, 2,
  141391. };
  141392. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  141393. _vq_quantthresh__44u2__p2_0,
  141394. _vq_quantmap__44u2__p2_0,
  141395. 3,
  141396. 3
  141397. };
  141398. static static_codebook _44u2__p2_0 = {
  141399. 4, 81,
  141400. _vq_lengthlist__44u2__p2_0,
  141401. 1, -535822336, 1611661312, 2, 0,
  141402. _vq_quantlist__44u2__p2_0,
  141403. NULL,
  141404. &_vq_auxt__44u2__p2_0,
  141405. NULL,
  141406. 0
  141407. };
  141408. static long _vq_quantlist__44u2__p3_0[] = {
  141409. 2,
  141410. 1,
  141411. 3,
  141412. 0,
  141413. 4,
  141414. };
  141415. static long _vq_lengthlist__44u2__p3_0[] = {
  141416. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  141417. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  141418. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  141419. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  141420. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  141421. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  141422. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  141423. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  141424. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  141425. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  141426. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  141427. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  141428. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  141429. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  141430. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  141431. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  141432. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  141433. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  141434. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  141435. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  141436. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  141437. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  141438. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  141439. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  141440. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  141441. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  141442. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  141443. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  141444. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  141445. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  141446. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  141447. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  141448. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  141449. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  141450. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  141451. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  141452. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  141453. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  141454. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  141455. 0,
  141456. };
  141457. static float _vq_quantthresh__44u2__p3_0[] = {
  141458. -1.5, -0.5, 0.5, 1.5,
  141459. };
  141460. static long _vq_quantmap__44u2__p3_0[] = {
  141461. 3, 1, 0, 2, 4,
  141462. };
  141463. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  141464. _vq_quantthresh__44u2__p3_0,
  141465. _vq_quantmap__44u2__p3_0,
  141466. 5,
  141467. 5
  141468. };
  141469. static static_codebook _44u2__p3_0 = {
  141470. 4, 625,
  141471. _vq_lengthlist__44u2__p3_0,
  141472. 1, -533725184, 1611661312, 3, 0,
  141473. _vq_quantlist__44u2__p3_0,
  141474. NULL,
  141475. &_vq_auxt__44u2__p3_0,
  141476. NULL,
  141477. 0
  141478. };
  141479. static long _vq_quantlist__44u2__p4_0[] = {
  141480. 2,
  141481. 1,
  141482. 3,
  141483. 0,
  141484. 4,
  141485. };
  141486. static long _vq_lengthlist__44u2__p4_0[] = {
  141487. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  141488. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  141489. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  141490. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  141491. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  141492. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  141493. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  141494. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  141495. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  141496. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  141497. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  141498. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  141499. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  141500. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  141501. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  141502. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  141503. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  141504. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  141505. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  141506. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  141507. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  141508. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  141509. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  141510. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  141511. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  141512. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  141513. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  141514. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  141515. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  141516. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  141517. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  141518. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  141519. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  141520. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  141521. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  141522. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  141523. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  141524. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  141525. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  141526. 13,
  141527. };
  141528. static float _vq_quantthresh__44u2__p4_0[] = {
  141529. -1.5, -0.5, 0.5, 1.5,
  141530. };
  141531. static long _vq_quantmap__44u2__p4_0[] = {
  141532. 3, 1, 0, 2, 4,
  141533. };
  141534. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  141535. _vq_quantthresh__44u2__p4_0,
  141536. _vq_quantmap__44u2__p4_0,
  141537. 5,
  141538. 5
  141539. };
  141540. static static_codebook _44u2__p4_0 = {
  141541. 4, 625,
  141542. _vq_lengthlist__44u2__p4_0,
  141543. 1, -533725184, 1611661312, 3, 0,
  141544. _vq_quantlist__44u2__p4_0,
  141545. NULL,
  141546. &_vq_auxt__44u2__p4_0,
  141547. NULL,
  141548. 0
  141549. };
  141550. static long _vq_quantlist__44u2__p5_0[] = {
  141551. 4,
  141552. 3,
  141553. 5,
  141554. 2,
  141555. 6,
  141556. 1,
  141557. 7,
  141558. 0,
  141559. 8,
  141560. };
  141561. static long _vq_lengthlist__44u2__p5_0[] = {
  141562. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  141563. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  141564. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  141565. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  141566. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  141567. 13,
  141568. };
  141569. static float _vq_quantthresh__44u2__p5_0[] = {
  141570. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141571. };
  141572. static long _vq_quantmap__44u2__p5_0[] = {
  141573. 7, 5, 3, 1, 0, 2, 4, 6,
  141574. 8,
  141575. };
  141576. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  141577. _vq_quantthresh__44u2__p5_0,
  141578. _vq_quantmap__44u2__p5_0,
  141579. 9,
  141580. 9
  141581. };
  141582. static static_codebook _44u2__p5_0 = {
  141583. 2, 81,
  141584. _vq_lengthlist__44u2__p5_0,
  141585. 1, -531628032, 1611661312, 4, 0,
  141586. _vq_quantlist__44u2__p5_0,
  141587. NULL,
  141588. &_vq_auxt__44u2__p5_0,
  141589. NULL,
  141590. 0
  141591. };
  141592. static long _vq_quantlist__44u2__p6_0[] = {
  141593. 6,
  141594. 5,
  141595. 7,
  141596. 4,
  141597. 8,
  141598. 3,
  141599. 9,
  141600. 2,
  141601. 10,
  141602. 1,
  141603. 11,
  141604. 0,
  141605. 12,
  141606. };
  141607. static long _vq_lengthlist__44u2__p6_0[] = {
  141608. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  141609. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  141610. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  141611. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  141612. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  141613. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  141614. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  141615. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  141616. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  141617. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  141618. 15,17,17,16,18,17,18, 0, 0,
  141619. };
  141620. static float _vq_quantthresh__44u2__p6_0[] = {
  141621. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141622. 12.5, 17.5, 22.5, 27.5,
  141623. };
  141624. static long _vq_quantmap__44u2__p6_0[] = {
  141625. 11, 9, 7, 5, 3, 1, 0, 2,
  141626. 4, 6, 8, 10, 12,
  141627. };
  141628. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  141629. _vq_quantthresh__44u2__p6_0,
  141630. _vq_quantmap__44u2__p6_0,
  141631. 13,
  141632. 13
  141633. };
  141634. static static_codebook _44u2__p6_0 = {
  141635. 2, 169,
  141636. _vq_lengthlist__44u2__p6_0,
  141637. 1, -526516224, 1616117760, 4, 0,
  141638. _vq_quantlist__44u2__p6_0,
  141639. NULL,
  141640. &_vq_auxt__44u2__p6_0,
  141641. NULL,
  141642. 0
  141643. };
  141644. static long _vq_quantlist__44u2__p6_1[] = {
  141645. 2,
  141646. 1,
  141647. 3,
  141648. 0,
  141649. 4,
  141650. };
  141651. static long _vq_lengthlist__44u2__p6_1[] = {
  141652. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  141653. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  141654. };
  141655. static float _vq_quantthresh__44u2__p6_1[] = {
  141656. -1.5, -0.5, 0.5, 1.5,
  141657. };
  141658. static long _vq_quantmap__44u2__p6_1[] = {
  141659. 3, 1, 0, 2, 4,
  141660. };
  141661. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  141662. _vq_quantthresh__44u2__p6_1,
  141663. _vq_quantmap__44u2__p6_1,
  141664. 5,
  141665. 5
  141666. };
  141667. static static_codebook _44u2__p6_1 = {
  141668. 2, 25,
  141669. _vq_lengthlist__44u2__p6_1,
  141670. 1, -533725184, 1611661312, 3, 0,
  141671. _vq_quantlist__44u2__p6_1,
  141672. NULL,
  141673. &_vq_auxt__44u2__p6_1,
  141674. NULL,
  141675. 0
  141676. };
  141677. static long _vq_quantlist__44u2__p7_0[] = {
  141678. 4,
  141679. 3,
  141680. 5,
  141681. 2,
  141682. 6,
  141683. 1,
  141684. 7,
  141685. 0,
  141686. 8,
  141687. };
  141688. static long _vq_lengthlist__44u2__p7_0[] = {
  141689. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  141690. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  141691. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141692. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141693. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141694. 11,
  141695. };
  141696. static float _vq_quantthresh__44u2__p7_0[] = {
  141697. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  141698. };
  141699. static long _vq_quantmap__44u2__p7_0[] = {
  141700. 7, 5, 3, 1, 0, 2, 4, 6,
  141701. 8,
  141702. };
  141703. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  141704. _vq_quantthresh__44u2__p7_0,
  141705. _vq_quantmap__44u2__p7_0,
  141706. 9,
  141707. 9
  141708. };
  141709. static static_codebook _44u2__p7_0 = {
  141710. 2, 81,
  141711. _vq_lengthlist__44u2__p7_0,
  141712. 1, -516612096, 1626677248, 4, 0,
  141713. _vq_quantlist__44u2__p7_0,
  141714. NULL,
  141715. &_vq_auxt__44u2__p7_0,
  141716. NULL,
  141717. 0
  141718. };
  141719. static long _vq_quantlist__44u2__p7_1[] = {
  141720. 6,
  141721. 5,
  141722. 7,
  141723. 4,
  141724. 8,
  141725. 3,
  141726. 9,
  141727. 2,
  141728. 10,
  141729. 1,
  141730. 11,
  141731. 0,
  141732. 12,
  141733. };
  141734. static long _vq_lengthlist__44u2__p7_1[] = {
  141735. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  141736. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  141737. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  141738. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  141739. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  141740. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  141741. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  141742. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  141743. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  141744. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  141745. 14,14,14,17,15,17,17,17,17,
  141746. };
  141747. static float _vq_quantthresh__44u2__p7_1[] = {
  141748. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  141749. 32.5, 45.5, 58.5, 71.5,
  141750. };
  141751. static long _vq_quantmap__44u2__p7_1[] = {
  141752. 11, 9, 7, 5, 3, 1, 0, 2,
  141753. 4, 6, 8, 10, 12,
  141754. };
  141755. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  141756. _vq_quantthresh__44u2__p7_1,
  141757. _vq_quantmap__44u2__p7_1,
  141758. 13,
  141759. 13
  141760. };
  141761. static static_codebook _44u2__p7_1 = {
  141762. 2, 169,
  141763. _vq_lengthlist__44u2__p7_1,
  141764. 1, -523010048, 1618608128, 4, 0,
  141765. _vq_quantlist__44u2__p7_1,
  141766. NULL,
  141767. &_vq_auxt__44u2__p7_1,
  141768. NULL,
  141769. 0
  141770. };
  141771. static long _vq_quantlist__44u2__p7_2[] = {
  141772. 6,
  141773. 5,
  141774. 7,
  141775. 4,
  141776. 8,
  141777. 3,
  141778. 9,
  141779. 2,
  141780. 10,
  141781. 1,
  141782. 11,
  141783. 0,
  141784. 12,
  141785. };
  141786. static long _vq_lengthlist__44u2__p7_2[] = {
  141787. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  141788. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  141789. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  141790. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  141791. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  141792. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  141793. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  141794. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141795. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  141796. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  141797. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141798. };
  141799. static float _vq_quantthresh__44u2__p7_2[] = {
  141800. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  141801. 2.5, 3.5, 4.5, 5.5,
  141802. };
  141803. static long _vq_quantmap__44u2__p7_2[] = {
  141804. 11, 9, 7, 5, 3, 1, 0, 2,
  141805. 4, 6, 8, 10, 12,
  141806. };
  141807. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  141808. _vq_quantthresh__44u2__p7_2,
  141809. _vq_quantmap__44u2__p7_2,
  141810. 13,
  141811. 13
  141812. };
  141813. static static_codebook _44u2__p7_2 = {
  141814. 2, 169,
  141815. _vq_lengthlist__44u2__p7_2,
  141816. 1, -531103744, 1611661312, 4, 0,
  141817. _vq_quantlist__44u2__p7_2,
  141818. NULL,
  141819. &_vq_auxt__44u2__p7_2,
  141820. NULL,
  141821. 0
  141822. };
  141823. static long _huff_lengthlist__44u2__short[] = {
  141824. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  141825. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  141826. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  141827. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  141828. };
  141829. static static_codebook _huff_book__44u2__short = {
  141830. 2, 64,
  141831. _huff_lengthlist__44u2__short,
  141832. 0, 0, 0, 0, 0,
  141833. NULL,
  141834. NULL,
  141835. NULL,
  141836. NULL,
  141837. 0
  141838. };
  141839. static long _huff_lengthlist__44u3__long[] = {
  141840. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  141841. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  141842. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  141843. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  141844. };
  141845. static static_codebook _huff_book__44u3__long = {
  141846. 2, 64,
  141847. _huff_lengthlist__44u3__long,
  141848. 0, 0, 0, 0, 0,
  141849. NULL,
  141850. NULL,
  141851. NULL,
  141852. NULL,
  141853. 0
  141854. };
  141855. static long _vq_quantlist__44u3__p1_0[] = {
  141856. 1,
  141857. 0,
  141858. 2,
  141859. };
  141860. static long _vq_lengthlist__44u3__p1_0[] = {
  141861. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  141862. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  141863. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  141864. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  141865. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  141866. 13,
  141867. };
  141868. static float _vq_quantthresh__44u3__p1_0[] = {
  141869. -0.5, 0.5,
  141870. };
  141871. static long _vq_quantmap__44u3__p1_0[] = {
  141872. 1, 0, 2,
  141873. };
  141874. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  141875. _vq_quantthresh__44u3__p1_0,
  141876. _vq_quantmap__44u3__p1_0,
  141877. 3,
  141878. 3
  141879. };
  141880. static static_codebook _44u3__p1_0 = {
  141881. 4, 81,
  141882. _vq_lengthlist__44u3__p1_0,
  141883. 1, -535822336, 1611661312, 2, 0,
  141884. _vq_quantlist__44u3__p1_0,
  141885. NULL,
  141886. &_vq_auxt__44u3__p1_0,
  141887. NULL,
  141888. 0
  141889. };
  141890. static long _vq_quantlist__44u3__p2_0[] = {
  141891. 1,
  141892. 0,
  141893. 2,
  141894. };
  141895. static long _vq_lengthlist__44u3__p2_0[] = {
  141896. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  141897. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  141898. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  141899. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  141900. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  141901. 9,
  141902. };
  141903. static float _vq_quantthresh__44u3__p2_0[] = {
  141904. -0.5, 0.5,
  141905. };
  141906. static long _vq_quantmap__44u3__p2_0[] = {
  141907. 1, 0, 2,
  141908. };
  141909. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  141910. _vq_quantthresh__44u3__p2_0,
  141911. _vq_quantmap__44u3__p2_0,
  141912. 3,
  141913. 3
  141914. };
  141915. static static_codebook _44u3__p2_0 = {
  141916. 4, 81,
  141917. _vq_lengthlist__44u3__p2_0,
  141918. 1, -535822336, 1611661312, 2, 0,
  141919. _vq_quantlist__44u3__p2_0,
  141920. NULL,
  141921. &_vq_auxt__44u3__p2_0,
  141922. NULL,
  141923. 0
  141924. };
  141925. static long _vq_quantlist__44u3__p3_0[] = {
  141926. 2,
  141927. 1,
  141928. 3,
  141929. 0,
  141930. 4,
  141931. };
  141932. static long _vq_lengthlist__44u3__p3_0[] = {
  141933. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  141934. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  141935. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  141936. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  141937. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  141938. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  141939. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  141940. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  141941. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  141942. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  141943. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  141944. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  141945. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  141946. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  141947. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  141948. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  141949. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  141950. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  141951. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  141952. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  141953. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  141954. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  141955. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  141956. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  141957. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  141958. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  141959. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  141960. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  141961. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  141962. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  141963. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  141964. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  141965. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  141966. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  141967. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  141968. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  141969. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  141970. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  141971. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  141972. 0,
  141973. };
  141974. static float _vq_quantthresh__44u3__p3_0[] = {
  141975. -1.5, -0.5, 0.5, 1.5,
  141976. };
  141977. static long _vq_quantmap__44u3__p3_0[] = {
  141978. 3, 1, 0, 2, 4,
  141979. };
  141980. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  141981. _vq_quantthresh__44u3__p3_0,
  141982. _vq_quantmap__44u3__p3_0,
  141983. 5,
  141984. 5
  141985. };
  141986. static static_codebook _44u3__p3_0 = {
  141987. 4, 625,
  141988. _vq_lengthlist__44u3__p3_0,
  141989. 1, -533725184, 1611661312, 3, 0,
  141990. _vq_quantlist__44u3__p3_0,
  141991. NULL,
  141992. &_vq_auxt__44u3__p3_0,
  141993. NULL,
  141994. 0
  141995. };
  141996. static long _vq_quantlist__44u3__p4_0[] = {
  141997. 2,
  141998. 1,
  141999. 3,
  142000. 0,
  142001. 4,
  142002. };
  142003. static long _vq_lengthlist__44u3__p4_0[] = {
  142004. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  142005. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  142006. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  142007. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  142008. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  142009. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  142010. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  142011. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  142012. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  142013. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  142014. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  142015. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  142016. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  142017. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  142018. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  142019. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  142020. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  142021. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  142022. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  142023. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  142024. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  142025. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  142026. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  142027. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  142028. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  142029. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  142030. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  142031. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  142032. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  142033. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  142034. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  142035. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  142036. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  142037. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  142038. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  142039. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  142040. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  142041. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  142042. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  142043. 13,
  142044. };
  142045. static float _vq_quantthresh__44u3__p4_0[] = {
  142046. -1.5, -0.5, 0.5, 1.5,
  142047. };
  142048. static long _vq_quantmap__44u3__p4_0[] = {
  142049. 3, 1, 0, 2, 4,
  142050. };
  142051. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  142052. _vq_quantthresh__44u3__p4_0,
  142053. _vq_quantmap__44u3__p4_0,
  142054. 5,
  142055. 5
  142056. };
  142057. static static_codebook _44u3__p4_0 = {
  142058. 4, 625,
  142059. _vq_lengthlist__44u3__p4_0,
  142060. 1, -533725184, 1611661312, 3, 0,
  142061. _vq_quantlist__44u3__p4_0,
  142062. NULL,
  142063. &_vq_auxt__44u3__p4_0,
  142064. NULL,
  142065. 0
  142066. };
  142067. static long _vq_quantlist__44u3__p5_0[] = {
  142068. 4,
  142069. 3,
  142070. 5,
  142071. 2,
  142072. 6,
  142073. 1,
  142074. 7,
  142075. 0,
  142076. 8,
  142077. };
  142078. static long _vq_lengthlist__44u3__p5_0[] = {
  142079. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  142080. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  142081. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  142082. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142083. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  142084. 12,
  142085. };
  142086. static float _vq_quantthresh__44u3__p5_0[] = {
  142087. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142088. };
  142089. static long _vq_quantmap__44u3__p5_0[] = {
  142090. 7, 5, 3, 1, 0, 2, 4, 6,
  142091. 8,
  142092. };
  142093. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  142094. _vq_quantthresh__44u3__p5_0,
  142095. _vq_quantmap__44u3__p5_0,
  142096. 9,
  142097. 9
  142098. };
  142099. static static_codebook _44u3__p5_0 = {
  142100. 2, 81,
  142101. _vq_lengthlist__44u3__p5_0,
  142102. 1, -531628032, 1611661312, 4, 0,
  142103. _vq_quantlist__44u3__p5_0,
  142104. NULL,
  142105. &_vq_auxt__44u3__p5_0,
  142106. NULL,
  142107. 0
  142108. };
  142109. static long _vq_quantlist__44u3__p6_0[] = {
  142110. 6,
  142111. 5,
  142112. 7,
  142113. 4,
  142114. 8,
  142115. 3,
  142116. 9,
  142117. 2,
  142118. 10,
  142119. 1,
  142120. 11,
  142121. 0,
  142122. 12,
  142123. };
  142124. static long _vq_lengthlist__44u3__p6_0[] = {
  142125. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  142126. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  142127. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  142128. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  142129. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  142130. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  142131. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  142132. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  142133. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  142134. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  142135. 15,16,16,16,17,18,16,20,18,
  142136. };
  142137. static float _vq_quantthresh__44u3__p6_0[] = {
  142138. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142139. 12.5, 17.5, 22.5, 27.5,
  142140. };
  142141. static long _vq_quantmap__44u3__p6_0[] = {
  142142. 11, 9, 7, 5, 3, 1, 0, 2,
  142143. 4, 6, 8, 10, 12,
  142144. };
  142145. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  142146. _vq_quantthresh__44u3__p6_0,
  142147. _vq_quantmap__44u3__p6_0,
  142148. 13,
  142149. 13
  142150. };
  142151. static static_codebook _44u3__p6_0 = {
  142152. 2, 169,
  142153. _vq_lengthlist__44u3__p6_0,
  142154. 1, -526516224, 1616117760, 4, 0,
  142155. _vq_quantlist__44u3__p6_0,
  142156. NULL,
  142157. &_vq_auxt__44u3__p6_0,
  142158. NULL,
  142159. 0
  142160. };
  142161. static long _vq_quantlist__44u3__p6_1[] = {
  142162. 2,
  142163. 1,
  142164. 3,
  142165. 0,
  142166. 4,
  142167. };
  142168. static long _vq_lengthlist__44u3__p6_1[] = {
  142169. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  142170. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  142171. };
  142172. static float _vq_quantthresh__44u3__p6_1[] = {
  142173. -1.5, -0.5, 0.5, 1.5,
  142174. };
  142175. static long _vq_quantmap__44u3__p6_1[] = {
  142176. 3, 1, 0, 2, 4,
  142177. };
  142178. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  142179. _vq_quantthresh__44u3__p6_1,
  142180. _vq_quantmap__44u3__p6_1,
  142181. 5,
  142182. 5
  142183. };
  142184. static static_codebook _44u3__p6_1 = {
  142185. 2, 25,
  142186. _vq_lengthlist__44u3__p6_1,
  142187. 1, -533725184, 1611661312, 3, 0,
  142188. _vq_quantlist__44u3__p6_1,
  142189. NULL,
  142190. &_vq_auxt__44u3__p6_1,
  142191. NULL,
  142192. 0
  142193. };
  142194. static long _vq_quantlist__44u3__p7_0[] = {
  142195. 4,
  142196. 3,
  142197. 5,
  142198. 2,
  142199. 6,
  142200. 1,
  142201. 7,
  142202. 0,
  142203. 8,
  142204. };
  142205. static long _vq_lengthlist__44u3__p7_0[] = {
  142206. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  142207. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  142208. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142209. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142210. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142211. 9,
  142212. };
  142213. static float _vq_quantthresh__44u3__p7_0[] = {
  142214. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  142215. };
  142216. static long _vq_quantmap__44u3__p7_0[] = {
  142217. 7, 5, 3, 1, 0, 2, 4, 6,
  142218. 8,
  142219. };
  142220. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  142221. _vq_quantthresh__44u3__p7_0,
  142222. _vq_quantmap__44u3__p7_0,
  142223. 9,
  142224. 9
  142225. };
  142226. static static_codebook _44u3__p7_0 = {
  142227. 2, 81,
  142228. _vq_lengthlist__44u3__p7_0,
  142229. 1, -515907584, 1627381760, 4, 0,
  142230. _vq_quantlist__44u3__p7_0,
  142231. NULL,
  142232. &_vq_auxt__44u3__p7_0,
  142233. NULL,
  142234. 0
  142235. };
  142236. static long _vq_quantlist__44u3__p7_1[] = {
  142237. 7,
  142238. 6,
  142239. 8,
  142240. 5,
  142241. 9,
  142242. 4,
  142243. 10,
  142244. 3,
  142245. 11,
  142246. 2,
  142247. 12,
  142248. 1,
  142249. 13,
  142250. 0,
  142251. 14,
  142252. };
  142253. static long _vq_lengthlist__44u3__p7_1[] = {
  142254. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  142255. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  142256. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  142257. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  142258. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  142259. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  142260. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  142261. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  142262. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  142263. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  142264. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  142265. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  142266. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  142267. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  142268. 17,
  142269. };
  142270. static float _vq_quantthresh__44u3__p7_1[] = {
  142271. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  142272. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  142273. };
  142274. static long _vq_quantmap__44u3__p7_1[] = {
  142275. 13, 11, 9, 7, 5, 3, 1, 0,
  142276. 2, 4, 6, 8, 10, 12, 14,
  142277. };
  142278. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  142279. _vq_quantthresh__44u3__p7_1,
  142280. _vq_quantmap__44u3__p7_1,
  142281. 15,
  142282. 15
  142283. };
  142284. static static_codebook _44u3__p7_1 = {
  142285. 2, 225,
  142286. _vq_lengthlist__44u3__p7_1,
  142287. 1, -522338304, 1620115456, 4, 0,
  142288. _vq_quantlist__44u3__p7_1,
  142289. NULL,
  142290. &_vq_auxt__44u3__p7_1,
  142291. NULL,
  142292. 0
  142293. };
  142294. static long _vq_quantlist__44u3__p7_2[] = {
  142295. 8,
  142296. 7,
  142297. 9,
  142298. 6,
  142299. 10,
  142300. 5,
  142301. 11,
  142302. 4,
  142303. 12,
  142304. 3,
  142305. 13,
  142306. 2,
  142307. 14,
  142308. 1,
  142309. 15,
  142310. 0,
  142311. 16,
  142312. };
  142313. static long _vq_lengthlist__44u3__p7_2[] = {
  142314. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142315. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142316. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  142317. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142318. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  142319. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142320. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  142321. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142322. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  142323. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  142324. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  142325. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  142326. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  142327. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  142328. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  142329. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  142330. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142331. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  142332. 11,
  142333. };
  142334. static float _vq_quantthresh__44u3__p7_2[] = {
  142335. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142336. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142337. };
  142338. static long _vq_quantmap__44u3__p7_2[] = {
  142339. 15, 13, 11, 9, 7, 5, 3, 1,
  142340. 0, 2, 4, 6, 8, 10, 12, 14,
  142341. 16,
  142342. };
  142343. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  142344. _vq_quantthresh__44u3__p7_2,
  142345. _vq_quantmap__44u3__p7_2,
  142346. 17,
  142347. 17
  142348. };
  142349. static static_codebook _44u3__p7_2 = {
  142350. 2, 289,
  142351. _vq_lengthlist__44u3__p7_2,
  142352. 1, -529530880, 1611661312, 5, 0,
  142353. _vq_quantlist__44u3__p7_2,
  142354. NULL,
  142355. &_vq_auxt__44u3__p7_2,
  142356. NULL,
  142357. 0
  142358. };
  142359. static long _huff_lengthlist__44u3__short[] = {
  142360. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  142361. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  142362. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  142363. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  142364. };
  142365. static static_codebook _huff_book__44u3__short = {
  142366. 2, 64,
  142367. _huff_lengthlist__44u3__short,
  142368. 0, 0, 0, 0, 0,
  142369. NULL,
  142370. NULL,
  142371. NULL,
  142372. NULL,
  142373. 0
  142374. };
  142375. static long _huff_lengthlist__44u4__long[] = {
  142376. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  142377. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  142378. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  142379. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  142380. };
  142381. static static_codebook _huff_book__44u4__long = {
  142382. 2, 64,
  142383. _huff_lengthlist__44u4__long,
  142384. 0, 0, 0, 0, 0,
  142385. NULL,
  142386. NULL,
  142387. NULL,
  142388. NULL,
  142389. 0
  142390. };
  142391. static long _vq_quantlist__44u4__p1_0[] = {
  142392. 1,
  142393. 0,
  142394. 2,
  142395. };
  142396. static long _vq_lengthlist__44u4__p1_0[] = {
  142397. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  142398. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  142399. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  142400. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  142401. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  142402. 13,
  142403. };
  142404. static float _vq_quantthresh__44u4__p1_0[] = {
  142405. -0.5, 0.5,
  142406. };
  142407. static long _vq_quantmap__44u4__p1_0[] = {
  142408. 1, 0, 2,
  142409. };
  142410. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  142411. _vq_quantthresh__44u4__p1_0,
  142412. _vq_quantmap__44u4__p1_0,
  142413. 3,
  142414. 3
  142415. };
  142416. static static_codebook _44u4__p1_0 = {
  142417. 4, 81,
  142418. _vq_lengthlist__44u4__p1_0,
  142419. 1, -535822336, 1611661312, 2, 0,
  142420. _vq_quantlist__44u4__p1_0,
  142421. NULL,
  142422. &_vq_auxt__44u4__p1_0,
  142423. NULL,
  142424. 0
  142425. };
  142426. static long _vq_quantlist__44u4__p2_0[] = {
  142427. 1,
  142428. 0,
  142429. 2,
  142430. };
  142431. static long _vq_lengthlist__44u4__p2_0[] = {
  142432. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  142433. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  142434. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  142435. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  142436. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  142437. 9,
  142438. };
  142439. static float _vq_quantthresh__44u4__p2_0[] = {
  142440. -0.5, 0.5,
  142441. };
  142442. static long _vq_quantmap__44u4__p2_0[] = {
  142443. 1, 0, 2,
  142444. };
  142445. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  142446. _vq_quantthresh__44u4__p2_0,
  142447. _vq_quantmap__44u4__p2_0,
  142448. 3,
  142449. 3
  142450. };
  142451. static static_codebook _44u4__p2_0 = {
  142452. 4, 81,
  142453. _vq_lengthlist__44u4__p2_0,
  142454. 1, -535822336, 1611661312, 2, 0,
  142455. _vq_quantlist__44u4__p2_0,
  142456. NULL,
  142457. &_vq_auxt__44u4__p2_0,
  142458. NULL,
  142459. 0
  142460. };
  142461. static long _vq_quantlist__44u4__p3_0[] = {
  142462. 2,
  142463. 1,
  142464. 3,
  142465. 0,
  142466. 4,
  142467. };
  142468. static long _vq_lengthlist__44u4__p3_0[] = {
  142469. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  142470. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  142471. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  142472. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  142473. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  142474. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  142475. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  142476. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  142477. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  142478. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  142479. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  142480. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  142481. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  142482. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  142483. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  142484. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  142485. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  142486. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  142487. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  142488. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  142489. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  142490. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  142491. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  142492. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  142493. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  142494. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  142495. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  142496. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  142497. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  142498. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  142499. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  142500. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  142501. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  142502. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  142503. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  142504. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  142505. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  142506. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  142507. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  142508. 0,
  142509. };
  142510. static float _vq_quantthresh__44u4__p3_0[] = {
  142511. -1.5, -0.5, 0.5, 1.5,
  142512. };
  142513. static long _vq_quantmap__44u4__p3_0[] = {
  142514. 3, 1, 0, 2, 4,
  142515. };
  142516. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  142517. _vq_quantthresh__44u4__p3_0,
  142518. _vq_quantmap__44u4__p3_0,
  142519. 5,
  142520. 5
  142521. };
  142522. static static_codebook _44u4__p3_0 = {
  142523. 4, 625,
  142524. _vq_lengthlist__44u4__p3_0,
  142525. 1, -533725184, 1611661312, 3, 0,
  142526. _vq_quantlist__44u4__p3_0,
  142527. NULL,
  142528. &_vq_auxt__44u4__p3_0,
  142529. NULL,
  142530. 0
  142531. };
  142532. static long _vq_quantlist__44u4__p4_0[] = {
  142533. 2,
  142534. 1,
  142535. 3,
  142536. 0,
  142537. 4,
  142538. };
  142539. static long _vq_lengthlist__44u4__p4_0[] = {
  142540. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  142541. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  142542. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  142543. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  142544. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  142545. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  142546. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  142547. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  142548. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  142549. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  142550. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  142551. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  142552. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  142553. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  142554. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  142555. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  142556. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  142557. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  142558. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  142559. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  142560. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  142561. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  142562. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  142563. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  142564. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  142565. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  142566. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  142567. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  142568. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  142569. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  142570. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  142571. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  142572. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  142573. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  142574. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  142575. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  142576. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  142577. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  142578. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  142579. 13,
  142580. };
  142581. static float _vq_quantthresh__44u4__p4_0[] = {
  142582. -1.5, -0.5, 0.5, 1.5,
  142583. };
  142584. static long _vq_quantmap__44u4__p4_0[] = {
  142585. 3, 1, 0, 2, 4,
  142586. };
  142587. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  142588. _vq_quantthresh__44u4__p4_0,
  142589. _vq_quantmap__44u4__p4_0,
  142590. 5,
  142591. 5
  142592. };
  142593. static static_codebook _44u4__p4_0 = {
  142594. 4, 625,
  142595. _vq_lengthlist__44u4__p4_0,
  142596. 1, -533725184, 1611661312, 3, 0,
  142597. _vq_quantlist__44u4__p4_0,
  142598. NULL,
  142599. &_vq_auxt__44u4__p4_0,
  142600. NULL,
  142601. 0
  142602. };
  142603. static long _vq_quantlist__44u4__p5_0[] = {
  142604. 4,
  142605. 3,
  142606. 5,
  142607. 2,
  142608. 6,
  142609. 1,
  142610. 7,
  142611. 0,
  142612. 8,
  142613. };
  142614. static long _vq_lengthlist__44u4__p5_0[] = {
  142615. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  142616. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  142617. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  142618. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142619. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  142620. 12,
  142621. };
  142622. static float _vq_quantthresh__44u4__p5_0[] = {
  142623. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142624. };
  142625. static long _vq_quantmap__44u4__p5_0[] = {
  142626. 7, 5, 3, 1, 0, 2, 4, 6,
  142627. 8,
  142628. };
  142629. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  142630. _vq_quantthresh__44u4__p5_0,
  142631. _vq_quantmap__44u4__p5_0,
  142632. 9,
  142633. 9
  142634. };
  142635. static static_codebook _44u4__p5_0 = {
  142636. 2, 81,
  142637. _vq_lengthlist__44u4__p5_0,
  142638. 1, -531628032, 1611661312, 4, 0,
  142639. _vq_quantlist__44u4__p5_0,
  142640. NULL,
  142641. &_vq_auxt__44u4__p5_0,
  142642. NULL,
  142643. 0
  142644. };
  142645. static long _vq_quantlist__44u4__p6_0[] = {
  142646. 6,
  142647. 5,
  142648. 7,
  142649. 4,
  142650. 8,
  142651. 3,
  142652. 9,
  142653. 2,
  142654. 10,
  142655. 1,
  142656. 11,
  142657. 0,
  142658. 12,
  142659. };
  142660. static long _vq_lengthlist__44u4__p6_0[] = {
  142661. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  142662. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  142663. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  142664. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  142665. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  142666. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  142667. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  142668. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  142669. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  142670. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  142671. 16,16,16,17,17,18,17,20,21,
  142672. };
  142673. static float _vq_quantthresh__44u4__p6_0[] = {
  142674. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142675. 12.5, 17.5, 22.5, 27.5,
  142676. };
  142677. static long _vq_quantmap__44u4__p6_0[] = {
  142678. 11, 9, 7, 5, 3, 1, 0, 2,
  142679. 4, 6, 8, 10, 12,
  142680. };
  142681. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  142682. _vq_quantthresh__44u4__p6_0,
  142683. _vq_quantmap__44u4__p6_0,
  142684. 13,
  142685. 13
  142686. };
  142687. static static_codebook _44u4__p6_0 = {
  142688. 2, 169,
  142689. _vq_lengthlist__44u4__p6_0,
  142690. 1, -526516224, 1616117760, 4, 0,
  142691. _vq_quantlist__44u4__p6_0,
  142692. NULL,
  142693. &_vq_auxt__44u4__p6_0,
  142694. NULL,
  142695. 0
  142696. };
  142697. static long _vq_quantlist__44u4__p6_1[] = {
  142698. 2,
  142699. 1,
  142700. 3,
  142701. 0,
  142702. 4,
  142703. };
  142704. static long _vq_lengthlist__44u4__p6_1[] = {
  142705. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  142706. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  142707. };
  142708. static float _vq_quantthresh__44u4__p6_1[] = {
  142709. -1.5, -0.5, 0.5, 1.5,
  142710. };
  142711. static long _vq_quantmap__44u4__p6_1[] = {
  142712. 3, 1, 0, 2, 4,
  142713. };
  142714. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  142715. _vq_quantthresh__44u4__p6_1,
  142716. _vq_quantmap__44u4__p6_1,
  142717. 5,
  142718. 5
  142719. };
  142720. static static_codebook _44u4__p6_1 = {
  142721. 2, 25,
  142722. _vq_lengthlist__44u4__p6_1,
  142723. 1, -533725184, 1611661312, 3, 0,
  142724. _vq_quantlist__44u4__p6_1,
  142725. NULL,
  142726. &_vq_auxt__44u4__p6_1,
  142727. NULL,
  142728. 0
  142729. };
  142730. static long _vq_quantlist__44u4__p7_0[] = {
  142731. 6,
  142732. 5,
  142733. 7,
  142734. 4,
  142735. 8,
  142736. 3,
  142737. 9,
  142738. 2,
  142739. 10,
  142740. 1,
  142741. 11,
  142742. 0,
  142743. 12,
  142744. };
  142745. static long _vq_lengthlist__44u4__p7_0[] = {
  142746. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  142747. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  142748. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142749. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142750. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142751. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142752. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142753. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142754. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142755. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142756. 11,11,11,11,11,11,11,11,11,
  142757. };
  142758. static float _vq_quantthresh__44u4__p7_0[] = {
  142759. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  142760. 637.5, 892.5, 1147.5, 1402.5,
  142761. };
  142762. static long _vq_quantmap__44u4__p7_0[] = {
  142763. 11, 9, 7, 5, 3, 1, 0, 2,
  142764. 4, 6, 8, 10, 12,
  142765. };
  142766. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  142767. _vq_quantthresh__44u4__p7_0,
  142768. _vq_quantmap__44u4__p7_0,
  142769. 13,
  142770. 13
  142771. };
  142772. static static_codebook _44u4__p7_0 = {
  142773. 2, 169,
  142774. _vq_lengthlist__44u4__p7_0,
  142775. 1, -514332672, 1627381760, 4, 0,
  142776. _vq_quantlist__44u4__p7_0,
  142777. NULL,
  142778. &_vq_auxt__44u4__p7_0,
  142779. NULL,
  142780. 0
  142781. };
  142782. static long _vq_quantlist__44u4__p7_1[] = {
  142783. 7,
  142784. 6,
  142785. 8,
  142786. 5,
  142787. 9,
  142788. 4,
  142789. 10,
  142790. 3,
  142791. 11,
  142792. 2,
  142793. 12,
  142794. 1,
  142795. 13,
  142796. 0,
  142797. 14,
  142798. };
  142799. static long _vq_lengthlist__44u4__p7_1[] = {
  142800. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  142801. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  142802. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  142803. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  142804. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  142805. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  142806. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  142807. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  142808. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  142809. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  142810. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  142811. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  142812. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  142813. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  142814. 16,
  142815. };
  142816. static float _vq_quantthresh__44u4__p7_1[] = {
  142817. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  142818. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  142819. };
  142820. static long _vq_quantmap__44u4__p7_1[] = {
  142821. 13, 11, 9, 7, 5, 3, 1, 0,
  142822. 2, 4, 6, 8, 10, 12, 14,
  142823. };
  142824. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  142825. _vq_quantthresh__44u4__p7_1,
  142826. _vq_quantmap__44u4__p7_1,
  142827. 15,
  142828. 15
  142829. };
  142830. static static_codebook _44u4__p7_1 = {
  142831. 2, 225,
  142832. _vq_lengthlist__44u4__p7_1,
  142833. 1, -522338304, 1620115456, 4, 0,
  142834. _vq_quantlist__44u4__p7_1,
  142835. NULL,
  142836. &_vq_auxt__44u4__p7_1,
  142837. NULL,
  142838. 0
  142839. };
  142840. static long _vq_quantlist__44u4__p7_2[] = {
  142841. 8,
  142842. 7,
  142843. 9,
  142844. 6,
  142845. 10,
  142846. 5,
  142847. 11,
  142848. 4,
  142849. 12,
  142850. 3,
  142851. 13,
  142852. 2,
  142853. 14,
  142854. 1,
  142855. 15,
  142856. 0,
  142857. 16,
  142858. };
  142859. static long _vq_lengthlist__44u4__p7_2[] = {
  142860. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142861. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142862. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142863. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142864. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  142865. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142866. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142867. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  142868. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  142869. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  142870. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  142871. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  142872. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  142873. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  142874. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  142875. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  142876. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142877. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  142878. 10,
  142879. };
  142880. static float _vq_quantthresh__44u4__p7_2[] = {
  142881. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142882. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142883. };
  142884. static long _vq_quantmap__44u4__p7_2[] = {
  142885. 15, 13, 11, 9, 7, 5, 3, 1,
  142886. 0, 2, 4, 6, 8, 10, 12, 14,
  142887. 16,
  142888. };
  142889. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  142890. _vq_quantthresh__44u4__p7_2,
  142891. _vq_quantmap__44u4__p7_2,
  142892. 17,
  142893. 17
  142894. };
  142895. static static_codebook _44u4__p7_2 = {
  142896. 2, 289,
  142897. _vq_lengthlist__44u4__p7_2,
  142898. 1, -529530880, 1611661312, 5, 0,
  142899. _vq_quantlist__44u4__p7_2,
  142900. NULL,
  142901. &_vq_auxt__44u4__p7_2,
  142902. NULL,
  142903. 0
  142904. };
  142905. static long _huff_lengthlist__44u4__short[] = {
  142906. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  142907. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  142908. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  142909. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  142910. };
  142911. static static_codebook _huff_book__44u4__short = {
  142912. 2, 64,
  142913. _huff_lengthlist__44u4__short,
  142914. 0, 0, 0, 0, 0,
  142915. NULL,
  142916. NULL,
  142917. NULL,
  142918. NULL,
  142919. 0
  142920. };
  142921. static long _huff_lengthlist__44u5__long[] = {
  142922. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  142923. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  142924. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  142925. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  142926. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  142927. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  142928. 14, 8, 7, 8,
  142929. };
  142930. static static_codebook _huff_book__44u5__long = {
  142931. 2, 100,
  142932. _huff_lengthlist__44u5__long,
  142933. 0, 0, 0, 0, 0,
  142934. NULL,
  142935. NULL,
  142936. NULL,
  142937. NULL,
  142938. 0
  142939. };
  142940. static long _vq_quantlist__44u5__p1_0[] = {
  142941. 1,
  142942. 0,
  142943. 2,
  142944. };
  142945. static long _vq_lengthlist__44u5__p1_0[] = {
  142946. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  142947. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  142948. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  142949. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  142950. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  142951. 12,
  142952. };
  142953. static float _vq_quantthresh__44u5__p1_0[] = {
  142954. -0.5, 0.5,
  142955. };
  142956. static long _vq_quantmap__44u5__p1_0[] = {
  142957. 1, 0, 2,
  142958. };
  142959. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  142960. _vq_quantthresh__44u5__p1_0,
  142961. _vq_quantmap__44u5__p1_0,
  142962. 3,
  142963. 3
  142964. };
  142965. static static_codebook _44u5__p1_0 = {
  142966. 4, 81,
  142967. _vq_lengthlist__44u5__p1_0,
  142968. 1, -535822336, 1611661312, 2, 0,
  142969. _vq_quantlist__44u5__p1_0,
  142970. NULL,
  142971. &_vq_auxt__44u5__p1_0,
  142972. NULL,
  142973. 0
  142974. };
  142975. static long _vq_quantlist__44u5__p2_0[] = {
  142976. 1,
  142977. 0,
  142978. 2,
  142979. };
  142980. static long _vq_lengthlist__44u5__p2_0[] = {
  142981. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  142982. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  142983. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  142984. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  142985. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  142986. 9,
  142987. };
  142988. static float _vq_quantthresh__44u5__p2_0[] = {
  142989. -0.5, 0.5,
  142990. };
  142991. static long _vq_quantmap__44u5__p2_0[] = {
  142992. 1, 0, 2,
  142993. };
  142994. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  142995. _vq_quantthresh__44u5__p2_0,
  142996. _vq_quantmap__44u5__p2_0,
  142997. 3,
  142998. 3
  142999. };
  143000. static static_codebook _44u5__p2_0 = {
  143001. 4, 81,
  143002. _vq_lengthlist__44u5__p2_0,
  143003. 1, -535822336, 1611661312, 2, 0,
  143004. _vq_quantlist__44u5__p2_0,
  143005. NULL,
  143006. &_vq_auxt__44u5__p2_0,
  143007. NULL,
  143008. 0
  143009. };
  143010. static long _vq_quantlist__44u5__p3_0[] = {
  143011. 2,
  143012. 1,
  143013. 3,
  143014. 0,
  143015. 4,
  143016. };
  143017. static long _vq_lengthlist__44u5__p3_0[] = {
  143018. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  143019. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  143020. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  143021. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  143022. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  143023. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  143024. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  143025. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  143026. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  143027. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  143028. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  143029. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  143030. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  143031. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  143032. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  143033. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  143034. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  143035. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  143036. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  143037. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  143038. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  143039. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  143040. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  143041. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  143042. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  143043. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  143044. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  143045. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  143046. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  143047. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  143048. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  143049. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  143050. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  143051. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  143052. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  143053. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  143054. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  143055. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  143056. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  143057. 0,
  143058. };
  143059. static float _vq_quantthresh__44u5__p3_0[] = {
  143060. -1.5, -0.5, 0.5, 1.5,
  143061. };
  143062. static long _vq_quantmap__44u5__p3_0[] = {
  143063. 3, 1, 0, 2, 4,
  143064. };
  143065. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  143066. _vq_quantthresh__44u5__p3_0,
  143067. _vq_quantmap__44u5__p3_0,
  143068. 5,
  143069. 5
  143070. };
  143071. static static_codebook _44u5__p3_0 = {
  143072. 4, 625,
  143073. _vq_lengthlist__44u5__p3_0,
  143074. 1, -533725184, 1611661312, 3, 0,
  143075. _vq_quantlist__44u5__p3_0,
  143076. NULL,
  143077. &_vq_auxt__44u5__p3_0,
  143078. NULL,
  143079. 0
  143080. };
  143081. static long _vq_quantlist__44u5__p4_0[] = {
  143082. 2,
  143083. 1,
  143084. 3,
  143085. 0,
  143086. 4,
  143087. };
  143088. static long _vq_lengthlist__44u5__p4_0[] = {
  143089. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  143090. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  143091. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  143092. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  143093. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  143094. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  143095. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  143096. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  143097. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  143098. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  143099. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  143100. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143101. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  143102. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  143103. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  143104. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  143105. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  143106. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  143107. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  143108. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  143109. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  143110. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  143111. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  143112. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  143113. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  143114. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  143115. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  143116. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  143117. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  143118. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  143119. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  143120. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  143121. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  143122. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  143123. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  143124. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  143125. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  143126. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  143127. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  143128. 12,
  143129. };
  143130. static float _vq_quantthresh__44u5__p4_0[] = {
  143131. -1.5, -0.5, 0.5, 1.5,
  143132. };
  143133. static long _vq_quantmap__44u5__p4_0[] = {
  143134. 3, 1, 0, 2, 4,
  143135. };
  143136. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  143137. _vq_quantthresh__44u5__p4_0,
  143138. _vq_quantmap__44u5__p4_0,
  143139. 5,
  143140. 5
  143141. };
  143142. static static_codebook _44u5__p4_0 = {
  143143. 4, 625,
  143144. _vq_lengthlist__44u5__p4_0,
  143145. 1, -533725184, 1611661312, 3, 0,
  143146. _vq_quantlist__44u5__p4_0,
  143147. NULL,
  143148. &_vq_auxt__44u5__p4_0,
  143149. NULL,
  143150. 0
  143151. };
  143152. static long _vq_quantlist__44u5__p5_0[] = {
  143153. 4,
  143154. 3,
  143155. 5,
  143156. 2,
  143157. 6,
  143158. 1,
  143159. 7,
  143160. 0,
  143161. 8,
  143162. };
  143163. static long _vq_lengthlist__44u5__p5_0[] = {
  143164. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  143165. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  143166. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  143167. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  143168. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  143169. 14,
  143170. };
  143171. static float _vq_quantthresh__44u5__p5_0[] = {
  143172. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143173. };
  143174. static long _vq_quantmap__44u5__p5_0[] = {
  143175. 7, 5, 3, 1, 0, 2, 4, 6,
  143176. 8,
  143177. };
  143178. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  143179. _vq_quantthresh__44u5__p5_0,
  143180. _vq_quantmap__44u5__p5_0,
  143181. 9,
  143182. 9
  143183. };
  143184. static static_codebook _44u5__p5_0 = {
  143185. 2, 81,
  143186. _vq_lengthlist__44u5__p5_0,
  143187. 1, -531628032, 1611661312, 4, 0,
  143188. _vq_quantlist__44u5__p5_0,
  143189. NULL,
  143190. &_vq_auxt__44u5__p5_0,
  143191. NULL,
  143192. 0
  143193. };
  143194. static long _vq_quantlist__44u5__p6_0[] = {
  143195. 4,
  143196. 3,
  143197. 5,
  143198. 2,
  143199. 6,
  143200. 1,
  143201. 7,
  143202. 0,
  143203. 8,
  143204. };
  143205. static long _vq_lengthlist__44u5__p6_0[] = {
  143206. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  143207. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  143208. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  143209. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  143210. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  143211. 11,
  143212. };
  143213. static float _vq_quantthresh__44u5__p6_0[] = {
  143214. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143215. };
  143216. static long _vq_quantmap__44u5__p6_0[] = {
  143217. 7, 5, 3, 1, 0, 2, 4, 6,
  143218. 8,
  143219. };
  143220. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  143221. _vq_quantthresh__44u5__p6_0,
  143222. _vq_quantmap__44u5__p6_0,
  143223. 9,
  143224. 9
  143225. };
  143226. static static_codebook _44u5__p6_0 = {
  143227. 2, 81,
  143228. _vq_lengthlist__44u5__p6_0,
  143229. 1, -531628032, 1611661312, 4, 0,
  143230. _vq_quantlist__44u5__p6_0,
  143231. NULL,
  143232. &_vq_auxt__44u5__p6_0,
  143233. NULL,
  143234. 0
  143235. };
  143236. static long _vq_quantlist__44u5__p7_0[] = {
  143237. 1,
  143238. 0,
  143239. 2,
  143240. };
  143241. static long _vq_lengthlist__44u5__p7_0[] = {
  143242. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  143243. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  143244. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  143245. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  143246. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  143247. 12,
  143248. };
  143249. static float _vq_quantthresh__44u5__p7_0[] = {
  143250. -5.5, 5.5,
  143251. };
  143252. static long _vq_quantmap__44u5__p7_0[] = {
  143253. 1, 0, 2,
  143254. };
  143255. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  143256. _vq_quantthresh__44u5__p7_0,
  143257. _vq_quantmap__44u5__p7_0,
  143258. 3,
  143259. 3
  143260. };
  143261. static static_codebook _44u5__p7_0 = {
  143262. 4, 81,
  143263. _vq_lengthlist__44u5__p7_0,
  143264. 1, -529137664, 1618345984, 2, 0,
  143265. _vq_quantlist__44u5__p7_0,
  143266. NULL,
  143267. &_vq_auxt__44u5__p7_0,
  143268. NULL,
  143269. 0
  143270. };
  143271. static long _vq_quantlist__44u5__p7_1[] = {
  143272. 5,
  143273. 4,
  143274. 6,
  143275. 3,
  143276. 7,
  143277. 2,
  143278. 8,
  143279. 1,
  143280. 9,
  143281. 0,
  143282. 10,
  143283. };
  143284. static long _vq_lengthlist__44u5__p7_1[] = {
  143285. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  143286. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  143287. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143288. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  143289. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  143290. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  143291. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  143292. 9, 9, 9, 9, 9,10,10,10,10,
  143293. };
  143294. static float _vq_quantthresh__44u5__p7_1[] = {
  143295. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143296. 3.5, 4.5,
  143297. };
  143298. static long _vq_quantmap__44u5__p7_1[] = {
  143299. 9, 7, 5, 3, 1, 0, 2, 4,
  143300. 6, 8, 10,
  143301. };
  143302. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  143303. _vq_quantthresh__44u5__p7_1,
  143304. _vq_quantmap__44u5__p7_1,
  143305. 11,
  143306. 11
  143307. };
  143308. static static_codebook _44u5__p7_1 = {
  143309. 2, 121,
  143310. _vq_lengthlist__44u5__p7_1,
  143311. 1, -531365888, 1611661312, 4, 0,
  143312. _vq_quantlist__44u5__p7_1,
  143313. NULL,
  143314. &_vq_auxt__44u5__p7_1,
  143315. NULL,
  143316. 0
  143317. };
  143318. static long _vq_quantlist__44u5__p8_0[] = {
  143319. 5,
  143320. 4,
  143321. 6,
  143322. 3,
  143323. 7,
  143324. 2,
  143325. 8,
  143326. 1,
  143327. 9,
  143328. 0,
  143329. 10,
  143330. };
  143331. static long _vq_lengthlist__44u5__p8_0[] = {
  143332. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  143333. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  143334. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  143335. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  143336. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  143337. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  143338. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  143339. 12,13,13,14,14,14,14,15,15,
  143340. };
  143341. static float _vq_quantthresh__44u5__p8_0[] = {
  143342. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143343. 38.5, 49.5,
  143344. };
  143345. static long _vq_quantmap__44u5__p8_0[] = {
  143346. 9, 7, 5, 3, 1, 0, 2, 4,
  143347. 6, 8, 10,
  143348. };
  143349. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  143350. _vq_quantthresh__44u5__p8_0,
  143351. _vq_quantmap__44u5__p8_0,
  143352. 11,
  143353. 11
  143354. };
  143355. static static_codebook _44u5__p8_0 = {
  143356. 2, 121,
  143357. _vq_lengthlist__44u5__p8_0,
  143358. 1, -524582912, 1618345984, 4, 0,
  143359. _vq_quantlist__44u5__p8_0,
  143360. NULL,
  143361. &_vq_auxt__44u5__p8_0,
  143362. NULL,
  143363. 0
  143364. };
  143365. static long _vq_quantlist__44u5__p8_1[] = {
  143366. 5,
  143367. 4,
  143368. 6,
  143369. 3,
  143370. 7,
  143371. 2,
  143372. 8,
  143373. 1,
  143374. 9,
  143375. 0,
  143376. 10,
  143377. };
  143378. static long _vq_lengthlist__44u5__p8_1[] = {
  143379. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  143380. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  143381. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  143382. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  143383. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  143384. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  143385. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143386. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143387. };
  143388. static float _vq_quantthresh__44u5__p8_1[] = {
  143389. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143390. 3.5, 4.5,
  143391. };
  143392. static long _vq_quantmap__44u5__p8_1[] = {
  143393. 9, 7, 5, 3, 1, 0, 2, 4,
  143394. 6, 8, 10,
  143395. };
  143396. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  143397. _vq_quantthresh__44u5__p8_1,
  143398. _vq_quantmap__44u5__p8_1,
  143399. 11,
  143400. 11
  143401. };
  143402. static static_codebook _44u5__p8_1 = {
  143403. 2, 121,
  143404. _vq_lengthlist__44u5__p8_1,
  143405. 1, -531365888, 1611661312, 4, 0,
  143406. _vq_quantlist__44u5__p8_1,
  143407. NULL,
  143408. &_vq_auxt__44u5__p8_1,
  143409. NULL,
  143410. 0
  143411. };
  143412. static long _vq_quantlist__44u5__p9_0[] = {
  143413. 6,
  143414. 5,
  143415. 7,
  143416. 4,
  143417. 8,
  143418. 3,
  143419. 9,
  143420. 2,
  143421. 10,
  143422. 1,
  143423. 11,
  143424. 0,
  143425. 12,
  143426. };
  143427. static long _vq_lengthlist__44u5__p9_0[] = {
  143428. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  143429. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  143430. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  143431. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  143432. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  143433. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  143434. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  143435. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  143436. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  143437. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143438. 12,12,12,12,12,12,12,12,12,
  143439. };
  143440. static float _vq_quantthresh__44u5__p9_0[] = {
  143441. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  143442. 637.5, 892.5, 1147.5, 1402.5,
  143443. };
  143444. static long _vq_quantmap__44u5__p9_0[] = {
  143445. 11, 9, 7, 5, 3, 1, 0, 2,
  143446. 4, 6, 8, 10, 12,
  143447. };
  143448. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  143449. _vq_quantthresh__44u5__p9_0,
  143450. _vq_quantmap__44u5__p9_0,
  143451. 13,
  143452. 13
  143453. };
  143454. static static_codebook _44u5__p9_0 = {
  143455. 2, 169,
  143456. _vq_lengthlist__44u5__p9_0,
  143457. 1, -514332672, 1627381760, 4, 0,
  143458. _vq_quantlist__44u5__p9_0,
  143459. NULL,
  143460. &_vq_auxt__44u5__p9_0,
  143461. NULL,
  143462. 0
  143463. };
  143464. static long _vq_quantlist__44u5__p9_1[] = {
  143465. 7,
  143466. 6,
  143467. 8,
  143468. 5,
  143469. 9,
  143470. 4,
  143471. 10,
  143472. 3,
  143473. 11,
  143474. 2,
  143475. 12,
  143476. 1,
  143477. 13,
  143478. 0,
  143479. 14,
  143480. };
  143481. static long _vq_lengthlist__44u5__p9_1[] = {
  143482. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  143483. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  143484. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  143485. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  143486. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  143487. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  143488. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  143489. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  143490. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  143491. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  143492. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  143493. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  143494. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  143495. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  143496. 14,
  143497. };
  143498. static float _vq_quantthresh__44u5__p9_1[] = {
  143499. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143500. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143501. };
  143502. static long _vq_quantmap__44u5__p9_1[] = {
  143503. 13, 11, 9, 7, 5, 3, 1, 0,
  143504. 2, 4, 6, 8, 10, 12, 14,
  143505. };
  143506. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  143507. _vq_quantthresh__44u5__p9_1,
  143508. _vq_quantmap__44u5__p9_1,
  143509. 15,
  143510. 15
  143511. };
  143512. static static_codebook _44u5__p9_1 = {
  143513. 2, 225,
  143514. _vq_lengthlist__44u5__p9_1,
  143515. 1, -522338304, 1620115456, 4, 0,
  143516. _vq_quantlist__44u5__p9_1,
  143517. NULL,
  143518. &_vq_auxt__44u5__p9_1,
  143519. NULL,
  143520. 0
  143521. };
  143522. static long _vq_quantlist__44u5__p9_2[] = {
  143523. 8,
  143524. 7,
  143525. 9,
  143526. 6,
  143527. 10,
  143528. 5,
  143529. 11,
  143530. 4,
  143531. 12,
  143532. 3,
  143533. 13,
  143534. 2,
  143535. 14,
  143536. 1,
  143537. 15,
  143538. 0,
  143539. 16,
  143540. };
  143541. static long _vq_lengthlist__44u5__p9_2[] = {
  143542. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  143543. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  143544. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  143545. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  143546. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  143547. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  143548. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  143549. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143550. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  143551. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  143552. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  143553. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  143554. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  143555. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  143556. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  143557. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  143558. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  143559. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  143560. 10,
  143561. };
  143562. static float _vq_quantthresh__44u5__p9_2[] = {
  143563. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143564. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143565. };
  143566. static long _vq_quantmap__44u5__p9_2[] = {
  143567. 15, 13, 11, 9, 7, 5, 3, 1,
  143568. 0, 2, 4, 6, 8, 10, 12, 14,
  143569. 16,
  143570. };
  143571. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  143572. _vq_quantthresh__44u5__p9_2,
  143573. _vq_quantmap__44u5__p9_2,
  143574. 17,
  143575. 17
  143576. };
  143577. static static_codebook _44u5__p9_2 = {
  143578. 2, 289,
  143579. _vq_lengthlist__44u5__p9_2,
  143580. 1, -529530880, 1611661312, 5, 0,
  143581. _vq_quantlist__44u5__p9_2,
  143582. NULL,
  143583. &_vq_auxt__44u5__p9_2,
  143584. NULL,
  143585. 0
  143586. };
  143587. static long _huff_lengthlist__44u5__short[] = {
  143588. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  143589. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  143590. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  143591. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  143592. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  143593. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  143594. 6, 8,15,17,
  143595. };
  143596. static static_codebook _huff_book__44u5__short = {
  143597. 2, 100,
  143598. _huff_lengthlist__44u5__short,
  143599. 0, 0, 0, 0, 0,
  143600. NULL,
  143601. NULL,
  143602. NULL,
  143603. NULL,
  143604. 0
  143605. };
  143606. static long _huff_lengthlist__44u6__long[] = {
  143607. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  143608. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  143609. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  143610. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  143611. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  143612. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  143613. 13, 8, 7, 7,
  143614. };
  143615. static static_codebook _huff_book__44u6__long = {
  143616. 2, 100,
  143617. _huff_lengthlist__44u6__long,
  143618. 0, 0, 0, 0, 0,
  143619. NULL,
  143620. NULL,
  143621. NULL,
  143622. NULL,
  143623. 0
  143624. };
  143625. static long _vq_quantlist__44u6__p1_0[] = {
  143626. 1,
  143627. 0,
  143628. 2,
  143629. };
  143630. static long _vq_lengthlist__44u6__p1_0[] = {
  143631. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  143632. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  143633. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  143634. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  143635. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  143636. 12,
  143637. };
  143638. static float _vq_quantthresh__44u6__p1_0[] = {
  143639. -0.5, 0.5,
  143640. };
  143641. static long _vq_quantmap__44u6__p1_0[] = {
  143642. 1, 0, 2,
  143643. };
  143644. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  143645. _vq_quantthresh__44u6__p1_0,
  143646. _vq_quantmap__44u6__p1_0,
  143647. 3,
  143648. 3
  143649. };
  143650. static static_codebook _44u6__p1_0 = {
  143651. 4, 81,
  143652. _vq_lengthlist__44u6__p1_0,
  143653. 1, -535822336, 1611661312, 2, 0,
  143654. _vq_quantlist__44u6__p1_0,
  143655. NULL,
  143656. &_vq_auxt__44u6__p1_0,
  143657. NULL,
  143658. 0
  143659. };
  143660. static long _vq_quantlist__44u6__p2_0[] = {
  143661. 1,
  143662. 0,
  143663. 2,
  143664. };
  143665. static long _vq_lengthlist__44u6__p2_0[] = {
  143666. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  143667. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  143668. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  143669. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  143670. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  143671. 9,
  143672. };
  143673. static float _vq_quantthresh__44u6__p2_0[] = {
  143674. -0.5, 0.5,
  143675. };
  143676. static long _vq_quantmap__44u6__p2_0[] = {
  143677. 1, 0, 2,
  143678. };
  143679. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  143680. _vq_quantthresh__44u6__p2_0,
  143681. _vq_quantmap__44u6__p2_0,
  143682. 3,
  143683. 3
  143684. };
  143685. static static_codebook _44u6__p2_0 = {
  143686. 4, 81,
  143687. _vq_lengthlist__44u6__p2_0,
  143688. 1, -535822336, 1611661312, 2, 0,
  143689. _vq_quantlist__44u6__p2_0,
  143690. NULL,
  143691. &_vq_auxt__44u6__p2_0,
  143692. NULL,
  143693. 0
  143694. };
  143695. static long _vq_quantlist__44u6__p3_0[] = {
  143696. 2,
  143697. 1,
  143698. 3,
  143699. 0,
  143700. 4,
  143701. };
  143702. static long _vq_lengthlist__44u6__p3_0[] = {
  143703. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  143704. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  143705. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  143706. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  143707. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  143708. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  143709. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  143710. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  143711. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  143712. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  143713. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  143714. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  143715. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  143716. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  143717. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  143718. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  143719. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  143720. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  143721. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  143722. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  143723. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  143724. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  143725. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  143726. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  143727. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  143728. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  143729. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  143730. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  143731. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  143732. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  143733. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  143734. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  143735. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  143736. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  143737. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  143738. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  143739. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  143740. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  143741. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  143742. 19,
  143743. };
  143744. static float _vq_quantthresh__44u6__p3_0[] = {
  143745. -1.5, -0.5, 0.5, 1.5,
  143746. };
  143747. static long _vq_quantmap__44u6__p3_0[] = {
  143748. 3, 1, 0, 2, 4,
  143749. };
  143750. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  143751. _vq_quantthresh__44u6__p3_0,
  143752. _vq_quantmap__44u6__p3_0,
  143753. 5,
  143754. 5
  143755. };
  143756. static static_codebook _44u6__p3_0 = {
  143757. 4, 625,
  143758. _vq_lengthlist__44u6__p3_0,
  143759. 1, -533725184, 1611661312, 3, 0,
  143760. _vq_quantlist__44u6__p3_0,
  143761. NULL,
  143762. &_vq_auxt__44u6__p3_0,
  143763. NULL,
  143764. 0
  143765. };
  143766. static long _vq_quantlist__44u6__p4_0[] = {
  143767. 2,
  143768. 1,
  143769. 3,
  143770. 0,
  143771. 4,
  143772. };
  143773. static long _vq_lengthlist__44u6__p4_0[] = {
  143774. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  143775. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  143776. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  143777. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  143778. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  143779. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  143780. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  143781. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  143782. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  143783. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  143784. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  143785. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  143786. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  143787. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  143788. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  143789. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  143790. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  143791. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143792. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  143793. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  143794. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  143795. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  143796. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  143797. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  143798. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  143799. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  143800. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  143801. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  143802. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  143803. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  143804. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  143805. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  143806. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  143807. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  143808. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  143809. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  143810. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  143811. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  143812. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  143813. 13,
  143814. };
  143815. static float _vq_quantthresh__44u6__p4_0[] = {
  143816. -1.5, -0.5, 0.5, 1.5,
  143817. };
  143818. static long _vq_quantmap__44u6__p4_0[] = {
  143819. 3, 1, 0, 2, 4,
  143820. };
  143821. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  143822. _vq_quantthresh__44u6__p4_0,
  143823. _vq_quantmap__44u6__p4_0,
  143824. 5,
  143825. 5
  143826. };
  143827. static static_codebook _44u6__p4_0 = {
  143828. 4, 625,
  143829. _vq_lengthlist__44u6__p4_0,
  143830. 1, -533725184, 1611661312, 3, 0,
  143831. _vq_quantlist__44u6__p4_0,
  143832. NULL,
  143833. &_vq_auxt__44u6__p4_0,
  143834. NULL,
  143835. 0
  143836. };
  143837. static long _vq_quantlist__44u6__p5_0[] = {
  143838. 4,
  143839. 3,
  143840. 5,
  143841. 2,
  143842. 6,
  143843. 1,
  143844. 7,
  143845. 0,
  143846. 8,
  143847. };
  143848. static long _vq_lengthlist__44u6__p5_0[] = {
  143849. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  143850. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  143851. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  143852. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  143853. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  143854. 14,
  143855. };
  143856. static float _vq_quantthresh__44u6__p5_0[] = {
  143857. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143858. };
  143859. static long _vq_quantmap__44u6__p5_0[] = {
  143860. 7, 5, 3, 1, 0, 2, 4, 6,
  143861. 8,
  143862. };
  143863. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  143864. _vq_quantthresh__44u6__p5_0,
  143865. _vq_quantmap__44u6__p5_0,
  143866. 9,
  143867. 9
  143868. };
  143869. static static_codebook _44u6__p5_0 = {
  143870. 2, 81,
  143871. _vq_lengthlist__44u6__p5_0,
  143872. 1, -531628032, 1611661312, 4, 0,
  143873. _vq_quantlist__44u6__p5_0,
  143874. NULL,
  143875. &_vq_auxt__44u6__p5_0,
  143876. NULL,
  143877. 0
  143878. };
  143879. static long _vq_quantlist__44u6__p6_0[] = {
  143880. 4,
  143881. 3,
  143882. 5,
  143883. 2,
  143884. 6,
  143885. 1,
  143886. 7,
  143887. 0,
  143888. 8,
  143889. };
  143890. static long _vq_lengthlist__44u6__p6_0[] = {
  143891. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  143892. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  143893. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  143894. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  143895. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  143896. 12,
  143897. };
  143898. static float _vq_quantthresh__44u6__p6_0[] = {
  143899. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143900. };
  143901. static long _vq_quantmap__44u6__p6_0[] = {
  143902. 7, 5, 3, 1, 0, 2, 4, 6,
  143903. 8,
  143904. };
  143905. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  143906. _vq_quantthresh__44u6__p6_0,
  143907. _vq_quantmap__44u6__p6_0,
  143908. 9,
  143909. 9
  143910. };
  143911. static static_codebook _44u6__p6_0 = {
  143912. 2, 81,
  143913. _vq_lengthlist__44u6__p6_0,
  143914. 1, -531628032, 1611661312, 4, 0,
  143915. _vq_quantlist__44u6__p6_0,
  143916. NULL,
  143917. &_vq_auxt__44u6__p6_0,
  143918. NULL,
  143919. 0
  143920. };
  143921. static long _vq_quantlist__44u6__p7_0[] = {
  143922. 1,
  143923. 0,
  143924. 2,
  143925. };
  143926. static long _vq_lengthlist__44u6__p7_0[] = {
  143927. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  143928. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  143929. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  143930. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  143931. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  143932. 10,
  143933. };
  143934. static float _vq_quantthresh__44u6__p7_0[] = {
  143935. -5.5, 5.5,
  143936. };
  143937. static long _vq_quantmap__44u6__p7_0[] = {
  143938. 1, 0, 2,
  143939. };
  143940. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  143941. _vq_quantthresh__44u6__p7_0,
  143942. _vq_quantmap__44u6__p7_0,
  143943. 3,
  143944. 3
  143945. };
  143946. static static_codebook _44u6__p7_0 = {
  143947. 4, 81,
  143948. _vq_lengthlist__44u6__p7_0,
  143949. 1, -529137664, 1618345984, 2, 0,
  143950. _vq_quantlist__44u6__p7_0,
  143951. NULL,
  143952. &_vq_auxt__44u6__p7_0,
  143953. NULL,
  143954. 0
  143955. };
  143956. static long _vq_quantlist__44u6__p7_1[] = {
  143957. 5,
  143958. 4,
  143959. 6,
  143960. 3,
  143961. 7,
  143962. 2,
  143963. 8,
  143964. 1,
  143965. 9,
  143966. 0,
  143967. 10,
  143968. };
  143969. static long _vq_lengthlist__44u6__p7_1[] = {
  143970. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  143971. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  143972. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  143973. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  143974. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143975. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143976. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143977. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143978. };
  143979. static float _vq_quantthresh__44u6__p7_1[] = {
  143980. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143981. 3.5, 4.5,
  143982. };
  143983. static long _vq_quantmap__44u6__p7_1[] = {
  143984. 9, 7, 5, 3, 1, 0, 2, 4,
  143985. 6, 8, 10,
  143986. };
  143987. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  143988. _vq_quantthresh__44u6__p7_1,
  143989. _vq_quantmap__44u6__p7_1,
  143990. 11,
  143991. 11
  143992. };
  143993. static static_codebook _44u6__p7_1 = {
  143994. 2, 121,
  143995. _vq_lengthlist__44u6__p7_1,
  143996. 1, -531365888, 1611661312, 4, 0,
  143997. _vq_quantlist__44u6__p7_1,
  143998. NULL,
  143999. &_vq_auxt__44u6__p7_1,
  144000. NULL,
  144001. 0
  144002. };
  144003. static long _vq_quantlist__44u6__p8_0[] = {
  144004. 5,
  144005. 4,
  144006. 6,
  144007. 3,
  144008. 7,
  144009. 2,
  144010. 8,
  144011. 1,
  144012. 9,
  144013. 0,
  144014. 10,
  144015. };
  144016. static long _vq_lengthlist__44u6__p8_0[] = {
  144017. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  144018. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  144019. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  144020. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  144021. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  144022. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  144023. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  144024. 12,13,13,14,14,14,15,15,15,
  144025. };
  144026. static float _vq_quantthresh__44u6__p8_0[] = {
  144027. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144028. 38.5, 49.5,
  144029. };
  144030. static long _vq_quantmap__44u6__p8_0[] = {
  144031. 9, 7, 5, 3, 1, 0, 2, 4,
  144032. 6, 8, 10,
  144033. };
  144034. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  144035. _vq_quantthresh__44u6__p8_0,
  144036. _vq_quantmap__44u6__p8_0,
  144037. 11,
  144038. 11
  144039. };
  144040. static static_codebook _44u6__p8_0 = {
  144041. 2, 121,
  144042. _vq_lengthlist__44u6__p8_0,
  144043. 1, -524582912, 1618345984, 4, 0,
  144044. _vq_quantlist__44u6__p8_0,
  144045. NULL,
  144046. &_vq_auxt__44u6__p8_0,
  144047. NULL,
  144048. 0
  144049. };
  144050. static long _vq_quantlist__44u6__p8_1[] = {
  144051. 5,
  144052. 4,
  144053. 6,
  144054. 3,
  144055. 7,
  144056. 2,
  144057. 8,
  144058. 1,
  144059. 9,
  144060. 0,
  144061. 10,
  144062. };
  144063. static long _vq_lengthlist__44u6__p8_1[] = {
  144064. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  144065. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  144066. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  144067. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  144068. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144069. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  144070. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144071. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144072. };
  144073. static float _vq_quantthresh__44u6__p8_1[] = {
  144074. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144075. 3.5, 4.5,
  144076. };
  144077. static long _vq_quantmap__44u6__p8_1[] = {
  144078. 9, 7, 5, 3, 1, 0, 2, 4,
  144079. 6, 8, 10,
  144080. };
  144081. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  144082. _vq_quantthresh__44u6__p8_1,
  144083. _vq_quantmap__44u6__p8_1,
  144084. 11,
  144085. 11
  144086. };
  144087. static static_codebook _44u6__p8_1 = {
  144088. 2, 121,
  144089. _vq_lengthlist__44u6__p8_1,
  144090. 1, -531365888, 1611661312, 4, 0,
  144091. _vq_quantlist__44u6__p8_1,
  144092. NULL,
  144093. &_vq_auxt__44u6__p8_1,
  144094. NULL,
  144095. 0
  144096. };
  144097. static long _vq_quantlist__44u6__p9_0[] = {
  144098. 7,
  144099. 6,
  144100. 8,
  144101. 5,
  144102. 9,
  144103. 4,
  144104. 10,
  144105. 3,
  144106. 11,
  144107. 2,
  144108. 12,
  144109. 1,
  144110. 13,
  144111. 0,
  144112. 14,
  144113. };
  144114. static long _vq_lengthlist__44u6__p9_0[] = {
  144115. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  144116. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  144117. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  144118. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  144119. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144120. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144121. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144122. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144123. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144124. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144125. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144126. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144127. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144128. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144129. 14,
  144130. };
  144131. static float _vq_quantthresh__44u6__p9_0[] = {
  144132. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  144133. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  144134. };
  144135. static long _vq_quantmap__44u6__p9_0[] = {
  144136. 13, 11, 9, 7, 5, 3, 1, 0,
  144137. 2, 4, 6, 8, 10, 12, 14,
  144138. };
  144139. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  144140. _vq_quantthresh__44u6__p9_0,
  144141. _vq_quantmap__44u6__p9_0,
  144142. 15,
  144143. 15
  144144. };
  144145. static static_codebook _44u6__p9_0 = {
  144146. 2, 225,
  144147. _vq_lengthlist__44u6__p9_0,
  144148. 1, -514071552, 1627381760, 4, 0,
  144149. _vq_quantlist__44u6__p9_0,
  144150. NULL,
  144151. &_vq_auxt__44u6__p9_0,
  144152. NULL,
  144153. 0
  144154. };
  144155. static long _vq_quantlist__44u6__p9_1[] = {
  144156. 7,
  144157. 6,
  144158. 8,
  144159. 5,
  144160. 9,
  144161. 4,
  144162. 10,
  144163. 3,
  144164. 11,
  144165. 2,
  144166. 12,
  144167. 1,
  144168. 13,
  144169. 0,
  144170. 14,
  144171. };
  144172. static long _vq_lengthlist__44u6__p9_1[] = {
  144173. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  144174. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  144175. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  144176. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  144177. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  144178. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  144179. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  144180. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  144181. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  144182. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  144183. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  144184. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  144185. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  144186. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  144187. 13,
  144188. };
  144189. static float _vq_quantthresh__44u6__p9_1[] = {
  144190. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144191. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144192. };
  144193. static long _vq_quantmap__44u6__p9_1[] = {
  144194. 13, 11, 9, 7, 5, 3, 1, 0,
  144195. 2, 4, 6, 8, 10, 12, 14,
  144196. };
  144197. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  144198. _vq_quantthresh__44u6__p9_1,
  144199. _vq_quantmap__44u6__p9_1,
  144200. 15,
  144201. 15
  144202. };
  144203. static static_codebook _44u6__p9_1 = {
  144204. 2, 225,
  144205. _vq_lengthlist__44u6__p9_1,
  144206. 1, -522338304, 1620115456, 4, 0,
  144207. _vq_quantlist__44u6__p9_1,
  144208. NULL,
  144209. &_vq_auxt__44u6__p9_1,
  144210. NULL,
  144211. 0
  144212. };
  144213. static long _vq_quantlist__44u6__p9_2[] = {
  144214. 8,
  144215. 7,
  144216. 9,
  144217. 6,
  144218. 10,
  144219. 5,
  144220. 11,
  144221. 4,
  144222. 12,
  144223. 3,
  144224. 13,
  144225. 2,
  144226. 14,
  144227. 1,
  144228. 15,
  144229. 0,
  144230. 16,
  144231. };
  144232. static long _vq_lengthlist__44u6__p9_2[] = {
  144233. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  144234. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  144235. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  144236. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144237. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144238. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144239. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144240. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144241. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  144242. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  144243. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  144244. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144245. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  144246. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  144247. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  144248. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  144249. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  144250. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  144251. 10,
  144252. };
  144253. static float _vq_quantthresh__44u6__p9_2[] = {
  144254. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144255. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144256. };
  144257. static long _vq_quantmap__44u6__p9_2[] = {
  144258. 15, 13, 11, 9, 7, 5, 3, 1,
  144259. 0, 2, 4, 6, 8, 10, 12, 14,
  144260. 16,
  144261. };
  144262. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  144263. _vq_quantthresh__44u6__p9_2,
  144264. _vq_quantmap__44u6__p9_2,
  144265. 17,
  144266. 17
  144267. };
  144268. static static_codebook _44u6__p9_2 = {
  144269. 2, 289,
  144270. _vq_lengthlist__44u6__p9_2,
  144271. 1, -529530880, 1611661312, 5, 0,
  144272. _vq_quantlist__44u6__p9_2,
  144273. NULL,
  144274. &_vq_auxt__44u6__p9_2,
  144275. NULL,
  144276. 0
  144277. };
  144278. static long _huff_lengthlist__44u6__short[] = {
  144279. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  144280. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  144281. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  144282. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  144283. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  144284. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  144285. 7, 6, 9,16,
  144286. };
  144287. static static_codebook _huff_book__44u6__short = {
  144288. 2, 100,
  144289. _huff_lengthlist__44u6__short,
  144290. 0, 0, 0, 0, 0,
  144291. NULL,
  144292. NULL,
  144293. NULL,
  144294. NULL,
  144295. 0
  144296. };
  144297. static long _huff_lengthlist__44u7__long[] = {
  144298. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  144299. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  144300. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  144301. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  144302. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  144303. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  144304. 12, 8, 6, 7,
  144305. };
  144306. static static_codebook _huff_book__44u7__long = {
  144307. 2, 100,
  144308. _huff_lengthlist__44u7__long,
  144309. 0, 0, 0, 0, 0,
  144310. NULL,
  144311. NULL,
  144312. NULL,
  144313. NULL,
  144314. 0
  144315. };
  144316. static long _vq_quantlist__44u7__p1_0[] = {
  144317. 1,
  144318. 0,
  144319. 2,
  144320. };
  144321. static long _vq_lengthlist__44u7__p1_0[] = {
  144322. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144323. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  144324. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  144325. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  144326. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  144327. 12,
  144328. };
  144329. static float _vq_quantthresh__44u7__p1_0[] = {
  144330. -0.5, 0.5,
  144331. };
  144332. static long _vq_quantmap__44u7__p1_0[] = {
  144333. 1, 0, 2,
  144334. };
  144335. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  144336. _vq_quantthresh__44u7__p1_0,
  144337. _vq_quantmap__44u7__p1_0,
  144338. 3,
  144339. 3
  144340. };
  144341. static static_codebook _44u7__p1_0 = {
  144342. 4, 81,
  144343. _vq_lengthlist__44u7__p1_0,
  144344. 1, -535822336, 1611661312, 2, 0,
  144345. _vq_quantlist__44u7__p1_0,
  144346. NULL,
  144347. &_vq_auxt__44u7__p1_0,
  144348. NULL,
  144349. 0
  144350. };
  144351. static long _vq_quantlist__44u7__p2_0[] = {
  144352. 1,
  144353. 0,
  144354. 2,
  144355. };
  144356. static long _vq_lengthlist__44u7__p2_0[] = {
  144357. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  144358. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  144359. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  144360. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  144361. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  144362. 9,
  144363. };
  144364. static float _vq_quantthresh__44u7__p2_0[] = {
  144365. -0.5, 0.5,
  144366. };
  144367. static long _vq_quantmap__44u7__p2_0[] = {
  144368. 1, 0, 2,
  144369. };
  144370. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  144371. _vq_quantthresh__44u7__p2_0,
  144372. _vq_quantmap__44u7__p2_0,
  144373. 3,
  144374. 3
  144375. };
  144376. static static_codebook _44u7__p2_0 = {
  144377. 4, 81,
  144378. _vq_lengthlist__44u7__p2_0,
  144379. 1, -535822336, 1611661312, 2, 0,
  144380. _vq_quantlist__44u7__p2_0,
  144381. NULL,
  144382. &_vq_auxt__44u7__p2_0,
  144383. NULL,
  144384. 0
  144385. };
  144386. static long _vq_quantlist__44u7__p3_0[] = {
  144387. 2,
  144388. 1,
  144389. 3,
  144390. 0,
  144391. 4,
  144392. };
  144393. static long _vq_lengthlist__44u7__p3_0[] = {
  144394. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  144395. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  144396. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  144397. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  144398. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  144399. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  144400. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  144401. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  144402. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  144403. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  144404. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  144405. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  144406. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  144407. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  144408. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  144409. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  144410. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  144411. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  144412. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  144413. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  144414. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  144415. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  144416. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  144417. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  144418. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  144419. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  144420. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  144421. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  144422. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  144423. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  144424. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  144425. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  144426. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  144427. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  144428. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  144429. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  144430. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  144431. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  144432. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  144433. 0,
  144434. };
  144435. static float _vq_quantthresh__44u7__p3_0[] = {
  144436. -1.5, -0.5, 0.5, 1.5,
  144437. };
  144438. static long _vq_quantmap__44u7__p3_0[] = {
  144439. 3, 1, 0, 2, 4,
  144440. };
  144441. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  144442. _vq_quantthresh__44u7__p3_0,
  144443. _vq_quantmap__44u7__p3_0,
  144444. 5,
  144445. 5
  144446. };
  144447. static static_codebook _44u7__p3_0 = {
  144448. 4, 625,
  144449. _vq_lengthlist__44u7__p3_0,
  144450. 1, -533725184, 1611661312, 3, 0,
  144451. _vq_quantlist__44u7__p3_0,
  144452. NULL,
  144453. &_vq_auxt__44u7__p3_0,
  144454. NULL,
  144455. 0
  144456. };
  144457. static long _vq_quantlist__44u7__p4_0[] = {
  144458. 2,
  144459. 1,
  144460. 3,
  144461. 0,
  144462. 4,
  144463. };
  144464. static long _vq_lengthlist__44u7__p4_0[] = {
  144465. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  144466. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  144467. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  144468. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  144469. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  144470. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  144471. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  144472. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  144473. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  144474. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  144475. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  144476. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  144477. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  144478. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  144479. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  144480. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  144481. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  144482. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  144483. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  144484. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  144485. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  144486. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  144487. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  144488. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  144489. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  144490. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  144491. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  144492. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  144493. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  144494. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  144495. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  144496. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  144497. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  144498. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  144499. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  144500. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  144501. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  144502. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  144503. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  144504. 14,
  144505. };
  144506. static float _vq_quantthresh__44u7__p4_0[] = {
  144507. -1.5, -0.5, 0.5, 1.5,
  144508. };
  144509. static long _vq_quantmap__44u7__p4_0[] = {
  144510. 3, 1, 0, 2, 4,
  144511. };
  144512. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  144513. _vq_quantthresh__44u7__p4_0,
  144514. _vq_quantmap__44u7__p4_0,
  144515. 5,
  144516. 5
  144517. };
  144518. static static_codebook _44u7__p4_0 = {
  144519. 4, 625,
  144520. _vq_lengthlist__44u7__p4_0,
  144521. 1, -533725184, 1611661312, 3, 0,
  144522. _vq_quantlist__44u7__p4_0,
  144523. NULL,
  144524. &_vq_auxt__44u7__p4_0,
  144525. NULL,
  144526. 0
  144527. };
  144528. static long _vq_quantlist__44u7__p5_0[] = {
  144529. 4,
  144530. 3,
  144531. 5,
  144532. 2,
  144533. 6,
  144534. 1,
  144535. 7,
  144536. 0,
  144537. 8,
  144538. };
  144539. static long _vq_lengthlist__44u7__p5_0[] = {
  144540. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  144541. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  144542. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  144543. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  144544. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  144545. 14,
  144546. };
  144547. static float _vq_quantthresh__44u7__p5_0[] = {
  144548. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144549. };
  144550. static long _vq_quantmap__44u7__p5_0[] = {
  144551. 7, 5, 3, 1, 0, 2, 4, 6,
  144552. 8,
  144553. };
  144554. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  144555. _vq_quantthresh__44u7__p5_0,
  144556. _vq_quantmap__44u7__p5_0,
  144557. 9,
  144558. 9
  144559. };
  144560. static static_codebook _44u7__p5_0 = {
  144561. 2, 81,
  144562. _vq_lengthlist__44u7__p5_0,
  144563. 1, -531628032, 1611661312, 4, 0,
  144564. _vq_quantlist__44u7__p5_0,
  144565. NULL,
  144566. &_vq_auxt__44u7__p5_0,
  144567. NULL,
  144568. 0
  144569. };
  144570. static long _vq_quantlist__44u7__p6_0[] = {
  144571. 4,
  144572. 3,
  144573. 5,
  144574. 2,
  144575. 6,
  144576. 1,
  144577. 7,
  144578. 0,
  144579. 8,
  144580. };
  144581. static long _vq_lengthlist__44u7__p6_0[] = {
  144582. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  144583. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  144584. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  144585. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  144586. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  144587. 12,
  144588. };
  144589. static float _vq_quantthresh__44u7__p6_0[] = {
  144590. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144591. };
  144592. static long _vq_quantmap__44u7__p6_0[] = {
  144593. 7, 5, 3, 1, 0, 2, 4, 6,
  144594. 8,
  144595. };
  144596. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  144597. _vq_quantthresh__44u7__p6_0,
  144598. _vq_quantmap__44u7__p6_0,
  144599. 9,
  144600. 9
  144601. };
  144602. static static_codebook _44u7__p6_0 = {
  144603. 2, 81,
  144604. _vq_lengthlist__44u7__p6_0,
  144605. 1, -531628032, 1611661312, 4, 0,
  144606. _vq_quantlist__44u7__p6_0,
  144607. NULL,
  144608. &_vq_auxt__44u7__p6_0,
  144609. NULL,
  144610. 0
  144611. };
  144612. static long _vq_quantlist__44u7__p7_0[] = {
  144613. 1,
  144614. 0,
  144615. 2,
  144616. };
  144617. static long _vq_lengthlist__44u7__p7_0[] = {
  144618. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  144619. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  144620. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  144621. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  144622. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  144623. 10,
  144624. };
  144625. static float _vq_quantthresh__44u7__p7_0[] = {
  144626. -5.5, 5.5,
  144627. };
  144628. static long _vq_quantmap__44u7__p7_0[] = {
  144629. 1, 0, 2,
  144630. };
  144631. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  144632. _vq_quantthresh__44u7__p7_0,
  144633. _vq_quantmap__44u7__p7_0,
  144634. 3,
  144635. 3
  144636. };
  144637. static static_codebook _44u7__p7_0 = {
  144638. 4, 81,
  144639. _vq_lengthlist__44u7__p7_0,
  144640. 1, -529137664, 1618345984, 2, 0,
  144641. _vq_quantlist__44u7__p7_0,
  144642. NULL,
  144643. &_vq_auxt__44u7__p7_0,
  144644. NULL,
  144645. 0
  144646. };
  144647. static long _vq_quantlist__44u7__p7_1[] = {
  144648. 5,
  144649. 4,
  144650. 6,
  144651. 3,
  144652. 7,
  144653. 2,
  144654. 8,
  144655. 1,
  144656. 9,
  144657. 0,
  144658. 10,
  144659. };
  144660. static long _vq_lengthlist__44u7__p7_1[] = {
  144661. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  144662. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  144663. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  144664. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  144665. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  144666. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  144667. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  144668. 8, 9, 9, 9, 9, 9,10,10,10,
  144669. };
  144670. static float _vq_quantthresh__44u7__p7_1[] = {
  144671. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144672. 3.5, 4.5,
  144673. };
  144674. static long _vq_quantmap__44u7__p7_1[] = {
  144675. 9, 7, 5, 3, 1, 0, 2, 4,
  144676. 6, 8, 10,
  144677. };
  144678. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  144679. _vq_quantthresh__44u7__p7_1,
  144680. _vq_quantmap__44u7__p7_1,
  144681. 11,
  144682. 11
  144683. };
  144684. static static_codebook _44u7__p7_1 = {
  144685. 2, 121,
  144686. _vq_lengthlist__44u7__p7_1,
  144687. 1, -531365888, 1611661312, 4, 0,
  144688. _vq_quantlist__44u7__p7_1,
  144689. NULL,
  144690. &_vq_auxt__44u7__p7_1,
  144691. NULL,
  144692. 0
  144693. };
  144694. static long _vq_quantlist__44u7__p8_0[] = {
  144695. 5,
  144696. 4,
  144697. 6,
  144698. 3,
  144699. 7,
  144700. 2,
  144701. 8,
  144702. 1,
  144703. 9,
  144704. 0,
  144705. 10,
  144706. };
  144707. static long _vq_lengthlist__44u7__p8_0[] = {
  144708. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  144709. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  144710. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  144711. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  144712. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  144713. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  144714. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  144715. 12,13,13,14,14,15,15,15,16,
  144716. };
  144717. static float _vq_quantthresh__44u7__p8_0[] = {
  144718. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144719. 38.5, 49.5,
  144720. };
  144721. static long _vq_quantmap__44u7__p8_0[] = {
  144722. 9, 7, 5, 3, 1, 0, 2, 4,
  144723. 6, 8, 10,
  144724. };
  144725. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  144726. _vq_quantthresh__44u7__p8_0,
  144727. _vq_quantmap__44u7__p8_0,
  144728. 11,
  144729. 11
  144730. };
  144731. static static_codebook _44u7__p8_0 = {
  144732. 2, 121,
  144733. _vq_lengthlist__44u7__p8_0,
  144734. 1, -524582912, 1618345984, 4, 0,
  144735. _vq_quantlist__44u7__p8_0,
  144736. NULL,
  144737. &_vq_auxt__44u7__p8_0,
  144738. NULL,
  144739. 0
  144740. };
  144741. static long _vq_quantlist__44u7__p8_1[] = {
  144742. 5,
  144743. 4,
  144744. 6,
  144745. 3,
  144746. 7,
  144747. 2,
  144748. 8,
  144749. 1,
  144750. 9,
  144751. 0,
  144752. 10,
  144753. };
  144754. static long _vq_lengthlist__44u7__p8_1[] = {
  144755. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144756. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  144757. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  144758. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  144759. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  144760. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  144761. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  144762. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  144763. };
  144764. static float _vq_quantthresh__44u7__p8_1[] = {
  144765. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144766. 3.5, 4.5,
  144767. };
  144768. static long _vq_quantmap__44u7__p8_1[] = {
  144769. 9, 7, 5, 3, 1, 0, 2, 4,
  144770. 6, 8, 10,
  144771. };
  144772. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  144773. _vq_quantthresh__44u7__p8_1,
  144774. _vq_quantmap__44u7__p8_1,
  144775. 11,
  144776. 11
  144777. };
  144778. static static_codebook _44u7__p8_1 = {
  144779. 2, 121,
  144780. _vq_lengthlist__44u7__p8_1,
  144781. 1, -531365888, 1611661312, 4, 0,
  144782. _vq_quantlist__44u7__p8_1,
  144783. NULL,
  144784. &_vq_auxt__44u7__p8_1,
  144785. NULL,
  144786. 0
  144787. };
  144788. static long _vq_quantlist__44u7__p9_0[] = {
  144789. 5,
  144790. 4,
  144791. 6,
  144792. 3,
  144793. 7,
  144794. 2,
  144795. 8,
  144796. 1,
  144797. 9,
  144798. 0,
  144799. 10,
  144800. };
  144801. static long _vq_lengthlist__44u7__p9_0[] = {
  144802. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  144803. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  144804. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144805. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144806. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144807. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144808. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  144809. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144810. };
  144811. static float _vq_quantthresh__44u7__p9_0[] = {
  144812. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  144813. 2229.5, 2866.5,
  144814. };
  144815. static long _vq_quantmap__44u7__p9_0[] = {
  144816. 9, 7, 5, 3, 1, 0, 2, 4,
  144817. 6, 8, 10,
  144818. };
  144819. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  144820. _vq_quantthresh__44u7__p9_0,
  144821. _vq_quantmap__44u7__p9_0,
  144822. 11,
  144823. 11
  144824. };
  144825. static static_codebook _44u7__p9_0 = {
  144826. 2, 121,
  144827. _vq_lengthlist__44u7__p9_0,
  144828. 1, -512171520, 1630791680, 4, 0,
  144829. _vq_quantlist__44u7__p9_0,
  144830. NULL,
  144831. &_vq_auxt__44u7__p9_0,
  144832. NULL,
  144833. 0
  144834. };
  144835. static long _vq_quantlist__44u7__p9_1[] = {
  144836. 6,
  144837. 5,
  144838. 7,
  144839. 4,
  144840. 8,
  144841. 3,
  144842. 9,
  144843. 2,
  144844. 10,
  144845. 1,
  144846. 11,
  144847. 0,
  144848. 12,
  144849. };
  144850. static long _vq_lengthlist__44u7__p9_1[] = {
  144851. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  144852. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  144853. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  144854. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  144855. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  144856. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  144857. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  144858. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  144859. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  144860. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  144861. 15,15,15,15,17,17,16,17,16,
  144862. };
  144863. static float _vq_quantthresh__44u7__p9_1[] = {
  144864. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  144865. 122.5, 171.5, 220.5, 269.5,
  144866. };
  144867. static long _vq_quantmap__44u7__p9_1[] = {
  144868. 11, 9, 7, 5, 3, 1, 0, 2,
  144869. 4, 6, 8, 10, 12,
  144870. };
  144871. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  144872. _vq_quantthresh__44u7__p9_1,
  144873. _vq_quantmap__44u7__p9_1,
  144874. 13,
  144875. 13
  144876. };
  144877. static static_codebook _44u7__p9_1 = {
  144878. 2, 169,
  144879. _vq_lengthlist__44u7__p9_1,
  144880. 1, -518889472, 1622704128, 4, 0,
  144881. _vq_quantlist__44u7__p9_1,
  144882. NULL,
  144883. &_vq_auxt__44u7__p9_1,
  144884. NULL,
  144885. 0
  144886. };
  144887. static long _vq_quantlist__44u7__p9_2[] = {
  144888. 24,
  144889. 23,
  144890. 25,
  144891. 22,
  144892. 26,
  144893. 21,
  144894. 27,
  144895. 20,
  144896. 28,
  144897. 19,
  144898. 29,
  144899. 18,
  144900. 30,
  144901. 17,
  144902. 31,
  144903. 16,
  144904. 32,
  144905. 15,
  144906. 33,
  144907. 14,
  144908. 34,
  144909. 13,
  144910. 35,
  144911. 12,
  144912. 36,
  144913. 11,
  144914. 37,
  144915. 10,
  144916. 38,
  144917. 9,
  144918. 39,
  144919. 8,
  144920. 40,
  144921. 7,
  144922. 41,
  144923. 6,
  144924. 42,
  144925. 5,
  144926. 43,
  144927. 4,
  144928. 44,
  144929. 3,
  144930. 45,
  144931. 2,
  144932. 46,
  144933. 1,
  144934. 47,
  144935. 0,
  144936. 48,
  144937. };
  144938. static long _vq_lengthlist__44u7__p9_2[] = {
  144939. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  144940. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144941. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  144942. 8,
  144943. };
  144944. static float _vq_quantthresh__44u7__p9_2[] = {
  144945. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144946. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144947. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144948. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144949. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144950. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144951. };
  144952. static long _vq_quantmap__44u7__p9_2[] = {
  144953. 47, 45, 43, 41, 39, 37, 35, 33,
  144954. 31, 29, 27, 25, 23, 21, 19, 17,
  144955. 15, 13, 11, 9, 7, 5, 3, 1,
  144956. 0, 2, 4, 6, 8, 10, 12, 14,
  144957. 16, 18, 20, 22, 24, 26, 28, 30,
  144958. 32, 34, 36, 38, 40, 42, 44, 46,
  144959. 48,
  144960. };
  144961. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  144962. _vq_quantthresh__44u7__p9_2,
  144963. _vq_quantmap__44u7__p9_2,
  144964. 49,
  144965. 49
  144966. };
  144967. static static_codebook _44u7__p9_2 = {
  144968. 1, 49,
  144969. _vq_lengthlist__44u7__p9_2,
  144970. 1, -526909440, 1611661312, 6, 0,
  144971. _vq_quantlist__44u7__p9_2,
  144972. NULL,
  144973. &_vq_auxt__44u7__p9_2,
  144974. NULL,
  144975. 0
  144976. };
  144977. static long _huff_lengthlist__44u7__short[] = {
  144978. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  144979. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  144980. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  144981. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  144982. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  144983. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  144984. 6, 8, 5, 9,
  144985. };
  144986. static static_codebook _huff_book__44u7__short = {
  144987. 2, 100,
  144988. _huff_lengthlist__44u7__short,
  144989. 0, 0, 0, 0, 0,
  144990. NULL,
  144991. NULL,
  144992. NULL,
  144993. NULL,
  144994. 0
  144995. };
  144996. static long _huff_lengthlist__44u8__long[] = {
  144997. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  144998. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  144999. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  145000. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  145001. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  145002. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  145003. 10, 8, 8, 9,
  145004. };
  145005. static static_codebook _huff_book__44u8__long = {
  145006. 2, 100,
  145007. _huff_lengthlist__44u8__long,
  145008. 0, 0, 0, 0, 0,
  145009. NULL,
  145010. NULL,
  145011. NULL,
  145012. NULL,
  145013. 0
  145014. };
  145015. static long _huff_lengthlist__44u8__short[] = {
  145016. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  145017. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  145018. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  145019. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  145020. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  145021. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  145022. 10,10,15,17,
  145023. };
  145024. static static_codebook _huff_book__44u8__short = {
  145025. 2, 100,
  145026. _huff_lengthlist__44u8__short,
  145027. 0, 0, 0, 0, 0,
  145028. NULL,
  145029. NULL,
  145030. NULL,
  145031. NULL,
  145032. 0
  145033. };
  145034. static long _vq_quantlist__44u8_p1_0[] = {
  145035. 1,
  145036. 0,
  145037. 2,
  145038. };
  145039. static long _vq_lengthlist__44u8_p1_0[] = {
  145040. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  145041. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  145042. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  145043. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  145044. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  145045. 10,
  145046. };
  145047. static float _vq_quantthresh__44u8_p1_0[] = {
  145048. -0.5, 0.5,
  145049. };
  145050. static long _vq_quantmap__44u8_p1_0[] = {
  145051. 1, 0, 2,
  145052. };
  145053. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  145054. _vq_quantthresh__44u8_p1_0,
  145055. _vq_quantmap__44u8_p1_0,
  145056. 3,
  145057. 3
  145058. };
  145059. static static_codebook _44u8_p1_0 = {
  145060. 4, 81,
  145061. _vq_lengthlist__44u8_p1_0,
  145062. 1, -535822336, 1611661312, 2, 0,
  145063. _vq_quantlist__44u8_p1_0,
  145064. NULL,
  145065. &_vq_auxt__44u8_p1_0,
  145066. NULL,
  145067. 0
  145068. };
  145069. static long _vq_quantlist__44u8_p2_0[] = {
  145070. 2,
  145071. 1,
  145072. 3,
  145073. 0,
  145074. 4,
  145075. };
  145076. static long _vq_lengthlist__44u8_p2_0[] = {
  145077. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  145078. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  145079. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  145080. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  145081. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  145082. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  145083. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  145084. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  145085. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  145086. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  145087. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  145088. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  145089. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  145090. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  145091. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  145092. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  145093. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  145094. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  145095. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  145096. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  145097. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  145098. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  145099. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  145100. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  145101. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  145102. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  145103. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  145104. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  145105. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  145106. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  145107. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  145108. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  145109. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  145110. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  145111. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  145112. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  145113. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  145114. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  145115. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  145116. 14,
  145117. };
  145118. static float _vq_quantthresh__44u8_p2_0[] = {
  145119. -1.5, -0.5, 0.5, 1.5,
  145120. };
  145121. static long _vq_quantmap__44u8_p2_0[] = {
  145122. 3, 1, 0, 2, 4,
  145123. };
  145124. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  145125. _vq_quantthresh__44u8_p2_0,
  145126. _vq_quantmap__44u8_p2_0,
  145127. 5,
  145128. 5
  145129. };
  145130. static static_codebook _44u8_p2_0 = {
  145131. 4, 625,
  145132. _vq_lengthlist__44u8_p2_0,
  145133. 1, -533725184, 1611661312, 3, 0,
  145134. _vq_quantlist__44u8_p2_0,
  145135. NULL,
  145136. &_vq_auxt__44u8_p2_0,
  145137. NULL,
  145138. 0
  145139. };
  145140. static long _vq_quantlist__44u8_p3_0[] = {
  145141. 4,
  145142. 3,
  145143. 5,
  145144. 2,
  145145. 6,
  145146. 1,
  145147. 7,
  145148. 0,
  145149. 8,
  145150. };
  145151. static long _vq_lengthlist__44u8_p3_0[] = {
  145152. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  145153. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  145154. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  145155. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  145156. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  145157. 12,
  145158. };
  145159. static float _vq_quantthresh__44u8_p3_0[] = {
  145160. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145161. };
  145162. static long _vq_quantmap__44u8_p3_0[] = {
  145163. 7, 5, 3, 1, 0, 2, 4, 6,
  145164. 8,
  145165. };
  145166. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  145167. _vq_quantthresh__44u8_p3_0,
  145168. _vq_quantmap__44u8_p3_0,
  145169. 9,
  145170. 9
  145171. };
  145172. static static_codebook _44u8_p3_0 = {
  145173. 2, 81,
  145174. _vq_lengthlist__44u8_p3_0,
  145175. 1, -531628032, 1611661312, 4, 0,
  145176. _vq_quantlist__44u8_p3_0,
  145177. NULL,
  145178. &_vq_auxt__44u8_p3_0,
  145179. NULL,
  145180. 0
  145181. };
  145182. static long _vq_quantlist__44u8_p4_0[] = {
  145183. 8,
  145184. 7,
  145185. 9,
  145186. 6,
  145187. 10,
  145188. 5,
  145189. 11,
  145190. 4,
  145191. 12,
  145192. 3,
  145193. 13,
  145194. 2,
  145195. 14,
  145196. 1,
  145197. 15,
  145198. 0,
  145199. 16,
  145200. };
  145201. static long _vq_lengthlist__44u8_p4_0[] = {
  145202. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  145203. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  145204. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  145205. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  145206. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  145207. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  145208. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  145209. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  145210. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  145211. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  145212. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  145213. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  145214. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  145215. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  145216. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  145217. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  145218. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  145219. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  145220. 14,
  145221. };
  145222. static float _vq_quantthresh__44u8_p4_0[] = {
  145223. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145224. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145225. };
  145226. static long _vq_quantmap__44u8_p4_0[] = {
  145227. 15, 13, 11, 9, 7, 5, 3, 1,
  145228. 0, 2, 4, 6, 8, 10, 12, 14,
  145229. 16,
  145230. };
  145231. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  145232. _vq_quantthresh__44u8_p4_0,
  145233. _vq_quantmap__44u8_p4_0,
  145234. 17,
  145235. 17
  145236. };
  145237. static static_codebook _44u8_p4_0 = {
  145238. 2, 289,
  145239. _vq_lengthlist__44u8_p4_0,
  145240. 1, -529530880, 1611661312, 5, 0,
  145241. _vq_quantlist__44u8_p4_0,
  145242. NULL,
  145243. &_vq_auxt__44u8_p4_0,
  145244. NULL,
  145245. 0
  145246. };
  145247. static long _vq_quantlist__44u8_p5_0[] = {
  145248. 1,
  145249. 0,
  145250. 2,
  145251. };
  145252. static long _vq_lengthlist__44u8_p5_0[] = {
  145253. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  145254. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  145255. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  145256. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145257. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  145258. 10,
  145259. };
  145260. static float _vq_quantthresh__44u8_p5_0[] = {
  145261. -5.5, 5.5,
  145262. };
  145263. static long _vq_quantmap__44u8_p5_0[] = {
  145264. 1, 0, 2,
  145265. };
  145266. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  145267. _vq_quantthresh__44u8_p5_0,
  145268. _vq_quantmap__44u8_p5_0,
  145269. 3,
  145270. 3
  145271. };
  145272. static static_codebook _44u8_p5_0 = {
  145273. 4, 81,
  145274. _vq_lengthlist__44u8_p5_0,
  145275. 1, -529137664, 1618345984, 2, 0,
  145276. _vq_quantlist__44u8_p5_0,
  145277. NULL,
  145278. &_vq_auxt__44u8_p5_0,
  145279. NULL,
  145280. 0
  145281. };
  145282. static long _vq_quantlist__44u8_p5_1[] = {
  145283. 5,
  145284. 4,
  145285. 6,
  145286. 3,
  145287. 7,
  145288. 2,
  145289. 8,
  145290. 1,
  145291. 9,
  145292. 0,
  145293. 10,
  145294. };
  145295. static long _vq_lengthlist__44u8_p5_1[] = {
  145296. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  145297. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  145298. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  145299. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  145300. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  145301. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  145302. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  145303. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  145304. };
  145305. static float _vq_quantthresh__44u8_p5_1[] = {
  145306. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145307. 3.5, 4.5,
  145308. };
  145309. static long _vq_quantmap__44u8_p5_1[] = {
  145310. 9, 7, 5, 3, 1, 0, 2, 4,
  145311. 6, 8, 10,
  145312. };
  145313. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  145314. _vq_quantthresh__44u8_p5_1,
  145315. _vq_quantmap__44u8_p5_1,
  145316. 11,
  145317. 11
  145318. };
  145319. static static_codebook _44u8_p5_1 = {
  145320. 2, 121,
  145321. _vq_lengthlist__44u8_p5_1,
  145322. 1, -531365888, 1611661312, 4, 0,
  145323. _vq_quantlist__44u8_p5_1,
  145324. NULL,
  145325. &_vq_auxt__44u8_p5_1,
  145326. NULL,
  145327. 0
  145328. };
  145329. static long _vq_quantlist__44u8_p6_0[] = {
  145330. 6,
  145331. 5,
  145332. 7,
  145333. 4,
  145334. 8,
  145335. 3,
  145336. 9,
  145337. 2,
  145338. 10,
  145339. 1,
  145340. 11,
  145341. 0,
  145342. 12,
  145343. };
  145344. static long _vq_lengthlist__44u8_p6_0[] = {
  145345. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  145346. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  145347. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  145348. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  145349. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  145350. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  145351. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  145352. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  145353. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  145354. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  145355. 11,11,11,11,11,12,11,12,12,
  145356. };
  145357. static float _vq_quantthresh__44u8_p6_0[] = {
  145358. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145359. 12.5, 17.5, 22.5, 27.5,
  145360. };
  145361. static long _vq_quantmap__44u8_p6_0[] = {
  145362. 11, 9, 7, 5, 3, 1, 0, 2,
  145363. 4, 6, 8, 10, 12,
  145364. };
  145365. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  145366. _vq_quantthresh__44u8_p6_0,
  145367. _vq_quantmap__44u8_p6_0,
  145368. 13,
  145369. 13
  145370. };
  145371. static static_codebook _44u8_p6_0 = {
  145372. 2, 169,
  145373. _vq_lengthlist__44u8_p6_0,
  145374. 1, -526516224, 1616117760, 4, 0,
  145375. _vq_quantlist__44u8_p6_0,
  145376. NULL,
  145377. &_vq_auxt__44u8_p6_0,
  145378. NULL,
  145379. 0
  145380. };
  145381. static long _vq_quantlist__44u8_p6_1[] = {
  145382. 2,
  145383. 1,
  145384. 3,
  145385. 0,
  145386. 4,
  145387. };
  145388. static long _vq_lengthlist__44u8_p6_1[] = {
  145389. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  145390. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  145391. };
  145392. static float _vq_quantthresh__44u8_p6_1[] = {
  145393. -1.5, -0.5, 0.5, 1.5,
  145394. };
  145395. static long _vq_quantmap__44u8_p6_1[] = {
  145396. 3, 1, 0, 2, 4,
  145397. };
  145398. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  145399. _vq_quantthresh__44u8_p6_1,
  145400. _vq_quantmap__44u8_p6_1,
  145401. 5,
  145402. 5
  145403. };
  145404. static static_codebook _44u8_p6_1 = {
  145405. 2, 25,
  145406. _vq_lengthlist__44u8_p6_1,
  145407. 1, -533725184, 1611661312, 3, 0,
  145408. _vq_quantlist__44u8_p6_1,
  145409. NULL,
  145410. &_vq_auxt__44u8_p6_1,
  145411. NULL,
  145412. 0
  145413. };
  145414. static long _vq_quantlist__44u8_p7_0[] = {
  145415. 6,
  145416. 5,
  145417. 7,
  145418. 4,
  145419. 8,
  145420. 3,
  145421. 9,
  145422. 2,
  145423. 10,
  145424. 1,
  145425. 11,
  145426. 0,
  145427. 12,
  145428. };
  145429. static long _vq_lengthlist__44u8_p7_0[] = {
  145430. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  145431. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  145432. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  145433. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  145434. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  145435. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  145436. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  145437. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  145438. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  145439. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  145440. 13,13,14,14,14,15,15,15,16,
  145441. };
  145442. static float _vq_quantthresh__44u8_p7_0[] = {
  145443. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  145444. 27.5, 38.5, 49.5, 60.5,
  145445. };
  145446. static long _vq_quantmap__44u8_p7_0[] = {
  145447. 11, 9, 7, 5, 3, 1, 0, 2,
  145448. 4, 6, 8, 10, 12,
  145449. };
  145450. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  145451. _vq_quantthresh__44u8_p7_0,
  145452. _vq_quantmap__44u8_p7_0,
  145453. 13,
  145454. 13
  145455. };
  145456. static static_codebook _44u8_p7_0 = {
  145457. 2, 169,
  145458. _vq_lengthlist__44u8_p7_0,
  145459. 1, -523206656, 1618345984, 4, 0,
  145460. _vq_quantlist__44u8_p7_0,
  145461. NULL,
  145462. &_vq_auxt__44u8_p7_0,
  145463. NULL,
  145464. 0
  145465. };
  145466. static long _vq_quantlist__44u8_p7_1[] = {
  145467. 5,
  145468. 4,
  145469. 6,
  145470. 3,
  145471. 7,
  145472. 2,
  145473. 8,
  145474. 1,
  145475. 9,
  145476. 0,
  145477. 10,
  145478. };
  145479. static long _vq_lengthlist__44u8_p7_1[] = {
  145480. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  145481. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  145482. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  145483. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  145484. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  145485. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  145486. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  145487. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  145488. };
  145489. static float _vq_quantthresh__44u8_p7_1[] = {
  145490. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145491. 3.5, 4.5,
  145492. };
  145493. static long _vq_quantmap__44u8_p7_1[] = {
  145494. 9, 7, 5, 3, 1, 0, 2, 4,
  145495. 6, 8, 10,
  145496. };
  145497. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  145498. _vq_quantthresh__44u8_p7_1,
  145499. _vq_quantmap__44u8_p7_1,
  145500. 11,
  145501. 11
  145502. };
  145503. static static_codebook _44u8_p7_1 = {
  145504. 2, 121,
  145505. _vq_lengthlist__44u8_p7_1,
  145506. 1, -531365888, 1611661312, 4, 0,
  145507. _vq_quantlist__44u8_p7_1,
  145508. NULL,
  145509. &_vq_auxt__44u8_p7_1,
  145510. NULL,
  145511. 0
  145512. };
  145513. static long _vq_quantlist__44u8_p8_0[] = {
  145514. 7,
  145515. 6,
  145516. 8,
  145517. 5,
  145518. 9,
  145519. 4,
  145520. 10,
  145521. 3,
  145522. 11,
  145523. 2,
  145524. 12,
  145525. 1,
  145526. 13,
  145527. 0,
  145528. 14,
  145529. };
  145530. static long _vq_lengthlist__44u8_p8_0[] = {
  145531. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  145532. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  145533. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  145534. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  145535. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  145536. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  145537. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  145538. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  145539. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  145540. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  145541. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  145542. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  145543. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  145544. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  145545. 17,
  145546. };
  145547. static float _vq_quantthresh__44u8_p8_0[] = {
  145548. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145549. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145550. };
  145551. static long _vq_quantmap__44u8_p8_0[] = {
  145552. 13, 11, 9, 7, 5, 3, 1, 0,
  145553. 2, 4, 6, 8, 10, 12, 14,
  145554. };
  145555. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  145556. _vq_quantthresh__44u8_p8_0,
  145557. _vq_quantmap__44u8_p8_0,
  145558. 15,
  145559. 15
  145560. };
  145561. static static_codebook _44u8_p8_0 = {
  145562. 2, 225,
  145563. _vq_lengthlist__44u8_p8_0,
  145564. 1, -520986624, 1620377600, 4, 0,
  145565. _vq_quantlist__44u8_p8_0,
  145566. NULL,
  145567. &_vq_auxt__44u8_p8_0,
  145568. NULL,
  145569. 0
  145570. };
  145571. static long _vq_quantlist__44u8_p8_1[] = {
  145572. 10,
  145573. 9,
  145574. 11,
  145575. 8,
  145576. 12,
  145577. 7,
  145578. 13,
  145579. 6,
  145580. 14,
  145581. 5,
  145582. 15,
  145583. 4,
  145584. 16,
  145585. 3,
  145586. 17,
  145587. 2,
  145588. 18,
  145589. 1,
  145590. 19,
  145591. 0,
  145592. 20,
  145593. };
  145594. static long _vq_lengthlist__44u8_p8_1[] = {
  145595. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145596. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  145597. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  145598. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  145599. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145600. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145601. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  145602. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  145603. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  145604. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  145605. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  145606. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  145607. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  145608. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  145609. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  145610. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145611. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  145612. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  145613. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  145614. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  145615. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145616. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  145617. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  145618. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145619. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145620. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  145621. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  145622. 10,10,10,10,10,10,10,10,10,
  145623. };
  145624. static float _vq_quantthresh__44u8_p8_1[] = {
  145625. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145626. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145627. 6.5, 7.5, 8.5, 9.5,
  145628. };
  145629. static long _vq_quantmap__44u8_p8_1[] = {
  145630. 19, 17, 15, 13, 11, 9, 7, 5,
  145631. 3, 1, 0, 2, 4, 6, 8, 10,
  145632. 12, 14, 16, 18, 20,
  145633. };
  145634. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  145635. _vq_quantthresh__44u8_p8_1,
  145636. _vq_quantmap__44u8_p8_1,
  145637. 21,
  145638. 21
  145639. };
  145640. static static_codebook _44u8_p8_1 = {
  145641. 2, 441,
  145642. _vq_lengthlist__44u8_p8_1,
  145643. 1, -529268736, 1611661312, 5, 0,
  145644. _vq_quantlist__44u8_p8_1,
  145645. NULL,
  145646. &_vq_auxt__44u8_p8_1,
  145647. NULL,
  145648. 0
  145649. };
  145650. static long _vq_quantlist__44u8_p9_0[] = {
  145651. 4,
  145652. 3,
  145653. 5,
  145654. 2,
  145655. 6,
  145656. 1,
  145657. 7,
  145658. 0,
  145659. 8,
  145660. };
  145661. static long _vq_lengthlist__44u8_p9_0[] = {
  145662. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  145663. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145664. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145665. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145666. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  145667. 8,
  145668. };
  145669. static float _vq_quantthresh__44u8_p9_0[] = {
  145670. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  145671. };
  145672. static long _vq_quantmap__44u8_p9_0[] = {
  145673. 7, 5, 3, 1, 0, 2, 4, 6,
  145674. 8,
  145675. };
  145676. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  145677. _vq_quantthresh__44u8_p9_0,
  145678. _vq_quantmap__44u8_p9_0,
  145679. 9,
  145680. 9
  145681. };
  145682. static static_codebook _44u8_p9_0 = {
  145683. 2, 81,
  145684. _vq_lengthlist__44u8_p9_0,
  145685. 1, -511895552, 1631393792, 4, 0,
  145686. _vq_quantlist__44u8_p9_0,
  145687. NULL,
  145688. &_vq_auxt__44u8_p9_0,
  145689. NULL,
  145690. 0
  145691. };
  145692. static long _vq_quantlist__44u8_p9_1[] = {
  145693. 9,
  145694. 8,
  145695. 10,
  145696. 7,
  145697. 11,
  145698. 6,
  145699. 12,
  145700. 5,
  145701. 13,
  145702. 4,
  145703. 14,
  145704. 3,
  145705. 15,
  145706. 2,
  145707. 16,
  145708. 1,
  145709. 17,
  145710. 0,
  145711. 18,
  145712. };
  145713. static long _vq_lengthlist__44u8_p9_1[] = {
  145714. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  145715. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  145716. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  145717. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  145718. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  145719. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  145720. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  145721. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  145722. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  145723. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  145724. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  145725. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  145726. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  145727. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  145728. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  145729. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  145730. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  145731. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  145732. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  145733. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  145734. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  145735. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  145736. 16,15,16,16,16,16,16,16,16,
  145737. };
  145738. static float _vq_quantthresh__44u8_p9_1[] = {
  145739. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  145740. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  145741. 367.5, 416.5,
  145742. };
  145743. static long _vq_quantmap__44u8_p9_1[] = {
  145744. 17, 15, 13, 11, 9, 7, 5, 3,
  145745. 1, 0, 2, 4, 6, 8, 10, 12,
  145746. 14, 16, 18,
  145747. };
  145748. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  145749. _vq_quantthresh__44u8_p9_1,
  145750. _vq_quantmap__44u8_p9_1,
  145751. 19,
  145752. 19
  145753. };
  145754. static static_codebook _44u8_p9_1 = {
  145755. 2, 361,
  145756. _vq_lengthlist__44u8_p9_1,
  145757. 1, -518287360, 1622704128, 5, 0,
  145758. _vq_quantlist__44u8_p9_1,
  145759. NULL,
  145760. &_vq_auxt__44u8_p9_1,
  145761. NULL,
  145762. 0
  145763. };
  145764. static long _vq_quantlist__44u8_p9_2[] = {
  145765. 24,
  145766. 23,
  145767. 25,
  145768. 22,
  145769. 26,
  145770. 21,
  145771. 27,
  145772. 20,
  145773. 28,
  145774. 19,
  145775. 29,
  145776. 18,
  145777. 30,
  145778. 17,
  145779. 31,
  145780. 16,
  145781. 32,
  145782. 15,
  145783. 33,
  145784. 14,
  145785. 34,
  145786. 13,
  145787. 35,
  145788. 12,
  145789. 36,
  145790. 11,
  145791. 37,
  145792. 10,
  145793. 38,
  145794. 9,
  145795. 39,
  145796. 8,
  145797. 40,
  145798. 7,
  145799. 41,
  145800. 6,
  145801. 42,
  145802. 5,
  145803. 43,
  145804. 4,
  145805. 44,
  145806. 3,
  145807. 45,
  145808. 2,
  145809. 46,
  145810. 1,
  145811. 47,
  145812. 0,
  145813. 48,
  145814. };
  145815. static long _vq_lengthlist__44u8_p9_2[] = {
  145816. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  145817. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145818. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145819. 7,
  145820. };
  145821. static float _vq_quantthresh__44u8_p9_2[] = {
  145822. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145823. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145824. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145825. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145826. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145827. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145828. };
  145829. static long _vq_quantmap__44u8_p9_2[] = {
  145830. 47, 45, 43, 41, 39, 37, 35, 33,
  145831. 31, 29, 27, 25, 23, 21, 19, 17,
  145832. 15, 13, 11, 9, 7, 5, 3, 1,
  145833. 0, 2, 4, 6, 8, 10, 12, 14,
  145834. 16, 18, 20, 22, 24, 26, 28, 30,
  145835. 32, 34, 36, 38, 40, 42, 44, 46,
  145836. 48,
  145837. };
  145838. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  145839. _vq_quantthresh__44u8_p9_2,
  145840. _vq_quantmap__44u8_p9_2,
  145841. 49,
  145842. 49
  145843. };
  145844. static static_codebook _44u8_p9_2 = {
  145845. 1, 49,
  145846. _vq_lengthlist__44u8_p9_2,
  145847. 1, -526909440, 1611661312, 6, 0,
  145848. _vq_quantlist__44u8_p9_2,
  145849. NULL,
  145850. &_vq_auxt__44u8_p9_2,
  145851. NULL,
  145852. 0
  145853. };
  145854. static long _huff_lengthlist__44u9__long[] = {
  145855. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  145856. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  145857. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  145858. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  145859. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  145860. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  145861. 10, 8, 8, 9,
  145862. };
  145863. static static_codebook _huff_book__44u9__long = {
  145864. 2, 100,
  145865. _huff_lengthlist__44u9__long,
  145866. 0, 0, 0, 0, 0,
  145867. NULL,
  145868. NULL,
  145869. NULL,
  145870. NULL,
  145871. 0
  145872. };
  145873. static long _huff_lengthlist__44u9__short[] = {
  145874. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  145875. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  145876. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  145877. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  145878. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  145879. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  145880. 9, 9,12,15,
  145881. };
  145882. static static_codebook _huff_book__44u9__short = {
  145883. 2, 100,
  145884. _huff_lengthlist__44u9__short,
  145885. 0, 0, 0, 0, 0,
  145886. NULL,
  145887. NULL,
  145888. NULL,
  145889. NULL,
  145890. 0
  145891. };
  145892. static long _vq_quantlist__44u9_p1_0[] = {
  145893. 1,
  145894. 0,
  145895. 2,
  145896. };
  145897. static long _vq_lengthlist__44u9_p1_0[] = {
  145898. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  145899. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  145900. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  145901. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  145902. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  145903. 10,
  145904. };
  145905. static float _vq_quantthresh__44u9_p1_0[] = {
  145906. -0.5, 0.5,
  145907. };
  145908. static long _vq_quantmap__44u9_p1_0[] = {
  145909. 1, 0, 2,
  145910. };
  145911. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  145912. _vq_quantthresh__44u9_p1_0,
  145913. _vq_quantmap__44u9_p1_0,
  145914. 3,
  145915. 3
  145916. };
  145917. static static_codebook _44u9_p1_0 = {
  145918. 4, 81,
  145919. _vq_lengthlist__44u9_p1_0,
  145920. 1, -535822336, 1611661312, 2, 0,
  145921. _vq_quantlist__44u9_p1_0,
  145922. NULL,
  145923. &_vq_auxt__44u9_p1_0,
  145924. NULL,
  145925. 0
  145926. };
  145927. static long _vq_quantlist__44u9_p2_0[] = {
  145928. 2,
  145929. 1,
  145930. 3,
  145931. 0,
  145932. 4,
  145933. };
  145934. static long _vq_lengthlist__44u9_p2_0[] = {
  145935. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145936. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  145937. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  145938. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  145939. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  145940. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  145941. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  145942. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  145943. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  145944. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  145945. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  145946. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  145947. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  145948. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  145949. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  145950. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  145951. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  145952. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  145953. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  145954. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  145955. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  145956. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  145957. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  145958. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  145959. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  145960. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  145961. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  145962. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  145963. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  145964. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  145965. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  145966. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  145967. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  145968. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  145969. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  145970. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  145971. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  145972. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  145973. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  145974. 14,
  145975. };
  145976. static float _vq_quantthresh__44u9_p2_0[] = {
  145977. -1.5, -0.5, 0.5, 1.5,
  145978. };
  145979. static long _vq_quantmap__44u9_p2_0[] = {
  145980. 3, 1, 0, 2, 4,
  145981. };
  145982. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  145983. _vq_quantthresh__44u9_p2_0,
  145984. _vq_quantmap__44u9_p2_0,
  145985. 5,
  145986. 5
  145987. };
  145988. static static_codebook _44u9_p2_0 = {
  145989. 4, 625,
  145990. _vq_lengthlist__44u9_p2_0,
  145991. 1, -533725184, 1611661312, 3, 0,
  145992. _vq_quantlist__44u9_p2_0,
  145993. NULL,
  145994. &_vq_auxt__44u9_p2_0,
  145995. NULL,
  145996. 0
  145997. };
  145998. static long _vq_quantlist__44u9_p3_0[] = {
  145999. 4,
  146000. 3,
  146001. 5,
  146002. 2,
  146003. 6,
  146004. 1,
  146005. 7,
  146006. 0,
  146007. 8,
  146008. };
  146009. static long _vq_lengthlist__44u9_p3_0[] = {
  146010. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  146011. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  146012. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  146013. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  146014. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  146015. 11,
  146016. };
  146017. static float _vq_quantthresh__44u9_p3_0[] = {
  146018. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146019. };
  146020. static long _vq_quantmap__44u9_p3_0[] = {
  146021. 7, 5, 3, 1, 0, 2, 4, 6,
  146022. 8,
  146023. };
  146024. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  146025. _vq_quantthresh__44u9_p3_0,
  146026. _vq_quantmap__44u9_p3_0,
  146027. 9,
  146028. 9
  146029. };
  146030. static static_codebook _44u9_p3_0 = {
  146031. 2, 81,
  146032. _vq_lengthlist__44u9_p3_0,
  146033. 1, -531628032, 1611661312, 4, 0,
  146034. _vq_quantlist__44u9_p3_0,
  146035. NULL,
  146036. &_vq_auxt__44u9_p3_0,
  146037. NULL,
  146038. 0
  146039. };
  146040. static long _vq_quantlist__44u9_p4_0[] = {
  146041. 8,
  146042. 7,
  146043. 9,
  146044. 6,
  146045. 10,
  146046. 5,
  146047. 11,
  146048. 4,
  146049. 12,
  146050. 3,
  146051. 13,
  146052. 2,
  146053. 14,
  146054. 1,
  146055. 15,
  146056. 0,
  146057. 16,
  146058. };
  146059. static long _vq_lengthlist__44u9_p4_0[] = {
  146060. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  146061. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  146062. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  146063. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  146064. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  146065. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  146066. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  146067. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  146068. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  146069. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  146070. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  146071. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  146072. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  146073. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  146074. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  146075. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  146076. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  146077. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  146078. 14,
  146079. };
  146080. static float _vq_quantthresh__44u9_p4_0[] = {
  146081. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146082. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146083. };
  146084. static long _vq_quantmap__44u9_p4_0[] = {
  146085. 15, 13, 11, 9, 7, 5, 3, 1,
  146086. 0, 2, 4, 6, 8, 10, 12, 14,
  146087. 16,
  146088. };
  146089. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  146090. _vq_quantthresh__44u9_p4_0,
  146091. _vq_quantmap__44u9_p4_0,
  146092. 17,
  146093. 17
  146094. };
  146095. static static_codebook _44u9_p4_0 = {
  146096. 2, 289,
  146097. _vq_lengthlist__44u9_p4_0,
  146098. 1, -529530880, 1611661312, 5, 0,
  146099. _vq_quantlist__44u9_p4_0,
  146100. NULL,
  146101. &_vq_auxt__44u9_p4_0,
  146102. NULL,
  146103. 0
  146104. };
  146105. static long _vq_quantlist__44u9_p5_0[] = {
  146106. 1,
  146107. 0,
  146108. 2,
  146109. };
  146110. static long _vq_lengthlist__44u9_p5_0[] = {
  146111. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  146112. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  146113. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  146114. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  146115. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  146116. 10,
  146117. };
  146118. static float _vq_quantthresh__44u9_p5_0[] = {
  146119. -5.5, 5.5,
  146120. };
  146121. static long _vq_quantmap__44u9_p5_0[] = {
  146122. 1, 0, 2,
  146123. };
  146124. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  146125. _vq_quantthresh__44u9_p5_0,
  146126. _vq_quantmap__44u9_p5_0,
  146127. 3,
  146128. 3
  146129. };
  146130. static static_codebook _44u9_p5_0 = {
  146131. 4, 81,
  146132. _vq_lengthlist__44u9_p5_0,
  146133. 1, -529137664, 1618345984, 2, 0,
  146134. _vq_quantlist__44u9_p5_0,
  146135. NULL,
  146136. &_vq_auxt__44u9_p5_0,
  146137. NULL,
  146138. 0
  146139. };
  146140. static long _vq_quantlist__44u9_p5_1[] = {
  146141. 5,
  146142. 4,
  146143. 6,
  146144. 3,
  146145. 7,
  146146. 2,
  146147. 8,
  146148. 1,
  146149. 9,
  146150. 0,
  146151. 10,
  146152. };
  146153. static long _vq_lengthlist__44u9_p5_1[] = {
  146154. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  146155. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  146156. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  146157. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  146158. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  146159. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  146160. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  146161. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146162. };
  146163. static float _vq_quantthresh__44u9_p5_1[] = {
  146164. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146165. 3.5, 4.5,
  146166. };
  146167. static long _vq_quantmap__44u9_p5_1[] = {
  146168. 9, 7, 5, 3, 1, 0, 2, 4,
  146169. 6, 8, 10,
  146170. };
  146171. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  146172. _vq_quantthresh__44u9_p5_1,
  146173. _vq_quantmap__44u9_p5_1,
  146174. 11,
  146175. 11
  146176. };
  146177. static static_codebook _44u9_p5_1 = {
  146178. 2, 121,
  146179. _vq_lengthlist__44u9_p5_1,
  146180. 1, -531365888, 1611661312, 4, 0,
  146181. _vq_quantlist__44u9_p5_1,
  146182. NULL,
  146183. &_vq_auxt__44u9_p5_1,
  146184. NULL,
  146185. 0
  146186. };
  146187. static long _vq_quantlist__44u9_p6_0[] = {
  146188. 6,
  146189. 5,
  146190. 7,
  146191. 4,
  146192. 8,
  146193. 3,
  146194. 9,
  146195. 2,
  146196. 10,
  146197. 1,
  146198. 11,
  146199. 0,
  146200. 12,
  146201. };
  146202. static long _vq_lengthlist__44u9_p6_0[] = {
  146203. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  146204. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  146205. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  146206. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  146207. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  146208. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  146209. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  146210. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  146211. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  146212. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  146213. 10,11,11,11,11,12,11,12,12,
  146214. };
  146215. static float _vq_quantthresh__44u9_p6_0[] = {
  146216. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146217. 12.5, 17.5, 22.5, 27.5,
  146218. };
  146219. static long _vq_quantmap__44u9_p6_0[] = {
  146220. 11, 9, 7, 5, 3, 1, 0, 2,
  146221. 4, 6, 8, 10, 12,
  146222. };
  146223. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  146224. _vq_quantthresh__44u9_p6_0,
  146225. _vq_quantmap__44u9_p6_0,
  146226. 13,
  146227. 13
  146228. };
  146229. static static_codebook _44u9_p6_0 = {
  146230. 2, 169,
  146231. _vq_lengthlist__44u9_p6_0,
  146232. 1, -526516224, 1616117760, 4, 0,
  146233. _vq_quantlist__44u9_p6_0,
  146234. NULL,
  146235. &_vq_auxt__44u9_p6_0,
  146236. NULL,
  146237. 0
  146238. };
  146239. static long _vq_quantlist__44u9_p6_1[] = {
  146240. 2,
  146241. 1,
  146242. 3,
  146243. 0,
  146244. 4,
  146245. };
  146246. static long _vq_lengthlist__44u9_p6_1[] = {
  146247. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  146248. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  146249. };
  146250. static float _vq_quantthresh__44u9_p6_1[] = {
  146251. -1.5, -0.5, 0.5, 1.5,
  146252. };
  146253. static long _vq_quantmap__44u9_p6_1[] = {
  146254. 3, 1, 0, 2, 4,
  146255. };
  146256. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  146257. _vq_quantthresh__44u9_p6_1,
  146258. _vq_quantmap__44u9_p6_1,
  146259. 5,
  146260. 5
  146261. };
  146262. static static_codebook _44u9_p6_1 = {
  146263. 2, 25,
  146264. _vq_lengthlist__44u9_p6_1,
  146265. 1, -533725184, 1611661312, 3, 0,
  146266. _vq_quantlist__44u9_p6_1,
  146267. NULL,
  146268. &_vq_auxt__44u9_p6_1,
  146269. NULL,
  146270. 0
  146271. };
  146272. static long _vq_quantlist__44u9_p7_0[] = {
  146273. 6,
  146274. 5,
  146275. 7,
  146276. 4,
  146277. 8,
  146278. 3,
  146279. 9,
  146280. 2,
  146281. 10,
  146282. 1,
  146283. 11,
  146284. 0,
  146285. 12,
  146286. };
  146287. static long _vq_lengthlist__44u9_p7_0[] = {
  146288. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  146289. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  146290. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  146291. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  146292. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  146293. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  146294. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  146295. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  146296. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  146297. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  146298. 12,13,13,14,14,14,15,15,15,
  146299. };
  146300. static float _vq_quantthresh__44u9_p7_0[] = {
  146301. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  146302. 27.5, 38.5, 49.5, 60.5,
  146303. };
  146304. static long _vq_quantmap__44u9_p7_0[] = {
  146305. 11, 9, 7, 5, 3, 1, 0, 2,
  146306. 4, 6, 8, 10, 12,
  146307. };
  146308. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  146309. _vq_quantthresh__44u9_p7_0,
  146310. _vq_quantmap__44u9_p7_0,
  146311. 13,
  146312. 13
  146313. };
  146314. static static_codebook _44u9_p7_0 = {
  146315. 2, 169,
  146316. _vq_lengthlist__44u9_p7_0,
  146317. 1, -523206656, 1618345984, 4, 0,
  146318. _vq_quantlist__44u9_p7_0,
  146319. NULL,
  146320. &_vq_auxt__44u9_p7_0,
  146321. NULL,
  146322. 0
  146323. };
  146324. static long _vq_quantlist__44u9_p7_1[] = {
  146325. 5,
  146326. 4,
  146327. 6,
  146328. 3,
  146329. 7,
  146330. 2,
  146331. 8,
  146332. 1,
  146333. 9,
  146334. 0,
  146335. 10,
  146336. };
  146337. static long _vq_lengthlist__44u9_p7_1[] = {
  146338. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  146339. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  146340. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  146341. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146342. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146343. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146344. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  146345. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  146346. };
  146347. static float _vq_quantthresh__44u9_p7_1[] = {
  146348. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146349. 3.5, 4.5,
  146350. };
  146351. static long _vq_quantmap__44u9_p7_1[] = {
  146352. 9, 7, 5, 3, 1, 0, 2, 4,
  146353. 6, 8, 10,
  146354. };
  146355. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  146356. _vq_quantthresh__44u9_p7_1,
  146357. _vq_quantmap__44u9_p7_1,
  146358. 11,
  146359. 11
  146360. };
  146361. static static_codebook _44u9_p7_1 = {
  146362. 2, 121,
  146363. _vq_lengthlist__44u9_p7_1,
  146364. 1, -531365888, 1611661312, 4, 0,
  146365. _vq_quantlist__44u9_p7_1,
  146366. NULL,
  146367. &_vq_auxt__44u9_p7_1,
  146368. NULL,
  146369. 0
  146370. };
  146371. static long _vq_quantlist__44u9_p8_0[] = {
  146372. 7,
  146373. 6,
  146374. 8,
  146375. 5,
  146376. 9,
  146377. 4,
  146378. 10,
  146379. 3,
  146380. 11,
  146381. 2,
  146382. 12,
  146383. 1,
  146384. 13,
  146385. 0,
  146386. 14,
  146387. };
  146388. static long _vq_lengthlist__44u9_p8_0[] = {
  146389. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  146390. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  146391. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  146392. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  146393. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  146394. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  146395. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  146396. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  146397. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  146398. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  146399. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  146400. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  146401. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  146402. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  146403. 15,
  146404. };
  146405. static float _vq_quantthresh__44u9_p8_0[] = {
  146406. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  146407. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  146408. };
  146409. static long _vq_quantmap__44u9_p8_0[] = {
  146410. 13, 11, 9, 7, 5, 3, 1, 0,
  146411. 2, 4, 6, 8, 10, 12, 14,
  146412. };
  146413. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  146414. _vq_quantthresh__44u9_p8_0,
  146415. _vq_quantmap__44u9_p8_0,
  146416. 15,
  146417. 15
  146418. };
  146419. static static_codebook _44u9_p8_0 = {
  146420. 2, 225,
  146421. _vq_lengthlist__44u9_p8_0,
  146422. 1, -520986624, 1620377600, 4, 0,
  146423. _vq_quantlist__44u9_p8_0,
  146424. NULL,
  146425. &_vq_auxt__44u9_p8_0,
  146426. NULL,
  146427. 0
  146428. };
  146429. static long _vq_quantlist__44u9_p8_1[] = {
  146430. 10,
  146431. 9,
  146432. 11,
  146433. 8,
  146434. 12,
  146435. 7,
  146436. 13,
  146437. 6,
  146438. 14,
  146439. 5,
  146440. 15,
  146441. 4,
  146442. 16,
  146443. 3,
  146444. 17,
  146445. 2,
  146446. 18,
  146447. 1,
  146448. 19,
  146449. 0,
  146450. 20,
  146451. };
  146452. static long _vq_lengthlist__44u9_p8_1[] = {
  146453. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146454. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  146455. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  146456. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  146457. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146458. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  146459. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  146460. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  146461. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146462. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146463. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  146464. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  146465. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  146466. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  146467. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146468. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146469. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  146470. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  146471. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  146472. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  146473. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146474. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  146475. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  146476. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  146477. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146478. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  146479. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  146480. 10,10,10,10,10,10,10,10,10,
  146481. };
  146482. static float _vq_quantthresh__44u9_p8_1[] = {
  146483. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  146484. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  146485. 6.5, 7.5, 8.5, 9.5,
  146486. };
  146487. static long _vq_quantmap__44u9_p8_1[] = {
  146488. 19, 17, 15, 13, 11, 9, 7, 5,
  146489. 3, 1, 0, 2, 4, 6, 8, 10,
  146490. 12, 14, 16, 18, 20,
  146491. };
  146492. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  146493. _vq_quantthresh__44u9_p8_1,
  146494. _vq_quantmap__44u9_p8_1,
  146495. 21,
  146496. 21
  146497. };
  146498. static static_codebook _44u9_p8_1 = {
  146499. 2, 441,
  146500. _vq_lengthlist__44u9_p8_1,
  146501. 1, -529268736, 1611661312, 5, 0,
  146502. _vq_quantlist__44u9_p8_1,
  146503. NULL,
  146504. &_vq_auxt__44u9_p8_1,
  146505. NULL,
  146506. 0
  146507. };
  146508. static long _vq_quantlist__44u9_p9_0[] = {
  146509. 7,
  146510. 6,
  146511. 8,
  146512. 5,
  146513. 9,
  146514. 4,
  146515. 10,
  146516. 3,
  146517. 11,
  146518. 2,
  146519. 12,
  146520. 1,
  146521. 13,
  146522. 0,
  146523. 14,
  146524. };
  146525. static long _vq_lengthlist__44u9_p9_0[] = {
  146526. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  146527. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  146528. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146529. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146530. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146531. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146532. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146533. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146534. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146535. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146536. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146537. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146538. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146539. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146540. 10,
  146541. };
  146542. static float _vq_quantthresh__44u9_p9_0[] = {
  146543. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  146544. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  146545. };
  146546. static long _vq_quantmap__44u9_p9_0[] = {
  146547. 13, 11, 9, 7, 5, 3, 1, 0,
  146548. 2, 4, 6, 8, 10, 12, 14,
  146549. };
  146550. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  146551. _vq_quantthresh__44u9_p9_0,
  146552. _vq_quantmap__44u9_p9_0,
  146553. 15,
  146554. 15
  146555. };
  146556. static static_codebook _44u9_p9_0 = {
  146557. 2, 225,
  146558. _vq_lengthlist__44u9_p9_0,
  146559. 1, -510036736, 1631393792, 4, 0,
  146560. _vq_quantlist__44u9_p9_0,
  146561. NULL,
  146562. &_vq_auxt__44u9_p9_0,
  146563. NULL,
  146564. 0
  146565. };
  146566. static long _vq_quantlist__44u9_p9_1[] = {
  146567. 9,
  146568. 8,
  146569. 10,
  146570. 7,
  146571. 11,
  146572. 6,
  146573. 12,
  146574. 5,
  146575. 13,
  146576. 4,
  146577. 14,
  146578. 3,
  146579. 15,
  146580. 2,
  146581. 16,
  146582. 1,
  146583. 17,
  146584. 0,
  146585. 18,
  146586. };
  146587. static long _vq_lengthlist__44u9_p9_1[] = {
  146588. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  146589. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  146590. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  146591. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  146592. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  146593. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  146594. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  146595. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  146596. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  146597. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  146598. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  146599. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  146600. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  146601. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  146602. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  146603. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  146604. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  146605. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  146606. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  146607. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  146608. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  146609. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  146610. 17,17,15,17,15,17,16,16,17,
  146611. };
  146612. static float _vq_quantthresh__44u9_p9_1[] = {
  146613. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  146614. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  146615. 367.5, 416.5,
  146616. };
  146617. static long _vq_quantmap__44u9_p9_1[] = {
  146618. 17, 15, 13, 11, 9, 7, 5, 3,
  146619. 1, 0, 2, 4, 6, 8, 10, 12,
  146620. 14, 16, 18,
  146621. };
  146622. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  146623. _vq_quantthresh__44u9_p9_1,
  146624. _vq_quantmap__44u9_p9_1,
  146625. 19,
  146626. 19
  146627. };
  146628. static static_codebook _44u9_p9_1 = {
  146629. 2, 361,
  146630. _vq_lengthlist__44u9_p9_1,
  146631. 1, -518287360, 1622704128, 5, 0,
  146632. _vq_quantlist__44u9_p9_1,
  146633. NULL,
  146634. &_vq_auxt__44u9_p9_1,
  146635. NULL,
  146636. 0
  146637. };
  146638. static long _vq_quantlist__44u9_p9_2[] = {
  146639. 24,
  146640. 23,
  146641. 25,
  146642. 22,
  146643. 26,
  146644. 21,
  146645. 27,
  146646. 20,
  146647. 28,
  146648. 19,
  146649. 29,
  146650. 18,
  146651. 30,
  146652. 17,
  146653. 31,
  146654. 16,
  146655. 32,
  146656. 15,
  146657. 33,
  146658. 14,
  146659. 34,
  146660. 13,
  146661. 35,
  146662. 12,
  146663. 36,
  146664. 11,
  146665. 37,
  146666. 10,
  146667. 38,
  146668. 9,
  146669. 39,
  146670. 8,
  146671. 40,
  146672. 7,
  146673. 41,
  146674. 6,
  146675. 42,
  146676. 5,
  146677. 43,
  146678. 4,
  146679. 44,
  146680. 3,
  146681. 45,
  146682. 2,
  146683. 46,
  146684. 1,
  146685. 47,
  146686. 0,
  146687. 48,
  146688. };
  146689. static long _vq_lengthlist__44u9_p9_2[] = {
  146690. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  146691. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146692. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146693. 7,
  146694. };
  146695. static float _vq_quantthresh__44u9_p9_2[] = {
  146696. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  146697. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  146698. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146699. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146700. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  146701. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  146702. };
  146703. static long _vq_quantmap__44u9_p9_2[] = {
  146704. 47, 45, 43, 41, 39, 37, 35, 33,
  146705. 31, 29, 27, 25, 23, 21, 19, 17,
  146706. 15, 13, 11, 9, 7, 5, 3, 1,
  146707. 0, 2, 4, 6, 8, 10, 12, 14,
  146708. 16, 18, 20, 22, 24, 26, 28, 30,
  146709. 32, 34, 36, 38, 40, 42, 44, 46,
  146710. 48,
  146711. };
  146712. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  146713. _vq_quantthresh__44u9_p9_2,
  146714. _vq_quantmap__44u9_p9_2,
  146715. 49,
  146716. 49
  146717. };
  146718. static static_codebook _44u9_p9_2 = {
  146719. 1, 49,
  146720. _vq_lengthlist__44u9_p9_2,
  146721. 1, -526909440, 1611661312, 6, 0,
  146722. _vq_quantlist__44u9_p9_2,
  146723. NULL,
  146724. &_vq_auxt__44u9_p9_2,
  146725. NULL,
  146726. 0
  146727. };
  146728. static long _huff_lengthlist__44un1__long[] = {
  146729. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  146730. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  146731. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  146732. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  146733. };
  146734. static static_codebook _huff_book__44un1__long = {
  146735. 2, 64,
  146736. _huff_lengthlist__44un1__long,
  146737. 0, 0, 0, 0, 0,
  146738. NULL,
  146739. NULL,
  146740. NULL,
  146741. NULL,
  146742. 0
  146743. };
  146744. static long _vq_quantlist__44un1__p1_0[] = {
  146745. 1,
  146746. 0,
  146747. 2,
  146748. };
  146749. static long _vq_lengthlist__44un1__p1_0[] = {
  146750. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  146751. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  146752. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  146753. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  146754. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  146755. 12,
  146756. };
  146757. static float _vq_quantthresh__44un1__p1_0[] = {
  146758. -0.5, 0.5,
  146759. };
  146760. static long _vq_quantmap__44un1__p1_0[] = {
  146761. 1, 0, 2,
  146762. };
  146763. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  146764. _vq_quantthresh__44un1__p1_0,
  146765. _vq_quantmap__44un1__p1_0,
  146766. 3,
  146767. 3
  146768. };
  146769. static static_codebook _44un1__p1_0 = {
  146770. 4, 81,
  146771. _vq_lengthlist__44un1__p1_0,
  146772. 1, -535822336, 1611661312, 2, 0,
  146773. _vq_quantlist__44un1__p1_0,
  146774. NULL,
  146775. &_vq_auxt__44un1__p1_0,
  146776. NULL,
  146777. 0
  146778. };
  146779. static long _vq_quantlist__44un1__p2_0[] = {
  146780. 1,
  146781. 0,
  146782. 2,
  146783. };
  146784. static long _vq_lengthlist__44un1__p2_0[] = {
  146785. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146786. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  146787. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  146788. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  146789. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  146790. 8,
  146791. };
  146792. static float _vq_quantthresh__44un1__p2_0[] = {
  146793. -0.5, 0.5,
  146794. };
  146795. static long _vq_quantmap__44un1__p2_0[] = {
  146796. 1, 0, 2,
  146797. };
  146798. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  146799. _vq_quantthresh__44un1__p2_0,
  146800. _vq_quantmap__44un1__p2_0,
  146801. 3,
  146802. 3
  146803. };
  146804. static static_codebook _44un1__p2_0 = {
  146805. 4, 81,
  146806. _vq_lengthlist__44un1__p2_0,
  146807. 1, -535822336, 1611661312, 2, 0,
  146808. _vq_quantlist__44un1__p2_0,
  146809. NULL,
  146810. &_vq_auxt__44un1__p2_0,
  146811. NULL,
  146812. 0
  146813. };
  146814. static long _vq_quantlist__44un1__p3_0[] = {
  146815. 2,
  146816. 1,
  146817. 3,
  146818. 0,
  146819. 4,
  146820. };
  146821. static long _vq_lengthlist__44un1__p3_0[] = {
  146822. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146823. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  146824. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  146825. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  146826. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  146827. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  146828. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  146829. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  146830. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  146831. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  146832. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  146833. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  146834. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  146835. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  146836. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  146837. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  146838. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  146839. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  146840. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  146841. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  146842. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  146843. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  146844. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  146845. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  146846. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  146847. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  146848. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  146849. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  146850. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  146851. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  146852. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  146853. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  146854. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  146855. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  146856. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  146857. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  146858. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  146859. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  146860. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  146861. 17,
  146862. };
  146863. static float _vq_quantthresh__44un1__p3_0[] = {
  146864. -1.5, -0.5, 0.5, 1.5,
  146865. };
  146866. static long _vq_quantmap__44un1__p3_0[] = {
  146867. 3, 1, 0, 2, 4,
  146868. };
  146869. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  146870. _vq_quantthresh__44un1__p3_0,
  146871. _vq_quantmap__44un1__p3_0,
  146872. 5,
  146873. 5
  146874. };
  146875. static static_codebook _44un1__p3_0 = {
  146876. 4, 625,
  146877. _vq_lengthlist__44un1__p3_0,
  146878. 1, -533725184, 1611661312, 3, 0,
  146879. _vq_quantlist__44un1__p3_0,
  146880. NULL,
  146881. &_vq_auxt__44un1__p3_0,
  146882. NULL,
  146883. 0
  146884. };
  146885. static long _vq_quantlist__44un1__p4_0[] = {
  146886. 2,
  146887. 1,
  146888. 3,
  146889. 0,
  146890. 4,
  146891. };
  146892. static long _vq_lengthlist__44un1__p4_0[] = {
  146893. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  146894. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  146895. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  146896. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  146897. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  146898. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  146899. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  146900. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  146901. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  146902. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  146903. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  146904. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  146905. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  146906. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  146907. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  146908. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  146909. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  146910. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  146911. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  146912. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  146913. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  146914. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  146915. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  146916. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  146917. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  146918. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  146919. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  146920. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  146921. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  146922. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  146923. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  146924. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  146925. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  146926. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  146927. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  146928. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  146929. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  146930. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  146931. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  146932. 12,
  146933. };
  146934. static float _vq_quantthresh__44un1__p4_0[] = {
  146935. -1.5, -0.5, 0.5, 1.5,
  146936. };
  146937. static long _vq_quantmap__44un1__p4_0[] = {
  146938. 3, 1, 0, 2, 4,
  146939. };
  146940. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  146941. _vq_quantthresh__44un1__p4_0,
  146942. _vq_quantmap__44un1__p4_0,
  146943. 5,
  146944. 5
  146945. };
  146946. static static_codebook _44un1__p4_0 = {
  146947. 4, 625,
  146948. _vq_lengthlist__44un1__p4_0,
  146949. 1, -533725184, 1611661312, 3, 0,
  146950. _vq_quantlist__44un1__p4_0,
  146951. NULL,
  146952. &_vq_auxt__44un1__p4_0,
  146953. NULL,
  146954. 0
  146955. };
  146956. static long _vq_quantlist__44un1__p5_0[] = {
  146957. 4,
  146958. 3,
  146959. 5,
  146960. 2,
  146961. 6,
  146962. 1,
  146963. 7,
  146964. 0,
  146965. 8,
  146966. };
  146967. static long _vq_lengthlist__44un1__p5_0[] = {
  146968. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  146969. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  146970. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  146971. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  146972. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  146973. 12,
  146974. };
  146975. static float _vq_quantthresh__44un1__p5_0[] = {
  146976. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146977. };
  146978. static long _vq_quantmap__44un1__p5_0[] = {
  146979. 7, 5, 3, 1, 0, 2, 4, 6,
  146980. 8,
  146981. };
  146982. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  146983. _vq_quantthresh__44un1__p5_0,
  146984. _vq_quantmap__44un1__p5_0,
  146985. 9,
  146986. 9
  146987. };
  146988. static static_codebook _44un1__p5_0 = {
  146989. 2, 81,
  146990. _vq_lengthlist__44un1__p5_0,
  146991. 1, -531628032, 1611661312, 4, 0,
  146992. _vq_quantlist__44un1__p5_0,
  146993. NULL,
  146994. &_vq_auxt__44un1__p5_0,
  146995. NULL,
  146996. 0
  146997. };
  146998. static long _vq_quantlist__44un1__p6_0[] = {
  146999. 6,
  147000. 5,
  147001. 7,
  147002. 4,
  147003. 8,
  147004. 3,
  147005. 9,
  147006. 2,
  147007. 10,
  147008. 1,
  147009. 11,
  147010. 0,
  147011. 12,
  147012. };
  147013. static long _vq_lengthlist__44un1__p6_0[] = {
  147014. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  147015. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  147016. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  147017. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  147018. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  147019. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  147020. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  147021. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  147022. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  147023. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  147024. 16, 0,15,18,18, 0,16, 0, 0,
  147025. };
  147026. static float _vq_quantthresh__44un1__p6_0[] = {
  147027. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147028. 12.5, 17.5, 22.5, 27.5,
  147029. };
  147030. static long _vq_quantmap__44un1__p6_0[] = {
  147031. 11, 9, 7, 5, 3, 1, 0, 2,
  147032. 4, 6, 8, 10, 12,
  147033. };
  147034. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  147035. _vq_quantthresh__44un1__p6_0,
  147036. _vq_quantmap__44un1__p6_0,
  147037. 13,
  147038. 13
  147039. };
  147040. static static_codebook _44un1__p6_0 = {
  147041. 2, 169,
  147042. _vq_lengthlist__44un1__p6_0,
  147043. 1, -526516224, 1616117760, 4, 0,
  147044. _vq_quantlist__44un1__p6_0,
  147045. NULL,
  147046. &_vq_auxt__44un1__p6_0,
  147047. NULL,
  147048. 0
  147049. };
  147050. static long _vq_quantlist__44un1__p6_1[] = {
  147051. 2,
  147052. 1,
  147053. 3,
  147054. 0,
  147055. 4,
  147056. };
  147057. static long _vq_lengthlist__44un1__p6_1[] = {
  147058. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  147059. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  147060. };
  147061. static float _vq_quantthresh__44un1__p6_1[] = {
  147062. -1.5, -0.5, 0.5, 1.5,
  147063. };
  147064. static long _vq_quantmap__44un1__p6_1[] = {
  147065. 3, 1, 0, 2, 4,
  147066. };
  147067. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  147068. _vq_quantthresh__44un1__p6_1,
  147069. _vq_quantmap__44un1__p6_1,
  147070. 5,
  147071. 5
  147072. };
  147073. static static_codebook _44un1__p6_1 = {
  147074. 2, 25,
  147075. _vq_lengthlist__44un1__p6_1,
  147076. 1, -533725184, 1611661312, 3, 0,
  147077. _vq_quantlist__44un1__p6_1,
  147078. NULL,
  147079. &_vq_auxt__44un1__p6_1,
  147080. NULL,
  147081. 0
  147082. };
  147083. static long _vq_quantlist__44un1__p7_0[] = {
  147084. 2,
  147085. 1,
  147086. 3,
  147087. 0,
  147088. 4,
  147089. };
  147090. static long _vq_lengthlist__44un1__p7_0[] = {
  147091. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  147092. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  147093. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147094. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147095. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147096. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147097. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147098. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  147099. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147100. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147101. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  147102. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147103. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147104. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147105. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147106. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  147107. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147108. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  147109. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147110. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147111. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147112. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147113. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147114. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147115. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147116. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147117. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147118. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147119. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147120. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147121. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147122. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147123. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147124. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147125. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147126. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147127. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147128. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147129. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147130. 10,
  147131. };
  147132. static float _vq_quantthresh__44un1__p7_0[] = {
  147133. -253.5, -84.5, 84.5, 253.5,
  147134. };
  147135. static long _vq_quantmap__44un1__p7_0[] = {
  147136. 3, 1, 0, 2, 4,
  147137. };
  147138. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  147139. _vq_quantthresh__44un1__p7_0,
  147140. _vq_quantmap__44un1__p7_0,
  147141. 5,
  147142. 5
  147143. };
  147144. static static_codebook _44un1__p7_0 = {
  147145. 4, 625,
  147146. _vq_lengthlist__44un1__p7_0,
  147147. 1, -518709248, 1626677248, 3, 0,
  147148. _vq_quantlist__44un1__p7_0,
  147149. NULL,
  147150. &_vq_auxt__44un1__p7_0,
  147151. NULL,
  147152. 0
  147153. };
  147154. static long _vq_quantlist__44un1__p7_1[] = {
  147155. 6,
  147156. 5,
  147157. 7,
  147158. 4,
  147159. 8,
  147160. 3,
  147161. 9,
  147162. 2,
  147163. 10,
  147164. 1,
  147165. 11,
  147166. 0,
  147167. 12,
  147168. };
  147169. static long _vq_lengthlist__44un1__p7_1[] = {
  147170. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  147171. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  147172. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  147173. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  147174. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  147175. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  147176. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  147177. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  147178. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  147179. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  147180. 12,13,13,12,13,13,14,14,14,
  147181. };
  147182. static float _vq_quantthresh__44un1__p7_1[] = {
  147183. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147184. 32.5, 45.5, 58.5, 71.5,
  147185. };
  147186. static long _vq_quantmap__44un1__p7_1[] = {
  147187. 11, 9, 7, 5, 3, 1, 0, 2,
  147188. 4, 6, 8, 10, 12,
  147189. };
  147190. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  147191. _vq_quantthresh__44un1__p7_1,
  147192. _vq_quantmap__44un1__p7_1,
  147193. 13,
  147194. 13
  147195. };
  147196. static static_codebook _44un1__p7_1 = {
  147197. 2, 169,
  147198. _vq_lengthlist__44un1__p7_1,
  147199. 1, -523010048, 1618608128, 4, 0,
  147200. _vq_quantlist__44un1__p7_1,
  147201. NULL,
  147202. &_vq_auxt__44un1__p7_1,
  147203. NULL,
  147204. 0
  147205. };
  147206. static long _vq_quantlist__44un1__p7_2[] = {
  147207. 6,
  147208. 5,
  147209. 7,
  147210. 4,
  147211. 8,
  147212. 3,
  147213. 9,
  147214. 2,
  147215. 10,
  147216. 1,
  147217. 11,
  147218. 0,
  147219. 12,
  147220. };
  147221. static long _vq_lengthlist__44un1__p7_2[] = {
  147222. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  147223. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  147224. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  147225. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  147226. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  147227. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  147228. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  147229. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  147230. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  147231. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  147232. 9, 9, 9,10,10,10,10,10,10,
  147233. };
  147234. static float _vq_quantthresh__44un1__p7_2[] = {
  147235. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147236. 2.5, 3.5, 4.5, 5.5,
  147237. };
  147238. static long _vq_quantmap__44un1__p7_2[] = {
  147239. 11, 9, 7, 5, 3, 1, 0, 2,
  147240. 4, 6, 8, 10, 12,
  147241. };
  147242. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  147243. _vq_quantthresh__44un1__p7_2,
  147244. _vq_quantmap__44un1__p7_2,
  147245. 13,
  147246. 13
  147247. };
  147248. static static_codebook _44un1__p7_2 = {
  147249. 2, 169,
  147250. _vq_lengthlist__44un1__p7_2,
  147251. 1, -531103744, 1611661312, 4, 0,
  147252. _vq_quantlist__44un1__p7_2,
  147253. NULL,
  147254. &_vq_auxt__44un1__p7_2,
  147255. NULL,
  147256. 0
  147257. };
  147258. static long _huff_lengthlist__44un1__short[] = {
  147259. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  147260. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  147261. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  147262. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  147263. };
  147264. static static_codebook _huff_book__44un1__short = {
  147265. 2, 64,
  147266. _huff_lengthlist__44un1__short,
  147267. 0, 0, 0, 0, 0,
  147268. NULL,
  147269. NULL,
  147270. NULL,
  147271. NULL,
  147272. 0
  147273. };
  147274. /********* End of inlined file: res_books_uncoupled.h *********/
  147275. /***** residue backends *********************************************/
  147276. static vorbis_info_residue0 _residue_44_low_un={
  147277. 0,-1, -1, 8,-1,
  147278. {0},
  147279. {-1},
  147280. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  147281. { -1, 25, -1, 45, -1, -1, -1}
  147282. };
  147283. static vorbis_info_residue0 _residue_44_mid_un={
  147284. 0,-1, -1, 10,-1,
  147285. /* 0 1 2 3 4 5 6 7 8 9 */
  147286. {0},
  147287. {-1},
  147288. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  147289. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  147290. };
  147291. static vorbis_info_residue0 _residue_44_hi_un={
  147292. 0,-1, -1, 10,-1,
  147293. /* 0 1 2 3 4 5 6 7 8 9 */
  147294. {0},
  147295. {-1},
  147296. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  147297. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  147298. };
  147299. /* mapping conventions:
  147300. only one submap (this would change for efficient 5.1 support for example)*/
  147301. /* Four psychoacoustic profiles are used, one for each blocktype */
  147302. static vorbis_info_mapping0 _map_nominal_u[2]={
  147303. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  147304. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  147305. };
  147306. static static_bookblock _resbook_44u_n1={
  147307. {
  147308. {0},
  147309. {0,0,&_44un1__p1_0},
  147310. {0,0,&_44un1__p2_0},
  147311. {0,0,&_44un1__p3_0},
  147312. {0,0,&_44un1__p4_0},
  147313. {0,0,&_44un1__p5_0},
  147314. {&_44un1__p6_0,&_44un1__p6_1},
  147315. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  147316. }
  147317. };
  147318. static static_bookblock _resbook_44u_0={
  147319. {
  147320. {0},
  147321. {0,0,&_44u0__p1_0},
  147322. {0,0,&_44u0__p2_0},
  147323. {0,0,&_44u0__p3_0},
  147324. {0,0,&_44u0__p4_0},
  147325. {0,0,&_44u0__p5_0},
  147326. {&_44u0__p6_0,&_44u0__p6_1},
  147327. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  147328. }
  147329. };
  147330. static static_bookblock _resbook_44u_1={
  147331. {
  147332. {0},
  147333. {0,0,&_44u1__p1_0},
  147334. {0,0,&_44u1__p2_0},
  147335. {0,0,&_44u1__p3_0},
  147336. {0,0,&_44u1__p4_0},
  147337. {0,0,&_44u1__p5_0},
  147338. {&_44u1__p6_0,&_44u1__p6_1},
  147339. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  147340. }
  147341. };
  147342. static static_bookblock _resbook_44u_2={
  147343. {
  147344. {0},
  147345. {0,0,&_44u2__p1_0},
  147346. {0,0,&_44u2__p2_0},
  147347. {0,0,&_44u2__p3_0},
  147348. {0,0,&_44u2__p4_0},
  147349. {0,0,&_44u2__p5_0},
  147350. {&_44u2__p6_0,&_44u2__p6_1},
  147351. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  147352. }
  147353. };
  147354. static static_bookblock _resbook_44u_3={
  147355. {
  147356. {0},
  147357. {0,0,&_44u3__p1_0},
  147358. {0,0,&_44u3__p2_0},
  147359. {0,0,&_44u3__p3_0},
  147360. {0,0,&_44u3__p4_0},
  147361. {0,0,&_44u3__p5_0},
  147362. {&_44u3__p6_0,&_44u3__p6_1},
  147363. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  147364. }
  147365. };
  147366. static static_bookblock _resbook_44u_4={
  147367. {
  147368. {0},
  147369. {0,0,&_44u4__p1_0},
  147370. {0,0,&_44u4__p2_0},
  147371. {0,0,&_44u4__p3_0},
  147372. {0,0,&_44u4__p4_0},
  147373. {0,0,&_44u4__p5_0},
  147374. {&_44u4__p6_0,&_44u4__p6_1},
  147375. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  147376. }
  147377. };
  147378. static static_bookblock _resbook_44u_5={
  147379. {
  147380. {0},
  147381. {0,0,&_44u5__p1_0},
  147382. {0,0,&_44u5__p2_0},
  147383. {0,0,&_44u5__p3_0},
  147384. {0,0,&_44u5__p4_0},
  147385. {0,0,&_44u5__p5_0},
  147386. {0,0,&_44u5__p6_0},
  147387. {&_44u5__p7_0,&_44u5__p7_1},
  147388. {&_44u5__p8_0,&_44u5__p8_1},
  147389. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  147390. }
  147391. };
  147392. static static_bookblock _resbook_44u_6={
  147393. {
  147394. {0},
  147395. {0,0,&_44u6__p1_0},
  147396. {0,0,&_44u6__p2_0},
  147397. {0,0,&_44u6__p3_0},
  147398. {0,0,&_44u6__p4_0},
  147399. {0,0,&_44u6__p5_0},
  147400. {0,0,&_44u6__p6_0},
  147401. {&_44u6__p7_0,&_44u6__p7_1},
  147402. {&_44u6__p8_0,&_44u6__p8_1},
  147403. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  147404. }
  147405. };
  147406. static static_bookblock _resbook_44u_7={
  147407. {
  147408. {0},
  147409. {0,0,&_44u7__p1_0},
  147410. {0,0,&_44u7__p2_0},
  147411. {0,0,&_44u7__p3_0},
  147412. {0,0,&_44u7__p4_0},
  147413. {0,0,&_44u7__p5_0},
  147414. {0,0,&_44u7__p6_0},
  147415. {&_44u7__p7_0,&_44u7__p7_1},
  147416. {&_44u7__p8_0,&_44u7__p8_1},
  147417. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  147418. }
  147419. };
  147420. static static_bookblock _resbook_44u_8={
  147421. {
  147422. {0},
  147423. {0,0,&_44u8_p1_0},
  147424. {0,0,&_44u8_p2_0},
  147425. {0,0,&_44u8_p3_0},
  147426. {0,0,&_44u8_p4_0},
  147427. {&_44u8_p5_0,&_44u8_p5_1},
  147428. {&_44u8_p6_0,&_44u8_p6_1},
  147429. {&_44u8_p7_0,&_44u8_p7_1},
  147430. {&_44u8_p8_0,&_44u8_p8_1},
  147431. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  147432. }
  147433. };
  147434. static static_bookblock _resbook_44u_9={
  147435. {
  147436. {0},
  147437. {0,0,&_44u9_p1_0},
  147438. {0,0,&_44u9_p2_0},
  147439. {0,0,&_44u9_p3_0},
  147440. {0,0,&_44u9_p4_0},
  147441. {&_44u9_p5_0,&_44u9_p5_1},
  147442. {&_44u9_p6_0,&_44u9_p6_1},
  147443. {&_44u9_p7_0,&_44u9_p7_1},
  147444. {&_44u9_p8_0,&_44u9_p8_1},
  147445. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  147446. }
  147447. };
  147448. static vorbis_residue_template _res_44u_n1[]={
  147449. {1,0, &_residue_44_low_un,
  147450. &_huff_book__44un1__short,&_huff_book__44un1__short,
  147451. &_resbook_44u_n1,&_resbook_44u_n1},
  147452. {1,0, &_residue_44_low_un,
  147453. &_huff_book__44un1__long,&_huff_book__44un1__long,
  147454. &_resbook_44u_n1,&_resbook_44u_n1}
  147455. };
  147456. static vorbis_residue_template _res_44u_0[]={
  147457. {1,0, &_residue_44_low_un,
  147458. &_huff_book__44u0__short,&_huff_book__44u0__short,
  147459. &_resbook_44u_0,&_resbook_44u_0},
  147460. {1,0, &_residue_44_low_un,
  147461. &_huff_book__44u0__long,&_huff_book__44u0__long,
  147462. &_resbook_44u_0,&_resbook_44u_0}
  147463. };
  147464. static vorbis_residue_template _res_44u_1[]={
  147465. {1,0, &_residue_44_low_un,
  147466. &_huff_book__44u1__short,&_huff_book__44u1__short,
  147467. &_resbook_44u_1,&_resbook_44u_1},
  147468. {1,0, &_residue_44_low_un,
  147469. &_huff_book__44u1__long,&_huff_book__44u1__long,
  147470. &_resbook_44u_1,&_resbook_44u_1}
  147471. };
  147472. static vorbis_residue_template _res_44u_2[]={
  147473. {1,0, &_residue_44_low_un,
  147474. &_huff_book__44u2__short,&_huff_book__44u2__short,
  147475. &_resbook_44u_2,&_resbook_44u_2},
  147476. {1,0, &_residue_44_low_un,
  147477. &_huff_book__44u2__long,&_huff_book__44u2__long,
  147478. &_resbook_44u_2,&_resbook_44u_2}
  147479. };
  147480. static vorbis_residue_template _res_44u_3[]={
  147481. {1,0, &_residue_44_low_un,
  147482. &_huff_book__44u3__short,&_huff_book__44u3__short,
  147483. &_resbook_44u_3,&_resbook_44u_3},
  147484. {1,0, &_residue_44_low_un,
  147485. &_huff_book__44u3__long,&_huff_book__44u3__long,
  147486. &_resbook_44u_3,&_resbook_44u_3}
  147487. };
  147488. static vorbis_residue_template _res_44u_4[]={
  147489. {1,0, &_residue_44_low_un,
  147490. &_huff_book__44u4__short,&_huff_book__44u4__short,
  147491. &_resbook_44u_4,&_resbook_44u_4},
  147492. {1,0, &_residue_44_low_un,
  147493. &_huff_book__44u4__long,&_huff_book__44u4__long,
  147494. &_resbook_44u_4,&_resbook_44u_4}
  147495. };
  147496. static vorbis_residue_template _res_44u_5[]={
  147497. {1,0, &_residue_44_mid_un,
  147498. &_huff_book__44u5__short,&_huff_book__44u5__short,
  147499. &_resbook_44u_5,&_resbook_44u_5},
  147500. {1,0, &_residue_44_mid_un,
  147501. &_huff_book__44u5__long,&_huff_book__44u5__long,
  147502. &_resbook_44u_5,&_resbook_44u_5}
  147503. };
  147504. static vorbis_residue_template _res_44u_6[]={
  147505. {1,0, &_residue_44_mid_un,
  147506. &_huff_book__44u6__short,&_huff_book__44u6__short,
  147507. &_resbook_44u_6,&_resbook_44u_6},
  147508. {1,0, &_residue_44_mid_un,
  147509. &_huff_book__44u6__long,&_huff_book__44u6__long,
  147510. &_resbook_44u_6,&_resbook_44u_6}
  147511. };
  147512. static vorbis_residue_template _res_44u_7[]={
  147513. {1,0, &_residue_44_mid_un,
  147514. &_huff_book__44u7__short,&_huff_book__44u7__short,
  147515. &_resbook_44u_7,&_resbook_44u_7},
  147516. {1,0, &_residue_44_mid_un,
  147517. &_huff_book__44u7__long,&_huff_book__44u7__long,
  147518. &_resbook_44u_7,&_resbook_44u_7}
  147519. };
  147520. static vorbis_residue_template _res_44u_8[]={
  147521. {1,0, &_residue_44_hi_un,
  147522. &_huff_book__44u8__short,&_huff_book__44u8__short,
  147523. &_resbook_44u_8,&_resbook_44u_8},
  147524. {1,0, &_residue_44_hi_un,
  147525. &_huff_book__44u8__long,&_huff_book__44u8__long,
  147526. &_resbook_44u_8,&_resbook_44u_8}
  147527. };
  147528. static vorbis_residue_template _res_44u_9[]={
  147529. {1,0, &_residue_44_hi_un,
  147530. &_huff_book__44u9__short,&_huff_book__44u9__short,
  147531. &_resbook_44u_9,&_resbook_44u_9},
  147532. {1,0, &_residue_44_hi_un,
  147533. &_huff_book__44u9__long,&_huff_book__44u9__long,
  147534. &_resbook_44u_9,&_resbook_44u_9}
  147535. };
  147536. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  147537. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  147538. { _map_nominal_u, _res_44u_0 }, /* 0 */
  147539. { _map_nominal_u, _res_44u_1 }, /* 1 */
  147540. { _map_nominal_u, _res_44u_2 }, /* 2 */
  147541. { _map_nominal_u, _res_44u_3 }, /* 3 */
  147542. { _map_nominal_u, _res_44u_4 }, /* 4 */
  147543. { _map_nominal_u, _res_44u_5 }, /* 5 */
  147544. { _map_nominal_u, _res_44u_6 }, /* 6 */
  147545. { _map_nominal_u, _res_44u_7 }, /* 7 */
  147546. { _map_nominal_u, _res_44u_8 }, /* 8 */
  147547. { _map_nominal_u, _res_44u_9 }, /* 9 */
  147548. };
  147549. /********* End of inlined file: residue_44u.h *********/
  147550. static double rate_mapping_44_un[12]={
  147551. 32000.,48000.,60000.,70000.,80000.,86000.,
  147552. 96000.,110000.,120000.,140000.,160000.,240001.
  147553. };
  147554. ve_setup_data_template ve_setup_44_uncoupled={
  147555. 11,
  147556. rate_mapping_44_un,
  147557. quality_mapping_44,
  147558. -1,
  147559. 40000,
  147560. 50000,
  147561. blocksize_short_44,
  147562. blocksize_long_44,
  147563. _psy_tone_masteratt_44,
  147564. _psy_tone_0dB,
  147565. _psy_tone_suppress,
  147566. _vp_tonemask_adj_otherblock,
  147567. _vp_tonemask_adj_longblock,
  147568. _vp_tonemask_adj_otherblock,
  147569. _psy_noiseguards_44,
  147570. _psy_noisebias_impulse,
  147571. _psy_noisebias_padding,
  147572. _psy_noisebias_trans,
  147573. _psy_noisebias_long,
  147574. _psy_noise_suppress,
  147575. _psy_compand_44,
  147576. _psy_compand_short_mapping,
  147577. _psy_compand_long_mapping,
  147578. {_noise_start_short_44,_noise_start_long_44},
  147579. {_noise_part_short_44,_noise_part_long_44},
  147580. _noise_thresh_44,
  147581. _psy_ath_floater,
  147582. _psy_ath_abs,
  147583. _psy_lowpass_44,
  147584. _psy_global_44,
  147585. _global_mapping_44,
  147586. NULL,
  147587. _floor_books,
  147588. _floor,
  147589. _floor_short_mapping_44,
  147590. _floor_long_mapping_44,
  147591. _mapres_template_44_uncoupled
  147592. };
  147593. /********* End of inlined file: setup_44u.h *********/
  147594. /********* Start of inlined file: setup_32.h *********/
  147595. static double rate_mapping_32[12]={
  147596. 18000.,28000.,35000.,45000.,56000.,60000.,
  147597. 75000.,90000.,100000.,115000.,150000.,190000.,
  147598. };
  147599. static double rate_mapping_32_un[12]={
  147600. 30000.,42000.,52000.,64000.,72000.,78000.,
  147601. 86000.,92000.,110000.,120000.,140000.,190000.,
  147602. };
  147603. static double _psy_lowpass_32[12]={
  147604. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  147605. };
  147606. ve_setup_data_template ve_setup_32_stereo={
  147607. 11,
  147608. rate_mapping_32,
  147609. quality_mapping_44,
  147610. 2,
  147611. 26000,
  147612. 40000,
  147613. blocksize_short_44,
  147614. blocksize_long_44,
  147615. _psy_tone_masteratt_44,
  147616. _psy_tone_0dB,
  147617. _psy_tone_suppress,
  147618. _vp_tonemask_adj_otherblock,
  147619. _vp_tonemask_adj_longblock,
  147620. _vp_tonemask_adj_otherblock,
  147621. _psy_noiseguards_44,
  147622. _psy_noisebias_impulse,
  147623. _psy_noisebias_padding,
  147624. _psy_noisebias_trans,
  147625. _psy_noisebias_long,
  147626. _psy_noise_suppress,
  147627. _psy_compand_44,
  147628. _psy_compand_short_mapping,
  147629. _psy_compand_long_mapping,
  147630. {_noise_start_short_44,_noise_start_long_44},
  147631. {_noise_part_short_44,_noise_part_long_44},
  147632. _noise_thresh_44,
  147633. _psy_ath_floater,
  147634. _psy_ath_abs,
  147635. _psy_lowpass_32,
  147636. _psy_global_44,
  147637. _global_mapping_44,
  147638. _psy_stereo_modes_44,
  147639. _floor_books,
  147640. _floor,
  147641. _floor_short_mapping_44,
  147642. _floor_long_mapping_44,
  147643. _mapres_template_44_stereo
  147644. };
  147645. ve_setup_data_template ve_setup_32_uncoupled={
  147646. 11,
  147647. rate_mapping_32_un,
  147648. quality_mapping_44,
  147649. -1,
  147650. 26000,
  147651. 40000,
  147652. blocksize_short_44,
  147653. blocksize_long_44,
  147654. _psy_tone_masteratt_44,
  147655. _psy_tone_0dB,
  147656. _psy_tone_suppress,
  147657. _vp_tonemask_adj_otherblock,
  147658. _vp_tonemask_adj_longblock,
  147659. _vp_tonemask_adj_otherblock,
  147660. _psy_noiseguards_44,
  147661. _psy_noisebias_impulse,
  147662. _psy_noisebias_padding,
  147663. _psy_noisebias_trans,
  147664. _psy_noisebias_long,
  147665. _psy_noise_suppress,
  147666. _psy_compand_44,
  147667. _psy_compand_short_mapping,
  147668. _psy_compand_long_mapping,
  147669. {_noise_start_short_44,_noise_start_long_44},
  147670. {_noise_part_short_44,_noise_part_long_44},
  147671. _noise_thresh_44,
  147672. _psy_ath_floater,
  147673. _psy_ath_abs,
  147674. _psy_lowpass_32,
  147675. _psy_global_44,
  147676. _global_mapping_44,
  147677. NULL,
  147678. _floor_books,
  147679. _floor,
  147680. _floor_short_mapping_44,
  147681. _floor_long_mapping_44,
  147682. _mapres_template_44_uncoupled
  147683. };
  147684. /********* End of inlined file: setup_32.h *********/
  147685. /********* Start of inlined file: setup_8.h *********/
  147686. /********* Start of inlined file: psych_8.h *********/
  147687. static att3 _psy_tone_masteratt_8[3]={
  147688. {{ 32, 25, 12}, 0, 0}, /* 0 */
  147689. {{ 30, 25, 12}, 0, 0}, /* 0 */
  147690. {{ 20, 0, -14}, 0, 0}, /* 0 */
  147691. };
  147692. static vp_adjblock _vp_tonemask_adj_8[3]={
  147693. /* adjust for mode zero */
  147694. /* 63 125 250 500 1 2 4 8 16 */
  147695. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  147696. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  147697. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  147698. };
  147699. static noise3 _psy_noisebias_8[3]={
  147700. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  147701. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  147702. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  147703. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  147704. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  147705. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  147706. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  147707. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  147708. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  147709. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  147710. };
  147711. /* stereo mode by base quality level */
  147712. static adj_stereo _psy_stereo_modes_8[3]={
  147713. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  147714. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147715. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147716. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  147717. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147718. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147719. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147720. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  147721. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147722. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147723. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147724. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  147725. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147726. };
  147727. static noiseguard _psy_noiseguards_8[2]={
  147728. {10,10,-1},
  147729. {10,10,-1},
  147730. };
  147731. static compandblock _psy_compand_8[2]={
  147732. {{
  147733. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  147734. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  147735. 12,12,13,13,14,14,15, 15, /* 23dB */
  147736. 16,16,17,17,17,18,18, 19, /* 31dB */
  147737. 19,19,20,21,22,23,24, 25, /* 39dB */
  147738. }},
  147739. {{
  147740. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  147741. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  147742. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  147743. 9,10,11,12,13,14,15, 16, /* 31dB */
  147744. 17,18,19,20,21,22,23, 24, /* 39dB */
  147745. }},
  147746. };
  147747. static double _psy_lowpass_8[3]={3.,4.,4.};
  147748. static int _noise_start_8[2]={
  147749. 64,64,
  147750. };
  147751. static int _noise_part_8[2]={
  147752. 8,8,
  147753. };
  147754. static int _psy_ath_floater_8[3]={
  147755. -100,-100,-105,
  147756. };
  147757. static int _psy_ath_abs_8[3]={
  147758. -130,-130,-140,
  147759. };
  147760. /********* End of inlined file: psych_8.h *********/
  147761. /********* Start of inlined file: residue_8.h *********/
  147762. /***** residue backends *********************************************/
  147763. static static_bookblock _resbook_8s_0={
  147764. {
  147765. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  147766. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  147767. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  147768. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  147769. }
  147770. };
  147771. static static_bookblock _resbook_8s_1={
  147772. {
  147773. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  147774. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  147775. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  147776. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  147777. }
  147778. };
  147779. static vorbis_residue_template _res_8s_0[]={
  147780. {2,0, &_residue_44_mid,
  147781. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  147782. &_resbook_8s_0,&_resbook_8s_0},
  147783. };
  147784. static vorbis_residue_template _res_8s_1[]={
  147785. {2,0, &_residue_44_mid,
  147786. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  147787. &_resbook_8s_1,&_resbook_8s_1},
  147788. };
  147789. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  147790. { _map_nominal, _res_8s_0 }, /* 0 */
  147791. { _map_nominal, _res_8s_1 }, /* 1 */
  147792. };
  147793. static static_bookblock _resbook_8u_0={
  147794. {
  147795. {0},
  147796. {0,0,&_8u0__p1_0},
  147797. {0,0,&_8u0__p2_0},
  147798. {0,0,&_8u0__p3_0},
  147799. {0,0,&_8u0__p4_0},
  147800. {0,0,&_8u0__p5_0},
  147801. {&_8u0__p6_0,&_8u0__p6_1},
  147802. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  147803. }
  147804. };
  147805. static static_bookblock _resbook_8u_1={
  147806. {
  147807. {0},
  147808. {0,0,&_8u1__p1_0},
  147809. {0,0,&_8u1__p2_0},
  147810. {0,0,&_8u1__p3_0},
  147811. {0,0,&_8u1__p4_0},
  147812. {0,0,&_8u1__p5_0},
  147813. {0,0,&_8u1__p6_0},
  147814. {&_8u1__p7_0,&_8u1__p7_1},
  147815. {&_8u1__p8_0,&_8u1__p8_1},
  147816. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  147817. }
  147818. };
  147819. static vorbis_residue_template _res_8u_0[]={
  147820. {1,0, &_residue_44_low_un,
  147821. &_huff_book__8u0__single,&_huff_book__8u0__single,
  147822. &_resbook_8u_0,&_resbook_8u_0},
  147823. };
  147824. static vorbis_residue_template _res_8u_1[]={
  147825. {1,0, &_residue_44_mid_un,
  147826. &_huff_book__8u1__single,&_huff_book__8u1__single,
  147827. &_resbook_8u_1,&_resbook_8u_1},
  147828. };
  147829. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  147830. { _map_nominal_u, _res_8u_0 }, /* 0 */
  147831. { _map_nominal_u, _res_8u_1 }, /* 1 */
  147832. };
  147833. /********* End of inlined file: residue_8.h *********/
  147834. static int blocksize_8[2]={
  147835. 512,512
  147836. };
  147837. static int _floor_mapping_8[2]={
  147838. 6,6,
  147839. };
  147840. static double rate_mapping_8[3]={
  147841. 6000.,9000.,32000.,
  147842. };
  147843. static double rate_mapping_8_uncoupled[3]={
  147844. 8000.,14000.,42000.,
  147845. };
  147846. static double quality_mapping_8[3]={
  147847. -.1,.0,1.
  147848. };
  147849. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  147850. static double _global_mapping_8[3]={ 1., 2., 3. };
  147851. ve_setup_data_template ve_setup_8_stereo={
  147852. 2,
  147853. rate_mapping_8,
  147854. quality_mapping_8,
  147855. 2,
  147856. 8000,
  147857. 9000,
  147858. blocksize_8,
  147859. blocksize_8,
  147860. _psy_tone_masteratt_8,
  147861. _psy_tone_0dB,
  147862. _psy_tone_suppress,
  147863. _vp_tonemask_adj_8,
  147864. NULL,
  147865. _vp_tonemask_adj_8,
  147866. _psy_noiseguards_8,
  147867. _psy_noisebias_8,
  147868. _psy_noisebias_8,
  147869. NULL,
  147870. NULL,
  147871. _psy_noise_suppress,
  147872. _psy_compand_8,
  147873. _psy_compand_8_mapping,
  147874. NULL,
  147875. {_noise_start_8,_noise_start_8},
  147876. {_noise_part_8,_noise_part_8},
  147877. _noise_thresh_5only,
  147878. _psy_ath_floater_8,
  147879. _psy_ath_abs_8,
  147880. _psy_lowpass_8,
  147881. _psy_global_44,
  147882. _global_mapping_8,
  147883. _psy_stereo_modes_8,
  147884. _floor_books,
  147885. _floor,
  147886. _floor_mapping_8,
  147887. NULL,
  147888. _mapres_template_8_stereo
  147889. };
  147890. ve_setup_data_template ve_setup_8_uncoupled={
  147891. 2,
  147892. rate_mapping_8_uncoupled,
  147893. quality_mapping_8,
  147894. -1,
  147895. 8000,
  147896. 9000,
  147897. blocksize_8,
  147898. blocksize_8,
  147899. _psy_tone_masteratt_8,
  147900. _psy_tone_0dB,
  147901. _psy_tone_suppress,
  147902. _vp_tonemask_adj_8,
  147903. NULL,
  147904. _vp_tonemask_adj_8,
  147905. _psy_noiseguards_8,
  147906. _psy_noisebias_8,
  147907. _psy_noisebias_8,
  147908. NULL,
  147909. NULL,
  147910. _psy_noise_suppress,
  147911. _psy_compand_8,
  147912. _psy_compand_8_mapping,
  147913. NULL,
  147914. {_noise_start_8,_noise_start_8},
  147915. {_noise_part_8,_noise_part_8},
  147916. _noise_thresh_5only,
  147917. _psy_ath_floater_8,
  147918. _psy_ath_abs_8,
  147919. _psy_lowpass_8,
  147920. _psy_global_44,
  147921. _global_mapping_8,
  147922. _psy_stereo_modes_8,
  147923. _floor_books,
  147924. _floor,
  147925. _floor_mapping_8,
  147926. NULL,
  147927. _mapres_template_8_uncoupled
  147928. };
  147929. /********* End of inlined file: setup_8.h *********/
  147930. /********* Start of inlined file: setup_11.h *********/
  147931. /********* Start of inlined file: psych_11.h *********/
  147932. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  147933. static att3 _psy_tone_masteratt_11[3]={
  147934. {{ 30, 25, 12}, 0, 0}, /* 0 */
  147935. {{ 30, 25, 12}, 0, 0}, /* 0 */
  147936. {{ 20, 0, -14}, 0, 0}, /* 0 */
  147937. };
  147938. static vp_adjblock _vp_tonemask_adj_11[3]={
  147939. /* adjust for mode zero */
  147940. /* 63 125 250 500 1 2 4 8 16 */
  147941. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  147942. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  147943. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  147944. };
  147945. static noise3 _psy_noisebias_11[3]={
  147946. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  147947. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  147948. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  147949. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  147950. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  147951. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  147952. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  147953. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  147954. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  147955. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  147956. };
  147957. static double _noise_thresh_11[3]={ .3,.5,.5 };
  147958. /********* End of inlined file: psych_11.h *********/
  147959. static int blocksize_11[2]={
  147960. 512,512
  147961. };
  147962. static int _floor_mapping_11[2]={
  147963. 6,6,
  147964. };
  147965. static double rate_mapping_11[3]={
  147966. 8000.,13000.,44000.,
  147967. };
  147968. static double rate_mapping_11_uncoupled[3]={
  147969. 12000.,20000.,50000.,
  147970. };
  147971. static double quality_mapping_11[3]={
  147972. -.1,.0,1.
  147973. };
  147974. ve_setup_data_template ve_setup_11_stereo={
  147975. 2,
  147976. rate_mapping_11,
  147977. quality_mapping_11,
  147978. 2,
  147979. 9000,
  147980. 15000,
  147981. blocksize_11,
  147982. blocksize_11,
  147983. _psy_tone_masteratt_11,
  147984. _psy_tone_0dB,
  147985. _psy_tone_suppress,
  147986. _vp_tonemask_adj_11,
  147987. NULL,
  147988. _vp_tonemask_adj_11,
  147989. _psy_noiseguards_8,
  147990. _psy_noisebias_11,
  147991. _psy_noisebias_11,
  147992. NULL,
  147993. NULL,
  147994. _psy_noise_suppress,
  147995. _psy_compand_8,
  147996. _psy_compand_8_mapping,
  147997. NULL,
  147998. {_noise_start_8,_noise_start_8},
  147999. {_noise_part_8,_noise_part_8},
  148000. _noise_thresh_11,
  148001. _psy_ath_floater_8,
  148002. _psy_ath_abs_8,
  148003. _psy_lowpass_11,
  148004. _psy_global_44,
  148005. _global_mapping_8,
  148006. _psy_stereo_modes_8,
  148007. _floor_books,
  148008. _floor,
  148009. _floor_mapping_11,
  148010. NULL,
  148011. _mapres_template_8_stereo
  148012. };
  148013. ve_setup_data_template ve_setup_11_uncoupled={
  148014. 2,
  148015. rate_mapping_11_uncoupled,
  148016. quality_mapping_11,
  148017. -1,
  148018. 9000,
  148019. 15000,
  148020. blocksize_11,
  148021. blocksize_11,
  148022. _psy_tone_masteratt_11,
  148023. _psy_tone_0dB,
  148024. _psy_tone_suppress,
  148025. _vp_tonemask_adj_11,
  148026. NULL,
  148027. _vp_tonemask_adj_11,
  148028. _psy_noiseguards_8,
  148029. _psy_noisebias_11,
  148030. _psy_noisebias_11,
  148031. NULL,
  148032. NULL,
  148033. _psy_noise_suppress,
  148034. _psy_compand_8,
  148035. _psy_compand_8_mapping,
  148036. NULL,
  148037. {_noise_start_8,_noise_start_8},
  148038. {_noise_part_8,_noise_part_8},
  148039. _noise_thresh_11,
  148040. _psy_ath_floater_8,
  148041. _psy_ath_abs_8,
  148042. _psy_lowpass_11,
  148043. _psy_global_44,
  148044. _global_mapping_8,
  148045. _psy_stereo_modes_8,
  148046. _floor_books,
  148047. _floor,
  148048. _floor_mapping_11,
  148049. NULL,
  148050. _mapres_template_8_uncoupled
  148051. };
  148052. /********* End of inlined file: setup_11.h *********/
  148053. /********* Start of inlined file: setup_16.h *********/
  148054. /********* Start of inlined file: psych_16.h *********/
  148055. /* stereo mode by base quality level */
  148056. static adj_stereo _psy_stereo_modes_16[4]={
  148057. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  148058. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148059. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  148060. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  148061. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148062. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148063. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  148064. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  148065. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148066. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148067. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148068. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  148069. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148070. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  148071. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  148072. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  148073. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148074. };
  148075. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  148076. static att3 _psy_tone_masteratt_16[4]={
  148077. {{ 30, 25, 12}, 0, 0}, /* 0 */
  148078. {{ 25, 22, 12}, 0, 0}, /* 0 */
  148079. {{ 20, 12, 0}, 0, 0}, /* 0 */
  148080. {{ 15, 0, -14}, 0, 0}, /* 0 */
  148081. };
  148082. static vp_adjblock _vp_tonemask_adj_16[4]={
  148083. /* adjust for mode zero */
  148084. /* 63 125 250 500 1 2 4 8 16 */
  148085. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  148086. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  148087. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  148088. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  148089. };
  148090. static noise3 _psy_noisebias_16_short[4]={
  148091. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  148092. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  148093. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  148094. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  148095. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  148096. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  148097. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  148098. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  148099. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  148100. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148101. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  148102. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  148103. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148104. };
  148105. static noise3 _psy_noisebias_16_impulse[4]={
  148106. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  148107. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  148108. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  148109. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  148110. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  148111. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  148112. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  148113. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  148114. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  148115. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148116. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  148117. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  148118. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148119. };
  148120. static noise3 _psy_noisebias_16[4]={
  148121. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  148122. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  148123. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  148124. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  148125. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  148126. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  148127. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  148128. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  148129. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  148130. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148131. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  148132. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  148133. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148134. };
  148135. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  148136. static int _noise_start_16[3]={ 256,256,9999 };
  148137. static int _noise_part_16[4]={ 8,8,8,8 };
  148138. static int _psy_ath_floater_16[4]={
  148139. -100,-100,-100,-105,
  148140. };
  148141. static int _psy_ath_abs_16[4]={
  148142. -130,-130,-130,-140,
  148143. };
  148144. /********* End of inlined file: psych_16.h *********/
  148145. /********* Start of inlined file: residue_16.h *********/
  148146. /***** residue backends *********************************************/
  148147. static static_bookblock _resbook_16s_0={
  148148. {
  148149. {0},
  148150. {0,0,&_16c0_s_p1_0},
  148151. {0,0,&_16c0_s_p2_0},
  148152. {0,0,&_16c0_s_p3_0},
  148153. {0,0,&_16c0_s_p4_0},
  148154. {0,0,&_16c0_s_p5_0},
  148155. {0,0,&_16c0_s_p6_0},
  148156. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  148157. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  148158. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  148159. }
  148160. };
  148161. static static_bookblock _resbook_16s_1={
  148162. {
  148163. {0},
  148164. {0,0,&_16c1_s_p1_0},
  148165. {0,0,&_16c1_s_p2_0},
  148166. {0,0,&_16c1_s_p3_0},
  148167. {0,0,&_16c1_s_p4_0},
  148168. {0,0,&_16c1_s_p5_0},
  148169. {0,0,&_16c1_s_p6_0},
  148170. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  148171. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  148172. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  148173. }
  148174. };
  148175. static static_bookblock _resbook_16s_2={
  148176. {
  148177. {0},
  148178. {0,0,&_16c2_s_p1_0},
  148179. {0,0,&_16c2_s_p2_0},
  148180. {0,0,&_16c2_s_p3_0},
  148181. {0,0,&_16c2_s_p4_0},
  148182. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  148183. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  148184. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  148185. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  148186. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  148187. }
  148188. };
  148189. static vorbis_residue_template _res_16s_0[]={
  148190. {2,0, &_residue_44_mid,
  148191. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  148192. &_resbook_16s_0,&_resbook_16s_0},
  148193. };
  148194. static vorbis_residue_template _res_16s_1[]={
  148195. {2,0, &_residue_44_mid,
  148196. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  148197. &_resbook_16s_1,&_resbook_16s_1},
  148198. {2,0, &_residue_44_mid,
  148199. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  148200. &_resbook_16s_1,&_resbook_16s_1}
  148201. };
  148202. static vorbis_residue_template _res_16s_2[]={
  148203. {2,0, &_residue_44_high,
  148204. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  148205. &_resbook_16s_2,&_resbook_16s_2},
  148206. {2,0, &_residue_44_high,
  148207. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  148208. &_resbook_16s_2,&_resbook_16s_2}
  148209. };
  148210. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  148211. { _map_nominal, _res_16s_0 }, /* 0 */
  148212. { _map_nominal, _res_16s_1 }, /* 1 */
  148213. { _map_nominal, _res_16s_2 }, /* 2 */
  148214. };
  148215. static static_bookblock _resbook_16u_0={
  148216. {
  148217. {0},
  148218. {0,0,&_16u0__p1_0},
  148219. {0,0,&_16u0__p2_0},
  148220. {0,0,&_16u0__p3_0},
  148221. {0,0,&_16u0__p4_0},
  148222. {0,0,&_16u0__p5_0},
  148223. {&_16u0__p6_0,&_16u0__p6_1},
  148224. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  148225. }
  148226. };
  148227. static static_bookblock _resbook_16u_1={
  148228. {
  148229. {0},
  148230. {0,0,&_16u1__p1_0},
  148231. {0,0,&_16u1__p2_0},
  148232. {0,0,&_16u1__p3_0},
  148233. {0,0,&_16u1__p4_0},
  148234. {0,0,&_16u1__p5_0},
  148235. {0,0,&_16u1__p6_0},
  148236. {&_16u1__p7_0,&_16u1__p7_1},
  148237. {&_16u1__p8_0,&_16u1__p8_1},
  148238. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  148239. }
  148240. };
  148241. static static_bookblock _resbook_16u_2={
  148242. {
  148243. {0},
  148244. {0,0,&_16u2_p1_0},
  148245. {0,0,&_16u2_p2_0},
  148246. {0,0,&_16u2_p3_0},
  148247. {0,0,&_16u2_p4_0},
  148248. {&_16u2_p5_0,&_16u2_p5_1},
  148249. {&_16u2_p6_0,&_16u2_p6_1},
  148250. {&_16u2_p7_0,&_16u2_p7_1},
  148251. {&_16u2_p8_0,&_16u2_p8_1},
  148252. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  148253. }
  148254. };
  148255. static vorbis_residue_template _res_16u_0[]={
  148256. {1,0, &_residue_44_low_un,
  148257. &_huff_book__16u0__single,&_huff_book__16u0__single,
  148258. &_resbook_16u_0,&_resbook_16u_0},
  148259. };
  148260. static vorbis_residue_template _res_16u_1[]={
  148261. {1,0, &_residue_44_mid_un,
  148262. &_huff_book__16u1__short,&_huff_book__16u1__short,
  148263. &_resbook_16u_1,&_resbook_16u_1},
  148264. {1,0, &_residue_44_mid_un,
  148265. &_huff_book__16u1__long,&_huff_book__16u1__long,
  148266. &_resbook_16u_1,&_resbook_16u_1}
  148267. };
  148268. static vorbis_residue_template _res_16u_2[]={
  148269. {1,0, &_residue_44_hi_un,
  148270. &_huff_book__16u2__short,&_huff_book__16u2__short,
  148271. &_resbook_16u_2,&_resbook_16u_2},
  148272. {1,0, &_residue_44_hi_un,
  148273. &_huff_book__16u2__long,&_huff_book__16u2__long,
  148274. &_resbook_16u_2,&_resbook_16u_2}
  148275. };
  148276. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  148277. { _map_nominal_u, _res_16u_0 }, /* 0 */
  148278. { _map_nominal_u, _res_16u_1 }, /* 1 */
  148279. { _map_nominal_u, _res_16u_2 }, /* 2 */
  148280. };
  148281. /********* End of inlined file: residue_16.h *********/
  148282. static int blocksize_16_short[3]={
  148283. 1024,512,512
  148284. };
  148285. static int blocksize_16_long[3]={
  148286. 1024,1024,1024
  148287. };
  148288. static int _floor_mapping_16_short[3]={
  148289. 9,3,3
  148290. };
  148291. static int _floor_mapping_16[3]={
  148292. 9,9,9
  148293. };
  148294. static double rate_mapping_16[4]={
  148295. 12000.,20000.,44000.,86000.
  148296. };
  148297. static double rate_mapping_16_uncoupled[4]={
  148298. 16000.,28000.,64000.,100000.
  148299. };
  148300. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  148301. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  148302. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  148303. ve_setup_data_template ve_setup_16_stereo={
  148304. 3,
  148305. rate_mapping_16,
  148306. quality_mapping_16,
  148307. 2,
  148308. 15000,
  148309. 19000,
  148310. blocksize_16_short,
  148311. blocksize_16_long,
  148312. _psy_tone_masteratt_16,
  148313. _psy_tone_0dB,
  148314. _psy_tone_suppress,
  148315. _vp_tonemask_adj_16,
  148316. _vp_tonemask_adj_16,
  148317. _vp_tonemask_adj_16,
  148318. _psy_noiseguards_8,
  148319. _psy_noisebias_16_impulse,
  148320. _psy_noisebias_16_short,
  148321. _psy_noisebias_16_short,
  148322. _psy_noisebias_16,
  148323. _psy_noise_suppress,
  148324. _psy_compand_8,
  148325. _psy_compand_16_mapping,
  148326. _psy_compand_16_mapping,
  148327. {_noise_start_16,_noise_start_16},
  148328. { _noise_part_16, _noise_part_16},
  148329. _noise_thresh_16,
  148330. _psy_ath_floater_16,
  148331. _psy_ath_abs_16,
  148332. _psy_lowpass_16,
  148333. _psy_global_44,
  148334. _global_mapping_16,
  148335. _psy_stereo_modes_16,
  148336. _floor_books,
  148337. _floor,
  148338. _floor_mapping_16_short,
  148339. _floor_mapping_16,
  148340. _mapres_template_16_stereo
  148341. };
  148342. ve_setup_data_template ve_setup_16_uncoupled={
  148343. 3,
  148344. rate_mapping_16_uncoupled,
  148345. quality_mapping_16,
  148346. -1,
  148347. 15000,
  148348. 19000,
  148349. blocksize_16_short,
  148350. blocksize_16_long,
  148351. _psy_tone_masteratt_16,
  148352. _psy_tone_0dB,
  148353. _psy_tone_suppress,
  148354. _vp_tonemask_adj_16,
  148355. _vp_tonemask_adj_16,
  148356. _vp_tonemask_adj_16,
  148357. _psy_noiseguards_8,
  148358. _psy_noisebias_16_impulse,
  148359. _psy_noisebias_16_short,
  148360. _psy_noisebias_16_short,
  148361. _psy_noisebias_16,
  148362. _psy_noise_suppress,
  148363. _psy_compand_8,
  148364. _psy_compand_16_mapping,
  148365. _psy_compand_16_mapping,
  148366. {_noise_start_16,_noise_start_16},
  148367. { _noise_part_16, _noise_part_16},
  148368. _noise_thresh_16,
  148369. _psy_ath_floater_16,
  148370. _psy_ath_abs_16,
  148371. _psy_lowpass_16,
  148372. _psy_global_44,
  148373. _global_mapping_16,
  148374. _psy_stereo_modes_16,
  148375. _floor_books,
  148376. _floor,
  148377. _floor_mapping_16_short,
  148378. _floor_mapping_16,
  148379. _mapres_template_16_uncoupled
  148380. };
  148381. /********* End of inlined file: setup_16.h *********/
  148382. /********* Start of inlined file: setup_22.h *********/
  148383. static double rate_mapping_22[4]={
  148384. 15000.,20000.,44000.,86000.
  148385. };
  148386. static double rate_mapping_22_uncoupled[4]={
  148387. 16000.,28000.,50000.,90000.
  148388. };
  148389. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  148390. ve_setup_data_template ve_setup_22_stereo={
  148391. 3,
  148392. rate_mapping_22,
  148393. quality_mapping_16,
  148394. 2,
  148395. 19000,
  148396. 26000,
  148397. blocksize_16_short,
  148398. blocksize_16_long,
  148399. _psy_tone_masteratt_16,
  148400. _psy_tone_0dB,
  148401. _psy_tone_suppress,
  148402. _vp_tonemask_adj_16,
  148403. _vp_tonemask_adj_16,
  148404. _vp_tonemask_adj_16,
  148405. _psy_noiseguards_8,
  148406. _psy_noisebias_16_impulse,
  148407. _psy_noisebias_16_short,
  148408. _psy_noisebias_16_short,
  148409. _psy_noisebias_16,
  148410. _psy_noise_suppress,
  148411. _psy_compand_8,
  148412. _psy_compand_8_mapping,
  148413. _psy_compand_8_mapping,
  148414. {_noise_start_16,_noise_start_16},
  148415. { _noise_part_16, _noise_part_16},
  148416. _noise_thresh_16,
  148417. _psy_ath_floater_16,
  148418. _psy_ath_abs_16,
  148419. _psy_lowpass_22,
  148420. _psy_global_44,
  148421. _global_mapping_16,
  148422. _psy_stereo_modes_16,
  148423. _floor_books,
  148424. _floor,
  148425. _floor_mapping_16_short,
  148426. _floor_mapping_16,
  148427. _mapres_template_16_stereo
  148428. };
  148429. ve_setup_data_template ve_setup_22_uncoupled={
  148430. 3,
  148431. rate_mapping_22_uncoupled,
  148432. quality_mapping_16,
  148433. -1,
  148434. 19000,
  148435. 26000,
  148436. blocksize_16_short,
  148437. blocksize_16_long,
  148438. _psy_tone_masteratt_16,
  148439. _psy_tone_0dB,
  148440. _psy_tone_suppress,
  148441. _vp_tonemask_adj_16,
  148442. _vp_tonemask_adj_16,
  148443. _vp_tonemask_adj_16,
  148444. _psy_noiseguards_8,
  148445. _psy_noisebias_16_impulse,
  148446. _psy_noisebias_16_short,
  148447. _psy_noisebias_16_short,
  148448. _psy_noisebias_16,
  148449. _psy_noise_suppress,
  148450. _psy_compand_8,
  148451. _psy_compand_8_mapping,
  148452. _psy_compand_8_mapping,
  148453. {_noise_start_16,_noise_start_16},
  148454. { _noise_part_16, _noise_part_16},
  148455. _noise_thresh_16,
  148456. _psy_ath_floater_16,
  148457. _psy_ath_abs_16,
  148458. _psy_lowpass_22,
  148459. _psy_global_44,
  148460. _global_mapping_16,
  148461. _psy_stereo_modes_16,
  148462. _floor_books,
  148463. _floor,
  148464. _floor_mapping_16_short,
  148465. _floor_mapping_16,
  148466. _mapres_template_16_uncoupled
  148467. };
  148468. /********* End of inlined file: setup_22.h *********/
  148469. /********* Start of inlined file: setup_X.h *********/
  148470. static double rate_mapping_X[12]={
  148471. -1.,-1.,-1.,-1.,-1.,-1.,
  148472. -1.,-1.,-1.,-1.,-1.,-1.
  148473. };
  148474. ve_setup_data_template ve_setup_X_stereo={
  148475. 11,
  148476. rate_mapping_X,
  148477. quality_mapping_44,
  148478. 2,
  148479. 50000,
  148480. 200000,
  148481. blocksize_short_44,
  148482. blocksize_long_44,
  148483. _psy_tone_masteratt_44,
  148484. _psy_tone_0dB,
  148485. _psy_tone_suppress,
  148486. _vp_tonemask_adj_otherblock,
  148487. _vp_tonemask_adj_longblock,
  148488. _vp_tonemask_adj_otherblock,
  148489. _psy_noiseguards_44,
  148490. _psy_noisebias_impulse,
  148491. _psy_noisebias_padding,
  148492. _psy_noisebias_trans,
  148493. _psy_noisebias_long,
  148494. _psy_noise_suppress,
  148495. _psy_compand_44,
  148496. _psy_compand_short_mapping,
  148497. _psy_compand_long_mapping,
  148498. {_noise_start_short_44,_noise_start_long_44},
  148499. {_noise_part_short_44,_noise_part_long_44},
  148500. _noise_thresh_44,
  148501. _psy_ath_floater,
  148502. _psy_ath_abs,
  148503. _psy_lowpass_44,
  148504. _psy_global_44,
  148505. _global_mapping_44,
  148506. _psy_stereo_modes_44,
  148507. _floor_books,
  148508. _floor,
  148509. _floor_short_mapping_44,
  148510. _floor_long_mapping_44,
  148511. _mapres_template_44_stereo
  148512. };
  148513. ve_setup_data_template ve_setup_X_uncoupled={
  148514. 11,
  148515. rate_mapping_X,
  148516. quality_mapping_44,
  148517. -1,
  148518. 50000,
  148519. 200000,
  148520. blocksize_short_44,
  148521. blocksize_long_44,
  148522. _psy_tone_masteratt_44,
  148523. _psy_tone_0dB,
  148524. _psy_tone_suppress,
  148525. _vp_tonemask_adj_otherblock,
  148526. _vp_tonemask_adj_longblock,
  148527. _vp_tonemask_adj_otherblock,
  148528. _psy_noiseguards_44,
  148529. _psy_noisebias_impulse,
  148530. _psy_noisebias_padding,
  148531. _psy_noisebias_trans,
  148532. _psy_noisebias_long,
  148533. _psy_noise_suppress,
  148534. _psy_compand_44,
  148535. _psy_compand_short_mapping,
  148536. _psy_compand_long_mapping,
  148537. {_noise_start_short_44,_noise_start_long_44},
  148538. {_noise_part_short_44,_noise_part_long_44},
  148539. _noise_thresh_44,
  148540. _psy_ath_floater,
  148541. _psy_ath_abs,
  148542. _psy_lowpass_44,
  148543. _psy_global_44,
  148544. _global_mapping_44,
  148545. NULL,
  148546. _floor_books,
  148547. _floor,
  148548. _floor_short_mapping_44,
  148549. _floor_long_mapping_44,
  148550. _mapres_template_44_uncoupled
  148551. };
  148552. ve_setup_data_template ve_setup_XX_stereo={
  148553. 2,
  148554. rate_mapping_X,
  148555. quality_mapping_8,
  148556. 2,
  148557. 0,
  148558. 8000,
  148559. blocksize_8,
  148560. blocksize_8,
  148561. _psy_tone_masteratt_8,
  148562. _psy_tone_0dB,
  148563. _psy_tone_suppress,
  148564. _vp_tonemask_adj_8,
  148565. NULL,
  148566. _vp_tonemask_adj_8,
  148567. _psy_noiseguards_8,
  148568. _psy_noisebias_8,
  148569. _psy_noisebias_8,
  148570. NULL,
  148571. NULL,
  148572. _psy_noise_suppress,
  148573. _psy_compand_8,
  148574. _psy_compand_8_mapping,
  148575. NULL,
  148576. {_noise_start_8,_noise_start_8},
  148577. {_noise_part_8,_noise_part_8},
  148578. _noise_thresh_5only,
  148579. _psy_ath_floater_8,
  148580. _psy_ath_abs_8,
  148581. _psy_lowpass_8,
  148582. _psy_global_44,
  148583. _global_mapping_8,
  148584. _psy_stereo_modes_8,
  148585. _floor_books,
  148586. _floor,
  148587. _floor_mapping_8,
  148588. NULL,
  148589. _mapres_template_8_stereo
  148590. };
  148591. ve_setup_data_template ve_setup_XX_uncoupled={
  148592. 2,
  148593. rate_mapping_X,
  148594. quality_mapping_8,
  148595. -1,
  148596. 0,
  148597. 8000,
  148598. blocksize_8,
  148599. blocksize_8,
  148600. _psy_tone_masteratt_8,
  148601. _psy_tone_0dB,
  148602. _psy_tone_suppress,
  148603. _vp_tonemask_adj_8,
  148604. NULL,
  148605. _vp_tonemask_adj_8,
  148606. _psy_noiseguards_8,
  148607. _psy_noisebias_8,
  148608. _psy_noisebias_8,
  148609. NULL,
  148610. NULL,
  148611. _psy_noise_suppress,
  148612. _psy_compand_8,
  148613. _psy_compand_8_mapping,
  148614. NULL,
  148615. {_noise_start_8,_noise_start_8},
  148616. {_noise_part_8,_noise_part_8},
  148617. _noise_thresh_5only,
  148618. _psy_ath_floater_8,
  148619. _psy_ath_abs_8,
  148620. _psy_lowpass_8,
  148621. _psy_global_44,
  148622. _global_mapping_8,
  148623. _psy_stereo_modes_8,
  148624. _floor_books,
  148625. _floor,
  148626. _floor_mapping_8,
  148627. NULL,
  148628. _mapres_template_8_uncoupled
  148629. };
  148630. /********* End of inlined file: setup_X.h *********/
  148631. static ve_setup_data_template *setup_list[]={
  148632. &ve_setup_44_stereo,
  148633. &ve_setup_44_uncoupled,
  148634. &ve_setup_32_stereo,
  148635. &ve_setup_32_uncoupled,
  148636. &ve_setup_22_stereo,
  148637. &ve_setup_22_uncoupled,
  148638. &ve_setup_16_stereo,
  148639. &ve_setup_16_uncoupled,
  148640. &ve_setup_11_stereo,
  148641. &ve_setup_11_uncoupled,
  148642. &ve_setup_8_stereo,
  148643. &ve_setup_8_uncoupled,
  148644. &ve_setup_X_stereo,
  148645. &ve_setup_X_uncoupled,
  148646. &ve_setup_XX_stereo,
  148647. &ve_setup_XX_uncoupled,
  148648. 0
  148649. };
  148650. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  148651. if(vi && vi->codec_setup){
  148652. vi->version=0;
  148653. vi->channels=ch;
  148654. vi->rate=rate;
  148655. return(0);
  148656. }
  148657. return(OV_EINVAL);
  148658. }
  148659. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  148660. static_codebook ***books,
  148661. vorbis_info_floor1 *in,
  148662. int *x){
  148663. int i,k,is=s;
  148664. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  148665. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148666. memcpy(f,in+x[is],sizeof(*f));
  148667. /* fill in the lowpass field, even if it's temporary */
  148668. f->n=ci->blocksizes[block]>>1;
  148669. /* books */
  148670. {
  148671. int partitions=f->partitions;
  148672. int maxclass=-1;
  148673. int maxbook=-1;
  148674. for(i=0;i<partitions;i++)
  148675. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  148676. for(i=0;i<=maxclass;i++){
  148677. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  148678. f->class_book[i]+=ci->books;
  148679. for(k=0;k<(1<<f->class_subs[i]);k++){
  148680. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  148681. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  148682. }
  148683. }
  148684. for(i=0;i<=maxbook;i++)
  148685. ci->book_param[ci->books++]=books[x[is]][i];
  148686. }
  148687. /* for now, we're only using floor 1 */
  148688. ci->floor_type[ci->floors]=1;
  148689. ci->floor_param[ci->floors]=f;
  148690. ci->floors++;
  148691. return;
  148692. }
  148693. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  148694. vorbis_info_psy_global *in,
  148695. double *x){
  148696. int i,is=s;
  148697. double ds=s-is;
  148698. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148699. vorbis_info_psy_global *g=&ci->psy_g_param;
  148700. memcpy(g,in+(int)x[is],sizeof(*g));
  148701. ds=x[is]*(1.-ds)+x[is+1]*ds;
  148702. is=(int)ds;
  148703. ds-=is;
  148704. if(ds==0 && is>0){
  148705. is--;
  148706. ds=1.;
  148707. }
  148708. /* interpolate the trigger threshholds */
  148709. for(i=0;i<4;i++){
  148710. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  148711. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  148712. }
  148713. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  148714. return;
  148715. }
  148716. static void vorbis_encode_global_stereo(vorbis_info *vi,
  148717. highlevel_encode_setup *hi,
  148718. adj_stereo *p){
  148719. float s=hi->stereo_point_setting;
  148720. int i,is=s;
  148721. double ds=s-is;
  148722. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148723. vorbis_info_psy_global *g=&ci->psy_g_param;
  148724. if(p){
  148725. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  148726. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  148727. if(hi->managed){
  148728. /* interpolate the kHz threshholds */
  148729. for(i=0;i<PACKETBLOBS;i++){
  148730. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  148731. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148732. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148733. g->coupling_pkHz[i]=kHz;
  148734. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  148735. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148736. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148737. }
  148738. }else{
  148739. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  148740. for(i=0;i<PACKETBLOBS;i++){
  148741. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148742. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148743. g->coupling_pkHz[i]=kHz;
  148744. }
  148745. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  148746. for(i=0;i<PACKETBLOBS;i++){
  148747. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148748. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148749. }
  148750. }
  148751. }else{
  148752. for(i=0;i<PACKETBLOBS;i++){
  148753. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  148754. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  148755. }
  148756. }
  148757. return;
  148758. }
  148759. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  148760. int *nn_start,
  148761. int *nn_partition,
  148762. double *nn_thresh,
  148763. int block){
  148764. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  148765. vorbis_info_psy *p=ci->psy_param[block];
  148766. highlevel_encode_setup *hi=&ci->hi;
  148767. int is=s;
  148768. if(block>=ci->psys)
  148769. ci->psys=block+1;
  148770. if(!p){
  148771. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  148772. ci->psy_param[block]=p;
  148773. }
  148774. memcpy(p,&_psy_info_template,sizeof(*p));
  148775. p->blockflag=block>>1;
  148776. if(hi->noise_normalize_p){
  148777. p->normal_channel_p=1;
  148778. p->normal_point_p=1;
  148779. p->normal_start=nn_start[is];
  148780. p->normal_partition=nn_partition[is];
  148781. p->normal_thresh=nn_thresh[is];
  148782. }
  148783. return;
  148784. }
  148785. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  148786. att3 *att,
  148787. int *max,
  148788. vp_adjblock *in){
  148789. int i,is=s;
  148790. double ds=s-is;
  148791. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  148792. vorbis_info_psy *p=ci->psy_param[block];
  148793. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  148794. filling the values in here */
  148795. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  148796. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  148797. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  148798. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  148799. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  148800. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  148801. for(i=0;i<P_BANDS;i++)
  148802. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  148803. return;
  148804. }
  148805. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  148806. compandblock *in, double *x){
  148807. int i,is=s;
  148808. double ds=s-is;
  148809. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148810. vorbis_info_psy *p=ci->psy_param[block];
  148811. ds=x[is]*(1.-ds)+x[is+1]*ds;
  148812. is=(int)ds;
  148813. ds-=is;
  148814. if(ds==0 && is>0){
  148815. is--;
  148816. ds=1.;
  148817. }
  148818. /* interpolate the compander settings */
  148819. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  148820. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  148821. return;
  148822. }
  148823. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  148824. int *suppress){
  148825. int is=s;
  148826. double ds=s-is;
  148827. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148828. vorbis_info_psy *p=ci->psy_param[block];
  148829. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  148830. return;
  148831. }
  148832. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  148833. int *suppress,
  148834. noise3 *in,
  148835. noiseguard *guard,
  148836. double userbias){
  148837. int i,is=s,j;
  148838. double ds=s-is;
  148839. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148840. vorbis_info_psy *p=ci->psy_param[block];
  148841. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  148842. p->noisewindowlomin=guard[block].lo;
  148843. p->noisewindowhimin=guard[block].hi;
  148844. p->noisewindowfixed=guard[block].fixed;
  148845. for(j=0;j<P_NOISECURVES;j++)
  148846. for(i=0;i<P_BANDS;i++)
  148847. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  148848. /* impulse blocks may take a user specified bias to boost the
  148849. nominal/high noise encoding depth */
  148850. for(j=0;j<P_NOISECURVES;j++){
  148851. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  148852. for(i=0;i<P_BANDS;i++){
  148853. p->noiseoff[j][i]+=userbias;
  148854. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  148855. }
  148856. }
  148857. return;
  148858. }
  148859. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  148860. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148861. vorbis_info_psy *p=ci->psy_param[block];
  148862. p->ath_adjatt=ci->hi.ath_floating_dB;
  148863. p->ath_maxatt=ci->hi.ath_absolute_dB;
  148864. return;
  148865. }
  148866. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  148867. int i;
  148868. for(i=0;i<ci->books;i++)
  148869. if(ci->book_param[i]==book)return(i);
  148870. return(ci->books++);
  148871. }
  148872. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  148873. int *shortb,int *longb){
  148874. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148875. int is=s;
  148876. int blockshort=shortb[is];
  148877. int blocklong=longb[is];
  148878. ci->blocksizes[0]=blockshort;
  148879. ci->blocksizes[1]=blocklong;
  148880. }
  148881. static void vorbis_encode_residue_setup(vorbis_info *vi,
  148882. int number, int block,
  148883. vorbis_residue_template *res){
  148884. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148885. int i,n;
  148886. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  148887. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  148888. memcpy(r,res->res,sizeof(*r));
  148889. if(ci->residues<=number)ci->residues=number+1;
  148890. switch(ci->blocksizes[block]){
  148891. case 64:case 128:case 256:
  148892. r->grouping=16;
  148893. break;
  148894. default:
  148895. r->grouping=32;
  148896. break;
  148897. }
  148898. ci->residue_type[number]=res->res_type;
  148899. /* to be adjusted by lowpass/pointlimit later */
  148900. n=r->end=ci->blocksizes[block]>>1;
  148901. if(res->res_type==2)
  148902. n=r->end*=vi->channels;
  148903. /* fill in all the books */
  148904. {
  148905. int booklist=0,k;
  148906. if(ci->hi.managed){
  148907. for(i=0;i<r->partitions;i++)
  148908. for(k=0;k<3;k++)
  148909. if(res->books_base_managed->books[i][k])
  148910. r->secondstages[i]|=(1<<k);
  148911. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  148912. ci->book_param[r->groupbook]=res->book_aux_managed;
  148913. for(i=0;i<r->partitions;i++){
  148914. for(k=0;k<3;k++){
  148915. if(res->books_base_managed->books[i][k]){
  148916. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  148917. r->booklist[booklist++]=bookid;
  148918. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  148919. }
  148920. }
  148921. }
  148922. }else{
  148923. for(i=0;i<r->partitions;i++)
  148924. for(k=0;k<3;k++)
  148925. if(res->books_base->books[i][k])
  148926. r->secondstages[i]|=(1<<k);
  148927. r->groupbook=book_dup_or_new(ci,res->book_aux);
  148928. ci->book_param[r->groupbook]=res->book_aux;
  148929. for(i=0;i<r->partitions;i++){
  148930. for(k=0;k<3;k++){
  148931. if(res->books_base->books[i][k]){
  148932. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  148933. r->booklist[booklist++]=bookid;
  148934. ci->book_param[bookid]=res->books_base->books[i][k];
  148935. }
  148936. }
  148937. }
  148938. }
  148939. }
  148940. /* lowpass setup/pointlimit */
  148941. {
  148942. double freq=ci->hi.lowpass_kHz*1000.;
  148943. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  148944. double nyq=vi->rate/2.;
  148945. long blocksize=ci->blocksizes[block]>>1;
  148946. /* lowpass needs to be set in the floor and the residue. */
  148947. if(freq>nyq)freq=nyq;
  148948. /* in the floor, the granularity can be very fine; it doesn't alter
  148949. the encoding structure, only the samples used to fit the floor
  148950. approximation */
  148951. f->n=freq/nyq*blocksize;
  148952. /* this res may by limited by the maximum pointlimit of the mode,
  148953. not the lowpass. the floor is always lowpass limited. */
  148954. if(res->limit_type){
  148955. if(ci->hi.managed)
  148956. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  148957. else
  148958. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  148959. if(freq>nyq)freq=nyq;
  148960. }
  148961. /* in the residue, we're constrained, physically, by partition
  148962. boundaries. We still lowpass 'wherever', but we have to round up
  148963. here to next boundary, or the vorbis spec will round it *down* to
  148964. previous boundary in encode/decode */
  148965. if(ci->residue_type[block]==2)
  148966. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  148967. r->grouping;
  148968. else
  148969. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  148970. r->grouping;
  148971. }
  148972. }
  148973. /* we assume two maps in this encoder */
  148974. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  148975. vorbis_mapping_template *maps){
  148976. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148977. int i,j,is=s,modes=2;
  148978. vorbis_info_mapping0 *map=maps[is].map;
  148979. vorbis_info_mode *mode=_mode_template;
  148980. vorbis_residue_template *res=maps[is].res;
  148981. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  148982. for(i=0;i<modes;i++){
  148983. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  148984. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  148985. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  148986. if(i>=ci->modes)ci->modes=i+1;
  148987. ci->map_type[i]=0;
  148988. memcpy(ci->map_param[i],map+i,sizeof(*map));
  148989. if(i>=ci->maps)ci->maps=i+1;
  148990. for(j=0;j<map[i].submaps;j++)
  148991. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  148992. ,res+map[i].residuesubmap[j]);
  148993. }
  148994. }
  148995. static double setting_to_approx_bitrate(vorbis_info *vi){
  148996. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148997. highlevel_encode_setup *hi=&ci->hi;
  148998. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  148999. int is=hi->base_setting;
  149000. double ds=hi->base_setting-is;
  149001. int ch=vi->channels;
  149002. double *r=setup->rate_mapping;
  149003. if(r==NULL)
  149004. return(-1);
  149005. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  149006. }
  149007. static void get_setup_template(vorbis_info *vi,
  149008. long ch,long srate,
  149009. double req,int q_or_bitrate){
  149010. int i=0,j;
  149011. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  149012. highlevel_encode_setup *hi=&ci->hi;
  149013. if(q_or_bitrate)req/=ch;
  149014. while(setup_list[i]){
  149015. if(setup_list[i]->coupling_restriction==-1 ||
  149016. setup_list[i]->coupling_restriction==ch){
  149017. if(srate>=setup_list[i]->samplerate_min_restriction &&
  149018. srate<=setup_list[i]->samplerate_max_restriction){
  149019. int mappings=setup_list[i]->mappings;
  149020. double *map=(q_or_bitrate?
  149021. setup_list[i]->rate_mapping:
  149022. setup_list[i]->quality_mapping);
  149023. /* the template matches. Does the requested quality mode
  149024. fall within this template's modes? */
  149025. if(req<map[0]){++i;continue;}
  149026. if(req>map[setup_list[i]->mappings]){++i;continue;}
  149027. for(j=0;j<mappings;j++)
  149028. if(req>=map[j] && req<map[j+1])break;
  149029. /* an all-points match */
  149030. hi->setup=setup_list[i];
  149031. if(j==mappings)
  149032. hi->base_setting=j-.001;
  149033. else{
  149034. float low=map[j];
  149035. float high=map[j+1];
  149036. float del=(req-low)/(high-low);
  149037. hi->base_setting=j+del;
  149038. }
  149039. return;
  149040. }
  149041. }
  149042. i++;
  149043. }
  149044. hi->setup=NULL;
  149045. }
  149046. /* encoders will need to use vorbis_info_init beforehand and call
  149047. vorbis_info clear when all done */
  149048. /* two interfaces; this, more detailed one, and later a convenience
  149049. layer on top */
  149050. /* the final setup call */
  149051. int vorbis_encode_setup_init(vorbis_info *vi){
  149052. int i0=0,singleblock=0;
  149053. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  149054. ve_setup_data_template *setup=NULL;
  149055. highlevel_encode_setup *hi=&ci->hi;
  149056. if(ci==NULL)return(OV_EINVAL);
  149057. if(!hi->impulse_block_p)i0=1;
  149058. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  149059. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  149060. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  149061. /* again, bound this to avoid the app shooting itself int he foot
  149062. too badly */
  149063. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  149064. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  149065. /* get the appropriate setup template; matches the fetch in previous
  149066. stages */
  149067. setup=(ve_setup_data_template *)hi->setup;
  149068. if(setup==NULL)return(OV_EINVAL);
  149069. hi->set_in_stone=1;
  149070. /* choose block sizes from configured sizes as well as paying
  149071. attention to long_block_p and short_block_p. If the configured
  149072. short and long blocks are the same length, we set long_block_p
  149073. and unset short_block_p */
  149074. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  149075. setup->blocksize_short,
  149076. setup->blocksize_long);
  149077. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  149078. /* floor setup; choose proper floor params. Allocated on the floor
  149079. stack in order; if we alloc only long floor, it's 0 */
  149080. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  149081. setup->floor_books,
  149082. setup->floor_params,
  149083. setup->floor_short_mapping);
  149084. if(!singleblock)
  149085. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  149086. setup->floor_books,
  149087. setup->floor_params,
  149088. setup->floor_long_mapping);
  149089. /* setup of [mostly] short block detection and stereo*/
  149090. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  149091. setup->global_params,
  149092. setup->global_mapping);
  149093. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  149094. /* basic psych setup and noise normalization */
  149095. vorbis_encode_psyset_setup(vi,hi->short_setting,
  149096. setup->psy_noise_normal_start[0],
  149097. setup->psy_noise_normal_partition[0],
  149098. setup->psy_noise_normal_thresh,
  149099. 0);
  149100. vorbis_encode_psyset_setup(vi,hi->short_setting,
  149101. setup->psy_noise_normal_start[0],
  149102. setup->psy_noise_normal_partition[0],
  149103. setup->psy_noise_normal_thresh,
  149104. 1);
  149105. if(!singleblock){
  149106. vorbis_encode_psyset_setup(vi,hi->long_setting,
  149107. setup->psy_noise_normal_start[1],
  149108. setup->psy_noise_normal_partition[1],
  149109. setup->psy_noise_normal_thresh,
  149110. 2);
  149111. vorbis_encode_psyset_setup(vi,hi->long_setting,
  149112. setup->psy_noise_normal_start[1],
  149113. setup->psy_noise_normal_partition[1],
  149114. setup->psy_noise_normal_thresh,
  149115. 3);
  149116. }
  149117. /* tone masking setup */
  149118. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  149119. setup->psy_tone_masteratt,
  149120. setup->psy_tone_0dB,
  149121. setup->psy_tone_adj_impulse);
  149122. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  149123. setup->psy_tone_masteratt,
  149124. setup->psy_tone_0dB,
  149125. setup->psy_tone_adj_other);
  149126. if(!singleblock){
  149127. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  149128. setup->psy_tone_masteratt,
  149129. setup->psy_tone_0dB,
  149130. setup->psy_tone_adj_other);
  149131. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  149132. setup->psy_tone_masteratt,
  149133. setup->psy_tone_0dB,
  149134. setup->psy_tone_adj_long);
  149135. }
  149136. /* noise companding setup */
  149137. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  149138. setup->psy_noise_compand,
  149139. setup->psy_noise_compand_short_mapping);
  149140. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  149141. setup->psy_noise_compand,
  149142. setup->psy_noise_compand_short_mapping);
  149143. if(!singleblock){
  149144. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  149145. setup->psy_noise_compand,
  149146. setup->psy_noise_compand_long_mapping);
  149147. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  149148. setup->psy_noise_compand,
  149149. setup->psy_noise_compand_long_mapping);
  149150. }
  149151. /* peak guarding setup */
  149152. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  149153. setup->psy_tone_dBsuppress);
  149154. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  149155. setup->psy_tone_dBsuppress);
  149156. if(!singleblock){
  149157. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  149158. setup->psy_tone_dBsuppress);
  149159. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  149160. setup->psy_tone_dBsuppress);
  149161. }
  149162. /* noise bias setup */
  149163. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  149164. setup->psy_noise_dBsuppress,
  149165. setup->psy_noise_bias_impulse,
  149166. setup->psy_noiseguards,
  149167. (i0==0?hi->impulse_noisetune:0.));
  149168. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  149169. setup->psy_noise_dBsuppress,
  149170. setup->psy_noise_bias_padding,
  149171. setup->psy_noiseguards,0.);
  149172. if(!singleblock){
  149173. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  149174. setup->psy_noise_dBsuppress,
  149175. setup->psy_noise_bias_trans,
  149176. setup->psy_noiseguards,0.);
  149177. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  149178. setup->psy_noise_dBsuppress,
  149179. setup->psy_noise_bias_long,
  149180. setup->psy_noiseguards,0.);
  149181. }
  149182. vorbis_encode_ath_setup(vi,0);
  149183. vorbis_encode_ath_setup(vi,1);
  149184. if(!singleblock){
  149185. vorbis_encode_ath_setup(vi,2);
  149186. vorbis_encode_ath_setup(vi,3);
  149187. }
  149188. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  149189. /* set bitrate readonlies and management */
  149190. if(hi->bitrate_av>0)
  149191. vi->bitrate_nominal=hi->bitrate_av;
  149192. else{
  149193. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  149194. }
  149195. vi->bitrate_lower=hi->bitrate_min;
  149196. vi->bitrate_upper=hi->bitrate_max;
  149197. if(hi->bitrate_av)
  149198. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  149199. else
  149200. vi->bitrate_window=0.;
  149201. if(hi->managed){
  149202. ci->bi.avg_rate=hi->bitrate_av;
  149203. ci->bi.min_rate=hi->bitrate_min;
  149204. ci->bi.max_rate=hi->bitrate_max;
  149205. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  149206. ci->bi.reservoir_bias=
  149207. hi->bitrate_reservoir_bias;
  149208. ci->bi.slew_damp=hi->bitrate_av_damp;
  149209. }
  149210. return(0);
  149211. }
  149212. static int vorbis_encode_setup_setting(vorbis_info *vi,
  149213. long channels,
  149214. long rate){
  149215. int ret=0,i,is;
  149216. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149217. highlevel_encode_setup *hi=&ci->hi;
  149218. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  149219. double ds;
  149220. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  149221. if(ret)return(ret);
  149222. is=hi->base_setting;
  149223. ds=hi->base_setting-is;
  149224. hi->short_setting=hi->base_setting;
  149225. hi->long_setting=hi->base_setting;
  149226. hi->managed=0;
  149227. hi->impulse_block_p=1;
  149228. hi->noise_normalize_p=1;
  149229. hi->stereo_point_setting=hi->base_setting;
  149230. hi->lowpass_kHz=
  149231. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  149232. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  149233. setup->psy_ath_float[is+1]*ds;
  149234. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  149235. setup->psy_ath_abs[is+1]*ds;
  149236. hi->amplitude_track_dBpersec=-6.;
  149237. hi->trigger_setting=hi->base_setting;
  149238. for(i=0;i<4;i++){
  149239. hi->block[i].tone_mask_setting=hi->base_setting;
  149240. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  149241. hi->block[i].noise_bias_setting=hi->base_setting;
  149242. hi->block[i].noise_compand_setting=hi->base_setting;
  149243. }
  149244. return(ret);
  149245. }
  149246. int vorbis_encode_setup_vbr(vorbis_info *vi,
  149247. long channels,
  149248. long rate,
  149249. float quality){
  149250. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  149251. highlevel_encode_setup *hi=&ci->hi;
  149252. quality+=.0000001;
  149253. if(quality>=1.)quality=.9999;
  149254. get_setup_template(vi,channels,rate,quality,0);
  149255. if(!hi->setup)return OV_EIMPL;
  149256. return vorbis_encode_setup_setting(vi,channels,rate);
  149257. }
  149258. int vorbis_encode_init_vbr(vorbis_info *vi,
  149259. long channels,
  149260. long rate,
  149261. float base_quality /* 0. to 1. */
  149262. ){
  149263. int ret=0;
  149264. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  149265. if(ret){
  149266. vorbis_info_clear(vi);
  149267. return ret;
  149268. }
  149269. ret=vorbis_encode_setup_init(vi);
  149270. if(ret)
  149271. vorbis_info_clear(vi);
  149272. return(ret);
  149273. }
  149274. int vorbis_encode_setup_managed(vorbis_info *vi,
  149275. long channels,
  149276. long rate,
  149277. long max_bitrate,
  149278. long nominal_bitrate,
  149279. long min_bitrate){
  149280. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149281. highlevel_encode_setup *hi=&ci->hi;
  149282. double tnominal=nominal_bitrate;
  149283. int ret=0;
  149284. if(nominal_bitrate<=0.){
  149285. if(max_bitrate>0.){
  149286. if(min_bitrate>0.)
  149287. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  149288. else
  149289. nominal_bitrate=max_bitrate*.875;
  149290. }else{
  149291. if(min_bitrate>0.){
  149292. nominal_bitrate=min_bitrate;
  149293. }else{
  149294. return(OV_EINVAL);
  149295. }
  149296. }
  149297. }
  149298. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  149299. if(!hi->setup)return OV_EIMPL;
  149300. ret=vorbis_encode_setup_setting(vi,channels,rate);
  149301. if(ret){
  149302. vorbis_info_clear(vi);
  149303. return ret;
  149304. }
  149305. /* initialize management with sane defaults */
  149306. hi->managed=1;
  149307. hi->bitrate_min=min_bitrate;
  149308. hi->bitrate_max=max_bitrate;
  149309. hi->bitrate_av=tnominal;
  149310. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  149311. hi->bitrate_reservoir=nominal_bitrate*2;
  149312. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  149313. return(ret);
  149314. }
  149315. int vorbis_encode_init(vorbis_info *vi,
  149316. long channels,
  149317. long rate,
  149318. long max_bitrate,
  149319. long nominal_bitrate,
  149320. long min_bitrate){
  149321. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  149322. max_bitrate,
  149323. nominal_bitrate,
  149324. min_bitrate);
  149325. if(ret){
  149326. vorbis_info_clear(vi);
  149327. return(ret);
  149328. }
  149329. ret=vorbis_encode_setup_init(vi);
  149330. if(ret)
  149331. vorbis_info_clear(vi);
  149332. return(ret);
  149333. }
  149334. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  149335. if(vi){
  149336. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149337. highlevel_encode_setup *hi=&ci->hi;
  149338. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  149339. if(setp && hi->set_in_stone)return(OV_EINVAL);
  149340. switch(number){
  149341. /* now deprecated *****************/
  149342. case OV_ECTL_RATEMANAGE_GET:
  149343. {
  149344. struct ovectl_ratemanage_arg *ai=
  149345. (struct ovectl_ratemanage_arg *)arg;
  149346. ai->management_active=hi->managed;
  149347. ai->bitrate_hard_window=ai->bitrate_av_window=
  149348. (double)hi->bitrate_reservoir/vi->rate;
  149349. ai->bitrate_av_window_center=1.;
  149350. ai->bitrate_hard_min=hi->bitrate_min;
  149351. ai->bitrate_hard_max=hi->bitrate_max;
  149352. ai->bitrate_av_lo=hi->bitrate_av;
  149353. ai->bitrate_av_hi=hi->bitrate_av;
  149354. }
  149355. return(0);
  149356. /* now deprecated *****************/
  149357. case OV_ECTL_RATEMANAGE_SET:
  149358. {
  149359. struct ovectl_ratemanage_arg *ai=
  149360. (struct ovectl_ratemanage_arg *)arg;
  149361. if(ai==NULL){
  149362. hi->managed=0;
  149363. }else{
  149364. hi->managed=ai->management_active;
  149365. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  149366. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  149367. }
  149368. }
  149369. return 0;
  149370. /* now deprecated *****************/
  149371. case OV_ECTL_RATEMANAGE_AVG:
  149372. {
  149373. struct ovectl_ratemanage_arg *ai=
  149374. (struct ovectl_ratemanage_arg *)arg;
  149375. if(ai==NULL){
  149376. hi->bitrate_av=0;
  149377. }else{
  149378. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  149379. }
  149380. }
  149381. return(0);
  149382. /* now deprecated *****************/
  149383. case OV_ECTL_RATEMANAGE_HARD:
  149384. {
  149385. struct ovectl_ratemanage_arg *ai=
  149386. (struct ovectl_ratemanage_arg *)arg;
  149387. if(ai==NULL){
  149388. hi->bitrate_min=0;
  149389. hi->bitrate_max=0;
  149390. }else{
  149391. hi->bitrate_min=ai->bitrate_hard_min;
  149392. hi->bitrate_max=ai->bitrate_hard_max;
  149393. hi->bitrate_reservoir=ai->bitrate_hard_window*
  149394. (hi->bitrate_max+hi->bitrate_min)*.5;
  149395. }
  149396. if(hi->bitrate_reservoir<128.)
  149397. hi->bitrate_reservoir=128.;
  149398. }
  149399. return(0);
  149400. /* replacement ratemanage interface */
  149401. case OV_ECTL_RATEMANAGE2_GET:
  149402. {
  149403. struct ovectl_ratemanage2_arg *ai=
  149404. (struct ovectl_ratemanage2_arg *)arg;
  149405. if(ai==NULL)return OV_EINVAL;
  149406. ai->management_active=hi->managed;
  149407. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  149408. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  149409. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  149410. ai->bitrate_average_damping=hi->bitrate_av_damp;
  149411. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  149412. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  149413. }
  149414. return (0);
  149415. case OV_ECTL_RATEMANAGE2_SET:
  149416. {
  149417. struct ovectl_ratemanage2_arg *ai=
  149418. (struct ovectl_ratemanage2_arg *)arg;
  149419. if(ai==NULL){
  149420. hi->managed=0;
  149421. }else{
  149422. /* sanity check; only catch invariant violations */
  149423. if(ai->bitrate_limit_min_kbps>0 &&
  149424. ai->bitrate_average_kbps>0 &&
  149425. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  149426. return OV_EINVAL;
  149427. if(ai->bitrate_limit_max_kbps>0 &&
  149428. ai->bitrate_average_kbps>0 &&
  149429. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  149430. return OV_EINVAL;
  149431. if(ai->bitrate_limit_min_kbps>0 &&
  149432. ai->bitrate_limit_max_kbps>0 &&
  149433. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  149434. return OV_EINVAL;
  149435. if(ai->bitrate_average_damping <= 0.)
  149436. return OV_EINVAL;
  149437. if(ai->bitrate_limit_reservoir_bits < 0)
  149438. return OV_EINVAL;
  149439. if(ai->bitrate_limit_reservoir_bias < 0.)
  149440. return OV_EINVAL;
  149441. if(ai->bitrate_limit_reservoir_bias > 1.)
  149442. return OV_EINVAL;
  149443. hi->managed=ai->management_active;
  149444. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  149445. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  149446. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  149447. hi->bitrate_av_damp=ai->bitrate_average_damping;
  149448. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  149449. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  149450. }
  149451. }
  149452. return 0;
  149453. case OV_ECTL_LOWPASS_GET:
  149454. {
  149455. double *farg=(double *)arg;
  149456. *farg=hi->lowpass_kHz;
  149457. }
  149458. return(0);
  149459. case OV_ECTL_LOWPASS_SET:
  149460. {
  149461. double *farg=(double *)arg;
  149462. hi->lowpass_kHz=*farg;
  149463. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  149464. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  149465. }
  149466. return(0);
  149467. case OV_ECTL_IBLOCK_GET:
  149468. {
  149469. double *farg=(double *)arg;
  149470. *farg=hi->impulse_noisetune;
  149471. }
  149472. return(0);
  149473. case OV_ECTL_IBLOCK_SET:
  149474. {
  149475. double *farg=(double *)arg;
  149476. hi->impulse_noisetune=*farg;
  149477. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  149478. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  149479. }
  149480. return(0);
  149481. }
  149482. return(OV_EIMPL);
  149483. }
  149484. return(OV_EINVAL);
  149485. }
  149486. #endif
  149487. /********* End of inlined file: vorbisenc.c *********/
  149488. /********* Start of inlined file: vorbisfile.c *********/
  149489. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  149490. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  149491. // tasks..
  149492. #ifdef _MSC_VER
  149493. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  149494. #endif
  149495. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  149496. #if JUCE_USE_OGGVORBIS
  149497. #include <stdlib.h>
  149498. #include <stdio.h>
  149499. #include <errno.h>
  149500. #include <string.h>
  149501. #include <math.h>
  149502. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  149503. one logical bitstream arranged end to end (the only form of Ogg
  149504. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  149505. multiplexing] is not allowed in Vorbis) */
  149506. /* A Vorbis file can be played beginning to end (streamed) without
  149507. worrying ahead of time about chaining (see decoder_example.c). If
  149508. we have the whole file, however, and want random access
  149509. (seeking/scrubbing) or desire to know the total length/time of a
  149510. file, we need to account for the possibility of chaining. */
  149511. /* We can handle things a number of ways; we can determine the entire
  149512. bitstream structure right off the bat, or find pieces on demand.
  149513. This example determines and caches structure for the entire
  149514. bitstream, but builds a virtual decoder on the fly when moving
  149515. between links in the chain. */
  149516. /* There are also different ways to implement seeking. Enough
  149517. information exists in an Ogg bitstream to seek to
  149518. sample-granularity positions in the output. Or, one can seek by
  149519. picking some portion of the stream roughly in the desired area if
  149520. we only want coarse navigation through the stream. */
  149521. /*************************************************************************
  149522. * Many, many internal helpers. The intention is not to be confusing;
  149523. * rampant duplication and monolithic function implementation would be
  149524. * harder to understand anyway. The high level functions are last. Begin
  149525. * grokking near the end of the file */
  149526. /* read a little more data from the file/pipe into the ogg_sync framer
  149527. */
  149528. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  149529. over 8k gets what they deserve */
  149530. static long _get_data(OggVorbis_File *vf){
  149531. errno=0;
  149532. if(vf->datasource){
  149533. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  149534. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  149535. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  149536. if(bytes==0 && errno)return(-1);
  149537. return(bytes);
  149538. }else
  149539. return(0);
  149540. }
  149541. /* save a tiny smidge of verbosity to make the code more readable */
  149542. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  149543. if(vf->datasource){
  149544. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  149545. vf->offset=offset;
  149546. ogg_sync_reset(&vf->oy);
  149547. }else{
  149548. /* shouldn't happen unless someone writes a broken callback */
  149549. return;
  149550. }
  149551. }
  149552. /* The read/seek functions track absolute position within the stream */
  149553. /* from the head of the stream, get the next page. boundary specifies
  149554. if the function is allowed to fetch more data from the stream (and
  149555. how much) or only use internally buffered data.
  149556. boundary: -1) unbounded search
  149557. 0) read no additional data; use cached only
  149558. n) search for a new page beginning for n bytes
  149559. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  149560. n) found a page at absolute offset n */
  149561. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  149562. ogg_int64_t boundary){
  149563. if(boundary>0)boundary+=vf->offset;
  149564. while(1){
  149565. long more;
  149566. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  149567. more=ogg_sync_pageseek(&vf->oy,og);
  149568. if(more<0){
  149569. /* skipped n bytes */
  149570. vf->offset-=more;
  149571. }else{
  149572. if(more==0){
  149573. /* send more paramedics */
  149574. if(!boundary)return(OV_FALSE);
  149575. {
  149576. long ret=_get_data(vf);
  149577. if(ret==0)return(OV_EOF);
  149578. if(ret<0)return(OV_EREAD);
  149579. }
  149580. }else{
  149581. /* got a page. Return the offset at the page beginning,
  149582. advance the internal offset past the page end */
  149583. ogg_int64_t ret=vf->offset;
  149584. vf->offset+=more;
  149585. return(ret);
  149586. }
  149587. }
  149588. }
  149589. }
  149590. /* find the latest page beginning before the current stream cursor
  149591. position. Much dirtier than the above as Ogg doesn't have any
  149592. backward search linkage. no 'readp' as it will certainly have to
  149593. read. */
  149594. /* returns offset or OV_EREAD, OV_FAULT */
  149595. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  149596. ogg_int64_t begin=vf->offset;
  149597. ogg_int64_t end=begin;
  149598. ogg_int64_t ret;
  149599. ogg_int64_t offset=-1;
  149600. while(offset==-1){
  149601. begin-=CHUNKSIZE;
  149602. if(begin<0)
  149603. begin=0;
  149604. _seek_helper(vf,begin);
  149605. while(vf->offset<end){
  149606. ret=_get_next_page(vf,og,end-vf->offset);
  149607. if(ret==OV_EREAD)return(OV_EREAD);
  149608. if(ret<0){
  149609. break;
  149610. }else{
  149611. offset=ret;
  149612. }
  149613. }
  149614. }
  149615. /* we have the offset. Actually snork and hold the page now */
  149616. _seek_helper(vf,offset);
  149617. ret=_get_next_page(vf,og,CHUNKSIZE);
  149618. if(ret<0)
  149619. /* this shouldn't be possible */
  149620. return(OV_EFAULT);
  149621. return(offset);
  149622. }
  149623. /* finds each bitstream link one at a time using a bisection search
  149624. (has to begin by knowing the offset of the lb's initial page).
  149625. Recurses for each link so it can alloc the link storage after
  149626. finding them all, then unroll and fill the cache at the same time */
  149627. static int _bisect_forward_serialno(OggVorbis_File *vf,
  149628. ogg_int64_t begin,
  149629. ogg_int64_t searched,
  149630. ogg_int64_t end,
  149631. long currentno,
  149632. long m){
  149633. ogg_int64_t endsearched=end;
  149634. ogg_int64_t next=end;
  149635. ogg_page og;
  149636. ogg_int64_t ret;
  149637. /* the below guards against garbage seperating the last and
  149638. first pages of two links. */
  149639. while(searched<endsearched){
  149640. ogg_int64_t bisect;
  149641. if(endsearched-searched<CHUNKSIZE){
  149642. bisect=searched;
  149643. }else{
  149644. bisect=(searched+endsearched)/2;
  149645. }
  149646. _seek_helper(vf,bisect);
  149647. ret=_get_next_page(vf,&og,-1);
  149648. if(ret==OV_EREAD)return(OV_EREAD);
  149649. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  149650. endsearched=bisect;
  149651. if(ret>=0)next=ret;
  149652. }else{
  149653. searched=ret+og.header_len+og.body_len;
  149654. }
  149655. }
  149656. _seek_helper(vf,next);
  149657. ret=_get_next_page(vf,&og,-1);
  149658. if(ret==OV_EREAD)return(OV_EREAD);
  149659. if(searched>=end || ret<0){
  149660. vf->links=m+1;
  149661. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  149662. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  149663. vf->offsets[m+1]=searched;
  149664. }else{
  149665. ret=_bisect_forward_serialno(vf,next,vf->offset,
  149666. end,ogg_page_serialno(&og),m+1);
  149667. if(ret==OV_EREAD)return(OV_EREAD);
  149668. }
  149669. vf->offsets[m]=begin;
  149670. vf->serialnos[m]=currentno;
  149671. return(0);
  149672. }
  149673. /* uses the local ogg_stream storage in vf; this is important for
  149674. non-streaming input sources */
  149675. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  149676. long *serialno,ogg_page *og_ptr){
  149677. ogg_page og;
  149678. ogg_packet op;
  149679. int i,ret;
  149680. if(!og_ptr){
  149681. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  149682. if(llret==OV_EREAD)return(OV_EREAD);
  149683. if(llret<0)return OV_ENOTVORBIS;
  149684. og_ptr=&og;
  149685. }
  149686. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  149687. if(serialno)*serialno=vf->os.serialno;
  149688. vf->ready_state=STREAMSET;
  149689. /* extract the initial header from the first page and verify that the
  149690. Ogg bitstream is in fact Vorbis data */
  149691. vorbis_info_init(vi);
  149692. vorbis_comment_init(vc);
  149693. i=0;
  149694. while(i<3){
  149695. ogg_stream_pagein(&vf->os,og_ptr);
  149696. while(i<3){
  149697. int result=ogg_stream_packetout(&vf->os,&op);
  149698. if(result==0)break;
  149699. if(result==-1){
  149700. ret=OV_EBADHEADER;
  149701. goto bail_header;
  149702. }
  149703. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  149704. goto bail_header;
  149705. }
  149706. i++;
  149707. }
  149708. if(i<3)
  149709. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  149710. ret=OV_EBADHEADER;
  149711. goto bail_header;
  149712. }
  149713. }
  149714. return 0;
  149715. bail_header:
  149716. vorbis_info_clear(vi);
  149717. vorbis_comment_clear(vc);
  149718. vf->ready_state=OPENED;
  149719. return ret;
  149720. }
  149721. /* last step of the OggVorbis_File initialization; get all the
  149722. vorbis_info structs and PCM positions. Only called by the seekable
  149723. initialization (local stream storage is hacked slightly; pay
  149724. attention to how that's done) */
  149725. /* this is void and does not propogate errors up because we want to be
  149726. able to open and use damaged bitstreams as well as we can. Just
  149727. watch out for missing information for links in the OggVorbis_File
  149728. struct */
  149729. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  149730. ogg_page og;
  149731. int i;
  149732. ogg_int64_t ret;
  149733. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  149734. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  149735. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  149736. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  149737. for(i=0;i<vf->links;i++){
  149738. if(i==0){
  149739. /* we already grabbed the initial header earlier. Just set the offset */
  149740. vf->dataoffsets[i]=dataoffset;
  149741. _seek_helper(vf,dataoffset);
  149742. }else{
  149743. /* seek to the location of the initial header */
  149744. _seek_helper(vf,vf->offsets[i]);
  149745. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  149746. vf->dataoffsets[i]=-1;
  149747. }else{
  149748. vf->dataoffsets[i]=vf->offset;
  149749. }
  149750. }
  149751. /* fetch beginning PCM offset */
  149752. if(vf->dataoffsets[i]!=-1){
  149753. ogg_int64_t accumulated=0;
  149754. long lastblock=-1;
  149755. int result;
  149756. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  149757. while(1){
  149758. ogg_packet op;
  149759. ret=_get_next_page(vf,&og,-1);
  149760. if(ret<0)
  149761. /* this should not be possible unless the file is
  149762. truncated/mangled */
  149763. break;
  149764. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  149765. break;
  149766. /* count blocksizes of all frames in the page */
  149767. ogg_stream_pagein(&vf->os,&og);
  149768. while((result=ogg_stream_packetout(&vf->os,&op))){
  149769. if(result>0){ /* ignore holes */
  149770. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  149771. if(lastblock!=-1)
  149772. accumulated+=(lastblock+thisblock)>>2;
  149773. lastblock=thisblock;
  149774. }
  149775. }
  149776. if(ogg_page_granulepos(&og)!=-1){
  149777. /* pcm offset of last packet on the first audio page */
  149778. accumulated= ogg_page_granulepos(&og)-accumulated;
  149779. break;
  149780. }
  149781. }
  149782. /* less than zero? This is a stream with samples trimmed off
  149783. the beginning, a normal occurrence; set the offset to zero */
  149784. if(accumulated<0)accumulated=0;
  149785. vf->pcmlengths[i*2]=accumulated;
  149786. }
  149787. /* get the PCM length of this link. To do this,
  149788. get the last page of the stream */
  149789. {
  149790. ogg_int64_t end=vf->offsets[i+1];
  149791. _seek_helper(vf,end);
  149792. while(1){
  149793. ret=_get_prev_page(vf,&og);
  149794. if(ret<0){
  149795. /* this should not be possible */
  149796. vorbis_info_clear(vf->vi+i);
  149797. vorbis_comment_clear(vf->vc+i);
  149798. break;
  149799. }
  149800. if(ogg_page_granulepos(&og)!=-1){
  149801. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  149802. break;
  149803. }
  149804. vf->offset=ret;
  149805. }
  149806. }
  149807. }
  149808. }
  149809. static int _make_decode_ready(OggVorbis_File *vf){
  149810. if(vf->ready_state>STREAMSET)return 0;
  149811. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  149812. if(vf->seekable){
  149813. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  149814. return OV_EBADLINK;
  149815. }else{
  149816. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  149817. return OV_EBADLINK;
  149818. }
  149819. vorbis_block_init(&vf->vd,&vf->vb);
  149820. vf->ready_state=INITSET;
  149821. vf->bittrack=0.f;
  149822. vf->samptrack=0.f;
  149823. return 0;
  149824. }
  149825. static int _open_seekable2(OggVorbis_File *vf){
  149826. long serialno=vf->current_serialno;
  149827. ogg_int64_t dataoffset=vf->offset, end;
  149828. ogg_page og;
  149829. /* we're partially open and have a first link header state in
  149830. storage in vf */
  149831. /* we can seek, so set out learning all about this file */
  149832. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  149833. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  149834. /* We get the offset for the last page of the physical bitstream.
  149835. Most OggVorbis files will contain a single logical bitstream */
  149836. end=_get_prev_page(vf,&og);
  149837. if(end<0)return(end);
  149838. /* more than one logical bitstream? */
  149839. if(ogg_page_serialno(&og)!=serialno){
  149840. /* Chained bitstream. Bisect-search each logical bitstream
  149841. section. Do so based on serial number only */
  149842. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  149843. }else{
  149844. /* Only one logical bitstream */
  149845. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  149846. }
  149847. /* the initial header memory is referenced by vf after; don't free it */
  149848. _prefetch_all_headers(vf,dataoffset);
  149849. return(ov_raw_seek(vf,0));
  149850. }
  149851. /* clear out the current logical bitstream decoder */
  149852. static void _decode_clear(OggVorbis_File *vf){
  149853. vorbis_dsp_clear(&vf->vd);
  149854. vorbis_block_clear(&vf->vb);
  149855. vf->ready_state=OPENED;
  149856. }
  149857. /* fetch and process a packet. Handles the case where we're at a
  149858. bitstream boundary and dumps the decoding machine. If the decoding
  149859. machine is unloaded, it loads it. It also keeps pcm_offset up to
  149860. date (seek and read both use this. seek uses a special hack with
  149861. readp).
  149862. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  149863. 0) need more data (only if readp==0)
  149864. 1) got a packet
  149865. */
  149866. static int _fetch_and_process_packet(OggVorbis_File *vf,
  149867. ogg_packet *op_in,
  149868. int readp,
  149869. int spanp){
  149870. ogg_page og;
  149871. /* handle one packet. Try to fetch it from current stream state */
  149872. /* extract packets from page */
  149873. while(1){
  149874. /* process a packet if we can. If the machine isn't loaded,
  149875. neither is a page */
  149876. if(vf->ready_state==INITSET){
  149877. while(1) {
  149878. ogg_packet op;
  149879. ogg_packet *op_ptr=(op_in?op_in:&op);
  149880. int result=ogg_stream_packetout(&vf->os,op_ptr);
  149881. ogg_int64_t granulepos;
  149882. op_in=NULL;
  149883. if(result==-1)return(OV_HOLE); /* hole in the data. */
  149884. if(result>0){
  149885. /* got a packet. process it */
  149886. granulepos=op_ptr->granulepos;
  149887. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  149888. header handling. The
  149889. header packets aren't
  149890. audio, so if/when we
  149891. submit them,
  149892. vorbis_synthesis will
  149893. reject them */
  149894. /* suck in the synthesis data and track bitrate */
  149895. {
  149896. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  149897. /* for proper use of libvorbis within libvorbisfile,
  149898. oldsamples will always be zero. */
  149899. if(oldsamples)return(OV_EFAULT);
  149900. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  149901. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  149902. vf->bittrack+=op_ptr->bytes*8;
  149903. }
  149904. /* update the pcm offset. */
  149905. if(granulepos!=-1 && !op_ptr->e_o_s){
  149906. int link=(vf->seekable?vf->current_link:0);
  149907. int i,samples;
  149908. /* this packet has a pcm_offset on it (the last packet
  149909. completed on a page carries the offset) After processing
  149910. (above), we know the pcm position of the *last* sample
  149911. ready to be returned. Find the offset of the *first*
  149912. As an aside, this trick is inaccurate if we begin
  149913. reading anew right at the last page; the end-of-stream
  149914. granulepos declares the last frame in the stream, and the
  149915. last packet of the last page may be a partial frame.
  149916. So, we need a previous granulepos from an in-sequence page
  149917. to have a reference point. Thus the !op_ptr->e_o_s clause
  149918. above */
  149919. if(vf->seekable && link>0)
  149920. granulepos-=vf->pcmlengths[link*2];
  149921. if(granulepos<0)granulepos=0; /* actually, this
  149922. shouldn't be possible
  149923. here unless the stream
  149924. is very broken */
  149925. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  149926. granulepos-=samples;
  149927. for(i=0;i<link;i++)
  149928. granulepos+=vf->pcmlengths[i*2+1];
  149929. vf->pcm_offset=granulepos;
  149930. }
  149931. return(1);
  149932. }
  149933. }
  149934. else
  149935. break;
  149936. }
  149937. }
  149938. if(vf->ready_state>=OPENED){
  149939. ogg_int64_t ret;
  149940. if(!readp)return(0);
  149941. if((ret=_get_next_page(vf,&og,-1))<0){
  149942. return(OV_EOF); /* eof.
  149943. leave unitialized */
  149944. }
  149945. /* bitrate tracking; add the header's bytes here, the body bytes
  149946. are done by packet above */
  149947. vf->bittrack+=og.header_len*8;
  149948. /* has our decoding just traversed a bitstream boundary? */
  149949. if(vf->ready_state==INITSET){
  149950. if(vf->current_serialno!=ogg_page_serialno(&og)){
  149951. if(!spanp)
  149952. return(OV_EOF);
  149953. _decode_clear(vf);
  149954. if(!vf->seekable){
  149955. vorbis_info_clear(vf->vi);
  149956. vorbis_comment_clear(vf->vc);
  149957. }
  149958. }
  149959. }
  149960. }
  149961. /* Do we need to load a new machine before submitting the page? */
  149962. /* This is different in the seekable and non-seekable cases.
  149963. In the seekable case, we already have all the header
  149964. information loaded and cached; we just initialize the machine
  149965. with it and continue on our merry way.
  149966. In the non-seekable (streaming) case, we'll only be at a
  149967. boundary if we just left the previous logical bitstream and
  149968. we're now nominally at the header of the next bitstream
  149969. */
  149970. if(vf->ready_state!=INITSET){
  149971. int link;
  149972. if(vf->ready_state<STREAMSET){
  149973. if(vf->seekable){
  149974. vf->current_serialno=ogg_page_serialno(&og);
  149975. /* match the serialno to bitstream section. We use this rather than
  149976. offset positions to avoid problems near logical bitstream
  149977. boundaries */
  149978. for(link=0;link<vf->links;link++)
  149979. if(vf->serialnos[link]==vf->current_serialno)break;
  149980. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  149981. stream. error out,
  149982. leave machine
  149983. uninitialized */
  149984. vf->current_link=link;
  149985. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  149986. vf->ready_state=STREAMSET;
  149987. }else{
  149988. /* we're streaming */
  149989. /* fetch the three header packets, build the info struct */
  149990. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  149991. if(ret)return(ret);
  149992. vf->current_link++;
  149993. link=0;
  149994. }
  149995. }
  149996. {
  149997. int ret=_make_decode_ready(vf);
  149998. if(ret<0)return ret;
  149999. }
  150000. }
  150001. ogg_stream_pagein(&vf->os,&og);
  150002. }
  150003. }
  150004. /* if, eg, 64 bit stdio is configured by default, this will build with
  150005. fseek64 */
  150006. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  150007. if(f==NULL)return(-1);
  150008. return fseek(f,off,whence);
  150009. }
  150010. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  150011. long ibytes, ov_callbacks callbacks){
  150012. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  150013. int ret;
  150014. memset(vf,0,sizeof(*vf));
  150015. vf->datasource=f;
  150016. vf->callbacks = callbacks;
  150017. /* init the framing state */
  150018. ogg_sync_init(&vf->oy);
  150019. /* perhaps some data was previously read into a buffer for testing
  150020. against other stream types. Allow initialization from this
  150021. previously read data (as we may be reading from a non-seekable
  150022. stream) */
  150023. if(initial){
  150024. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  150025. memcpy(buffer,initial,ibytes);
  150026. ogg_sync_wrote(&vf->oy,ibytes);
  150027. }
  150028. /* can we seek? Stevens suggests the seek test was portable */
  150029. if(offsettest!=-1)vf->seekable=1;
  150030. /* No seeking yet; Set up a 'single' (current) logical bitstream
  150031. entry for partial open */
  150032. vf->links=1;
  150033. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  150034. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  150035. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  150036. /* Try to fetch the headers, maintaining all the storage */
  150037. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  150038. vf->datasource=NULL;
  150039. ov_clear(vf);
  150040. }else
  150041. vf->ready_state=PARTOPEN;
  150042. return(ret);
  150043. }
  150044. static int _ov_open2(OggVorbis_File *vf){
  150045. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  150046. vf->ready_state=OPENED;
  150047. if(vf->seekable){
  150048. int ret=_open_seekable2(vf);
  150049. if(ret){
  150050. vf->datasource=NULL;
  150051. ov_clear(vf);
  150052. }
  150053. return(ret);
  150054. }else
  150055. vf->ready_state=STREAMSET;
  150056. return 0;
  150057. }
  150058. /* clear out the OggVorbis_File struct */
  150059. int ov_clear(OggVorbis_File *vf){
  150060. if(vf){
  150061. vorbis_block_clear(&vf->vb);
  150062. vorbis_dsp_clear(&vf->vd);
  150063. ogg_stream_clear(&vf->os);
  150064. if(vf->vi && vf->links){
  150065. int i;
  150066. for(i=0;i<vf->links;i++){
  150067. vorbis_info_clear(vf->vi+i);
  150068. vorbis_comment_clear(vf->vc+i);
  150069. }
  150070. _ogg_free(vf->vi);
  150071. _ogg_free(vf->vc);
  150072. }
  150073. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  150074. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  150075. if(vf->serialnos)_ogg_free(vf->serialnos);
  150076. if(vf->offsets)_ogg_free(vf->offsets);
  150077. ogg_sync_clear(&vf->oy);
  150078. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  150079. memset(vf,0,sizeof(*vf));
  150080. }
  150081. #ifdef DEBUG_LEAKS
  150082. _VDBG_dump();
  150083. #endif
  150084. return(0);
  150085. }
  150086. /* inspects the OggVorbis file and finds/documents all the logical
  150087. bitstreams contained in it. Tries to be tolerant of logical
  150088. bitstream sections that are truncated/woogie.
  150089. return: -1) error
  150090. 0) OK
  150091. */
  150092. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  150093. ov_callbacks callbacks){
  150094. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  150095. if(ret)return ret;
  150096. return _ov_open2(vf);
  150097. }
  150098. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  150099. ov_callbacks callbacks = {
  150100. (size_t (*)(void *, size_t, size_t, void *)) fread,
  150101. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  150102. (int (*)(void *)) fclose,
  150103. (long (*)(void *)) ftell
  150104. };
  150105. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  150106. }
  150107. /* cheap hack for game usage where downsampling is desirable; there's
  150108. no need for SRC as we can just do it cheaply in libvorbis. */
  150109. int ov_halfrate(OggVorbis_File *vf,int flag){
  150110. int i;
  150111. if(vf->vi==NULL)return OV_EINVAL;
  150112. if(!vf->seekable)return OV_EINVAL;
  150113. if(vf->ready_state>=STREAMSET)
  150114. _decode_clear(vf); /* clear out stream state; later on libvorbis
  150115. will be able to swap this on the fly, but
  150116. for now dumping the decode machine is needed
  150117. to reinit the MDCT lookups. 1.1 libvorbis
  150118. is planned to be able to switch on the fly */
  150119. for(i=0;i<vf->links;i++){
  150120. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  150121. ov_halfrate(vf,0);
  150122. return OV_EINVAL;
  150123. }
  150124. }
  150125. return 0;
  150126. }
  150127. int ov_halfrate_p(OggVorbis_File *vf){
  150128. if(vf->vi==NULL)return OV_EINVAL;
  150129. return vorbis_synthesis_halfrate_p(vf->vi);
  150130. }
  150131. /* Only partially open the vorbis file; test for Vorbisness, and load
  150132. the headers for the first chain. Do not seek (although test for
  150133. seekability). Use ov_test_open to finish opening the file, else
  150134. ov_clear to close/free it. Same return codes as open. */
  150135. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  150136. ov_callbacks callbacks)
  150137. {
  150138. return _ov_open1(f,vf,initial,ibytes,callbacks);
  150139. }
  150140. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  150141. ov_callbacks callbacks = {
  150142. (size_t (*)(void *, size_t, size_t, void *)) fread,
  150143. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  150144. (int (*)(void *)) fclose,
  150145. (long (*)(void *)) ftell
  150146. };
  150147. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  150148. }
  150149. int ov_test_open(OggVorbis_File *vf){
  150150. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  150151. return _ov_open2(vf);
  150152. }
  150153. /* How many logical bitstreams in this physical bitstream? */
  150154. long ov_streams(OggVorbis_File *vf){
  150155. return vf->links;
  150156. }
  150157. /* Is the FILE * associated with vf seekable? */
  150158. long ov_seekable(OggVorbis_File *vf){
  150159. return vf->seekable;
  150160. }
  150161. /* returns the bitrate for a given logical bitstream or the entire
  150162. physical bitstream. If the file is open for random access, it will
  150163. find the *actual* average bitrate. If the file is streaming, it
  150164. returns the nominal bitrate (if set) else the average of the
  150165. upper/lower bounds (if set) else -1 (unset).
  150166. If you want the actual bitrate field settings, get them from the
  150167. vorbis_info structs */
  150168. long ov_bitrate(OggVorbis_File *vf,int i){
  150169. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150170. if(i>=vf->links)return(OV_EINVAL);
  150171. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  150172. if(i<0){
  150173. ogg_int64_t bits=0;
  150174. int i;
  150175. float br;
  150176. for(i=0;i<vf->links;i++)
  150177. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  150178. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  150179. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  150180. * so this is slightly transformed to make it work.
  150181. */
  150182. br = bits/ov_time_total(vf,-1);
  150183. return(rint(br));
  150184. }else{
  150185. if(vf->seekable){
  150186. /* return the actual bitrate */
  150187. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  150188. }else{
  150189. /* return nominal if set */
  150190. if(vf->vi[i].bitrate_nominal>0){
  150191. return vf->vi[i].bitrate_nominal;
  150192. }else{
  150193. if(vf->vi[i].bitrate_upper>0){
  150194. if(vf->vi[i].bitrate_lower>0){
  150195. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  150196. }else{
  150197. return vf->vi[i].bitrate_upper;
  150198. }
  150199. }
  150200. return(OV_FALSE);
  150201. }
  150202. }
  150203. }
  150204. }
  150205. /* returns the actual bitrate since last call. returns -1 if no
  150206. additional data to offer since last call (or at beginning of stream),
  150207. EINVAL if stream is only partially open
  150208. */
  150209. long ov_bitrate_instant(OggVorbis_File *vf){
  150210. int link=(vf->seekable?vf->current_link:0);
  150211. long ret;
  150212. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150213. if(vf->samptrack==0)return(OV_FALSE);
  150214. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  150215. vf->bittrack=0.f;
  150216. vf->samptrack=0.f;
  150217. return(ret);
  150218. }
  150219. /* Guess */
  150220. long ov_serialnumber(OggVorbis_File *vf,int i){
  150221. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  150222. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  150223. if(i<0){
  150224. return(vf->current_serialno);
  150225. }else{
  150226. return(vf->serialnos[i]);
  150227. }
  150228. }
  150229. /* returns: total raw (compressed) length of content if i==-1
  150230. raw (compressed) length of that logical bitstream for i==0 to n
  150231. OV_EINVAL if the stream is not seekable (we can't know the length)
  150232. or if stream is only partially open
  150233. */
  150234. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  150235. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150236. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  150237. if(i<0){
  150238. ogg_int64_t acc=0;
  150239. int i;
  150240. for(i=0;i<vf->links;i++)
  150241. acc+=ov_raw_total(vf,i);
  150242. return(acc);
  150243. }else{
  150244. return(vf->offsets[i+1]-vf->offsets[i]);
  150245. }
  150246. }
  150247. /* returns: total PCM length (samples) of content if i==-1 PCM length
  150248. (samples) of that logical bitstream for i==0 to n
  150249. OV_EINVAL if the stream is not seekable (we can't know the
  150250. length) or only partially open
  150251. */
  150252. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  150253. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150254. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  150255. if(i<0){
  150256. ogg_int64_t acc=0;
  150257. int i;
  150258. for(i=0;i<vf->links;i++)
  150259. acc+=ov_pcm_total(vf,i);
  150260. return(acc);
  150261. }else{
  150262. return(vf->pcmlengths[i*2+1]);
  150263. }
  150264. }
  150265. /* returns: total seconds of content if i==-1
  150266. seconds in that logical bitstream for i==0 to n
  150267. OV_EINVAL if the stream is not seekable (we can't know the
  150268. length) or only partially open
  150269. */
  150270. double ov_time_total(OggVorbis_File *vf,int i){
  150271. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150272. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  150273. if(i<0){
  150274. double acc=0;
  150275. int i;
  150276. for(i=0;i<vf->links;i++)
  150277. acc+=ov_time_total(vf,i);
  150278. return(acc);
  150279. }else{
  150280. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  150281. }
  150282. }
  150283. /* seek to an offset relative to the *compressed* data. This also
  150284. scans packets to update the PCM cursor. It will cross a logical
  150285. bitstream boundary, but only if it can't get any packets out of the
  150286. tail of the bitstream we seek to (so no surprises).
  150287. returns zero on success, nonzero on failure */
  150288. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  150289. ogg_stream_state work_os;
  150290. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150291. if(!vf->seekable)
  150292. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  150293. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  150294. /* don't yet clear out decoding machine (if it's initialized), in
  150295. the case we're in the same link. Restart the decode lapping, and
  150296. let _fetch_and_process_packet deal with a potential bitstream
  150297. boundary */
  150298. vf->pcm_offset=-1;
  150299. ogg_stream_reset_serialno(&vf->os,
  150300. vf->current_serialno); /* must set serialno */
  150301. vorbis_synthesis_restart(&vf->vd);
  150302. _seek_helper(vf,pos);
  150303. /* we need to make sure the pcm_offset is set, but we don't want to
  150304. advance the raw cursor past good packets just to get to the first
  150305. with a granulepos. That's not equivalent behavior to beginning
  150306. decoding as immediately after the seek position as possible.
  150307. So, a hack. We use two stream states; a local scratch state and
  150308. the shared vf->os stream state. We use the local state to
  150309. scan, and the shared state as a buffer for later decode.
  150310. Unfortuantely, on the last page we still advance to last packet
  150311. because the granulepos on the last page is not necessarily on a
  150312. packet boundary, and we need to make sure the granpos is
  150313. correct.
  150314. */
  150315. {
  150316. ogg_page og;
  150317. ogg_packet op;
  150318. int lastblock=0;
  150319. int accblock=0;
  150320. int thisblock;
  150321. int eosflag;
  150322. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  150323. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  150324. return from not necessarily
  150325. starting from the beginning */
  150326. while(1){
  150327. if(vf->ready_state>=STREAMSET){
  150328. /* snarf/scan a packet if we can */
  150329. int result=ogg_stream_packetout(&work_os,&op);
  150330. if(result>0){
  150331. if(vf->vi[vf->current_link].codec_setup){
  150332. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  150333. if(thisblock<0){
  150334. ogg_stream_packetout(&vf->os,NULL);
  150335. thisblock=0;
  150336. }else{
  150337. if(eosflag)
  150338. ogg_stream_packetout(&vf->os,NULL);
  150339. else
  150340. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  150341. }
  150342. if(op.granulepos!=-1){
  150343. int i,link=vf->current_link;
  150344. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  150345. if(granulepos<0)granulepos=0;
  150346. for(i=0;i<link;i++)
  150347. granulepos+=vf->pcmlengths[i*2+1];
  150348. vf->pcm_offset=granulepos-accblock;
  150349. break;
  150350. }
  150351. lastblock=thisblock;
  150352. continue;
  150353. }else
  150354. ogg_stream_packetout(&vf->os,NULL);
  150355. }
  150356. }
  150357. if(!lastblock){
  150358. if(_get_next_page(vf,&og,-1)<0){
  150359. vf->pcm_offset=ov_pcm_total(vf,-1);
  150360. break;
  150361. }
  150362. }else{
  150363. /* huh? Bogus stream with packets but no granulepos */
  150364. vf->pcm_offset=-1;
  150365. break;
  150366. }
  150367. /* has our decoding just traversed a bitstream boundary? */
  150368. if(vf->ready_state>=STREAMSET)
  150369. if(vf->current_serialno!=ogg_page_serialno(&og)){
  150370. _decode_clear(vf); /* clear out stream state */
  150371. ogg_stream_clear(&work_os);
  150372. }
  150373. if(vf->ready_state<STREAMSET){
  150374. int link;
  150375. vf->current_serialno=ogg_page_serialno(&og);
  150376. for(link=0;link<vf->links;link++)
  150377. if(vf->serialnos[link]==vf->current_serialno)break;
  150378. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  150379. error out, leave
  150380. machine uninitialized */
  150381. vf->current_link=link;
  150382. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  150383. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  150384. vf->ready_state=STREAMSET;
  150385. }
  150386. ogg_stream_pagein(&vf->os,&og);
  150387. ogg_stream_pagein(&work_os,&og);
  150388. eosflag=ogg_page_eos(&og);
  150389. }
  150390. }
  150391. ogg_stream_clear(&work_os);
  150392. vf->bittrack=0.f;
  150393. vf->samptrack=0.f;
  150394. return(0);
  150395. seek_error:
  150396. /* dump the machine so we're in a known state */
  150397. vf->pcm_offset=-1;
  150398. ogg_stream_clear(&work_os);
  150399. _decode_clear(vf);
  150400. return OV_EBADLINK;
  150401. }
  150402. /* Page granularity seek (faster than sample granularity because we
  150403. don't do the last bit of decode to find a specific sample).
  150404. Seek to the last [granule marked] page preceeding the specified pos
  150405. location, such that decoding past the returned point will quickly
  150406. arrive at the requested position. */
  150407. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  150408. int link=-1;
  150409. ogg_int64_t result=0;
  150410. ogg_int64_t total=ov_pcm_total(vf,-1);
  150411. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150412. if(!vf->seekable)return(OV_ENOSEEK);
  150413. if(pos<0 || pos>total)return(OV_EINVAL);
  150414. /* which bitstream section does this pcm offset occur in? */
  150415. for(link=vf->links-1;link>=0;link--){
  150416. total-=vf->pcmlengths[link*2+1];
  150417. if(pos>=total)break;
  150418. }
  150419. /* search within the logical bitstream for the page with the highest
  150420. pcm_pos preceeding (or equal to) pos. There is a danger here;
  150421. missing pages or incorrect frame number information in the
  150422. bitstream could make our task impossible. Account for that (it
  150423. would be an error condition) */
  150424. /* new search algorithm by HB (Nicholas Vinen) */
  150425. {
  150426. ogg_int64_t end=vf->offsets[link+1];
  150427. ogg_int64_t begin=vf->offsets[link];
  150428. ogg_int64_t begintime = vf->pcmlengths[link*2];
  150429. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  150430. ogg_int64_t target=pos-total+begintime;
  150431. ogg_int64_t best=begin;
  150432. ogg_page og;
  150433. while(begin<end){
  150434. ogg_int64_t bisect;
  150435. if(end-begin<CHUNKSIZE){
  150436. bisect=begin;
  150437. }else{
  150438. /* take a (pretty decent) guess. */
  150439. bisect=begin +
  150440. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  150441. if(bisect<=begin)
  150442. bisect=begin+1;
  150443. }
  150444. _seek_helper(vf,bisect);
  150445. while(begin<end){
  150446. result=_get_next_page(vf,&og,end-vf->offset);
  150447. if(result==OV_EREAD) goto seek_error;
  150448. if(result<0){
  150449. if(bisect<=begin+1)
  150450. end=begin; /* found it */
  150451. else{
  150452. if(bisect==0) goto seek_error;
  150453. bisect-=CHUNKSIZE;
  150454. if(bisect<=begin)bisect=begin+1;
  150455. _seek_helper(vf,bisect);
  150456. }
  150457. }else{
  150458. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  150459. if(granulepos==-1)continue;
  150460. if(granulepos<target){
  150461. best=result; /* raw offset of packet with granulepos */
  150462. begin=vf->offset; /* raw offset of next page */
  150463. begintime=granulepos;
  150464. if(target-begintime>44100)break;
  150465. bisect=begin; /* *not* begin + 1 */
  150466. }else{
  150467. if(bisect<=begin+1)
  150468. end=begin; /* found it */
  150469. else{
  150470. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  150471. end=result;
  150472. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  150473. if(bisect<=begin)bisect=begin+1;
  150474. _seek_helper(vf,bisect);
  150475. }else{
  150476. end=result;
  150477. endtime=granulepos;
  150478. break;
  150479. }
  150480. }
  150481. }
  150482. }
  150483. }
  150484. }
  150485. /* found our page. seek to it, update pcm offset. Easier case than
  150486. raw_seek, don't keep packets preceeding granulepos. */
  150487. {
  150488. ogg_page og;
  150489. ogg_packet op;
  150490. /* seek */
  150491. _seek_helper(vf,best);
  150492. vf->pcm_offset=-1;
  150493. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  150494. if(link!=vf->current_link){
  150495. /* Different link; dump entire decode machine */
  150496. _decode_clear(vf);
  150497. vf->current_link=link;
  150498. vf->current_serialno=ogg_page_serialno(&og);
  150499. vf->ready_state=STREAMSET;
  150500. }else{
  150501. vorbis_synthesis_restart(&vf->vd);
  150502. }
  150503. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  150504. ogg_stream_pagein(&vf->os,&og);
  150505. /* pull out all but last packet; the one with granulepos */
  150506. while(1){
  150507. result=ogg_stream_packetpeek(&vf->os,&op);
  150508. if(result==0){
  150509. /* !!! the packet finishing this page originated on a
  150510. preceeding page. Keep fetching previous pages until we
  150511. get one with a granulepos or without the 'continued' flag
  150512. set. Then just use raw_seek for simplicity. */
  150513. _seek_helper(vf,best);
  150514. while(1){
  150515. result=_get_prev_page(vf,&og);
  150516. if(result<0) goto seek_error;
  150517. if(ogg_page_granulepos(&og)>-1 ||
  150518. !ogg_page_continued(&og)){
  150519. return ov_raw_seek(vf,result);
  150520. }
  150521. vf->offset=result;
  150522. }
  150523. }
  150524. if(result<0){
  150525. result = OV_EBADPACKET;
  150526. goto seek_error;
  150527. }
  150528. if(op.granulepos!=-1){
  150529. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  150530. if(vf->pcm_offset<0)vf->pcm_offset=0;
  150531. vf->pcm_offset+=total;
  150532. break;
  150533. }else
  150534. result=ogg_stream_packetout(&vf->os,NULL);
  150535. }
  150536. }
  150537. }
  150538. /* verify result */
  150539. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  150540. result=OV_EFAULT;
  150541. goto seek_error;
  150542. }
  150543. vf->bittrack=0.f;
  150544. vf->samptrack=0.f;
  150545. return(0);
  150546. seek_error:
  150547. /* dump machine so we're in a known state */
  150548. vf->pcm_offset=-1;
  150549. _decode_clear(vf);
  150550. return (int)result;
  150551. }
  150552. /* seek to a sample offset relative to the decompressed pcm stream
  150553. returns zero on success, nonzero on failure */
  150554. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  150555. int thisblock,lastblock=0;
  150556. int ret=ov_pcm_seek_page(vf,pos);
  150557. if(ret<0)return(ret);
  150558. if((ret=_make_decode_ready(vf)))return ret;
  150559. /* discard leading packets we don't need for the lapping of the
  150560. position we want; don't decode them */
  150561. while(1){
  150562. ogg_packet op;
  150563. ogg_page og;
  150564. int ret=ogg_stream_packetpeek(&vf->os,&op);
  150565. if(ret>0){
  150566. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  150567. if(thisblock<0){
  150568. ogg_stream_packetout(&vf->os,NULL);
  150569. continue; /* non audio packet */
  150570. }
  150571. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  150572. if(vf->pcm_offset+((thisblock+
  150573. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  150574. /* remove the packet from packet queue and track its granulepos */
  150575. ogg_stream_packetout(&vf->os,NULL);
  150576. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  150577. only tracking, no
  150578. pcm_decode */
  150579. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  150580. /* end of logical stream case is hard, especially with exact
  150581. length positioning. */
  150582. if(op.granulepos>-1){
  150583. int i;
  150584. /* always believe the stream markers */
  150585. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  150586. if(vf->pcm_offset<0)vf->pcm_offset=0;
  150587. for(i=0;i<vf->current_link;i++)
  150588. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  150589. }
  150590. lastblock=thisblock;
  150591. }else{
  150592. if(ret<0 && ret!=OV_HOLE)break;
  150593. /* suck in a new page */
  150594. if(_get_next_page(vf,&og,-1)<0)break;
  150595. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  150596. if(vf->ready_state<STREAMSET){
  150597. int link;
  150598. vf->current_serialno=ogg_page_serialno(&og);
  150599. for(link=0;link<vf->links;link++)
  150600. if(vf->serialnos[link]==vf->current_serialno)break;
  150601. if(link==vf->links)return(OV_EBADLINK);
  150602. vf->current_link=link;
  150603. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  150604. vf->ready_state=STREAMSET;
  150605. ret=_make_decode_ready(vf);
  150606. if(ret)return ret;
  150607. lastblock=0;
  150608. }
  150609. ogg_stream_pagein(&vf->os,&og);
  150610. }
  150611. }
  150612. vf->bittrack=0.f;
  150613. vf->samptrack=0.f;
  150614. /* discard samples until we reach the desired position. Crossing a
  150615. logical bitstream boundary with abandon is OK. */
  150616. while(vf->pcm_offset<pos){
  150617. ogg_int64_t target=pos-vf->pcm_offset;
  150618. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  150619. if(samples>target)samples=target;
  150620. vorbis_synthesis_read(&vf->vd,samples);
  150621. vf->pcm_offset+=samples;
  150622. if(samples<target)
  150623. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  150624. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  150625. }
  150626. return 0;
  150627. }
  150628. /* seek to a playback time relative to the decompressed pcm stream
  150629. returns zero on success, nonzero on failure */
  150630. int ov_time_seek(OggVorbis_File *vf,double seconds){
  150631. /* translate time to PCM position and call ov_pcm_seek */
  150632. int link=-1;
  150633. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  150634. double time_total=ov_time_total(vf,-1);
  150635. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150636. if(!vf->seekable)return(OV_ENOSEEK);
  150637. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  150638. /* which bitstream section does this time offset occur in? */
  150639. for(link=vf->links-1;link>=0;link--){
  150640. pcm_total-=vf->pcmlengths[link*2+1];
  150641. time_total-=ov_time_total(vf,link);
  150642. if(seconds>=time_total)break;
  150643. }
  150644. /* enough information to convert time offset to pcm offset */
  150645. {
  150646. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  150647. return(ov_pcm_seek(vf,target));
  150648. }
  150649. }
  150650. /* page-granularity version of ov_time_seek
  150651. returns zero on success, nonzero on failure */
  150652. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  150653. /* translate time to PCM position and call ov_pcm_seek */
  150654. int link=-1;
  150655. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  150656. double time_total=ov_time_total(vf,-1);
  150657. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150658. if(!vf->seekable)return(OV_ENOSEEK);
  150659. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  150660. /* which bitstream section does this time offset occur in? */
  150661. for(link=vf->links-1;link>=0;link--){
  150662. pcm_total-=vf->pcmlengths[link*2+1];
  150663. time_total-=ov_time_total(vf,link);
  150664. if(seconds>=time_total)break;
  150665. }
  150666. /* enough information to convert time offset to pcm offset */
  150667. {
  150668. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  150669. return(ov_pcm_seek_page(vf,target));
  150670. }
  150671. }
  150672. /* tell the current stream offset cursor. Note that seek followed by
  150673. tell will likely not give the set offset due to caching */
  150674. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  150675. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150676. return(vf->offset);
  150677. }
  150678. /* return PCM offset (sample) of next PCM sample to be read */
  150679. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  150680. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150681. return(vf->pcm_offset);
  150682. }
  150683. /* return time offset (seconds) of next PCM sample to be read */
  150684. double ov_time_tell(OggVorbis_File *vf){
  150685. int link=0;
  150686. ogg_int64_t pcm_total=0;
  150687. double time_total=0.f;
  150688. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150689. if(vf->seekable){
  150690. pcm_total=ov_pcm_total(vf,-1);
  150691. time_total=ov_time_total(vf,-1);
  150692. /* which bitstream section does this time offset occur in? */
  150693. for(link=vf->links-1;link>=0;link--){
  150694. pcm_total-=vf->pcmlengths[link*2+1];
  150695. time_total-=ov_time_total(vf,link);
  150696. if(vf->pcm_offset>=pcm_total)break;
  150697. }
  150698. }
  150699. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  150700. }
  150701. /* link: -1) return the vorbis_info struct for the bitstream section
  150702. currently being decoded
  150703. 0-n) to request information for a specific bitstream section
  150704. In the case of a non-seekable bitstream, any call returns the
  150705. current bitstream. NULL in the case that the machine is not
  150706. initialized */
  150707. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  150708. if(vf->seekable){
  150709. if(link<0)
  150710. if(vf->ready_state>=STREAMSET)
  150711. return vf->vi+vf->current_link;
  150712. else
  150713. return vf->vi;
  150714. else
  150715. if(link>=vf->links)
  150716. return NULL;
  150717. else
  150718. return vf->vi+link;
  150719. }else{
  150720. return vf->vi;
  150721. }
  150722. }
  150723. /* grr, strong typing, grr, no templates/inheritence, grr */
  150724. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  150725. if(vf->seekable){
  150726. if(link<0)
  150727. if(vf->ready_state>=STREAMSET)
  150728. return vf->vc+vf->current_link;
  150729. else
  150730. return vf->vc;
  150731. else
  150732. if(link>=vf->links)
  150733. return NULL;
  150734. else
  150735. return vf->vc+link;
  150736. }else{
  150737. return vf->vc;
  150738. }
  150739. }
  150740. static int host_is_big_endian() {
  150741. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  150742. unsigned char *bytewise = (unsigned char *)&pattern;
  150743. if (bytewise[0] == 0xfe) return 1;
  150744. return 0;
  150745. }
  150746. /* up to this point, everything could more or less hide the multiple
  150747. logical bitstream nature of chaining from the toplevel application
  150748. if the toplevel application didn't particularly care. However, at
  150749. the point that we actually read audio back, the multiple-section
  150750. nature must surface: Multiple bitstream sections do not necessarily
  150751. have to have the same number of channels or sampling rate.
  150752. ov_read returns the sequential logical bitstream number currently
  150753. being decoded along with the PCM data in order that the toplevel
  150754. application can take action on channel/sample rate changes. This
  150755. number will be incremented even for streamed (non-seekable) streams
  150756. (for seekable streams, it represents the actual logical bitstream
  150757. index within the physical bitstream. Note that the accessor
  150758. functions above are aware of this dichotomy).
  150759. input values: buffer) a buffer to hold packed PCM data for return
  150760. length) the byte length requested to be placed into buffer
  150761. bigendianp) should the data be packed LSB first (0) or
  150762. MSB first (1)
  150763. word) word size for output. currently 1 (byte) or
  150764. 2 (16 bit short)
  150765. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  150766. 0) EOF
  150767. n) number of bytes of PCM actually returned. The
  150768. below works on a packet-by-packet basis, so the
  150769. return length is not related to the 'length' passed
  150770. in, just guaranteed to fit.
  150771. *section) set to the logical bitstream number */
  150772. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  150773. int bigendianp,int word,int sgned,int *bitstream){
  150774. int i,j;
  150775. int host_endian = host_is_big_endian();
  150776. float **pcm;
  150777. long samples;
  150778. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150779. while(1){
  150780. if(vf->ready_state==INITSET){
  150781. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  150782. if(samples)break;
  150783. }
  150784. /* suck in another packet */
  150785. {
  150786. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  150787. if(ret==OV_EOF)
  150788. return(0);
  150789. if(ret<=0)
  150790. return(ret);
  150791. }
  150792. }
  150793. if(samples>0){
  150794. /* yay! proceed to pack data into the byte buffer */
  150795. long channels=ov_info(vf,-1)->channels;
  150796. long bytespersample=word * channels;
  150797. vorbis_fpu_control fpu;
  150798. (void) fpu; // (to avoid a warning about it being unused)
  150799. if(samples>length/bytespersample)samples=length/bytespersample;
  150800. if(samples <= 0)
  150801. return OV_EINVAL;
  150802. /* a tight loop to pack each size */
  150803. {
  150804. int val;
  150805. if(word==1){
  150806. int off=(sgned?0:128);
  150807. vorbis_fpu_setround(&fpu);
  150808. for(j=0;j<samples;j++)
  150809. for(i=0;i<channels;i++){
  150810. val=vorbis_ftoi(pcm[i][j]*128.f);
  150811. if(val>127)val=127;
  150812. else if(val<-128)val=-128;
  150813. *buffer++=val+off;
  150814. }
  150815. vorbis_fpu_restore(fpu);
  150816. }else{
  150817. int off=(sgned?0:32768);
  150818. if(host_endian==bigendianp){
  150819. if(sgned){
  150820. vorbis_fpu_setround(&fpu);
  150821. for(i=0;i<channels;i++) { /* It's faster in this order */
  150822. float *src=pcm[i];
  150823. short *dest=((short *)buffer)+i;
  150824. for(j=0;j<samples;j++) {
  150825. val=vorbis_ftoi(src[j]*32768.f);
  150826. if(val>32767)val=32767;
  150827. else if(val<-32768)val=-32768;
  150828. *dest=val;
  150829. dest+=channels;
  150830. }
  150831. }
  150832. vorbis_fpu_restore(fpu);
  150833. }else{
  150834. vorbis_fpu_setround(&fpu);
  150835. for(i=0;i<channels;i++) {
  150836. float *src=pcm[i];
  150837. short *dest=((short *)buffer)+i;
  150838. for(j=0;j<samples;j++) {
  150839. val=vorbis_ftoi(src[j]*32768.f);
  150840. if(val>32767)val=32767;
  150841. else if(val<-32768)val=-32768;
  150842. *dest=val+off;
  150843. dest+=channels;
  150844. }
  150845. }
  150846. vorbis_fpu_restore(fpu);
  150847. }
  150848. }else if(bigendianp){
  150849. vorbis_fpu_setround(&fpu);
  150850. for(j=0;j<samples;j++)
  150851. for(i=0;i<channels;i++){
  150852. val=vorbis_ftoi(pcm[i][j]*32768.f);
  150853. if(val>32767)val=32767;
  150854. else if(val<-32768)val=-32768;
  150855. val+=off;
  150856. *buffer++=(val>>8);
  150857. *buffer++=(val&0xff);
  150858. }
  150859. vorbis_fpu_restore(fpu);
  150860. }else{
  150861. int val;
  150862. vorbis_fpu_setround(&fpu);
  150863. for(j=0;j<samples;j++)
  150864. for(i=0;i<channels;i++){
  150865. val=vorbis_ftoi(pcm[i][j]*32768.f);
  150866. if(val>32767)val=32767;
  150867. else if(val<-32768)val=-32768;
  150868. val+=off;
  150869. *buffer++=(val&0xff);
  150870. *buffer++=(val>>8);
  150871. }
  150872. vorbis_fpu_restore(fpu);
  150873. }
  150874. }
  150875. }
  150876. vorbis_synthesis_read(&vf->vd,samples);
  150877. vf->pcm_offset+=samples;
  150878. if(bitstream)*bitstream=vf->current_link;
  150879. return(samples*bytespersample);
  150880. }else{
  150881. return(samples);
  150882. }
  150883. }
  150884. /* input values: pcm_channels) a float vector per channel of output
  150885. length) the sample length being read by the app
  150886. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  150887. 0) EOF
  150888. n) number of samples of PCM actually returned. The
  150889. below works on a packet-by-packet basis, so the
  150890. return length is not related to the 'length' passed
  150891. in, just guaranteed to fit.
  150892. *section) set to the logical bitstream number */
  150893. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  150894. int *bitstream){
  150895. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150896. while(1){
  150897. if(vf->ready_state==INITSET){
  150898. float **pcm;
  150899. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  150900. if(samples){
  150901. if(pcm_channels)*pcm_channels=pcm;
  150902. if(samples>length)samples=length;
  150903. vorbis_synthesis_read(&vf->vd,samples);
  150904. vf->pcm_offset+=samples;
  150905. if(bitstream)*bitstream=vf->current_link;
  150906. return samples;
  150907. }
  150908. }
  150909. /* suck in another packet */
  150910. {
  150911. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  150912. if(ret==OV_EOF)return(0);
  150913. if(ret<=0)return(ret);
  150914. }
  150915. }
  150916. }
  150917. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  150918. extern void _analysis_output_always(char *base,int i,float *v,int n,int bark,int dB,
  150919. ogg_int64_t off);
  150920. static void _ov_splice(float **pcm,float **lappcm,
  150921. int n1, int n2,
  150922. int ch1, int ch2,
  150923. float *w1, float *w2){
  150924. int i,j;
  150925. float *w=w1;
  150926. int n=n1;
  150927. if(n1>n2){
  150928. n=n2;
  150929. w=w2;
  150930. }
  150931. /* splice */
  150932. for(j=0;j<ch1 && j<ch2;j++){
  150933. float *s=lappcm[j];
  150934. float *d=pcm[j];
  150935. for(i=0;i<n;i++){
  150936. float wd=w[i]*w[i];
  150937. float ws=1.-wd;
  150938. d[i]=d[i]*wd + s[i]*ws;
  150939. }
  150940. }
  150941. /* window from zero */
  150942. for(;j<ch2;j++){
  150943. float *d=pcm[j];
  150944. for(i=0;i<n;i++){
  150945. float wd=w[i]*w[i];
  150946. d[i]=d[i]*wd;
  150947. }
  150948. }
  150949. }
  150950. /* make sure vf is INITSET */
  150951. static int _ov_initset(OggVorbis_File *vf){
  150952. while(1){
  150953. if(vf->ready_state==INITSET)break;
  150954. /* suck in another packet */
  150955. {
  150956. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  150957. if(ret<0 && ret!=OV_HOLE)return(ret);
  150958. }
  150959. }
  150960. return 0;
  150961. }
  150962. /* make sure vf is INITSET and that we have a primed buffer; if
  150963. we're crosslapping at a stream section boundary, this also makes
  150964. sure we're sanity checking against the right stream information */
  150965. static int _ov_initprime(OggVorbis_File *vf){
  150966. vorbis_dsp_state *vd=&vf->vd;
  150967. while(1){
  150968. if(vf->ready_state==INITSET)
  150969. if(vorbis_synthesis_pcmout(vd,NULL))break;
  150970. /* suck in another packet */
  150971. {
  150972. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  150973. if(ret<0 && ret!=OV_HOLE)return(ret);
  150974. }
  150975. }
  150976. return 0;
  150977. }
  150978. /* grab enough data for lapping from vf; this may be in the form of
  150979. unreturned, already-decoded pcm, remaining PCM we will need to
  150980. decode, or synthetic postextrapolation from last packets. */
  150981. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  150982. float **lappcm,int lapsize){
  150983. int lapcount=0,i;
  150984. float **pcm;
  150985. /* try first to decode the lapping data */
  150986. while(lapcount<lapsize){
  150987. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  150988. if(samples){
  150989. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  150990. for(i=0;i<vi->channels;i++)
  150991. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  150992. lapcount+=samples;
  150993. vorbis_synthesis_read(vd,samples);
  150994. }else{
  150995. /* suck in another packet */
  150996. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  150997. if(ret==OV_EOF)break;
  150998. }
  150999. }
  151000. if(lapcount<lapsize){
  151001. /* failed to get lapping data from normal decode; pry it from the
  151002. postextrapolation buffering, or the second half of the MDCT
  151003. from the last packet */
  151004. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  151005. if(samples==0){
  151006. for(i=0;i<vi->channels;i++)
  151007. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  151008. lapcount=lapsize;
  151009. }else{
  151010. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  151011. for(i=0;i<vi->channels;i++)
  151012. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  151013. lapcount+=samples;
  151014. }
  151015. }
  151016. }
  151017. /* this sets up crosslapping of a sample by using trailing data from
  151018. sample 1 and lapping it into the windowing buffer of sample 2 */
  151019. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  151020. vorbis_info *vi1,*vi2;
  151021. float **lappcm;
  151022. float **pcm;
  151023. float *w1,*w2;
  151024. int n1,n2,i,ret,hs1,hs2;
  151025. if(vf1==vf2)return(0); /* degenerate case */
  151026. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  151027. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  151028. /* the relevant overlap buffers must be pre-checked and pre-primed
  151029. before looking at settings in the event that priming would cross
  151030. a bitstream boundary. So, do it now */
  151031. ret=_ov_initset(vf1);
  151032. if(ret)return(ret);
  151033. ret=_ov_initprime(vf2);
  151034. if(ret)return(ret);
  151035. vi1=ov_info(vf1,-1);
  151036. vi2=ov_info(vf2,-1);
  151037. hs1=ov_halfrate_p(vf1);
  151038. hs2=ov_halfrate_p(vf2);
  151039. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  151040. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  151041. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  151042. w1=vorbis_window(&vf1->vd,0);
  151043. w2=vorbis_window(&vf2->vd,0);
  151044. for(i=0;i<vi1->channels;i++)
  151045. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  151046. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  151047. /* have a lapping buffer from vf1; now to splice it into the lapping
  151048. buffer of vf2 */
  151049. /* consolidate and expose the buffer. */
  151050. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  151051. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  151052. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  151053. /* splice */
  151054. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  151055. /* done */
  151056. return(0);
  151057. }
  151058. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  151059. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  151060. vorbis_info *vi;
  151061. float **lappcm;
  151062. float **pcm;
  151063. float *w1,*w2;
  151064. int n1,n2,ch1,ch2,hs;
  151065. int i,ret;
  151066. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151067. ret=_ov_initset(vf);
  151068. if(ret)return(ret);
  151069. vi=ov_info(vf,-1);
  151070. hs=ov_halfrate_p(vf);
  151071. ch1=vi->channels;
  151072. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  151073. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  151074. persistent; even if the decode state
  151075. from this link gets dumped, this
  151076. window array continues to exist */
  151077. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  151078. for(i=0;i<ch1;i++)
  151079. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  151080. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  151081. /* have lapping data; seek and prime the buffer */
  151082. ret=localseek(vf,pos);
  151083. if(ret)return ret;
  151084. ret=_ov_initprime(vf);
  151085. if(ret)return(ret);
  151086. /* Guard against cross-link changes; they're perfectly legal */
  151087. vi=ov_info(vf,-1);
  151088. ch2=vi->channels;
  151089. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  151090. w2=vorbis_window(&vf->vd,0);
  151091. /* consolidate and expose the buffer. */
  151092. vorbis_synthesis_lapout(&vf->vd,&pcm);
  151093. /* splice */
  151094. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  151095. /* done */
  151096. return(0);
  151097. }
  151098. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  151099. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  151100. }
  151101. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  151102. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  151103. }
  151104. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  151105. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  151106. }
  151107. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  151108. int (*localseek)(OggVorbis_File *,double)){
  151109. vorbis_info *vi;
  151110. float **lappcm;
  151111. float **pcm;
  151112. float *w1,*w2;
  151113. int n1,n2,ch1,ch2,hs;
  151114. int i,ret;
  151115. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151116. ret=_ov_initset(vf);
  151117. if(ret)return(ret);
  151118. vi=ov_info(vf,-1);
  151119. hs=ov_halfrate_p(vf);
  151120. ch1=vi->channels;
  151121. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  151122. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  151123. persistent; even if the decode state
  151124. from this link gets dumped, this
  151125. window array continues to exist */
  151126. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  151127. for(i=0;i<ch1;i++)
  151128. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  151129. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  151130. /* have lapping data; seek and prime the buffer */
  151131. ret=localseek(vf,pos);
  151132. if(ret)return ret;
  151133. ret=_ov_initprime(vf);
  151134. if(ret)return(ret);
  151135. /* Guard against cross-link changes; they're perfectly legal */
  151136. vi=ov_info(vf,-1);
  151137. ch2=vi->channels;
  151138. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  151139. w2=vorbis_window(&vf->vd,0);
  151140. /* consolidate and expose the buffer. */
  151141. vorbis_synthesis_lapout(&vf->vd,&pcm);
  151142. /* splice */
  151143. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  151144. /* done */
  151145. return(0);
  151146. }
  151147. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  151148. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  151149. }
  151150. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  151151. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  151152. }
  151153. #endif
  151154. /********* End of inlined file: vorbisfile.c *********/
  151155. /********* Start of inlined file: window.c *********/
  151156. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  151157. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  151158. // tasks..
  151159. #ifdef _MSC_VER
  151160. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  151161. #endif
  151162. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  151163. #if JUCE_USE_OGGVORBIS
  151164. #include <stdlib.h>
  151165. #include <math.h>
  151166. static float vwin64[32] = {
  151167. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  151168. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  151169. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  151170. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  151171. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  151172. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  151173. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  151174. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  151175. };
  151176. static float vwin128[64] = {
  151177. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  151178. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  151179. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  151180. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  151181. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  151182. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  151183. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  151184. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  151185. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  151186. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  151187. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  151188. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  151189. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  151190. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  151191. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  151192. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  151193. };
  151194. static float vwin256[128] = {
  151195. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  151196. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  151197. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  151198. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  151199. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  151200. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  151201. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  151202. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  151203. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  151204. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  151205. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  151206. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  151207. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  151208. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  151209. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  151210. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  151211. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  151212. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  151213. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  151214. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  151215. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  151216. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  151217. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  151218. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  151219. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  151220. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  151221. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  151222. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  151223. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  151224. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  151225. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  151226. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  151227. };
  151228. static float vwin512[256] = {
  151229. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  151230. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  151231. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  151232. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  151233. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  151234. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  151235. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  151236. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  151237. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  151238. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  151239. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  151240. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  151241. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  151242. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  151243. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  151244. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  151245. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  151246. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  151247. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  151248. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  151249. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  151250. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  151251. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  151252. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  151253. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  151254. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  151255. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  151256. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  151257. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  151258. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  151259. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  151260. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  151261. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  151262. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  151263. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  151264. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  151265. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  151266. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  151267. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  151268. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  151269. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  151270. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  151271. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  151272. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  151273. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  151274. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  151275. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  151276. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  151277. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  151278. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  151279. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  151280. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  151281. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  151282. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  151283. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  151284. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  151285. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  151286. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  151287. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  151288. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  151289. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  151290. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  151291. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  151292. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  151293. };
  151294. static float vwin1024[512] = {
  151295. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  151296. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  151297. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  151298. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  151299. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  151300. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  151301. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  151302. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  151303. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  151304. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  151305. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  151306. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  151307. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  151308. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  151309. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  151310. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  151311. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  151312. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  151313. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  151314. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  151315. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  151316. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  151317. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  151318. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  151319. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  151320. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  151321. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  151322. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  151323. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  151324. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  151325. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  151326. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  151327. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  151328. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  151329. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  151330. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  151331. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  151332. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  151333. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  151334. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  151335. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  151336. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  151337. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  151338. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  151339. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  151340. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  151341. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  151342. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  151343. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  151344. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  151345. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  151346. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  151347. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  151348. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  151349. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  151350. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  151351. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  151352. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  151353. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  151354. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  151355. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  151356. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  151357. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  151358. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  151359. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  151360. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  151361. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  151362. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  151363. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  151364. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  151365. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  151366. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  151367. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  151368. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  151369. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  151370. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  151371. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  151372. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  151373. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  151374. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  151375. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  151376. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  151377. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  151378. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  151379. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  151380. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  151381. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  151382. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  151383. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  151384. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  151385. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  151386. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  151387. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  151388. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  151389. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  151390. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  151391. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  151392. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  151393. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  151394. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  151395. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  151396. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  151397. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  151398. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  151399. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  151400. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  151401. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  151402. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  151403. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  151404. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  151405. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  151406. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  151407. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  151408. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  151409. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  151410. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  151411. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  151412. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  151413. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  151414. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  151415. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  151416. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  151417. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  151418. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  151419. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  151420. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  151421. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  151422. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  151423. };
  151424. static float vwin2048[1024] = {
  151425. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  151426. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  151427. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  151428. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  151429. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  151430. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  151431. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  151432. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  151433. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  151434. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  151435. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  151436. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  151437. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  151438. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  151439. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  151440. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  151441. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  151442. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  151443. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  151444. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  151445. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  151446. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  151447. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  151448. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  151449. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  151450. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  151451. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  151452. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  151453. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  151454. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  151455. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  151456. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  151457. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  151458. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  151459. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  151460. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  151461. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  151462. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  151463. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  151464. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  151465. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  151466. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  151467. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  151468. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  151469. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  151470. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  151471. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  151472. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  151473. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  151474. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  151475. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  151476. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  151477. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  151478. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  151479. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  151480. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  151481. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  151482. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  151483. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  151484. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  151485. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  151486. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  151487. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  151488. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  151489. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  151490. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  151491. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  151492. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  151493. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  151494. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  151495. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  151496. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  151497. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  151498. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  151499. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  151500. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  151501. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  151502. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  151503. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  151504. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  151505. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  151506. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  151507. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  151508. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  151509. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  151510. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  151511. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  151512. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  151513. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  151514. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  151515. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  151516. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  151517. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  151518. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  151519. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  151520. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  151521. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  151522. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  151523. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  151524. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  151525. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  151526. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  151527. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  151528. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  151529. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  151530. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  151531. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  151532. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  151533. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  151534. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  151535. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  151536. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  151537. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  151538. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  151539. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  151540. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  151541. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  151542. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  151543. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  151544. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  151545. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  151546. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  151547. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  151548. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  151549. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  151550. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  151551. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  151552. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  151553. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  151554. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  151555. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  151556. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  151557. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  151558. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  151559. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  151560. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  151561. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  151562. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  151563. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  151564. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  151565. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  151566. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  151567. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  151568. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  151569. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  151570. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  151571. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  151572. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  151573. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  151574. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  151575. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  151576. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  151577. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  151578. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  151579. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  151580. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  151581. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  151582. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  151583. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  151584. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  151585. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  151586. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  151587. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  151588. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  151589. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  151590. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  151591. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  151592. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  151593. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  151594. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  151595. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  151596. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  151597. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  151598. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  151599. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  151600. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  151601. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  151602. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  151603. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  151604. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  151605. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  151606. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  151607. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  151608. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  151609. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  151610. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  151611. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  151612. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  151613. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  151614. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  151615. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  151616. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  151617. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  151618. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  151619. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  151620. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  151621. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  151622. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  151623. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  151624. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  151625. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  151626. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  151627. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  151628. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  151629. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  151630. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  151631. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  151632. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  151633. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  151634. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  151635. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  151636. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  151637. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  151638. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  151639. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  151640. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  151641. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  151642. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  151643. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  151644. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  151645. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  151646. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  151647. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  151648. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  151649. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  151650. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  151651. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  151652. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  151653. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  151654. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  151655. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  151656. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  151657. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  151658. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  151659. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  151660. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  151661. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  151662. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  151663. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  151664. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  151665. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  151666. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  151667. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  151668. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  151669. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  151670. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  151671. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  151672. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  151673. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  151674. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  151675. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  151676. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  151677. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  151678. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  151679. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  151680. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  151681. };
  151682. static float vwin4096[2048] = {
  151683. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  151684. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  151685. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  151686. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  151687. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  151688. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  151689. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  151690. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  151691. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  151692. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  151693. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  151694. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  151695. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  151696. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  151697. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  151698. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  151699. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  151700. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  151701. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  151702. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  151703. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  151704. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  151705. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  151706. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  151707. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  151708. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  151709. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  151710. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  151711. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  151712. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  151713. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  151714. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  151715. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  151716. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  151717. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  151718. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  151719. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  151720. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  151721. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  151722. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  151723. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  151724. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  151725. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  151726. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  151727. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  151728. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  151729. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  151730. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  151731. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  151732. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  151733. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  151734. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  151735. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  151736. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  151737. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  151738. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  151739. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  151740. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  151741. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  151742. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  151743. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  151744. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  151745. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  151746. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  151747. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  151748. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  151749. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  151750. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  151751. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  151752. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  151753. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  151754. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  151755. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  151756. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  151757. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  151758. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  151759. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  151760. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  151761. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  151762. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  151763. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  151764. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  151765. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  151766. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  151767. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  151768. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  151769. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  151770. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  151771. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  151772. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  151773. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  151774. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  151775. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  151776. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  151777. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  151778. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  151779. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  151780. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  151781. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  151782. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  151783. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  151784. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  151785. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  151786. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  151787. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  151788. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  151789. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  151790. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  151791. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  151792. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  151793. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  151794. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  151795. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  151796. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  151797. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  151798. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  151799. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  151800. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  151801. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  151802. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  151803. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  151804. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  151805. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  151806. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  151807. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  151808. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  151809. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  151810. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  151811. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  151812. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  151813. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  151814. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  151815. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  151816. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  151817. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  151818. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  151819. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  151820. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  151821. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  151822. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  151823. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  151824. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  151825. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  151826. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  151827. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  151828. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  151829. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  151830. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  151831. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  151832. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  151833. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  151834. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  151835. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  151836. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  151837. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  151838. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  151839. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  151840. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  151841. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  151842. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  151843. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  151844. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  151845. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  151846. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  151847. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  151848. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  151849. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  151850. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  151851. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  151852. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  151853. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  151854. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  151855. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  151856. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  151857. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  151858. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  151859. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  151860. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  151861. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  151862. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  151863. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  151864. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  151865. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  151866. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  151867. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  151868. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  151869. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  151870. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  151871. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  151872. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  151873. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  151874. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  151875. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  151876. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  151877. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  151878. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  151879. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  151880. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  151881. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  151882. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  151883. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  151884. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  151885. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  151886. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  151887. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  151888. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  151889. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  151890. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  151891. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  151892. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  151893. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  151894. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  151895. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  151896. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  151897. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  151898. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  151899. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  151900. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  151901. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  151902. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  151903. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  151904. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  151905. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  151906. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  151907. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  151908. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  151909. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  151910. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  151911. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  151912. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  151913. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  151914. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  151915. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  151916. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  151917. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  151918. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  151919. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  151920. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  151921. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  151922. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  151923. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  151924. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  151925. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  151926. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  151927. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  151928. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  151929. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  151930. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  151931. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  151932. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  151933. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  151934. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  151935. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  151936. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  151937. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  151938. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  151939. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  151940. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  151941. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  151942. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  151943. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  151944. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  151945. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  151946. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  151947. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  151948. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  151949. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  151950. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  151951. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  151952. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  151953. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  151954. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  151955. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  151956. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  151957. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  151958. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  151959. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  151960. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  151961. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  151962. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  151963. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  151964. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  151965. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  151966. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  151967. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  151968. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  151969. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  151970. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  151971. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  151972. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  151973. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  151974. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  151975. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  151976. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  151977. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  151978. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  151979. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  151980. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  151981. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  151982. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  151983. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  151984. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  151985. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  151986. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  151987. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  151988. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  151989. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  151990. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  151991. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  151992. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  151993. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  151994. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  151995. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  151996. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  151997. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  151998. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  151999. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  152000. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  152001. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  152002. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  152003. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  152004. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  152005. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  152006. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  152007. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  152008. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  152009. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  152010. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  152011. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  152012. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  152013. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  152014. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  152015. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  152016. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  152017. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  152018. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  152019. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  152020. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  152021. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  152022. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  152023. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  152024. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  152025. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  152026. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  152027. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  152028. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  152029. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  152030. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  152031. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  152032. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  152033. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  152034. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  152035. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  152036. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  152037. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  152038. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  152039. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  152040. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  152041. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  152042. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  152043. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  152044. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  152045. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  152046. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  152047. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  152048. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  152049. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  152050. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  152051. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  152052. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  152053. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  152054. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  152055. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  152056. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  152057. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  152058. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  152059. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  152060. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  152061. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  152062. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  152063. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  152064. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  152065. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  152066. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  152067. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  152068. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  152069. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  152070. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  152071. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  152072. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  152073. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  152074. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  152075. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  152076. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  152077. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  152078. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  152079. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  152080. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  152081. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  152082. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  152083. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  152084. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  152085. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  152086. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  152087. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  152088. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  152089. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  152090. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  152091. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  152092. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  152093. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  152094. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  152095. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  152096. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  152097. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  152098. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  152099. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  152100. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  152101. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  152102. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  152103. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  152104. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  152105. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  152106. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  152107. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  152108. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  152109. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  152110. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  152111. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  152112. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  152113. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  152114. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  152115. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  152116. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  152117. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  152118. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  152119. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  152120. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  152121. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  152122. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  152123. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  152124. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  152125. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  152126. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  152127. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  152128. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  152129. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  152130. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  152131. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  152132. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  152133. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  152134. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  152135. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  152136. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  152137. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  152138. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  152139. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  152140. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  152141. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  152142. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  152143. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  152144. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  152145. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  152146. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  152147. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  152148. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  152149. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  152150. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  152151. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  152152. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  152153. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  152154. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  152155. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  152156. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  152157. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  152158. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  152159. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  152160. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  152161. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  152162. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  152163. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  152164. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  152165. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  152166. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  152167. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  152168. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  152169. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  152170. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  152171. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  152172. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  152173. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  152174. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  152175. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  152176. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  152177. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  152178. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  152179. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  152180. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  152181. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  152182. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  152183. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  152184. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  152185. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  152186. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  152187. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  152188. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  152189. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  152190. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  152191. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  152192. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  152193. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  152194. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  152195. };
  152196. static float vwin8192[4096] = {
  152197. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  152198. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  152199. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  152200. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  152201. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  152202. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  152203. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  152204. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  152205. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  152206. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  152207. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  152208. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  152209. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  152210. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  152211. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  152212. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  152213. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  152214. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  152215. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  152216. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  152217. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  152218. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  152219. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  152220. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  152221. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  152222. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  152223. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  152224. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  152225. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  152226. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  152227. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  152228. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  152229. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  152230. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  152231. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  152232. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  152233. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  152234. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  152235. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  152236. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  152237. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  152238. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  152239. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  152240. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  152241. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  152242. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  152243. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  152244. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  152245. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  152246. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  152247. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  152248. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  152249. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  152250. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  152251. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  152252. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  152253. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  152254. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  152255. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  152256. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  152257. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  152258. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  152259. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  152260. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  152261. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  152262. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  152263. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  152264. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  152265. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  152266. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  152267. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  152268. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  152269. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  152270. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  152271. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  152272. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  152273. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  152274. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  152275. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  152276. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  152277. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  152278. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  152279. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  152280. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  152281. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  152282. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  152283. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  152284. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  152285. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  152286. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  152287. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  152288. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  152289. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  152290. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  152291. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  152292. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  152293. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  152294. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  152295. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  152296. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  152297. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  152298. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  152299. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  152300. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  152301. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  152302. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  152303. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  152304. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  152305. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  152306. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  152307. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  152308. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  152309. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  152310. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  152311. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  152312. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  152313. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  152314. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  152315. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  152316. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  152317. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  152318. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  152319. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  152320. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  152321. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  152322. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  152323. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  152324. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  152325. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  152326. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  152327. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  152328. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  152329. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  152330. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  152331. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  152332. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  152333. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  152334. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  152335. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  152336. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  152337. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  152338. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  152339. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  152340. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  152341. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  152342. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  152343. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  152344. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  152345. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  152346. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  152347. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  152348. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  152349. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  152350. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  152351. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  152352. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  152353. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  152354. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  152355. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  152356. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  152357. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  152358. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  152359. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  152360. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  152361. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  152362. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  152363. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  152364. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  152365. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  152366. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  152367. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  152368. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  152369. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  152370. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  152371. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  152372. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  152373. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  152374. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  152375. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  152376. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  152377. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  152378. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  152379. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  152380. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  152381. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  152382. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  152383. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  152384. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  152385. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  152386. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  152387. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  152388. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  152389. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  152390. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  152391. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  152392. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  152393. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  152394. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  152395. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  152396. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  152397. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  152398. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  152399. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  152400. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  152401. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  152402. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  152403. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  152404. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  152405. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  152406. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  152407. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  152408. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  152409. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  152410. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  152411. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  152412. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  152413. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  152414. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  152415. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  152416. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  152417. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  152418. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  152419. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  152420. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  152421. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  152422. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  152423. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  152424. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  152425. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  152426. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  152427. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  152428. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  152429. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  152430. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  152431. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  152432. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  152433. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  152434. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  152435. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  152436. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  152437. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  152438. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  152439. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  152440. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  152441. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  152442. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  152443. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  152444. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  152445. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  152446. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  152447. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  152448. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  152449. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  152450. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  152451. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  152452. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  152453. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  152454. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  152455. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  152456. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  152457. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  152458. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  152459. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  152460. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  152461. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  152462. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  152463. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  152464. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  152465. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  152466. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  152467. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  152468. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  152469. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  152470. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  152471. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  152472. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  152473. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  152474. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  152475. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  152476. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  152477. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  152478. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  152479. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  152480. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  152481. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  152482. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  152483. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  152484. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  152485. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  152486. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  152487. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  152488. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  152489. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  152490. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  152491. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  152492. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  152493. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  152494. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  152495. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  152496. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  152497. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  152498. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  152499. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  152500. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  152501. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  152502. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  152503. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  152504. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  152505. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  152506. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  152507. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  152508. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  152509. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  152510. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  152511. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  152512. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  152513. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  152514. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  152515. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  152516. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  152517. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  152518. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  152519. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  152520. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  152521. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  152522. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  152523. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  152524. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  152525. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  152526. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  152527. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  152528. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  152529. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  152530. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  152531. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  152532. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  152533. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  152534. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  152535. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  152536. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  152537. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  152538. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  152539. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  152540. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  152541. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  152542. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  152543. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  152544. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  152545. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  152546. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  152547. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  152548. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  152549. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  152550. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  152551. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  152552. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  152553. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  152554. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  152555. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  152556. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  152557. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  152558. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  152559. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  152560. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  152561. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  152562. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  152563. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  152564. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  152565. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  152566. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  152567. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  152568. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  152569. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  152570. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  152571. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  152572. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  152573. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  152574. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  152575. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  152576. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  152577. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  152578. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  152579. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  152580. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  152581. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  152582. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  152583. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  152584. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  152585. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  152586. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  152587. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  152588. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  152589. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  152590. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  152591. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  152592. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  152593. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  152594. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  152595. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  152596. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  152597. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  152598. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  152599. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  152600. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  152601. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  152602. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  152603. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  152604. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  152605. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  152606. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  152607. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  152608. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  152609. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  152610. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  152611. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  152612. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  152613. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  152614. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  152615. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  152616. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  152617. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  152618. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  152619. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  152620. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  152621. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  152622. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  152623. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  152624. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  152625. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  152626. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  152627. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  152628. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  152629. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  152630. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  152631. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  152632. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  152633. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  152634. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  152635. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  152636. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  152637. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  152638. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  152639. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  152640. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  152641. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  152642. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  152643. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  152644. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  152645. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  152646. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  152647. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  152648. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  152649. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  152650. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  152651. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  152652. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  152653. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  152654. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  152655. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  152656. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  152657. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  152658. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  152659. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  152660. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  152661. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  152662. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  152663. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  152664. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  152665. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  152666. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  152667. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  152668. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  152669. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  152670. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  152671. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  152672. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  152673. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  152674. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  152675. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  152676. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  152677. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  152678. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  152679. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  152680. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  152681. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  152682. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  152683. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  152684. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  152685. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  152686. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  152687. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  152688. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  152689. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  152690. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  152691. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  152692. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  152693. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  152694. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  152695. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  152696. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  152697. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  152698. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  152699. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  152700. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  152701. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  152702. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  152703. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  152704. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  152705. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  152706. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  152707. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  152708. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  152709. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  152710. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  152711. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  152712. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  152713. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  152714. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  152715. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  152716. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  152717. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  152718. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  152719. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  152720. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  152721. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  152722. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  152723. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  152724. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  152725. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  152726. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  152727. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  152728. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  152729. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  152730. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  152731. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  152732. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  152733. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  152734. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  152735. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  152736. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  152737. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  152738. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  152739. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  152740. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  152741. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  152742. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  152743. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  152744. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  152745. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  152746. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  152747. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  152748. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  152749. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  152750. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  152751. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  152752. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  152753. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  152754. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  152755. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  152756. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  152757. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  152758. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  152759. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  152760. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  152761. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  152762. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  152763. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  152764. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  152765. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  152766. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  152767. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  152768. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  152769. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  152770. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  152771. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  152772. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  152773. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  152774. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  152775. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  152776. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  152777. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  152778. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  152779. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  152780. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  152781. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  152782. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  152783. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  152784. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  152785. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  152786. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  152787. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  152788. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  152789. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  152790. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  152791. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  152792. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  152793. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  152794. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  152795. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  152796. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  152797. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  152798. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  152799. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  152800. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  152801. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  152802. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  152803. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  152804. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  152805. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  152806. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  152807. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  152808. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  152809. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  152810. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  152811. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  152812. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  152813. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  152814. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  152815. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  152816. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  152817. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  152818. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  152819. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  152820. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  152821. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  152822. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  152823. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  152824. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  152825. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  152826. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  152827. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  152828. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  152829. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  152830. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  152831. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  152832. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  152833. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  152834. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  152835. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  152836. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  152837. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  152838. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  152839. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  152840. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  152841. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  152842. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  152843. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  152844. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  152845. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  152846. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  152847. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  152848. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  152849. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  152850. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  152851. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  152852. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  152853. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  152854. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  152855. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  152856. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  152857. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  152858. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  152859. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  152860. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  152861. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  152862. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  152863. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  152864. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  152865. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  152866. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  152867. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  152868. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  152869. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  152870. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  152871. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  152872. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  152873. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  152874. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  152875. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  152876. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  152877. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  152878. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  152879. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  152880. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  152881. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  152882. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  152883. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  152884. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  152885. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  152886. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  152887. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  152888. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  152889. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  152890. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  152891. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  152892. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  152893. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  152894. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  152895. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  152896. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  152897. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  152898. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  152899. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  152900. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  152901. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  152902. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  152903. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  152904. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  152905. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  152906. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  152907. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  152908. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  152909. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  152910. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  152911. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  152912. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  152913. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  152914. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  152915. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  152916. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  152917. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  152918. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  152919. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  152920. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  152921. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  152922. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  152923. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  152924. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  152925. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  152926. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  152927. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  152928. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  152929. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  152930. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  152931. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  152932. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  152933. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  152934. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  152935. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  152936. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  152937. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  152938. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  152939. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  152940. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  152941. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  152942. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  152943. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  152944. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  152945. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  152946. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  152947. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  152948. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  152949. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  152950. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  152951. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  152952. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  152953. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  152954. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  152955. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  152956. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  152957. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  152958. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  152959. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  152960. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  152961. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  152962. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  152963. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  152964. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  152965. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  152966. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  152967. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  152968. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  152969. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  152970. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  152971. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  152972. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  152973. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  152974. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  152975. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  152976. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  152977. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  152978. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  152979. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  152980. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  152981. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  152982. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  152983. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  152984. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  152985. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  152986. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  152987. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  152988. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  152989. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  152990. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  152991. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  152992. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  152993. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  152994. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  152995. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  152996. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  152997. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  152998. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  152999. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  153000. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  153001. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  153002. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  153003. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  153004. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  153005. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  153006. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  153007. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  153008. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  153009. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  153010. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  153011. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  153012. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  153013. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  153014. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  153015. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  153016. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  153017. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  153018. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  153019. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  153020. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  153021. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  153022. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  153023. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  153024. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  153025. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  153026. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  153027. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  153028. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  153029. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  153030. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  153031. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  153032. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  153033. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  153034. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  153035. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  153036. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  153037. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  153038. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  153039. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  153040. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  153041. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  153042. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  153043. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  153044. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  153045. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  153046. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  153047. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  153048. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  153049. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  153050. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  153051. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  153052. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  153053. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  153054. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  153055. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  153056. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  153057. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  153058. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  153059. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  153060. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  153061. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  153062. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  153063. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  153064. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  153065. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  153066. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  153067. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  153068. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  153069. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  153070. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  153071. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  153072. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  153073. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  153074. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  153075. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  153076. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  153077. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  153078. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  153079. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  153080. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  153081. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  153082. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  153083. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  153084. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  153085. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  153086. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  153087. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  153088. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  153089. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  153090. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  153091. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  153092. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  153093. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  153094. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  153095. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  153096. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  153097. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  153098. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  153099. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  153100. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  153101. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  153102. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  153103. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  153104. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  153105. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  153106. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  153107. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  153108. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  153109. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  153110. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  153111. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  153112. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  153113. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  153114. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  153115. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  153116. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  153117. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  153118. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  153119. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  153120. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  153121. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  153122. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  153123. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  153124. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  153125. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  153126. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  153127. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  153128. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  153129. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  153130. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  153131. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  153132. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  153133. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  153134. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  153135. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  153136. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  153137. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  153138. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  153139. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  153140. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  153141. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  153142. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  153143. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  153144. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  153145. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  153146. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  153147. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  153148. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  153149. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  153150. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  153151. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  153152. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  153153. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  153154. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  153155. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  153156. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  153157. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  153158. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  153159. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  153160. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  153161. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  153162. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  153163. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  153164. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  153165. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  153166. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  153167. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  153168. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  153169. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  153170. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  153171. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  153172. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  153173. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  153174. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  153175. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  153176. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  153177. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  153178. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  153179. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  153180. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  153181. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  153182. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  153183. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  153184. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  153185. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  153186. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  153187. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  153188. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  153189. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  153190. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  153191. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  153192. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  153193. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  153194. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  153195. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  153196. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  153197. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  153198. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  153199. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  153200. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  153201. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  153202. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  153203. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  153204. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  153205. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  153206. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  153207. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  153208. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  153209. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  153210. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  153211. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  153212. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  153213. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  153214. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  153215. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  153216. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  153217. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  153218. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  153219. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  153220. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  153221. };
  153222. static float *vwin[8] = {
  153223. vwin64,
  153224. vwin128,
  153225. vwin256,
  153226. vwin512,
  153227. vwin1024,
  153228. vwin2048,
  153229. vwin4096,
  153230. vwin8192,
  153231. };
  153232. float *_vorbis_window_get(int n){
  153233. return vwin[n];
  153234. }
  153235. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  153236. int lW,int W,int nW){
  153237. lW=(W?lW:0);
  153238. nW=(W?nW:0);
  153239. {
  153240. float *windowLW=vwin[winno[lW]];
  153241. float *windowNW=vwin[winno[nW]];
  153242. long n=blocksizes[W];
  153243. long ln=blocksizes[lW];
  153244. long rn=blocksizes[nW];
  153245. long leftbegin=n/4-ln/4;
  153246. long leftend=leftbegin+ln/2;
  153247. long rightbegin=n/2+n/4-rn/4;
  153248. long rightend=rightbegin+rn/2;
  153249. int i,p;
  153250. for(i=0;i<leftbegin;i++)
  153251. d[i]=0.f;
  153252. for(p=0;i<leftend;i++,p++)
  153253. d[i]*=windowLW[p];
  153254. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  153255. d[i]*=windowNW[p];
  153256. for(;i<n;i++)
  153257. d[i]=0.f;
  153258. }
  153259. }
  153260. #endif
  153261. /********* End of inlined file: window.c *********/
  153262. }
  153263. BEGIN_JUCE_NAMESPACE
  153264. using namespace OggVorbisNamespace;
  153265. #define oggFormatName TRANS("Ogg-Vorbis file")
  153266. static const tchar* const oggExtensions[] = { T(".ogg"), 0 };
  153267. class OggReader : public AudioFormatReader
  153268. {
  153269. OggVorbis_File ovFile;
  153270. ov_callbacks callbacks;
  153271. AudioSampleBuffer reservoir;
  153272. int reservoirStart, samplesInReservoir;
  153273. public:
  153274. OggReader (InputStream* const inp)
  153275. : AudioFormatReader (inp, oggFormatName),
  153276. reservoir (2, 4096),
  153277. reservoirStart (0),
  153278. samplesInReservoir (0)
  153279. {
  153280. sampleRate = 0;
  153281. usesFloatingPointData = true;
  153282. callbacks.read_func = &oggReadCallback;
  153283. callbacks.seek_func = &oggSeekCallback;
  153284. callbacks.close_func = &oggCloseCallback;
  153285. callbacks.tell_func = &oggTellCallback;
  153286. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  153287. if (err == 0)
  153288. {
  153289. vorbis_info* info = ov_info (&ovFile, -1);
  153290. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  153291. numChannels = info->channels;
  153292. bitsPerSample = 16;
  153293. sampleRate = info->rate;
  153294. reservoir.setSize (numChannels,
  153295. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  153296. }
  153297. }
  153298. ~OggReader()
  153299. {
  153300. ov_clear (&ovFile);
  153301. }
  153302. bool read (int** destSamples,
  153303. int64 startSampleInFile,
  153304. int numSamples)
  153305. {
  153306. int writeOffset = 0;
  153307. while (numSamples > 0)
  153308. {
  153309. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  153310. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  153311. {
  153312. // got a few samples overlapping, so use them before seeking..
  153313. for (unsigned int i = 0; i < numChannels; ++i)
  153314. {
  153315. if (destSamples[i] == 0)
  153316. break;
  153317. memcpy (destSamples[i] + writeOffset,
  153318. reservoir.getSampleData (jmin (i, reservoir.getNumChannels()),
  153319. (int) (startSampleInFile - reservoirStart)),
  153320. sizeof (float) * numSamples);
  153321. }
  153322. startSampleInFile += numAvailable;
  153323. numSamples -= numAvailable;
  153324. writeOffset += numAvailable;
  153325. if (numSamples == 0)
  153326. break;
  153327. }
  153328. if (startSampleInFile < reservoirStart
  153329. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  153330. {
  153331. // buffer miss, so refill the reservoir
  153332. int bitStream = 0;
  153333. reservoirStart = jmax (0, (int) startSampleInFile);
  153334. samplesInReservoir = reservoir.getNumSamples();
  153335. if (reservoirStart != (int) ov_pcm_tell (&ovFile))
  153336. ov_pcm_seek (&ovFile, reservoirStart);
  153337. int offset = 0;
  153338. int numToRead = samplesInReservoir;
  153339. while (numToRead > 0)
  153340. {
  153341. float** dataIn = 0;
  153342. const int samps = ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  153343. if (samps == 0)
  153344. break;
  153345. jassert (samps <= numToRead);
  153346. for (int i = jmin (numChannels, reservoir.getNumChannels()); --i >= 0;)
  153347. {
  153348. memcpy (reservoir.getSampleData (i, offset),
  153349. dataIn[i],
  153350. sizeof (float) * samps);
  153351. }
  153352. numToRead -= samps;
  153353. offset += samps;
  153354. }
  153355. if (numToRead > 0)
  153356. reservoir.clear (offset, numToRead);
  153357. }
  153358. }
  153359. return true;
  153360. }
  153361. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  153362. {
  153363. return (size_t) (((InputStream*) datasource)->read (ptr, (int) (size * nmemb)) / size);
  153364. }
  153365. static int oggSeekCallback (void* datasource, ogg_int64_t offset, int whence)
  153366. {
  153367. InputStream* const in = (InputStream*) datasource;
  153368. if (whence == SEEK_CUR)
  153369. offset += in->getPosition();
  153370. else if (whence == SEEK_END)
  153371. offset += in->getTotalLength();
  153372. in->setPosition (offset);
  153373. return 0;
  153374. }
  153375. static int oggCloseCallback (void*)
  153376. {
  153377. return 0;
  153378. }
  153379. static long oggTellCallback (void* datasource)
  153380. {
  153381. return (long) ((InputStream*) datasource)->getPosition();
  153382. }
  153383. juce_UseDebuggingNewOperator
  153384. };
  153385. class OggWriter : public AudioFormatWriter
  153386. {
  153387. ogg_stream_state os;
  153388. ogg_page og;
  153389. ogg_packet op;
  153390. vorbis_info vi;
  153391. vorbis_comment vc;
  153392. vorbis_dsp_state vd;
  153393. vorbis_block vb;
  153394. public:
  153395. bool ok;
  153396. OggWriter (OutputStream* const out,
  153397. const double sampleRate,
  153398. const int numChannels,
  153399. const int bitsPerSample,
  153400. const int qualityIndex)
  153401. : AudioFormatWriter (out, oggFormatName,
  153402. sampleRate,
  153403. numChannels,
  153404. bitsPerSample)
  153405. {
  153406. ok = false;
  153407. vorbis_info_init (&vi);
  153408. if (vorbis_encode_init_vbr (&vi,
  153409. numChannels,
  153410. (int) sampleRate,
  153411. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  153412. {
  153413. vorbis_comment_init (&vc);
  153414. if (JUCEApplication::getInstance() != 0)
  153415. vorbis_comment_add_tag (&vc, "ENCODER",
  153416. (char*) (const char*) JUCEApplication::getInstance()->getApplicationName());
  153417. vorbis_analysis_init (&vd, &vi);
  153418. vorbis_block_init (&vd, &vb);
  153419. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  153420. ogg_packet header;
  153421. ogg_packet header_comm;
  153422. ogg_packet header_code;
  153423. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  153424. ogg_stream_packetin (&os, &header);
  153425. ogg_stream_packetin (&os, &header_comm);
  153426. ogg_stream_packetin (&os, &header_code);
  153427. for (;;)
  153428. {
  153429. if (ogg_stream_flush (&os, &og) == 0)
  153430. break;
  153431. output->write (og.header, og.header_len);
  153432. output->write (og.body, og.body_len);
  153433. }
  153434. ok = true;
  153435. }
  153436. }
  153437. ~OggWriter()
  153438. {
  153439. if (ok)
  153440. {
  153441. ogg_stream_clear (&os);
  153442. vorbis_block_clear (&vb);
  153443. vorbis_dsp_clear (&vd);
  153444. vorbis_comment_clear (&vc);
  153445. vorbis_info_clear (&vi);
  153446. output->flush();
  153447. }
  153448. else
  153449. {
  153450. vorbis_info_clear (&vi);
  153451. output = 0; // to stop the base class deleting this, as it needs to be returned
  153452. // to the caller of createWriter()
  153453. }
  153454. }
  153455. bool write (const int** samplesToWrite, int numSamples)
  153456. {
  153457. if (! ok)
  153458. return false;
  153459. if (numSamples > 0)
  153460. {
  153461. const double gain = 1.0 / 0x80000000u;
  153462. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  153463. for (int i = numChannels; --i >= 0;)
  153464. {
  153465. float* const dst = vorbisBuffer[i];
  153466. const int* const src = samplesToWrite [i];
  153467. if (src != 0 && dst != 0)
  153468. {
  153469. for (int j = 0; j < numSamples; ++j)
  153470. dst[j] = (float) (src[j] * gain);
  153471. }
  153472. }
  153473. }
  153474. vorbis_analysis_wrote (&vd, numSamples);
  153475. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  153476. {
  153477. vorbis_analysis (&vb, 0);
  153478. vorbis_bitrate_addblock (&vb);
  153479. while (vorbis_bitrate_flushpacket (&vd, &op))
  153480. {
  153481. ogg_stream_packetin (&os, &op);
  153482. for (;;)
  153483. {
  153484. if (ogg_stream_pageout (&os, &og) == 0)
  153485. break;
  153486. output->write (og.header, og.header_len);
  153487. output->write (og.body, og.body_len);
  153488. if (ogg_page_eos (&og))
  153489. break;
  153490. }
  153491. }
  153492. }
  153493. return true;
  153494. }
  153495. juce_UseDebuggingNewOperator
  153496. };
  153497. OggVorbisAudioFormat::OggVorbisAudioFormat()
  153498. : AudioFormat (oggFormatName, (const tchar**) oggExtensions)
  153499. {
  153500. }
  153501. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  153502. {
  153503. }
  153504. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  153505. {
  153506. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  153507. return Array <int> (rates);
  153508. }
  153509. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  153510. {
  153511. Array <int> depths;
  153512. depths.add (32);
  153513. return depths;
  153514. }
  153515. bool OggVorbisAudioFormat::canDoStereo()
  153516. {
  153517. return true;
  153518. }
  153519. bool OggVorbisAudioFormat::canDoMono()
  153520. {
  153521. return true;
  153522. }
  153523. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  153524. const bool deleteStreamIfOpeningFails)
  153525. {
  153526. OggReader* r = new OggReader (in);
  153527. if (r->sampleRate == 0)
  153528. {
  153529. if (! deleteStreamIfOpeningFails)
  153530. r->input = 0;
  153531. deleteAndZero (r);
  153532. }
  153533. return r;
  153534. }
  153535. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  153536. double sampleRate,
  153537. unsigned int numChannels,
  153538. int bitsPerSample,
  153539. const StringPairArray& /*metadataValues*/,
  153540. int qualityOptionIndex)
  153541. {
  153542. OggWriter* w = new OggWriter (out,
  153543. sampleRate,
  153544. numChannels,
  153545. bitsPerSample,
  153546. qualityOptionIndex);
  153547. if (! w->ok)
  153548. deleteAndZero (w);
  153549. return w;
  153550. }
  153551. bool OggVorbisAudioFormat::isCompressed()
  153552. {
  153553. return true;
  153554. }
  153555. const StringArray OggVorbisAudioFormat::getQualityOptions()
  153556. {
  153557. StringArray s;
  153558. s.add ("Low Quality");
  153559. s.add ("Medium Quality");
  153560. s.add ("High Quality");
  153561. return s;
  153562. }
  153563. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  153564. {
  153565. FileInputStream* const in = source.createInputStream();
  153566. if (in != 0)
  153567. {
  153568. AudioFormatReader* const r = createReaderFor (in, true);
  153569. if (r != 0)
  153570. {
  153571. const int64 numSamps = r->lengthInSamples;
  153572. delete r;
  153573. const int64 fileNumSamps = source.getSize() / 4;
  153574. const double ratio = numSamps / (double) fileNumSamps;
  153575. if (ratio > 12.0)
  153576. return 0;
  153577. else if (ratio > 6.0)
  153578. return 1;
  153579. else
  153580. return 2;
  153581. }
  153582. }
  153583. return 1;
  153584. }
  153585. END_JUCE_NAMESPACE
  153586. #endif
  153587. /********* End of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  153588. /********* Start of inlined file: juce_JPEGLoader.cpp *********/
  153589. #if JUCE_MSVC
  153590. #pragma warning (push)
  153591. #endif
  153592. namespace jpeglibNamespace
  153593. {
  153594. extern "C"
  153595. {
  153596. #define JPEG_INTERNALS
  153597. #undef FAR
  153598. /********* Start of inlined file: jpeglib.h *********/
  153599. #ifndef JPEGLIB_H
  153600. #define JPEGLIB_H
  153601. /*
  153602. * First we include the configuration files that record how this
  153603. * installation of the JPEG library is set up. jconfig.h can be
  153604. * generated automatically for many systems. jmorecfg.h contains
  153605. * manual configuration options that most people need not worry about.
  153606. */
  153607. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  153608. /********* Start of inlined file: jconfig.h *********/
  153609. /* see jconfig.doc for explanations */
  153610. // disable all the warnings under MSVC
  153611. #ifdef _MSC_VER
  153612. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  153613. #endif
  153614. #ifdef __BORLANDC__
  153615. #pragma warn -8057
  153616. #pragma warn -8019
  153617. #pragma warn -8004
  153618. #pragma warn -8008
  153619. #endif
  153620. #define HAVE_PROTOTYPES
  153621. #define HAVE_UNSIGNED_CHAR
  153622. #define HAVE_UNSIGNED_SHORT
  153623. /* #define void char */
  153624. /* #define const */
  153625. #undef CHAR_IS_UNSIGNED
  153626. #define HAVE_STDDEF_H
  153627. #define HAVE_STDLIB_H
  153628. #undef NEED_BSD_STRINGS
  153629. #undef NEED_SYS_TYPES_H
  153630. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  153631. #undef NEED_SHORT_EXTERNAL_NAMES
  153632. #undef INCOMPLETE_TYPES_BROKEN
  153633. /* Define "boolean" as unsigned char, not int, per Windows custom */
  153634. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  153635. typedef unsigned char boolean;
  153636. #endif
  153637. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  153638. #ifdef JPEG_INTERNALS
  153639. #undef RIGHT_SHIFT_IS_UNSIGNED
  153640. #endif /* JPEG_INTERNALS */
  153641. #ifdef JPEG_CJPEG_DJPEG
  153642. #define BMP_SUPPORTED /* BMP image file format */
  153643. #define GIF_SUPPORTED /* GIF image file format */
  153644. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  153645. #undef RLE_SUPPORTED /* Utah RLE image file format */
  153646. #define TARGA_SUPPORTED /* Targa image file format */
  153647. #define TWO_FILE_COMMANDLINE /* optional */
  153648. #define USE_SETMODE /* Microsoft has setmode() */
  153649. #undef NEED_SIGNAL_CATCHER
  153650. #undef DONT_USE_B_MODE
  153651. #undef PROGRESS_REPORT /* optional */
  153652. #endif /* JPEG_CJPEG_DJPEG */
  153653. /********* End of inlined file: jconfig.h *********/
  153654. /* widely used configuration options */
  153655. #endif
  153656. /********* Start of inlined file: jmorecfg.h *********/
  153657. /*
  153658. * Define BITS_IN_JSAMPLE as either
  153659. * 8 for 8-bit sample values (the usual setting)
  153660. * 12 for 12-bit sample values
  153661. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  153662. * JPEG standard, and the IJG code does not support anything else!
  153663. * We do not support run-time selection of data precision, sorry.
  153664. */
  153665. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  153666. /*
  153667. * Maximum number of components (color channels) allowed in JPEG image.
  153668. * To meet the letter of the JPEG spec, set this to 255. However, darn
  153669. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  153670. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  153671. * really short on memory. (Each allowed component costs a hundred or so
  153672. * bytes of storage, whether actually used in an image or not.)
  153673. */
  153674. #define MAX_COMPONENTS 10 /* maximum number of image components */
  153675. /*
  153676. * Basic data types.
  153677. * You may need to change these if you have a machine with unusual data
  153678. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  153679. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  153680. * but it had better be at least 16.
  153681. */
  153682. /* Representation of a single sample (pixel element value).
  153683. * We frequently allocate large arrays of these, so it's important to keep
  153684. * them small. But if you have memory to burn and access to char or short
  153685. * arrays is very slow on your hardware, you might want to change these.
  153686. */
  153687. #if BITS_IN_JSAMPLE == 8
  153688. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  153689. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  153690. */
  153691. #ifdef HAVE_UNSIGNED_CHAR
  153692. typedef unsigned char JSAMPLE;
  153693. #define GETJSAMPLE(value) ((int) (value))
  153694. #else /* not HAVE_UNSIGNED_CHAR */
  153695. typedef char JSAMPLE;
  153696. #ifdef CHAR_IS_UNSIGNED
  153697. #define GETJSAMPLE(value) ((int) (value))
  153698. #else
  153699. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  153700. #endif /* CHAR_IS_UNSIGNED */
  153701. #endif /* HAVE_UNSIGNED_CHAR */
  153702. #define MAXJSAMPLE 255
  153703. #define CENTERJSAMPLE 128
  153704. #endif /* BITS_IN_JSAMPLE == 8 */
  153705. #if BITS_IN_JSAMPLE == 12
  153706. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  153707. * On nearly all machines "short" will do nicely.
  153708. */
  153709. typedef short JSAMPLE;
  153710. #define GETJSAMPLE(value) ((int) (value))
  153711. #define MAXJSAMPLE 4095
  153712. #define CENTERJSAMPLE 2048
  153713. #endif /* BITS_IN_JSAMPLE == 12 */
  153714. /* Representation of a DCT frequency coefficient.
  153715. * This should be a signed value of at least 16 bits; "short" is usually OK.
  153716. * Again, we allocate large arrays of these, but you can change to int
  153717. * if you have memory to burn and "short" is really slow.
  153718. */
  153719. typedef short JCOEF;
  153720. /* Compressed datastreams are represented as arrays of JOCTET.
  153721. * These must be EXACTLY 8 bits wide, at least once they are written to
  153722. * external storage. Note that when using the stdio data source/destination
  153723. * managers, this is also the data type passed to fread/fwrite.
  153724. */
  153725. #ifdef HAVE_UNSIGNED_CHAR
  153726. typedef unsigned char JOCTET;
  153727. #define GETJOCTET(value) (value)
  153728. #else /* not HAVE_UNSIGNED_CHAR */
  153729. typedef char JOCTET;
  153730. #ifdef CHAR_IS_UNSIGNED
  153731. #define GETJOCTET(value) (value)
  153732. #else
  153733. #define GETJOCTET(value) ((value) & 0xFF)
  153734. #endif /* CHAR_IS_UNSIGNED */
  153735. #endif /* HAVE_UNSIGNED_CHAR */
  153736. /* These typedefs are used for various table entries and so forth.
  153737. * They must be at least as wide as specified; but making them too big
  153738. * won't cost a huge amount of memory, so we don't provide special
  153739. * extraction code like we did for JSAMPLE. (In other words, these
  153740. * typedefs live at a different point on the speed/space tradeoff curve.)
  153741. */
  153742. /* UINT8 must hold at least the values 0..255. */
  153743. #ifdef HAVE_UNSIGNED_CHAR
  153744. typedef unsigned char UINT8;
  153745. #else /* not HAVE_UNSIGNED_CHAR */
  153746. #ifdef CHAR_IS_UNSIGNED
  153747. typedef char UINT8;
  153748. #else /* not CHAR_IS_UNSIGNED */
  153749. typedef short UINT8;
  153750. #endif /* CHAR_IS_UNSIGNED */
  153751. #endif /* HAVE_UNSIGNED_CHAR */
  153752. /* UINT16 must hold at least the values 0..65535. */
  153753. #ifdef HAVE_UNSIGNED_SHORT
  153754. typedef unsigned short UINT16;
  153755. #else /* not HAVE_UNSIGNED_SHORT */
  153756. typedef unsigned int UINT16;
  153757. #endif /* HAVE_UNSIGNED_SHORT */
  153758. /* INT16 must hold at least the values -32768..32767. */
  153759. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  153760. typedef short INT16;
  153761. #endif
  153762. /* INT32 must hold at least signed 32-bit values. */
  153763. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  153764. typedef long INT32;
  153765. #endif
  153766. /* Datatype used for image dimensions. The JPEG standard only supports
  153767. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  153768. * "unsigned int" is sufficient on all machines. However, if you need to
  153769. * handle larger images and you don't mind deviating from the spec, you
  153770. * can change this datatype.
  153771. */
  153772. typedef unsigned int JDIMENSION;
  153773. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  153774. /* These macros are used in all function definitions and extern declarations.
  153775. * You could modify them if you need to change function linkage conventions;
  153776. * in particular, you'll need to do that to make the library a Windows DLL.
  153777. * Another application is to make all functions global for use with debuggers
  153778. * or code profilers that require it.
  153779. */
  153780. /* a function called through method pointers: */
  153781. #define METHODDEF(type) static type
  153782. /* a function used only in its module: */
  153783. #define LOCAL(type) static type
  153784. /* a function referenced thru EXTERNs: */
  153785. #define GLOBAL(type) type
  153786. /* a reference to a GLOBAL function: */
  153787. #define EXTERN(type) extern type
  153788. /* This macro is used to declare a "method", that is, a function pointer.
  153789. * We want to supply prototype parameters if the compiler can cope.
  153790. * Note that the arglist parameter must be parenthesized!
  153791. * Again, you can customize this if you need special linkage keywords.
  153792. */
  153793. #ifdef HAVE_PROTOTYPES
  153794. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  153795. #else
  153796. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  153797. #endif
  153798. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  153799. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  153800. * by just saying "FAR *" where such a pointer is needed. In a few places
  153801. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  153802. */
  153803. #ifdef NEED_FAR_POINTERS
  153804. #define FAR far
  153805. #else
  153806. #define FAR
  153807. #endif
  153808. /*
  153809. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  153810. * in standard header files. Or you may have conflicts with application-
  153811. * specific header files that you want to include together with these files.
  153812. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  153813. */
  153814. #ifndef HAVE_BOOLEAN
  153815. typedef int boolean;
  153816. #endif
  153817. #ifndef FALSE /* in case these macros already exist */
  153818. #define FALSE 0 /* values of boolean */
  153819. #endif
  153820. #ifndef TRUE
  153821. #define TRUE 1
  153822. #endif
  153823. /*
  153824. * The remaining options affect code selection within the JPEG library,
  153825. * but they don't need to be visible to most applications using the library.
  153826. * To minimize application namespace pollution, the symbols won't be
  153827. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  153828. */
  153829. #ifdef JPEG_INTERNALS
  153830. #define JPEG_INTERNAL_OPTIONS
  153831. #endif
  153832. #ifdef JPEG_INTERNAL_OPTIONS
  153833. /*
  153834. * These defines indicate whether to include various optional functions.
  153835. * Undefining some of these symbols will produce a smaller but less capable
  153836. * library. Note that you can leave certain source files out of the
  153837. * compilation/linking process if you've #undef'd the corresponding symbols.
  153838. * (You may HAVE to do that if your compiler doesn't like null source files.)
  153839. */
  153840. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  153841. /* Capability options common to encoder and decoder: */
  153842. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  153843. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  153844. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  153845. /* Encoder capability options: */
  153846. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  153847. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  153848. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  153849. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  153850. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  153851. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  153852. * precision, so jchuff.c normally uses entropy optimization to compute
  153853. * usable tables for higher precision. If you don't want to do optimization,
  153854. * you'll have to supply different default Huffman tables.
  153855. * The exact same statements apply for progressive JPEG: the default tables
  153856. * don't work for progressive mode. (This may get fixed, however.)
  153857. */
  153858. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  153859. /* Decoder capability options: */
  153860. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  153861. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  153862. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  153863. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  153864. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  153865. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  153866. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  153867. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  153868. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  153869. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  153870. /* more capability options later, no doubt */
  153871. /*
  153872. * Ordering of RGB data in scanlines passed to or from the application.
  153873. * If your application wants to deal with data in the order B,G,R, just
  153874. * change these macros. You can also deal with formats such as R,G,B,X
  153875. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  153876. * the offsets will also change the order in which colormap data is organized.
  153877. * RESTRICTIONS:
  153878. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  153879. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  153880. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  153881. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  153882. * is not 3 (they don't understand about dummy color components!). So you
  153883. * can't use color quantization if you change that value.
  153884. */
  153885. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  153886. #define RGB_GREEN 1 /* Offset of Green */
  153887. #define RGB_BLUE 2 /* Offset of Blue */
  153888. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  153889. /* Definitions for speed-related optimizations. */
  153890. /* If your compiler supports inline functions, define INLINE
  153891. * as the inline keyword; otherwise define it as empty.
  153892. */
  153893. #ifndef INLINE
  153894. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  153895. #define INLINE __inline__
  153896. #endif
  153897. #ifndef INLINE
  153898. #define INLINE /* default is to define it as empty */
  153899. #endif
  153900. #endif
  153901. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  153902. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  153903. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  153904. */
  153905. #ifndef MULTIPLIER
  153906. #define MULTIPLIER int /* type for fastest integer multiply */
  153907. #endif
  153908. /* FAST_FLOAT should be either float or double, whichever is done faster
  153909. * by your compiler. (Note that this type is only used in the floating point
  153910. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  153911. * Typically, float is faster in ANSI C compilers, while double is faster in
  153912. * pre-ANSI compilers (because they insist on converting to double anyway).
  153913. * The code below therefore chooses float if we have ANSI-style prototypes.
  153914. */
  153915. #ifndef FAST_FLOAT
  153916. #ifdef HAVE_PROTOTYPES
  153917. #define FAST_FLOAT float
  153918. #else
  153919. #define FAST_FLOAT double
  153920. #endif
  153921. #endif
  153922. #endif /* JPEG_INTERNAL_OPTIONS */
  153923. /********* End of inlined file: jmorecfg.h *********/
  153924. /* seldom changed options */
  153925. /* Version ID for the JPEG library.
  153926. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  153927. */
  153928. #define JPEG_LIB_VERSION 62 /* Version 6b */
  153929. /* Various constants determining the sizes of things.
  153930. * All of these are specified by the JPEG standard, so don't change them
  153931. * if you want to be compatible.
  153932. */
  153933. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  153934. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  153935. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  153936. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  153937. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  153938. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  153939. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  153940. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  153941. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  153942. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  153943. * to handle it. We even let you do this from the jconfig.h file. However,
  153944. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  153945. * sometimes emits noncompliant files doesn't mean you should too.
  153946. */
  153947. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  153948. #ifndef D_MAX_BLOCKS_IN_MCU
  153949. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  153950. #endif
  153951. /* Data structures for images (arrays of samples and of DCT coefficients).
  153952. * On 80x86 machines, the image arrays are too big for near pointers,
  153953. * but the pointer arrays can fit in near memory.
  153954. */
  153955. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  153956. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  153957. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  153958. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  153959. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  153960. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  153961. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  153962. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  153963. /* Types for JPEG compression parameters and working tables. */
  153964. /* DCT coefficient quantization tables. */
  153965. typedef struct {
  153966. /* This array gives the coefficient quantizers in natural array order
  153967. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  153968. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  153969. */
  153970. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  153971. /* This field is used only during compression. It's initialized FALSE when
  153972. * the table is created, and set TRUE when it's been output to the file.
  153973. * You could suppress output of a table by setting this to TRUE.
  153974. * (See jpeg_suppress_tables for an example.)
  153975. */
  153976. boolean sent_table; /* TRUE when table has been output */
  153977. } JQUANT_TBL;
  153978. /* Huffman coding tables. */
  153979. typedef struct {
  153980. /* These two fields directly represent the contents of a JPEG DHT marker */
  153981. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  153982. /* length k bits; bits[0] is unused */
  153983. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  153984. /* This field is used only during compression. It's initialized FALSE when
  153985. * the table is created, and set TRUE when it's been output to the file.
  153986. * You could suppress output of a table by setting this to TRUE.
  153987. * (See jpeg_suppress_tables for an example.)
  153988. */
  153989. boolean sent_table; /* TRUE when table has been output */
  153990. } JHUFF_TBL;
  153991. /* Basic info about one component (color channel). */
  153992. typedef struct {
  153993. /* These values are fixed over the whole image. */
  153994. /* For compression, they must be supplied by parameter setup; */
  153995. /* for decompression, they are read from the SOF marker. */
  153996. int component_id; /* identifier for this component (0..255) */
  153997. int component_index; /* its index in SOF or cinfo->comp_info[] */
  153998. int h_samp_factor; /* horizontal sampling factor (1..4) */
  153999. int v_samp_factor; /* vertical sampling factor (1..4) */
  154000. int quant_tbl_no; /* quantization table selector (0..3) */
  154001. /* These values may vary between scans. */
  154002. /* For compression, they must be supplied by parameter setup; */
  154003. /* for decompression, they are read from the SOS marker. */
  154004. /* The decompressor output side may not use these variables. */
  154005. int dc_tbl_no; /* DC entropy table selector (0..3) */
  154006. int ac_tbl_no; /* AC entropy table selector (0..3) */
  154007. /* Remaining fields should be treated as private by applications. */
  154008. /* These values are computed during compression or decompression startup: */
  154009. /* Component's size in DCT blocks.
  154010. * Any dummy blocks added to complete an MCU are not counted; therefore
  154011. * these values do not depend on whether a scan is interleaved or not.
  154012. */
  154013. JDIMENSION width_in_blocks;
  154014. JDIMENSION height_in_blocks;
  154015. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  154016. * For decompression this is the size of the output from one DCT block,
  154017. * reflecting any scaling we choose to apply during the IDCT step.
  154018. * Values of 1,2,4,8 are likely to be supported. Note that different
  154019. * components may receive different IDCT scalings.
  154020. */
  154021. int DCT_scaled_size;
  154022. /* The downsampled dimensions are the component's actual, unpadded number
  154023. * of samples at the main buffer (preprocessing/compression interface), thus
  154024. * downsampled_width = ceil(image_width * Hi/Hmax)
  154025. * and similarly for height. For decompression, IDCT scaling is included, so
  154026. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  154027. */
  154028. JDIMENSION downsampled_width; /* actual width in samples */
  154029. JDIMENSION downsampled_height; /* actual height in samples */
  154030. /* This flag is used only for decompression. In cases where some of the
  154031. * components will be ignored (eg grayscale output from YCbCr image),
  154032. * we can skip most computations for the unused components.
  154033. */
  154034. boolean component_needed; /* do we need the value of this component? */
  154035. /* These values are computed before starting a scan of the component. */
  154036. /* The decompressor output side may not use these variables. */
  154037. int MCU_width; /* number of blocks per MCU, horizontally */
  154038. int MCU_height; /* number of blocks per MCU, vertically */
  154039. int MCU_blocks; /* MCU_width * MCU_height */
  154040. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  154041. int last_col_width; /* # of non-dummy blocks across in last MCU */
  154042. int last_row_height; /* # of non-dummy blocks down in last MCU */
  154043. /* Saved quantization table for component; NULL if none yet saved.
  154044. * See jdinput.c comments about the need for this information.
  154045. * This field is currently used only for decompression.
  154046. */
  154047. JQUANT_TBL * quant_table;
  154048. /* Private per-component storage for DCT or IDCT subsystem. */
  154049. void * dct_table;
  154050. } jpeg_component_info;
  154051. /* The script for encoding a multiple-scan file is an array of these: */
  154052. typedef struct {
  154053. int comps_in_scan; /* number of components encoded in this scan */
  154054. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  154055. int Ss, Se; /* progressive JPEG spectral selection parms */
  154056. int Ah, Al; /* progressive JPEG successive approx. parms */
  154057. } jpeg_scan_info;
  154058. /* The decompressor can save APPn and COM markers in a list of these: */
  154059. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  154060. struct jpeg_marker_struct {
  154061. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  154062. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  154063. unsigned int original_length; /* # bytes of data in the file */
  154064. unsigned int data_length; /* # bytes of data saved at data[] */
  154065. JOCTET FAR * data; /* the data contained in the marker */
  154066. /* the marker length word is not counted in data_length or original_length */
  154067. };
  154068. /* Known color spaces. */
  154069. typedef enum {
  154070. JCS_UNKNOWN, /* error/unspecified */
  154071. JCS_GRAYSCALE, /* monochrome */
  154072. JCS_RGB, /* red/green/blue */
  154073. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  154074. JCS_CMYK, /* C/M/Y/K */
  154075. JCS_YCCK /* Y/Cb/Cr/K */
  154076. } J_COLOR_SPACE;
  154077. /* DCT/IDCT algorithm options. */
  154078. typedef enum {
  154079. JDCT_ISLOW, /* slow but accurate integer algorithm */
  154080. JDCT_IFAST, /* faster, less accurate integer method */
  154081. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  154082. } J_DCT_METHOD;
  154083. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  154084. #define JDCT_DEFAULT JDCT_ISLOW
  154085. #endif
  154086. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  154087. #define JDCT_FASTEST JDCT_IFAST
  154088. #endif
  154089. /* Dithering options for decompression. */
  154090. typedef enum {
  154091. JDITHER_NONE, /* no dithering */
  154092. JDITHER_ORDERED, /* simple ordered dither */
  154093. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  154094. } J_DITHER_MODE;
  154095. /* Common fields between JPEG compression and decompression master structs. */
  154096. #define jpeg_common_fields \
  154097. struct jpeg_error_mgr * err; /* Error handler module */\
  154098. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  154099. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  154100. void * client_data; /* Available for use by application */\
  154101. boolean is_decompressor; /* So common code can tell which is which */\
  154102. int global_state /* For checking call sequence validity */
  154103. /* Routines that are to be used by both halves of the library are declared
  154104. * to receive a pointer to this structure. There are no actual instances of
  154105. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  154106. */
  154107. struct jpeg_common_struct {
  154108. jpeg_common_fields; /* Fields common to both master struct types */
  154109. /* Additional fields follow in an actual jpeg_compress_struct or
  154110. * jpeg_decompress_struct. All three structs must agree on these
  154111. * initial fields! (This would be a lot cleaner in C++.)
  154112. */
  154113. };
  154114. typedef struct jpeg_common_struct * j_common_ptr;
  154115. typedef struct jpeg_compress_struct * j_compress_ptr;
  154116. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  154117. /* Master record for a compression instance */
  154118. struct jpeg_compress_struct {
  154119. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  154120. /* Destination for compressed data */
  154121. struct jpeg_destination_mgr * dest;
  154122. /* Description of source image --- these fields must be filled in by
  154123. * outer application before starting compression. in_color_space must
  154124. * be correct before you can even call jpeg_set_defaults().
  154125. */
  154126. JDIMENSION image_width; /* input image width */
  154127. JDIMENSION image_height; /* input image height */
  154128. int input_components; /* # of color components in input image */
  154129. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  154130. double input_gamma; /* image gamma of input image */
  154131. /* Compression parameters --- these fields must be set before calling
  154132. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  154133. * initialize everything to reasonable defaults, then changing anything
  154134. * the application specifically wants to change. That way you won't get
  154135. * burnt when new parameters are added. Also note that there are several
  154136. * helper routines to simplify changing parameters.
  154137. */
  154138. int data_precision; /* bits of precision in image data */
  154139. int num_components; /* # of color components in JPEG image */
  154140. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  154141. jpeg_component_info * comp_info;
  154142. /* comp_info[i] describes component that appears i'th in SOF */
  154143. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  154144. /* ptrs to coefficient quantization tables, or NULL if not defined */
  154145. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  154146. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  154147. /* ptrs to Huffman coding tables, or NULL if not defined */
  154148. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  154149. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  154150. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  154151. int num_scans; /* # of entries in scan_info array */
  154152. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  154153. /* The default value of scan_info is NULL, which causes a single-scan
  154154. * sequential JPEG file to be emitted. To create a multi-scan file,
  154155. * set num_scans and scan_info to point to an array of scan definitions.
  154156. */
  154157. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  154158. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  154159. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  154160. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  154161. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  154162. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  154163. /* The restart interval can be specified in absolute MCUs by setting
  154164. * restart_interval, or in MCU rows by setting restart_in_rows
  154165. * (in which case the correct restart_interval will be figured
  154166. * for each scan).
  154167. */
  154168. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  154169. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  154170. /* Parameters controlling emission of special markers. */
  154171. boolean write_JFIF_header; /* should a JFIF marker be written? */
  154172. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  154173. UINT8 JFIF_minor_version;
  154174. /* These three values are not used by the JPEG code, merely copied */
  154175. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  154176. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  154177. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  154178. UINT8 density_unit; /* JFIF code for pixel size units */
  154179. UINT16 X_density; /* Horizontal pixel density */
  154180. UINT16 Y_density; /* Vertical pixel density */
  154181. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  154182. /* State variable: index of next scanline to be written to
  154183. * jpeg_write_scanlines(). Application may use this to control its
  154184. * processing loop, e.g., "while (next_scanline < image_height)".
  154185. */
  154186. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  154187. /* Remaining fields are known throughout compressor, but generally
  154188. * should not be touched by a surrounding application.
  154189. */
  154190. /*
  154191. * These fields are computed during compression startup
  154192. */
  154193. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  154194. int max_h_samp_factor; /* largest h_samp_factor */
  154195. int max_v_samp_factor; /* largest v_samp_factor */
  154196. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  154197. /* The coefficient controller receives data in units of MCU rows as defined
  154198. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  154199. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  154200. * "iMCU" (interleaved MCU) row.
  154201. */
  154202. /*
  154203. * These fields are valid during any one scan.
  154204. * They describe the components and MCUs actually appearing in the scan.
  154205. */
  154206. int comps_in_scan; /* # of JPEG components in this scan */
  154207. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  154208. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  154209. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  154210. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  154211. int blocks_in_MCU; /* # of DCT blocks per MCU */
  154212. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  154213. /* MCU_membership[i] is index in cur_comp_info of component owning */
  154214. /* i'th block in an MCU */
  154215. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  154216. /*
  154217. * Links to compression subobjects (methods and private variables of modules)
  154218. */
  154219. struct jpeg_comp_master * master;
  154220. struct jpeg_c_main_controller * main;
  154221. struct jpeg_c_prep_controller * prep;
  154222. struct jpeg_c_coef_controller * coef;
  154223. struct jpeg_marker_writer * marker;
  154224. struct jpeg_color_converter * cconvert;
  154225. struct jpeg_downsampler * downsample;
  154226. struct jpeg_forward_dct * fdct;
  154227. struct jpeg_entropy_encoder * entropy;
  154228. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  154229. int script_space_size;
  154230. };
  154231. /* Master record for a decompression instance */
  154232. struct jpeg_decompress_struct {
  154233. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  154234. /* Source of compressed data */
  154235. struct jpeg_source_mgr * src;
  154236. /* Basic description of image --- filled in by jpeg_read_header(). */
  154237. /* Application may inspect these values to decide how to process image. */
  154238. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  154239. JDIMENSION image_height; /* nominal image height */
  154240. int num_components; /* # of color components in JPEG image */
  154241. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  154242. /* Decompression processing parameters --- these fields must be set before
  154243. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  154244. * them to default values.
  154245. */
  154246. J_COLOR_SPACE out_color_space; /* colorspace for output */
  154247. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  154248. double output_gamma; /* image gamma wanted in output */
  154249. boolean buffered_image; /* TRUE=multiple output passes */
  154250. boolean raw_data_out; /* TRUE=downsampled data wanted */
  154251. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  154252. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  154253. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  154254. boolean quantize_colors; /* TRUE=colormapped output wanted */
  154255. /* the following are ignored if not quantize_colors: */
  154256. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  154257. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  154258. int desired_number_of_colors; /* max # colors to use in created colormap */
  154259. /* these are significant only in buffered-image mode: */
  154260. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  154261. boolean enable_external_quant;/* enable future use of external colormap */
  154262. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  154263. /* Description of actual output image that will be returned to application.
  154264. * These fields are computed by jpeg_start_decompress().
  154265. * You can also use jpeg_calc_output_dimensions() to determine these values
  154266. * in advance of calling jpeg_start_decompress().
  154267. */
  154268. JDIMENSION output_width; /* scaled image width */
  154269. JDIMENSION output_height; /* scaled image height */
  154270. int out_color_components; /* # of color components in out_color_space */
  154271. int output_components; /* # of color components returned */
  154272. /* output_components is 1 (a colormap index) when quantizing colors;
  154273. * otherwise it equals out_color_components.
  154274. */
  154275. int rec_outbuf_height; /* min recommended height of scanline buffer */
  154276. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  154277. * high, space and time will be wasted due to unnecessary data copying.
  154278. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  154279. */
  154280. /* When quantizing colors, the output colormap is described by these fields.
  154281. * The application can supply a colormap by setting colormap non-NULL before
  154282. * calling jpeg_start_decompress; otherwise a colormap is created during
  154283. * jpeg_start_decompress or jpeg_start_output.
  154284. * The map has out_color_components rows and actual_number_of_colors columns.
  154285. */
  154286. int actual_number_of_colors; /* number of entries in use */
  154287. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  154288. /* State variables: these variables indicate the progress of decompression.
  154289. * The application may examine these but must not modify them.
  154290. */
  154291. /* Row index of next scanline to be read from jpeg_read_scanlines().
  154292. * Application may use this to control its processing loop, e.g.,
  154293. * "while (output_scanline < output_height)".
  154294. */
  154295. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  154296. /* Current input scan number and number of iMCU rows completed in scan.
  154297. * These indicate the progress of the decompressor input side.
  154298. */
  154299. int input_scan_number; /* Number of SOS markers seen so far */
  154300. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  154301. /* The "output scan number" is the notional scan being displayed by the
  154302. * output side. The decompressor will not allow output scan/row number
  154303. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  154304. */
  154305. int output_scan_number; /* Nominal scan number being displayed */
  154306. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  154307. /* Current progression status. coef_bits[c][i] indicates the precision
  154308. * with which component c's DCT coefficient i (in zigzag order) is known.
  154309. * It is -1 when no data has yet been received, otherwise it is the point
  154310. * transform (shift) value for the most recent scan of the coefficient
  154311. * (thus, 0 at completion of the progression).
  154312. * This pointer is NULL when reading a non-progressive file.
  154313. */
  154314. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  154315. /* Internal JPEG parameters --- the application usually need not look at
  154316. * these fields. Note that the decompressor output side may not use
  154317. * any parameters that can change between scans.
  154318. */
  154319. /* Quantization and Huffman tables are carried forward across input
  154320. * datastreams when processing abbreviated JPEG datastreams.
  154321. */
  154322. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  154323. /* ptrs to coefficient quantization tables, or NULL if not defined */
  154324. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  154325. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  154326. /* ptrs to Huffman coding tables, or NULL if not defined */
  154327. /* These parameters are never carried across datastreams, since they
  154328. * are given in SOF/SOS markers or defined to be reset by SOI.
  154329. */
  154330. int data_precision; /* bits of precision in image data */
  154331. jpeg_component_info * comp_info;
  154332. /* comp_info[i] describes component that appears i'th in SOF */
  154333. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  154334. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  154335. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  154336. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  154337. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  154338. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  154339. /* These fields record data obtained from optional markers recognized by
  154340. * the JPEG library.
  154341. */
  154342. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  154343. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  154344. UINT8 JFIF_major_version; /* JFIF version number */
  154345. UINT8 JFIF_minor_version;
  154346. UINT8 density_unit; /* JFIF code for pixel size units */
  154347. UINT16 X_density; /* Horizontal pixel density */
  154348. UINT16 Y_density; /* Vertical pixel density */
  154349. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  154350. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  154351. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  154352. /* Aside from the specific data retained from APPn markers known to the
  154353. * library, the uninterpreted contents of any or all APPn and COM markers
  154354. * can be saved in a list for examination by the application.
  154355. */
  154356. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  154357. /* Remaining fields are known throughout decompressor, but generally
  154358. * should not be touched by a surrounding application.
  154359. */
  154360. /*
  154361. * These fields are computed during decompression startup
  154362. */
  154363. int max_h_samp_factor; /* largest h_samp_factor */
  154364. int max_v_samp_factor; /* largest v_samp_factor */
  154365. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  154366. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  154367. /* The coefficient controller's input and output progress is measured in
  154368. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  154369. * in fully interleaved JPEG scans, but are used whether the scan is
  154370. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  154371. * rows of each component. Therefore, the IDCT output contains
  154372. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  154373. */
  154374. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  154375. /*
  154376. * These fields are valid during any one scan.
  154377. * They describe the components and MCUs actually appearing in the scan.
  154378. * Note that the decompressor output side must not use these fields.
  154379. */
  154380. int comps_in_scan; /* # of JPEG components in this scan */
  154381. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  154382. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  154383. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  154384. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  154385. int blocks_in_MCU; /* # of DCT blocks per MCU */
  154386. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  154387. /* MCU_membership[i] is index in cur_comp_info of component owning */
  154388. /* i'th block in an MCU */
  154389. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  154390. /* This field is shared between entropy decoder and marker parser.
  154391. * It is either zero or the code of a JPEG marker that has been
  154392. * read from the data source, but has not yet been processed.
  154393. */
  154394. int unread_marker;
  154395. /*
  154396. * Links to decompression subobjects (methods, private variables of modules)
  154397. */
  154398. struct jpeg_decomp_master * master;
  154399. struct jpeg_d_main_controller * main;
  154400. struct jpeg_d_coef_controller * coef;
  154401. struct jpeg_d_post_controller * post;
  154402. struct jpeg_input_controller * inputctl;
  154403. struct jpeg_marker_reader * marker;
  154404. struct jpeg_entropy_decoder * entropy;
  154405. struct jpeg_inverse_dct * idct;
  154406. struct jpeg_upsampler * upsample;
  154407. struct jpeg_color_deconverter * cconvert;
  154408. struct jpeg_color_quantizer * cquantize;
  154409. };
  154410. /* "Object" declarations for JPEG modules that may be supplied or called
  154411. * directly by the surrounding application.
  154412. * As with all objects in the JPEG library, these structs only define the
  154413. * publicly visible methods and state variables of a module. Additional
  154414. * private fields may exist after the public ones.
  154415. */
  154416. /* Error handler object */
  154417. struct jpeg_error_mgr {
  154418. /* Error exit handler: does not return to caller */
  154419. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  154420. /* Conditionally emit a trace or warning message */
  154421. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  154422. /* Routine that actually outputs a trace or error message */
  154423. JMETHOD(void, output_message, (j_common_ptr cinfo));
  154424. /* Format a message string for the most recent JPEG error or message */
  154425. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  154426. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  154427. /* Reset error state variables at start of a new image */
  154428. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  154429. /* The message ID code and any parameters are saved here.
  154430. * A message can have one string parameter or up to 8 int parameters.
  154431. */
  154432. int msg_code;
  154433. #define JMSG_STR_PARM_MAX 80
  154434. union {
  154435. int i[8];
  154436. char s[JMSG_STR_PARM_MAX];
  154437. } msg_parm;
  154438. /* Standard state variables for error facility */
  154439. int trace_level; /* max msg_level that will be displayed */
  154440. /* For recoverable corrupt-data errors, we emit a warning message,
  154441. * but keep going unless emit_message chooses to abort. emit_message
  154442. * should count warnings in num_warnings. The surrounding application
  154443. * can check for bad data by seeing if num_warnings is nonzero at the
  154444. * end of processing.
  154445. */
  154446. long num_warnings; /* number of corrupt-data warnings */
  154447. /* These fields point to the table(s) of error message strings.
  154448. * An application can change the table pointer to switch to a different
  154449. * message list (typically, to change the language in which errors are
  154450. * reported). Some applications may wish to add additional error codes
  154451. * that will be handled by the JPEG library error mechanism; the second
  154452. * table pointer is used for this purpose.
  154453. *
  154454. * First table includes all errors generated by JPEG library itself.
  154455. * Error code 0 is reserved for a "no such error string" message.
  154456. */
  154457. const char * const * jpeg_message_table; /* Library errors */
  154458. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  154459. /* Second table can be added by application (see cjpeg/djpeg for example).
  154460. * It contains strings numbered first_addon_message..last_addon_message.
  154461. */
  154462. const char * const * addon_message_table; /* Non-library errors */
  154463. int first_addon_message; /* code for first string in addon table */
  154464. int last_addon_message; /* code for last string in addon table */
  154465. };
  154466. /* Progress monitor object */
  154467. struct jpeg_progress_mgr {
  154468. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  154469. long pass_counter; /* work units completed in this pass */
  154470. long pass_limit; /* total number of work units in this pass */
  154471. int completed_passes; /* passes completed so far */
  154472. int total_passes; /* total number of passes expected */
  154473. };
  154474. /* Data destination object for compression */
  154475. struct jpeg_destination_mgr {
  154476. JOCTET * next_output_byte; /* => next byte to write in buffer */
  154477. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  154478. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  154479. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  154480. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  154481. };
  154482. /* Data source object for decompression */
  154483. struct jpeg_source_mgr {
  154484. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  154485. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  154486. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  154487. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  154488. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  154489. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  154490. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  154491. };
  154492. /* Memory manager object.
  154493. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  154494. * and "really big" objects (virtual arrays with backing store if needed).
  154495. * The memory manager does not allow individual objects to be freed; rather,
  154496. * each created object is assigned to a pool, and whole pools can be freed
  154497. * at once. This is faster and more convenient than remembering exactly what
  154498. * to free, especially where malloc()/free() are not too speedy.
  154499. * NB: alloc routines never return NULL. They exit to error_exit if not
  154500. * successful.
  154501. */
  154502. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  154503. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  154504. #define JPOOL_NUMPOOLS 2
  154505. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  154506. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  154507. struct jpeg_memory_mgr {
  154508. /* Method pointers */
  154509. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  154510. size_t sizeofobject));
  154511. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  154512. size_t sizeofobject));
  154513. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  154514. JDIMENSION samplesperrow,
  154515. JDIMENSION numrows));
  154516. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  154517. JDIMENSION blocksperrow,
  154518. JDIMENSION numrows));
  154519. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  154520. int pool_id,
  154521. boolean pre_zero,
  154522. JDIMENSION samplesperrow,
  154523. JDIMENSION numrows,
  154524. JDIMENSION maxaccess));
  154525. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  154526. int pool_id,
  154527. boolean pre_zero,
  154528. JDIMENSION blocksperrow,
  154529. JDIMENSION numrows,
  154530. JDIMENSION maxaccess));
  154531. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  154532. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  154533. jvirt_sarray_ptr ptr,
  154534. JDIMENSION start_row,
  154535. JDIMENSION num_rows,
  154536. boolean writable));
  154537. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  154538. jvirt_barray_ptr ptr,
  154539. JDIMENSION start_row,
  154540. JDIMENSION num_rows,
  154541. boolean writable));
  154542. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  154543. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  154544. /* Limit on memory allocation for this JPEG object. (Note that this is
  154545. * merely advisory, not a guaranteed maximum; it only affects the space
  154546. * used for virtual-array buffers.) May be changed by outer application
  154547. * after creating the JPEG object.
  154548. */
  154549. long max_memory_to_use;
  154550. /* Maximum allocation request accepted by alloc_large. */
  154551. long max_alloc_chunk;
  154552. };
  154553. /* Routine signature for application-supplied marker processing methods.
  154554. * Need not pass marker code since it is stored in cinfo->unread_marker.
  154555. */
  154556. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  154557. /* Declarations for routines called by application.
  154558. * The JPP macro hides prototype parameters from compilers that can't cope.
  154559. * Note JPP requires double parentheses.
  154560. */
  154561. #ifdef HAVE_PROTOTYPES
  154562. #define JPP(arglist) arglist
  154563. #else
  154564. #define JPP(arglist) ()
  154565. #endif
  154566. /* Short forms of external names for systems with brain-damaged linkers.
  154567. * We shorten external names to be unique in the first six letters, which
  154568. * is good enough for all known systems.
  154569. * (If your compiler itself needs names to be unique in less than 15
  154570. * characters, you are out of luck. Get a better compiler.)
  154571. */
  154572. #ifdef NEED_SHORT_EXTERNAL_NAMES
  154573. #define jpeg_std_error jStdError
  154574. #define jpeg_CreateCompress jCreaCompress
  154575. #define jpeg_CreateDecompress jCreaDecompress
  154576. #define jpeg_destroy_compress jDestCompress
  154577. #define jpeg_destroy_decompress jDestDecompress
  154578. #define jpeg_stdio_dest jStdDest
  154579. #define jpeg_stdio_src jStdSrc
  154580. #define jpeg_set_defaults jSetDefaults
  154581. #define jpeg_set_colorspace jSetColorspace
  154582. #define jpeg_default_colorspace jDefColorspace
  154583. #define jpeg_set_quality jSetQuality
  154584. #define jpeg_set_linear_quality jSetLQuality
  154585. #define jpeg_add_quant_table jAddQuantTable
  154586. #define jpeg_quality_scaling jQualityScaling
  154587. #define jpeg_simple_progression jSimProgress
  154588. #define jpeg_suppress_tables jSuppressTables
  154589. #define jpeg_alloc_quant_table jAlcQTable
  154590. #define jpeg_alloc_huff_table jAlcHTable
  154591. #define jpeg_start_compress jStrtCompress
  154592. #define jpeg_write_scanlines jWrtScanlines
  154593. #define jpeg_finish_compress jFinCompress
  154594. #define jpeg_write_raw_data jWrtRawData
  154595. #define jpeg_write_marker jWrtMarker
  154596. #define jpeg_write_m_header jWrtMHeader
  154597. #define jpeg_write_m_byte jWrtMByte
  154598. #define jpeg_write_tables jWrtTables
  154599. #define jpeg_read_header jReadHeader
  154600. #define jpeg_start_decompress jStrtDecompress
  154601. #define jpeg_read_scanlines jReadScanlines
  154602. #define jpeg_finish_decompress jFinDecompress
  154603. #define jpeg_read_raw_data jReadRawData
  154604. #define jpeg_has_multiple_scans jHasMultScn
  154605. #define jpeg_start_output jStrtOutput
  154606. #define jpeg_finish_output jFinOutput
  154607. #define jpeg_input_complete jInComplete
  154608. #define jpeg_new_colormap jNewCMap
  154609. #define jpeg_consume_input jConsumeInput
  154610. #define jpeg_calc_output_dimensions jCalcDimensions
  154611. #define jpeg_save_markers jSaveMarkers
  154612. #define jpeg_set_marker_processor jSetMarker
  154613. #define jpeg_read_coefficients jReadCoefs
  154614. #define jpeg_write_coefficients jWrtCoefs
  154615. #define jpeg_copy_critical_parameters jCopyCrit
  154616. #define jpeg_abort_compress jAbrtCompress
  154617. #define jpeg_abort_decompress jAbrtDecompress
  154618. #define jpeg_abort jAbort
  154619. #define jpeg_destroy jDestroy
  154620. #define jpeg_resync_to_restart jResyncRestart
  154621. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  154622. /* Default error-management setup */
  154623. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  154624. JPP((struct jpeg_error_mgr * err));
  154625. /* Initialization of JPEG compression objects.
  154626. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  154627. * names that applications should call. These expand to calls on
  154628. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  154629. * passed for version mismatch checking.
  154630. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  154631. */
  154632. #define jpeg_create_compress(cinfo) \
  154633. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  154634. (size_t) sizeof(struct jpeg_compress_struct))
  154635. #define jpeg_create_decompress(cinfo) \
  154636. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  154637. (size_t) sizeof(struct jpeg_decompress_struct))
  154638. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  154639. int version, size_t structsize));
  154640. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  154641. int version, size_t structsize));
  154642. /* Destruction of JPEG compression objects */
  154643. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  154644. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  154645. /* Standard data source and destination managers: stdio streams. */
  154646. /* Caller is responsible for opening the file before and closing after. */
  154647. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  154648. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  154649. /* Default parameter setup for compression */
  154650. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  154651. /* Compression parameter setup aids */
  154652. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  154653. J_COLOR_SPACE colorspace));
  154654. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  154655. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  154656. boolean force_baseline));
  154657. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  154658. int scale_factor,
  154659. boolean force_baseline));
  154660. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  154661. const unsigned int *basic_table,
  154662. int scale_factor,
  154663. boolean force_baseline));
  154664. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  154665. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  154666. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  154667. boolean suppress));
  154668. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  154669. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  154670. /* Main entry points for compression */
  154671. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  154672. boolean write_all_tables));
  154673. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  154674. JSAMPARRAY scanlines,
  154675. JDIMENSION num_lines));
  154676. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  154677. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  154678. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  154679. JSAMPIMAGE data,
  154680. JDIMENSION num_lines));
  154681. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  154682. EXTERN(void) jpeg_write_marker
  154683. JPP((j_compress_ptr cinfo, int marker,
  154684. const JOCTET * dataptr, unsigned int datalen));
  154685. /* Same, but piecemeal. */
  154686. EXTERN(void) jpeg_write_m_header
  154687. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  154688. EXTERN(void) jpeg_write_m_byte
  154689. JPP((j_compress_ptr cinfo, int val));
  154690. /* Alternate compression function: just write an abbreviated table file */
  154691. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  154692. /* Decompression startup: read start of JPEG datastream to see what's there */
  154693. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  154694. boolean require_image));
  154695. /* Return value is one of: */
  154696. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  154697. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  154698. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  154699. /* If you pass require_image = TRUE (normal case), you need not check for
  154700. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  154701. * JPEG_SUSPENDED is only possible if you use a data source module that can
  154702. * give a suspension return (the stdio source module doesn't).
  154703. */
  154704. /* Main entry points for decompression */
  154705. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  154706. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  154707. JSAMPARRAY scanlines,
  154708. JDIMENSION max_lines));
  154709. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  154710. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  154711. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  154712. JSAMPIMAGE data,
  154713. JDIMENSION max_lines));
  154714. /* Additional entry points for buffered-image mode. */
  154715. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  154716. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  154717. int scan_number));
  154718. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  154719. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  154720. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  154721. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  154722. /* Return value is one of: */
  154723. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  154724. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  154725. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  154726. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  154727. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  154728. /* Precalculate output dimensions for current decompression parameters. */
  154729. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  154730. /* Control saving of COM and APPn markers into marker_list. */
  154731. EXTERN(void) jpeg_save_markers
  154732. JPP((j_decompress_ptr cinfo, int marker_code,
  154733. unsigned int length_limit));
  154734. /* Install a special processing method for COM or APPn markers. */
  154735. EXTERN(void) jpeg_set_marker_processor
  154736. JPP((j_decompress_ptr cinfo, int marker_code,
  154737. jpeg_marker_parser_method routine));
  154738. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  154739. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  154740. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  154741. jvirt_barray_ptr * coef_arrays));
  154742. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  154743. j_compress_ptr dstinfo));
  154744. /* If you choose to abort compression or decompression before completing
  154745. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  154746. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  154747. * if you're done with the JPEG object, but if you want to clean it up and
  154748. * reuse it, call this:
  154749. */
  154750. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  154751. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  154752. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  154753. * flavor of JPEG object. These may be more convenient in some places.
  154754. */
  154755. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  154756. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  154757. /* Default restart-marker-resync procedure for use by data source modules */
  154758. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  154759. int desired));
  154760. /* These marker codes are exported since applications and data source modules
  154761. * are likely to want to use them.
  154762. */
  154763. #define JPEG_RST0 0xD0 /* RST0 marker code */
  154764. #define JPEG_EOI 0xD9 /* EOI marker code */
  154765. #define JPEG_APP0 0xE0 /* APP0 marker code */
  154766. #define JPEG_COM 0xFE /* COM marker code */
  154767. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  154768. * for structure definitions that are never filled in, keep it quiet by
  154769. * supplying dummy definitions for the various substructures.
  154770. */
  154771. #ifdef INCOMPLETE_TYPES_BROKEN
  154772. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  154773. struct jvirt_sarray_control { long dummy; };
  154774. struct jvirt_barray_control { long dummy; };
  154775. struct jpeg_comp_master { long dummy; };
  154776. struct jpeg_c_main_controller { long dummy; };
  154777. struct jpeg_c_prep_controller { long dummy; };
  154778. struct jpeg_c_coef_controller { long dummy; };
  154779. struct jpeg_marker_writer { long dummy; };
  154780. struct jpeg_color_converter { long dummy; };
  154781. struct jpeg_downsampler { long dummy; };
  154782. struct jpeg_forward_dct { long dummy; };
  154783. struct jpeg_entropy_encoder { long dummy; };
  154784. struct jpeg_decomp_master { long dummy; };
  154785. struct jpeg_d_main_controller { long dummy; };
  154786. struct jpeg_d_coef_controller { long dummy; };
  154787. struct jpeg_d_post_controller { long dummy; };
  154788. struct jpeg_input_controller { long dummy; };
  154789. struct jpeg_marker_reader { long dummy; };
  154790. struct jpeg_entropy_decoder { long dummy; };
  154791. struct jpeg_inverse_dct { long dummy; };
  154792. struct jpeg_upsampler { long dummy; };
  154793. struct jpeg_color_deconverter { long dummy; };
  154794. struct jpeg_color_quantizer { long dummy; };
  154795. #endif /* JPEG_INTERNALS */
  154796. #endif /* INCOMPLETE_TYPES_BROKEN */
  154797. /*
  154798. * The JPEG library modules define JPEG_INTERNALS before including this file.
  154799. * The internal structure declarations are read only when that is true.
  154800. * Applications using the library should not include jpegint.h, but may wish
  154801. * to include jerror.h.
  154802. */
  154803. #ifdef JPEG_INTERNALS
  154804. /********* Start of inlined file: jpegint.h *********/
  154805. /* Declarations for both compression & decompression */
  154806. typedef enum { /* Operating modes for buffer controllers */
  154807. JBUF_PASS_THRU, /* Plain stripwise operation */
  154808. /* Remaining modes require a full-image buffer to have been created */
  154809. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  154810. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  154811. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  154812. } J_BUF_MODE;
  154813. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  154814. #define CSTATE_START 100 /* after create_compress */
  154815. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  154816. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  154817. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  154818. #define DSTATE_START 200 /* after create_decompress */
  154819. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  154820. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  154821. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  154822. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  154823. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  154824. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  154825. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  154826. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  154827. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  154828. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  154829. /* Declarations for compression modules */
  154830. /* Master control module */
  154831. struct jpeg_comp_master {
  154832. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  154833. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  154834. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  154835. /* State variables made visible to other modules */
  154836. boolean call_pass_startup; /* True if pass_startup must be called */
  154837. boolean is_last_pass; /* True during last pass */
  154838. };
  154839. /* Main buffer control (downsampled-data buffer) */
  154840. struct jpeg_c_main_controller {
  154841. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  154842. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  154843. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  154844. JDIMENSION in_rows_avail));
  154845. };
  154846. /* Compression preprocessing (downsampling input buffer control) */
  154847. struct jpeg_c_prep_controller {
  154848. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  154849. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  154850. JSAMPARRAY input_buf,
  154851. JDIMENSION *in_row_ctr,
  154852. JDIMENSION in_rows_avail,
  154853. JSAMPIMAGE output_buf,
  154854. JDIMENSION *out_row_group_ctr,
  154855. JDIMENSION out_row_groups_avail));
  154856. };
  154857. /* Coefficient buffer control */
  154858. struct jpeg_c_coef_controller {
  154859. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  154860. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  154861. JSAMPIMAGE input_buf));
  154862. };
  154863. /* Colorspace conversion */
  154864. struct jpeg_color_converter {
  154865. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  154866. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  154867. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  154868. JDIMENSION output_row, int num_rows));
  154869. };
  154870. /* Downsampling */
  154871. struct jpeg_downsampler {
  154872. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  154873. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  154874. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  154875. JSAMPIMAGE output_buf,
  154876. JDIMENSION out_row_group_index));
  154877. boolean need_context_rows; /* TRUE if need rows above & below */
  154878. };
  154879. /* Forward DCT (also controls coefficient quantization) */
  154880. struct jpeg_forward_dct {
  154881. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  154882. /* perhaps this should be an array??? */
  154883. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  154884. jpeg_component_info * compptr,
  154885. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  154886. JDIMENSION start_row, JDIMENSION start_col,
  154887. JDIMENSION num_blocks));
  154888. };
  154889. /* Entropy encoding */
  154890. struct jpeg_entropy_encoder {
  154891. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  154892. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  154893. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  154894. };
  154895. /* Marker writing */
  154896. struct jpeg_marker_writer {
  154897. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  154898. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  154899. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  154900. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  154901. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  154902. /* These routines are exported to allow insertion of extra markers */
  154903. /* Probably only COM and APPn markers should be written this way */
  154904. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  154905. unsigned int datalen));
  154906. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  154907. };
  154908. /* Declarations for decompression modules */
  154909. /* Master control module */
  154910. struct jpeg_decomp_master {
  154911. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  154912. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  154913. /* State variables made visible to other modules */
  154914. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  154915. };
  154916. /* Input control module */
  154917. struct jpeg_input_controller {
  154918. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  154919. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  154920. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  154921. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  154922. /* State variables made visible to other modules */
  154923. boolean has_multiple_scans; /* True if file has multiple scans */
  154924. boolean eoi_reached; /* True when EOI has been consumed */
  154925. };
  154926. /* Main buffer control (downsampled-data buffer) */
  154927. struct jpeg_d_main_controller {
  154928. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  154929. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  154930. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  154931. JDIMENSION out_rows_avail));
  154932. };
  154933. /* Coefficient buffer control */
  154934. struct jpeg_d_coef_controller {
  154935. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  154936. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  154937. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  154938. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  154939. JSAMPIMAGE output_buf));
  154940. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  154941. jvirt_barray_ptr *coef_arrays;
  154942. };
  154943. /* Decompression postprocessing (color quantization buffer control) */
  154944. struct jpeg_d_post_controller {
  154945. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  154946. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  154947. JSAMPIMAGE input_buf,
  154948. JDIMENSION *in_row_group_ctr,
  154949. JDIMENSION in_row_groups_avail,
  154950. JSAMPARRAY output_buf,
  154951. JDIMENSION *out_row_ctr,
  154952. JDIMENSION out_rows_avail));
  154953. };
  154954. /* Marker reading & parsing */
  154955. struct jpeg_marker_reader {
  154956. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  154957. /* Read markers until SOS or EOI.
  154958. * Returns same codes as are defined for jpeg_consume_input:
  154959. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  154960. */
  154961. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  154962. /* Read a restart marker --- exported for use by entropy decoder only */
  154963. jpeg_marker_parser_method read_restart_marker;
  154964. /* State of marker reader --- nominally internal, but applications
  154965. * supplying COM or APPn handlers might like to know the state.
  154966. */
  154967. boolean saw_SOI; /* found SOI? */
  154968. boolean saw_SOF; /* found SOF? */
  154969. int next_restart_num; /* next restart number expected (0-7) */
  154970. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  154971. };
  154972. /* Entropy decoding */
  154973. struct jpeg_entropy_decoder {
  154974. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  154975. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  154976. JBLOCKROW *MCU_data));
  154977. /* This is here to share code between baseline and progressive decoders; */
  154978. /* other modules probably should not use it */
  154979. boolean insufficient_data; /* set TRUE after emitting warning */
  154980. };
  154981. /* Inverse DCT (also performs dequantization) */
  154982. typedef JMETHOD(void, inverse_DCT_method_ptr,
  154983. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  154984. JCOEFPTR coef_block,
  154985. JSAMPARRAY output_buf, JDIMENSION output_col));
  154986. struct jpeg_inverse_dct {
  154987. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  154988. /* It is useful to allow each component to have a separate IDCT method. */
  154989. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  154990. };
  154991. /* Upsampling (note that upsampler must also call color converter) */
  154992. struct jpeg_upsampler {
  154993. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  154994. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  154995. JSAMPIMAGE input_buf,
  154996. JDIMENSION *in_row_group_ctr,
  154997. JDIMENSION in_row_groups_avail,
  154998. JSAMPARRAY output_buf,
  154999. JDIMENSION *out_row_ctr,
  155000. JDIMENSION out_rows_avail));
  155001. boolean need_context_rows; /* TRUE if need rows above & below */
  155002. };
  155003. /* Colorspace conversion */
  155004. struct jpeg_color_deconverter {
  155005. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  155006. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  155007. JSAMPIMAGE input_buf, JDIMENSION input_row,
  155008. JSAMPARRAY output_buf, int num_rows));
  155009. };
  155010. /* Color quantization or color precision reduction */
  155011. struct jpeg_color_quantizer {
  155012. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  155013. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  155014. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  155015. int num_rows));
  155016. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  155017. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  155018. };
  155019. /* Miscellaneous useful macros */
  155020. #undef MAX
  155021. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  155022. #undef MIN
  155023. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  155024. /* We assume that right shift corresponds to signed division by 2 with
  155025. * rounding towards minus infinity. This is correct for typical "arithmetic
  155026. * shift" instructions that shift in copies of the sign bit. But some
  155027. * C compilers implement >> with an unsigned shift. For these machines you
  155028. * must define RIGHT_SHIFT_IS_UNSIGNED.
  155029. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  155030. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  155031. * included in the variables of any routine using RIGHT_SHIFT.
  155032. */
  155033. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  155034. #define SHIFT_TEMPS INT32 shift_temp;
  155035. #define RIGHT_SHIFT(x,shft) \
  155036. ((shift_temp = (x)) < 0 ? \
  155037. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  155038. (shift_temp >> (shft)))
  155039. #else
  155040. #define SHIFT_TEMPS
  155041. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  155042. #endif
  155043. /* Short forms of external names for systems with brain-damaged linkers. */
  155044. #ifdef NEED_SHORT_EXTERNAL_NAMES
  155045. #define jinit_compress_master jICompress
  155046. #define jinit_c_master_control jICMaster
  155047. #define jinit_c_main_controller jICMainC
  155048. #define jinit_c_prep_controller jICPrepC
  155049. #define jinit_c_coef_controller jICCoefC
  155050. #define jinit_color_converter jICColor
  155051. #define jinit_downsampler jIDownsampler
  155052. #define jinit_forward_dct jIFDCT
  155053. #define jinit_huff_encoder jIHEncoder
  155054. #define jinit_phuff_encoder jIPHEncoder
  155055. #define jinit_marker_writer jIMWriter
  155056. #define jinit_master_decompress jIDMaster
  155057. #define jinit_d_main_controller jIDMainC
  155058. #define jinit_d_coef_controller jIDCoefC
  155059. #define jinit_d_post_controller jIDPostC
  155060. #define jinit_input_controller jIInCtlr
  155061. #define jinit_marker_reader jIMReader
  155062. #define jinit_huff_decoder jIHDecoder
  155063. #define jinit_phuff_decoder jIPHDecoder
  155064. #define jinit_inverse_dct jIIDCT
  155065. #define jinit_upsampler jIUpsampler
  155066. #define jinit_color_deconverter jIDColor
  155067. #define jinit_1pass_quantizer jI1Quant
  155068. #define jinit_2pass_quantizer jI2Quant
  155069. #define jinit_merged_upsampler jIMUpsampler
  155070. #define jinit_memory_mgr jIMemMgr
  155071. #define jdiv_round_up jDivRound
  155072. #define jround_up jRound
  155073. #define jcopy_sample_rows jCopySamples
  155074. #define jcopy_block_row jCopyBlocks
  155075. #define jzero_far jZeroFar
  155076. #define jpeg_zigzag_order jZIGTable
  155077. #define jpeg_natural_order jZAGTable
  155078. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  155079. /* Compression module initialization routines */
  155080. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  155081. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  155082. boolean transcode_only));
  155083. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  155084. boolean need_full_buffer));
  155085. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  155086. boolean need_full_buffer));
  155087. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  155088. boolean need_full_buffer));
  155089. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  155090. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  155091. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  155092. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  155093. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  155094. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  155095. /* Decompression module initialization routines */
  155096. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  155097. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  155098. boolean need_full_buffer));
  155099. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  155100. boolean need_full_buffer));
  155101. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  155102. boolean need_full_buffer));
  155103. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  155104. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  155105. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  155106. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  155107. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  155108. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  155109. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  155110. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  155111. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  155112. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  155113. /* Memory manager initialization */
  155114. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  155115. /* Utility routines in jutils.c */
  155116. EXTERN(long) jdiv_round_up JPP((long a, long b));
  155117. EXTERN(long) jround_up JPP((long a, long b));
  155118. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  155119. JSAMPARRAY output_array, int dest_row,
  155120. int num_rows, JDIMENSION num_cols));
  155121. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  155122. JDIMENSION num_blocks));
  155123. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  155124. /* Constant tables in jutils.c */
  155125. #if 0 /* This table is not actually needed in v6a */
  155126. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  155127. #endif
  155128. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  155129. /* Suppress undefined-structure complaints if necessary. */
  155130. #ifdef INCOMPLETE_TYPES_BROKEN
  155131. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  155132. struct jvirt_sarray_control { long dummy; };
  155133. struct jvirt_barray_control { long dummy; };
  155134. #endif
  155135. #endif /* INCOMPLETE_TYPES_BROKEN */
  155136. /********* End of inlined file: jpegint.h *********/
  155137. /* fetch private declarations */
  155138. /********* Start of inlined file: jerror.h *********/
  155139. /*
  155140. * To define the enum list of message codes, include this file without
  155141. * defining macro JMESSAGE. To create a message string table, include it
  155142. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  155143. */
  155144. #ifndef JMESSAGE
  155145. #ifndef JERROR_H
  155146. /* First time through, define the enum list */
  155147. #define JMAKE_ENUM_LIST
  155148. #else
  155149. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  155150. #define JMESSAGE(code,string)
  155151. #endif /* JERROR_H */
  155152. #endif /* JMESSAGE */
  155153. #ifdef JMAKE_ENUM_LIST
  155154. typedef enum {
  155155. #define JMESSAGE(code,string) code ,
  155156. #endif /* JMAKE_ENUM_LIST */
  155157. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  155158. /* For maintenance convenience, list is alphabetical by message code name */
  155159. JMESSAGE(JERR_ARITH_NOTIMPL,
  155160. "Sorry, there are legal restrictions on arithmetic coding")
  155161. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  155162. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  155163. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  155164. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  155165. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  155166. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  155167. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  155168. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  155169. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  155170. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  155171. JMESSAGE(JERR_BAD_LIB_VERSION,
  155172. "Wrong JPEG library version: library is %d, caller expects %d")
  155173. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  155174. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  155175. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  155176. JMESSAGE(JERR_BAD_PROGRESSION,
  155177. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  155178. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  155179. "Invalid progressive parameters at scan script entry %d")
  155180. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  155181. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  155182. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  155183. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  155184. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  155185. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  155186. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  155187. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  155188. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  155189. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  155190. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  155191. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  155192. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  155193. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  155194. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  155195. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  155196. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  155197. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  155198. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  155199. JMESSAGE(JERR_FILE_READ, "Input file read error")
  155200. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  155201. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  155202. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  155203. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  155204. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  155205. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  155206. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  155207. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  155208. "Cannot transcode due to multiple use of quantization table %d")
  155209. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  155210. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  155211. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  155212. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  155213. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  155214. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  155215. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  155216. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  155217. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  155218. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  155219. JMESSAGE(JERR_QUANT_COMPONENTS,
  155220. "Cannot quantize more than %d color components")
  155221. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  155222. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  155223. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  155224. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  155225. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  155226. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  155227. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  155228. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  155229. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  155230. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  155231. JMESSAGE(JERR_TFILE_WRITE,
  155232. "Write failed on temporary file --- out of disk space?")
  155233. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  155234. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  155235. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  155236. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  155237. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  155238. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  155239. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  155240. JMESSAGE(JMSG_VERSION, JVERSION)
  155241. JMESSAGE(JTRC_16BIT_TABLES,
  155242. "Caution: quantization tables are too coarse for baseline JPEG")
  155243. JMESSAGE(JTRC_ADOBE,
  155244. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  155245. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  155246. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  155247. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  155248. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  155249. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  155250. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  155251. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  155252. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  155253. JMESSAGE(JTRC_EOI, "End Of Image")
  155254. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  155255. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  155256. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  155257. "Warning: thumbnail image size does not match data length %u")
  155258. JMESSAGE(JTRC_JFIF_EXTENSION,
  155259. "JFIF extension marker: type 0x%02x, length %u")
  155260. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  155261. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  155262. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  155263. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  155264. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  155265. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  155266. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  155267. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  155268. JMESSAGE(JTRC_RST, "RST%d")
  155269. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  155270. "Smoothing not supported with nonstandard sampling ratios")
  155271. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  155272. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  155273. JMESSAGE(JTRC_SOI, "Start of Image")
  155274. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  155275. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  155276. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  155277. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  155278. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  155279. JMESSAGE(JTRC_THUMB_JPEG,
  155280. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  155281. JMESSAGE(JTRC_THUMB_PALETTE,
  155282. "JFIF extension marker: palette thumbnail image, length %u")
  155283. JMESSAGE(JTRC_THUMB_RGB,
  155284. "JFIF extension marker: RGB thumbnail image, length %u")
  155285. JMESSAGE(JTRC_UNKNOWN_IDS,
  155286. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  155287. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  155288. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  155289. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  155290. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  155291. "Inconsistent progression sequence for component %d coefficient %d")
  155292. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  155293. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  155294. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  155295. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  155296. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  155297. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  155298. JMESSAGE(JWRN_MUST_RESYNC,
  155299. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  155300. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  155301. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  155302. #ifdef JMAKE_ENUM_LIST
  155303. JMSG_LASTMSGCODE
  155304. } J_MESSAGE_CODE;
  155305. #undef JMAKE_ENUM_LIST
  155306. #endif /* JMAKE_ENUM_LIST */
  155307. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  155308. #undef JMESSAGE
  155309. #ifndef JERROR_H
  155310. #define JERROR_H
  155311. /* Macros to simplify using the error and trace message stuff */
  155312. /* The first parameter is either type of cinfo pointer */
  155313. /* Fatal errors (print message and exit) */
  155314. #define ERREXIT(cinfo,code) \
  155315. ((cinfo)->err->msg_code = (code), \
  155316. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  155317. #define ERREXIT1(cinfo,code,p1) \
  155318. ((cinfo)->err->msg_code = (code), \
  155319. (cinfo)->err->msg_parm.i[0] = (p1), \
  155320. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  155321. #define ERREXIT2(cinfo,code,p1,p2) \
  155322. ((cinfo)->err->msg_code = (code), \
  155323. (cinfo)->err->msg_parm.i[0] = (p1), \
  155324. (cinfo)->err->msg_parm.i[1] = (p2), \
  155325. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  155326. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  155327. ((cinfo)->err->msg_code = (code), \
  155328. (cinfo)->err->msg_parm.i[0] = (p1), \
  155329. (cinfo)->err->msg_parm.i[1] = (p2), \
  155330. (cinfo)->err->msg_parm.i[2] = (p3), \
  155331. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  155332. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  155333. ((cinfo)->err->msg_code = (code), \
  155334. (cinfo)->err->msg_parm.i[0] = (p1), \
  155335. (cinfo)->err->msg_parm.i[1] = (p2), \
  155336. (cinfo)->err->msg_parm.i[2] = (p3), \
  155337. (cinfo)->err->msg_parm.i[3] = (p4), \
  155338. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  155339. #define ERREXITS(cinfo,code,str) \
  155340. ((cinfo)->err->msg_code = (code), \
  155341. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  155342. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  155343. #define MAKESTMT(stuff) do { stuff } while (0)
  155344. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  155345. #define WARNMS(cinfo,code) \
  155346. ((cinfo)->err->msg_code = (code), \
  155347. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  155348. #define WARNMS1(cinfo,code,p1) \
  155349. ((cinfo)->err->msg_code = (code), \
  155350. (cinfo)->err->msg_parm.i[0] = (p1), \
  155351. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  155352. #define WARNMS2(cinfo,code,p1,p2) \
  155353. ((cinfo)->err->msg_code = (code), \
  155354. (cinfo)->err->msg_parm.i[0] = (p1), \
  155355. (cinfo)->err->msg_parm.i[1] = (p2), \
  155356. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  155357. /* Informational/debugging messages */
  155358. #define TRACEMS(cinfo,lvl,code) \
  155359. ((cinfo)->err->msg_code = (code), \
  155360. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  155361. #define TRACEMS1(cinfo,lvl,code,p1) \
  155362. ((cinfo)->err->msg_code = (code), \
  155363. (cinfo)->err->msg_parm.i[0] = (p1), \
  155364. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  155365. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  155366. ((cinfo)->err->msg_code = (code), \
  155367. (cinfo)->err->msg_parm.i[0] = (p1), \
  155368. (cinfo)->err->msg_parm.i[1] = (p2), \
  155369. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  155370. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  155371. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  155372. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  155373. (cinfo)->err->msg_code = (code); \
  155374. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  155375. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  155376. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  155377. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  155378. (cinfo)->err->msg_code = (code); \
  155379. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  155380. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  155381. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  155382. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  155383. _mp[4] = (p5); \
  155384. (cinfo)->err->msg_code = (code); \
  155385. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  155386. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  155387. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  155388. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  155389. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  155390. (cinfo)->err->msg_code = (code); \
  155391. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  155392. #define TRACEMSS(cinfo,lvl,code,str) \
  155393. ((cinfo)->err->msg_code = (code), \
  155394. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  155395. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  155396. #endif /* JERROR_H */
  155397. /********* End of inlined file: jerror.h *********/
  155398. /* fetch error codes too */
  155399. #endif
  155400. #endif /* JPEGLIB_H */
  155401. /********* End of inlined file: jpeglib.h *********/
  155402. /********* Start of inlined file: jcapimin.c *********/
  155403. #define JPEG_INTERNALS
  155404. /********* Start of inlined file: jinclude.h *********/
  155405. /* Include auto-config file to find out which system include files we need. */
  155406. #ifndef __jinclude_h__
  155407. #define __jinclude_h__
  155408. /********* Start of inlined file: jconfig.h *********/
  155409. /* see jconfig.doc for explanations */
  155410. // disable all the warnings under MSVC
  155411. #ifdef _MSC_VER
  155412. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  155413. #endif
  155414. #ifdef __BORLANDC__
  155415. #pragma warn -8057
  155416. #pragma warn -8019
  155417. #pragma warn -8004
  155418. #pragma warn -8008
  155419. #endif
  155420. #define HAVE_PROTOTYPES
  155421. #define HAVE_UNSIGNED_CHAR
  155422. #define HAVE_UNSIGNED_SHORT
  155423. /* #define void char */
  155424. /* #define const */
  155425. #undef CHAR_IS_UNSIGNED
  155426. #define HAVE_STDDEF_H
  155427. #define HAVE_STDLIB_H
  155428. #undef NEED_BSD_STRINGS
  155429. #undef NEED_SYS_TYPES_H
  155430. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  155431. #undef NEED_SHORT_EXTERNAL_NAMES
  155432. #undef INCOMPLETE_TYPES_BROKEN
  155433. /* Define "boolean" as unsigned char, not int, per Windows custom */
  155434. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  155435. typedef unsigned char boolean;
  155436. #endif
  155437. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  155438. #ifdef JPEG_INTERNALS
  155439. #undef RIGHT_SHIFT_IS_UNSIGNED
  155440. #endif /* JPEG_INTERNALS */
  155441. #ifdef JPEG_CJPEG_DJPEG
  155442. #define BMP_SUPPORTED /* BMP image file format */
  155443. #define GIF_SUPPORTED /* GIF image file format */
  155444. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  155445. #undef RLE_SUPPORTED /* Utah RLE image file format */
  155446. #define TARGA_SUPPORTED /* Targa image file format */
  155447. #define TWO_FILE_COMMANDLINE /* optional */
  155448. #define USE_SETMODE /* Microsoft has setmode() */
  155449. #undef NEED_SIGNAL_CATCHER
  155450. #undef DONT_USE_B_MODE
  155451. #undef PROGRESS_REPORT /* optional */
  155452. #endif /* JPEG_CJPEG_DJPEG */
  155453. /********* End of inlined file: jconfig.h *********/
  155454. /* auto configuration options */
  155455. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  155456. /*
  155457. * We need the NULL macro and size_t typedef.
  155458. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  155459. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  155460. * pull in <sys/types.h> as well.
  155461. * Note that the core JPEG library does not require <stdio.h>;
  155462. * only the default error handler and data source/destination modules do.
  155463. * But we must pull it in because of the references to FILE in jpeglib.h.
  155464. * You can remove those references if you want to compile without <stdio.h>.
  155465. */
  155466. #ifdef HAVE_STDDEF_H
  155467. #include <stddef.h>
  155468. #endif
  155469. #ifdef HAVE_STDLIB_H
  155470. #include <stdlib.h>
  155471. #endif
  155472. #ifdef NEED_SYS_TYPES_H
  155473. #include <sys/types.h>
  155474. #endif
  155475. #include <stdio.h>
  155476. /*
  155477. * We need memory copying and zeroing functions, plus strncpy().
  155478. * ANSI and System V implementations declare these in <string.h>.
  155479. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  155480. * Some systems may declare memset and memcpy in <memory.h>.
  155481. *
  155482. * NOTE: we assume the size parameters to these functions are of type size_t.
  155483. * Change the casts in these macros if not!
  155484. */
  155485. #ifdef NEED_BSD_STRINGS
  155486. #include <strings.h>
  155487. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  155488. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  155489. #else /* not BSD, assume ANSI/SysV string lib */
  155490. #include <string.h>
  155491. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  155492. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  155493. #endif
  155494. /*
  155495. * In ANSI C, and indeed any rational implementation, size_t is also the
  155496. * type returned by sizeof(). However, it seems there are some irrational
  155497. * implementations out there, in which sizeof() returns an int even though
  155498. * size_t is defined as long or unsigned long. To ensure consistent results
  155499. * we always use this SIZEOF() macro in place of using sizeof() directly.
  155500. */
  155501. #define SIZEOF(object) ((size_t) sizeof(object))
  155502. /*
  155503. * The modules that use fread() and fwrite() always invoke them through
  155504. * these macros. On some systems you may need to twiddle the argument casts.
  155505. * CAUTION: argument order is different from underlying functions!
  155506. */
  155507. #define JFREAD(file,buf,sizeofbuf) \
  155508. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  155509. #define JFWRITE(file,buf,sizeofbuf) \
  155510. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  155511. typedef enum { /* JPEG marker codes */
  155512. M_SOF0 = 0xc0,
  155513. M_SOF1 = 0xc1,
  155514. M_SOF2 = 0xc2,
  155515. M_SOF3 = 0xc3,
  155516. M_SOF5 = 0xc5,
  155517. M_SOF6 = 0xc6,
  155518. M_SOF7 = 0xc7,
  155519. M_JPG = 0xc8,
  155520. M_SOF9 = 0xc9,
  155521. M_SOF10 = 0xca,
  155522. M_SOF11 = 0xcb,
  155523. M_SOF13 = 0xcd,
  155524. M_SOF14 = 0xce,
  155525. M_SOF15 = 0xcf,
  155526. M_DHT = 0xc4,
  155527. M_DAC = 0xcc,
  155528. M_RST0 = 0xd0,
  155529. M_RST1 = 0xd1,
  155530. M_RST2 = 0xd2,
  155531. M_RST3 = 0xd3,
  155532. M_RST4 = 0xd4,
  155533. M_RST5 = 0xd5,
  155534. M_RST6 = 0xd6,
  155535. M_RST7 = 0xd7,
  155536. M_SOI = 0xd8,
  155537. M_EOI = 0xd9,
  155538. M_SOS = 0xda,
  155539. M_DQT = 0xdb,
  155540. M_DNL = 0xdc,
  155541. M_DRI = 0xdd,
  155542. M_DHP = 0xde,
  155543. M_EXP = 0xdf,
  155544. M_APP0 = 0xe0,
  155545. M_APP1 = 0xe1,
  155546. M_APP2 = 0xe2,
  155547. M_APP3 = 0xe3,
  155548. M_APP4 = 0xe4,
  155549. M_APP5 = 0xe5,
  155550. M_APP6 = 0xe6,
  155551. M_APP7 = 0xe7,
  155552. M_APP8 = 0xe8,
  155553. M_APP9 = 0xe9,
  155554. M_APP10 = 0xea,
  155555. M_APP11 = 0xeb,
  155556. M_APP12 = 0xec,
  155557. M_APP13 = 0xed,
  155558. M_APP14 = 0xee,
  155559. M_APP15 = 0xef,
  155560. M_JPG0 = 0xf0,
  155561. M_JPG13 = 0xfd,
  155562. M_COM = 0xfe,
  155563. M_TEM = 0x01,
  155564. M_ERROR = 0x100
  155565. } JPEG_MARKER;
  155566. /*
  155567. * Figure F.12: extend sign bit.
  155568. * On some machines, a shift and add will be faster than a table lookup.
  155569. */
  155570. #ifdef AVOID_TABLES
  155571. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  155572. #else
  155573. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  155574. static const int extend_test[16] = /* entry n is 2**(n-1) */
  155575. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  155576. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  155577. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  155578. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  155579. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  155580. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  155581. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  155582. #endif /* AVOID_TABLES */
  155583. #endif
  155584. /********* End of inlined file: jinclude.h *********/
  155585. /*
  155586. * Initialization of a JPEG compression object.
  155587. * The error manager must already be set up (in case memory manager fails).
  155588. */
  155589. GLOBAL(void)
  155590. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  155591. {
  155592. int i;
  155593. /* Guard against version mismatches between library and caller. */
  155594. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  155595. if (version != JPEG_LIB_VERSION)
  155596. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  155597. if (structsize != SIZEOF(struct jpeg_compress_struct))
  155598. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  155599. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  155600. /* For debugging purposes, we zero the whole master structure.
  155601. * But the application has already set the err pointer, and may have set
  155602. * client_data, so we have to save and restore those fields.
  155603. * Note: if application hasn't set client_data, tools like Purify may
  155604. * complain here.
  155605. */
  155606. {
  155607. struct jpeg_error_mgr * err = cinfo->err;
  155608. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  155609. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  155610. cinfo->err = err;
  155611. cinfo->client_data = client_data;
  155612. }
  155613. cinfo->is_decompressor = FALSE;
  155614. /* Initialize a memory manager instance for this object */
  155615. jinit_memory_mgr((j_common_ptr) cinfo);
  155616. /* Zero out pointers to permanent structures. */
  155617. cinfo->progress = NULL;
  155618. cinfo->dest = NULL;
  155619. cinfo->comp_info = NULL;
  155620. for (i = 0; i < NUM_QUANT_TBLS; i++)
  155621. cinfo->quant_tbl_ptrs[i] = NULL;
  155622. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  155623. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  155624. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  155625. }
  155626. cinfo->script_space = NULL;
  155627. cinfo->input_gamma = 1.0; /* in case application forgets */
  155628. /* OK, I'm ready */
  155629. cinfo->global_state = CSTATE_START;
  155630. }
  155631. /*
  155632. * Destruction of a JPEG compression object
  155633. */
  155634. GLOBAL(void)
  155635. jpeg_destroy_compress (j_compress_ptr cinfo)
  155636. {
  155637. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  155638. }
  155639. /*
  155640. * Abort processing of a JPEG compression operation,
  155641. * but don't destroy the object itself.
  155642. */
  155643. GLOBAL(void)
  155644. jpeg_abort_compress (j_compress_ptr cinfo)
  155645. {
  155646. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  155647. }
  155648. /*
  155649. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  155650. * Marks all currently defined tables as already written (if suppress)
  155651. * or not written (if !suppress). This will control whether they get emitted
  155652. * by a subsequent jpeg_start_compress call.
  155653. *
  155654. * This routine is exported for use by applications that want to produce
  155655. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  155656. * since it is called by jpeg_start_compress, we put it here --- otherwise
  155657. * jcparam.o would be linked whether the application used it or not.
  155658. */
  155659. GLOBAL(void)
  155660. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  155661. {
  155662. int i;
  155663. JQUANT_TBL * qtbl;
  155664. JHUFF_TBL * htbl;
  155665. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  155666. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  155667. qtbl->sent_table = suppress;
  155668. }
  155669. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  155670. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  155671. htbl->sent_table = suppress;
  155672. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  155673. htbl->sent_table = suppress;
  155674. }
  155675. }
  155676. /*
  155677. * Finish JPEG compression.
  155678. *
  155679. * If a multipass operating mode was selected, this may do a great deal of
  155680. * work including most of the actual output.
  155681. */
  155682. GLOBAL(void)
  155683. jpeg_finish_compress (j_compress_ptr cinfo)
  155684. {
  155685. JDIMENSION iMCU_row;
  155686. if (cinfo->global_state == CSTATE_SCANNING ||
  155687. cinfo->global_state == CSTATE_RAW_OK) {
  155688. /* Terminate first pass */
  155689. if (cinfo->next_scanline < cinfo->image_height)
  155690. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  155691. (*cinfo->master->finish_pass) (cinfo);
  155692. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  155693. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155694. /* Perform any remaining passes */
  155695. while (! cinfo->master->is_last_pass) {
  155696. (*cinfo->master->prepare_for_pass) (cinfo);
  155697. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  155698. if (cinfo->progress != NULL) {
  155699. cinfo->progress->pass_counter = (long) iMCU_row;
  155700. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  155701. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  155702. }
  155703. /* We bypass the main controller and invoke coef controller directly;
  155704. * all work is being done from the coefficient buffer.
  155705. */
  155706. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  155707. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  155708. }
  155709. (*cinfo->master->finish_pass) (cinfo);
  155710. }
  155711. /* Write EOI, do final cleanup */
  155712. (*cinfo->marker->write_file_trailer) (cinfo);
  155713. (*cinfo->dest->term_destination) (cinfo);
  155714. /* We can use jpeg_abort to release memory and reset global_state */
  155715. jpeg_abort((j_common_ptr) cinfo);
  155716. }
  155717. /*
  155718. * Write a special marker.
  155719. * This is only recommended for writing COM or APPn markers.
  155720. * Must be called after jpeg_start_compress() and before
  155721. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  155722. */
  155723. GLOBAL(void)
  155724. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  155725. const JOCTET *dataptr, unsigned int datalen)
  155726. {
  155727. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  155728. if (cinfo->next_scanline != 0 ||
  155729. (cinfo->global_state != CSTATE_SCANNING &&
  155730. cinfo->global_state != CSTATE_RAW_OK &&
  155731. cinfo->global_state != CSTATE_WRCOEFS))
  155732. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155733. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  155734. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  155735. while (datalen--) {
  155736. (*write_marker_byte) (cinfo, *dataptr);
  155737. dataptr++;
  155738. }
  155739. }
  155740. /* Same, but piecemeal. */
  155741. GLOBAL(void)
  155742. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  155743. {
  155744. if (cinfo->next_scanline != 0 ||
  155745. (cinfo->global_state != CSTATE_SCANNING &&
  155746. cinfo->global_state != CSTATE_RAW_OK &&
  155747. cinfo->global_state != CSTATE_WRCOEFS))
  155748. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155749. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  155750. }
  155751. GLOBAL(void)
  155752. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  155753. {
  155754. (*cinfo->marker->write_marker_byte) (cinfo, val);
  155755. }
  155756. /*
  155757. * Alternate compression function: just write an abbreviated table file.
  155758. * Before calling this, all parameters and a data destination must be set up.
  155759. *
  155760. * To produce a pair of files containing abbreviated tables and abbreviated
  155761. * image data, one would proceed as follows:
  155762. *
  155763. * initialize JPEG object
  155764. * set JPEG parameters
  155765. * set destination to table file
  155766. * jpeg_write_tables(cinfo);
  155767. * set destination to image file
  155768. * jpeg_start_compress(cinfo, FALSE);
  155769. * write data...
  155770. * jpeg_finish_compress(cinfo);
  155771. *
  155772. * jpeg_write_tables has the side effect of marking all tables written
  155773. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  155774. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  155775. */
  155776. GLOBAL(void)
  155777. jpeg_write_tables (j_compress_ptr cinfo)
  155778. {
  155779. if (cinfo->global_state != CSTATE_START)
  155780. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155781. /* (Re)initialize error mgr and destination modules */
  155782. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  155783. (*cinfo->dest->init_destination) (cinfo);
  155784. /* Initialize the marker writer ... bit of a crock to do it here. */
  155785. jinit_marker_writer(cinfo);
  155786. /* Write them tables! */
  155787. (*cinfo->marker->write_tables_only) (cinfo);
  155788. /* And clean up. */
  155789. (*cinfo->dest->term_destination) (cinfo);
  155790. /*
  155791. * In library releases up through v6a, we called jpeg_abort() here to free
  155792. * any working memory allocated by the destination manager and marker
  155793. * writer. Some applications had a problem with that: they allocated space
  155794. * of their own from the library memory manager, and didn't want it to go
  155795. * away during write_tables. So now we do nothing. This will cause a
  155796. * memory leak if an app calls write_tables repeatedly without doing a full
  155797. * compression cycle or otherwise resetting the JPEG object. However, that
  155798. * seems less bad than unexpectedly freeing memory in the normal case.
  155799. * An app that prefers the old behavior can call jpeg_abort for itself after
  155800. * each call to jpeg_write_tables().
  155801. */
  155802. }
  155803. /********* End of inlined file: jcapimin.c *********/
  155804. /********* Start of inlined file: jcapistd.c *********/
  155805. #define JPEG_INTERNALS
  155806. /*
  155807. * Compression initialization.
  155808. * Before calling this, all parameters and a data destination must be set up.
  155809. *
  155810. * We require a write_all_tables parameter as a failsafe check when writing
  155811. * multiple datastreams from the same compression object. Since prior runs
  155812. * will have left all the tables marked sent_table=TRUE, a subsequent run
  155813. * would emit an abbreviated stream (no tables) by default. This may be what
  155814. * is wanted, but for safety's sake it should not be the default behavior:
  155815. * programmers should have to make a deliberate choice to emit abbreviated
  155816. * images. Therefore the documentation and examples should encourage people
  155817. * to pass write_all_tables=TRUE; then it will take active thought to do the
  155818. * wrong thing.
  155819. */
  155820. GLOBAL(void)
  155821. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  155822. {
  155823. if (cinfo->global_state != CSTATE_START)
  155824. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155825. if (write_all_tables)
  155826. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  155827. /* (Re)initialize error mgr and destination modules */
  155828. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  155829. (*cinfo->dest->init_destination) (cinfo);
  155830. /* Perform master selection of active modules */
  155831. jinit_compress_master(cinfo);
  155832. /* Set up for the first pass */
  155833. (*cinfo->master->prepare_for_pass) (cinfo);
  155834. /* Ready for application to drive first pass through jpeg_write_scanlines
  155835. * or jpeg_write_raw_data.
  155836. */
  155837. cinfo->next_scanline = 0;
  155838. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  155839. }
  155840. /*
  155841. * Write some scanlines of data to the JPEG compressor.
  155842. *
  155843. * The return value will be the number of lines actually written.
  155844. * This should be less than the supplied num_lines only in case that
  155845. * the data destination module has requested suspension of the compressor,
  155846. * or if more than image_height scanlines are passed in.
  155847. *
  155848. * Note: we warn about excess calls to jpeg_write_scanlines() since
  155849. * this likely signals an application programmer error. However,
  155850. * excess scanlines passed in the last valid call are *silently* ignored,
  155851. * so that the application need not adjust num_lines for end-of-image
  155852. * when using a multiple-scanline buffer.
  155853. */
  155854. GLOBAL(JDIMENSION)
  155855. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  155856. JDIMENSION num_lines)
  155857. {
  155858. JDIMENSION row_ctr, rows_left;
  155859. if (cinfo->global_state != CSTATE_SCANNING)
  155860. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155861. if (cinfo->next_scanline >= cinfo->image_height)
  155862. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  155863. /* Call progress monitor hook if present */
  155864. if (cinfo->progress != NULL) {
  155865. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  155866. cinfo->progress->pass_limit = (long) cinfo->image_height;
  155867. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  155868. }
  155869. /* Give master control module another chance if this is first call to
  155870. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  155871. * delayed so that application can write COM, etc, markers between
  155872. * jpeg_start_compress and jpeg_write_scanlines.
  155873. */
  155874. if (cinfo->master->call_pass_startup)
  155875. (*cinfo->master->pass_startup) (cinfo);
  155876. /* Ignore any extra scanlines at bottom of image. */
  155877. rows_left = cinfo->image_height - cinfo->next_scanline;
  155878. if (num_lines > rows_left)
  155879. num_lines = rows_left;
  155880. row_ctr = 0;
  155881. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  155882. cinfo->next_scanline += row_ctr;
  155883. return row_ctr;
  155884. }
  155885. /*
  155886. * Alternate entry point to write raw data.
  155887. * Processes exactly one iMCU row per call, unless suspended.
  155888. */
  155889. GLOBAL(JDIMENSION)
  155890. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  155891. JDIMENSION num_lines)
  155892. {
  155893. JDIMENSION lines_per_iMCU_row;
  155894. if (cinfo->global_state != CSTATE_RAW_OK)
  155895. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155896. if (cinfo->next_scanline >= cinfo->image_height) {
  155897. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  155898. return 0;
  155899. }
  155900. /* Call progress monitor hook if present */
  155901. if (cinfo->progress != NULL) {
  155902. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  155903. cinfo->progress->pass_limit = (long) cinfo->image_height;
  155904. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  155905. }
  155906. /* Give master control module another chance if this is first call to
  155907. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  155908. * delayed so that application can write COM, etc, markers between
  155909. * jpeg_start_compress and jpeg_write_raw_data.
  155910. */
  155911. if (cinfo->master->call_pass_startup)
  155912. (*cinfo->master->pass_startup) (cinfo);
  155913. /* Verify that at least one iMCU row has been passed. */
  155914. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  155915. if (num_lines < lines_per_iMCU_row)
  155916. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  155917. /* Directly compress the row. */
  155918. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  155919. /* If compressor did not consume the whole row, suspend processing. */
  155920. return 0;
  155921. }
  155922. /* OK, we processed one iMCU row. */
  155923. cinfo->next_scanline += lines_per_iMCU_row;
  155924. return lines_per_iMCU_row;
  155925. }
  155926. /********* End of inlined file: jcapistd.c *********/
  155927. /********* Start of inlined file: jccoefct.c *********/
  155928. #define JPEG_INTERNALS
  155929. /* We use a full-image coefficient buffer when doing Huffman optimization,
  155930. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  155931. * step is run during the first pass, and subsequent passes need only read
  155932. * the buffered coefficients.
  155933. */
  155934. #ifdef ENTROPY_OPT_SUPPORTED
  155935. #define FULL_COEF_BUFFER_SUPPORTED
  155936. #else
  155937. #ifdef C_MULTISCAN_FILES_SUPPORTED
  155938. #define FULL_COEF_BUFFER_SUPPORTED
  155939. #endif
  155940. #endif
  155941. /* Private buffer controller object */
  155942. typedef struct {
  155943. struct jpeg_c_coef_controller pub; /* public fields */
  155944. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  155945. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  155946. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  155947. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  155948. /* For single-pass compression, it's sufficient to buffer just one MCU
  155949. * (although this may prove a bit slow in practice). We allocate a
  155950. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  155951. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  155952. * it's not really very big; this is to keep the module interfaces unchanged
  155953. * when a large coefficient buffer is necessary.)
  155954. * In multi-pass modes, this array points to the current MCU's blocks
  155955. * within the virtual arrays.
  155956. */
  155957. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  155958. /* In multi-pass modes, we need a virtual block array for each component. */
  155959. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  155960. } my_coef_controller;
  155961. typedef my_coef_controller * my_coef_ptr;
  155962. /* Forward declarations */
  155963. METHODDEF(boolean) compress_data
  155964. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  155965. #ifdef FULL_COEF_BUFFER_SUPPORTED
  155966. METHODDEF(boolean) compress_first_pass
  155967. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  155968. METHODDEF(boolean) compress_output
  155969. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  155970. #endif
  155971. LOCAL(void)
  155972. start_iMCU_row (j_compress_ptr cinfo)
  155973. /* Reset within-iMCU-row counters for a new row */
  155974. {
  155975. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  155976. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  155977. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  155978. * But at the bottom of the image, process only what's left.
  155979. */
  155980. if (cinfo->comps_in_scan > 1) {
  155981. coef->MCU_rows_per_iMCU_row = 1;
  155982. } else {
  155983. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  155984. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  155985. else
  155986. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  155987. }
  155988. coef->mcu_ctr = 0;
  155989. coef->MCU_vert_offset = 0;
  155990. }
  155991. /*
  155992. * Initialize for a processing pass.
  155993. */
  155994. METHODDEF(void)
  155995. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  155996. {
  155997. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  155998. coef->iMCU_row_num = 0;
  155999. start_iMCU_row(cinfo);
  156000. switch (pass_mode) {
  156001. case JBUF_PASS_THRU:
  156002. if (coef->whole_image[0] != NULL)
  156003. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  156004. coef->pub.compress_data = compress_data;
  156005. break;
  156006. #ifdef FULL_COEF_BUFFER_SUPPORTED
  156007. case JBUF_SAVE_AND_PASS:
  156008. if (coef->whole_image[0] == NULL)
  156009. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  156010. coef->pub.compress_data = compress_first_pass;
  156011. break;
  156012. case JBUF_CRANK_DEST:
  156013. if (coef->whole_image[0] == NULL)
  156014. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  156015. coef->pub.compress_data = compress_output;
  156016. break;
  156017. #endif
  156018. default:
  156019. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  156020. break;
  156021. }
  156022. }
  156023. /*
  156024. * Process some data in the single-pass case.
  156025. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  156026. * per call, ie, v_samp_factor block rows for each component in the image.
  156027. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  156028. *
  156029. * NB: input_buf contains a plane for each component in image,
  156030. * which we index according to the component's SOF position.
  156031. */
  156032. METHODDEF(boolean)
  156033. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  156034. {
  156035. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  156036. JDIMENSION MCU_col_num; /* index of current MCU within row */
  156037. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  156038. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  156039. int blkn, bi, ci, yindex, yoffset, blockcnt;
  156040. JDIMENSION ypos, xpos;
  156041. jpeg_component_info *compptr;
  156042. /* Loop to write as much as one whole iMCU row */
  156043. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  156044. yoffset++) {
  156045. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  156046. MCU_col_num++) {
  156047. /* Determine where data comes from in input_buf and do the DCT thing.
  156048. * Each call on forward_DCT processes a horizontal row of DCT blocks
  156049. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  156050. * sequentially. Dummy blocks at the right or bottom edge are filled in
  156051. * specially. The data in them does not matter for image reconstruction,
  156052. * so we fill them with values that will encode to the smallest amount of
  156053. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  156054. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  156055. */
  156056. blkn = 0;
  156057. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  156058. compptr = cinfo->cur_comp_info[ci];
  156059. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  156060. : compptr->last_col_width;
  156061. xpos = MCU_col_num * compptr->MCU_sample_width;
  156062. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  156063. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  156064. if (coef->iMCU_row_num < last_iMCU_row ||
  156065. yoffset+yindex < compptr->last_row_height) {
  156066. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  156067. input_buf[compptr->component_index],
  156068. coef->MCU_buffer[blkn],
  156069. ypos, xpos, (JDIMENSION) blockcnt);
  156070. if (blockcnt < compptr->MCU_width) {
  156071. /* Create some dummy blocks at the right edge of the image. */
  156072. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  156073. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  156074. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  156075. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  156076. }
  156077. }
  156078. } else {
  156079. /* Create a row of dummy blocks at the bottom of the image. */
  156080. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  156081. compptr->MCU_width * SIZEOF(JBLOCK));
  156082. for (bi = 0; bi < compptr->MCU_width; bi++) {
  156083. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  156084. }
  156085. }
  156086. blkn += compptr->MCU_width;
  156087. ypos += DCTSIZE;
  156088. }
  156089. }
  156090. /* Try to write the MCU. In event of a suspension failure, we will
  156091. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  156092. */
  156093. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  156094. /* Suspension forced; update state counters and exit */
  156095. coef->MCU_vert_offset = yoffset;
  156096. coef->mcu_ctr = MCU_col_num;
  156097. return FALSE;
  156098. }
  156099. }
  156100. /* Completed an MCU row, but perhaps not an iMCU row */
  156101. coef->mcu_ctr = 0;
  156102. }
  156103. /* Completed the iMCU row, advance counters for next one */
  156104. coef->iMCU_row_num++;
  156105. start_iMCU_row(cinfo);
  156106. return TRUE;
  156107. }
  156108. #ifdef FULL_COEF_BUFFER_SUPPORTED
  156109. /*
  156110. * Process some data in the first pass of a multi-pass case.
  156111. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  156112. * per call, ie, v_samp_factor block rows for each component in the image.
  156113. * This amount of data is read from the source buffer, DCT'd and quantized,
  156114. * and saved into the virtual arrays. We also generate suitable dummy blocks
  156115. * as needed at the right and lower edges. (The dummy blocks are constructed
  156116. * in the virtual arrays, which have been padded appropriately.) This makes
  156117. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  156118. *
  156119. * We must also emit the data to the entropy encoder. This is conveniently
  156120. * done by calling compress_output() after we've loaded the current strip
  156121. * of the virtual arrays.
  156122. *
  156123. * NB: input_buf contains a plane for each component in image. All
  156124. * components are DCT'd and loaded into the virtual arrays in this pass.
  156125. * However, it may be that only a subset of the components are emitted to
  156126. * the entropy encoder during this first pass; be careful about looking
  156127. * at the scan-dependent variables (MCU dimensions, etc).
  156128. */
  156129. METHODDEF(boolean)
  156130. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  156131. {
  156132. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  156133. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  156134. JDIMENSION blocks_across, MCUs_across, MCUindex;
  156135. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  156136. JCOEF lastDC;
  156137. jpeg_component_info *compptr;
  156138. JBLOCKARRAY buffer;
  156139. JBLOCKROW thisblockrow, lastblockrow;
  156140. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  156141. ci++, compptr++) {
  156142. /* Align the virtual buffer for this component. */
  156143. buffer = (*cinfo->mem->access_virt_barray)
  156144. ((j_common_ptr) cinfo, coef->whole_image[ci],
  156145. coef->iMCU_row_num * compptr->v_samp_factor,
  156146. (JDIMENSION) compptr->v_samp_factor, TRUE);
  156147. /* Count non-dummy DCT block rows in this iMCU row. */
  156148. if (coef->iMCU_row_num < last_iMCU_row)
  156149. block_rows = compptr->v_samp_factor;
  156150. else {
  156151. /* NB: can't use last_row_height here, since may not be set! */
  156152. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  156153. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  156154. }
  156155. blocks_across = compptr->width_in_blocks;
  156156. h_samp_factor = compptr->h_samp_factor;
  156157. /* Count number of dummy blocks to be added at the right margin. */
  156158. ndummy = (int) (blocks_across % h_samp_factor);
  156159. if (ndummy > 0)
  156160. ndummy = h_samp_factor - ndummy;
  156161. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  156162. * on forward_DCT processes a complete horizontal row of DCT blocks.
  156163. */
  156164. for (block_row = 0; block_row < block_rows; block_row++) {
  156165. thisblockrow = buffer[block_row];
  156166. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  156167. input_buf[ci], thisblockrow,
  156168. (JDIMENSION) (block_row * DCTSIZE),
  156169. (JDIMENSION) 0, blocks_across);
  156170. if (ndummy > 0) {
  156171. /* Create dummy blocks at the right edge of the image. */
  156172. thisblockrow += blocks_across; /* => first dummy block */
  156173. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  156174. lastDC = thisblockrow[-1][0];
  156175. for (bi = 0; bi < ndummy; bi++) {
  156176. thisblockrow[bi][0] = lastDC;
  156177. }
  156178. }
  156179. }
  156180. /* If at end of image, create dummy block rows as needed.
  156181. * The tricky part here is that within each MCU, we want the DC values
  156182. * of the dummy blocks to match the last real block's DC value.
  156183. * This squeezes a few more bytes out of the resulting file...
  156184. */
  156185. if (coef->iMCU_row_num == last_iMCU_row) {
  156186. blocks_across += ndummy; /* include lower right corner */
  156187. MCUs_across = blocks_across / h_samp_factor;
  156188. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  156189. block_row++) {
  156190. thisblockrow = buffer[block_row];
  156191. lastblockrow = buffer[block_row-1];
  156192. jzero_far((void FAR *) thisblockrow,
  156193. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  156194. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  156195. lastDC = lastblockrow[h_samp_factor-1][0];
  156196. for (bi = 0; bi < h_samp_factor; bi++) {
  156197. thisblockrow[bi][0] = lastDC;
  156198. }
  156199. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  156200. lastblockrow += h_samp_factor;
  156201. }
  156202. }
  156203. }
  156204. }
  156205. /* NB: compress_output will increment iMCU_row_num if successful.
  156206. * A suspension return will result in redoing all the work above next time.
  156207. */
  156208. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  156209. return compress_output(cinfo, input_buf);
  156210. }
  156211. /*
  156212. * Process some data in subsequent passes of a multi-pass case.
  156213. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  156214. * per call, ie, v_samp_factor block rows for each component in the scan.
  156215. * The data is obtained from the virtual arrays and fed to the entropy coder.
  156216. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  156217. *
  156218. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  156219. */
  156220. METHODDEF(boolean)
  156221. compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  156222. {
  156223. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  156224. JDIMENSION MCU_col_num; /* index of current MCU within row */
  156225. int blkn, ci, xindex, yindex, yoffset;
  156226. JDIMENSION start_col;
  156227. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  156228. JBLOCKROW buffer_ptr;
  156229. jpeg_component_info *compptr;
  156230. /* Align the virtual buffers for the components used in this scan.
  156231. * NB: during first pass, this is safe only because the buffers will
  156232. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  156233. */
  156234. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  156235. compptr = cinfo->cur_comp_info[ci];
  156236. buffer[ci] = (*cinfo->mem->access_virt_barray)
  156237. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  156238. coef->iMCU_row_num * compptr->v_samp_factor,
  156239. (JDIMENSION) compptr->v_samp_factor, FALSE);
  156240. }
  156241. /* Loop to process one whole iMCU row */
  156242. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  156243. yoffset++) {
  156244. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  156245. MCU_col_num++) {
  156246. /* Construct list of pointers to DCT blocks belonging to this MCU */
  156247. blkn = 0; /* index of current DCT block within MCU */
  156248. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  156249. compptr = cinfo->cur_comp_info[ci];
  156250. start_col = MCU_col_num * compptr->MCU_width;
  156251. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  156252. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  156253. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  156254. coef->MCU_buffer[blkn++] = buffer_ptr++;
  156255. }
  156256. }
  156257. }
  156258. /* Try to write the MCU. */
  156259. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  156260. /* Suspension forced; update state counters and exit */
  156261. coef->MCU_vert_offset = yoffset;
  156262. coef->mcu_ctr = MCU_col_num;
  156263. return FALSE;
  156264. }
  156265. }
  156266. /* Completed an MCU row, but perhaps not an iMCU row */
  156267. coef->mcu_ctr = 0;
  156268. }
  156269. /* Completed the iMCU row, advance counters for next one */
  156270. coef->iMCU_row_num++;
  156271. start_iMCU_row(cinfo);
  156272. return TRUE;
  156273. }
  156274. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  156275. /*
  156276. * Initialize coefficient buffer controller.
  156277. */
  156278. GLOBAL(void)
  156279. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  156280. {
  156281. my_coef_ptr coef;
  156282. coef = (my_coef_ptr)
  156283. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156284. SIZEOF(my_coef_controller));
  156285. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  156286. coef->pub.start_pass = start_pass_coef;
  156287. /* Create the coefficient buffer. */
  156288. if (need_full_buffer) {
  156289. #ifdef FULL_COEF_BUFFER_SUPPORTED
  156290. /* Allocate a full-image virtual array for each component, */
  156291. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  156292. int ci;
  156293. jpeg_component_info *compptr;
  156294. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  156295. ci++, compptr++) {
  156296. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  156297. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  156298. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  156299. (long) compptr->h_samp_factor),
  156300. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  156301. (long) compptr->v_samp_factor),
  156302. (JDIMENSION) compptr->v_samp_factor);
  156303. }
  156304. #else
  156305. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  156306. #endif
  156307. } else {
  156308. /* We only need a single-MCU buffer. */
  156309. JBLOCKROW buffer;
  156310. int i;
  156311. buffer = (JBLOCKROW)
  156312. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156313. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  156314. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  156315. coef->MCU_buffer[i] = buffer + i;
  156316. }
  156317. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  156318. }
  156319. }
  156320. /********* End of inlined file: jccoefct.c *********/
  156321. /********* Start of inlined file: jccolor.c *********/
  156322. #define JPEG_INTERNALS
  156323. /* Private subobject */
  156324. typedef struct {
  156325. struct jpeg_color_converter pub; /* public fields */
  156326. /* Private state for RGB->YCC conversion */
  156327. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  156328. } my_color_converter;
  156329. typedef my_color_converter * my_cconvert_ptr;
  156330. /**************** RGB -> YCbCr conversion: most common case **************/
  156331. /*
  156332. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  156333. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  156334. * The conversion equations to be implemented are therefore
  156335. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  156336. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  156337. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  156338. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  156339. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  156340. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  156341. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  156342. * were not represented exactly. Now we sacrifice exact representation of
  156343. * maximum red and maximum blue in order to get exact grayscales.
  156344. *
  156345. * To avoid floating-point arithmetic, we represent the fractional constants
  156346. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  156347. * the products by 2^16, with appropriate rounding, to get the correct answer.
  156348. *
  156349. * For even more speed, we avoid doing any multiplications in the inner loop
  156350. * by precalculating the constants times R,G,B for all possible values.
  156351. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  156352. * for 12-bit samples it is still acceptable. It's not very reasonable for
  156353. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  156354. * colorspace anyway.
  156355. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  156356. * in the tables to save adding them separately in the inner loop.
  156357. */
  156358. #define SCALEBITS 16 /* speediest right-shift on some machines */
  156359. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  156360. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  156361. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  156362. /* We allocate one big table and divide it up into eight parts, instead of
  156363. * doing eight alloc_small requests. This lets us use a single table base
  156364. * address, which can be held in a register in the inner loops on many
  156365. * machines (more than can hold all eight addresses, anyway).
  156366. */
  156367. #define R_Y_OFF 0 /* offset to R => Y section */
  156368. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  156369. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  156370. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  156371. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  156372. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  156373. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  156374. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  156375. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  156376. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  156377. /*
  156378. * Initialize for RGB->YCC colorspace conversion.
  156379. */
  156380. METHODDEF(void)
  156381. rgb_ycc_start (j_compress_ptr cinfo)
  156382. {
  156383. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  156384. INT32 * rgb_ycc_tab;
  156385. INT32 i;
  156386. /* Allocate and fill in the conversion tables. */
  156387. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  156388. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156389. (TABLE_SIZE * SIZEOF(INT32)));
  156390. for (i = 0; i <= MAXJSAMPLE; i++) {
  156391. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  156392. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  156393. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  156394. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  156395. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  156396. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  156397. * This ensures that the maximum output will round to MAXJSAMPLE
  156398. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  156399. */
  156400. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  156401. /* B=>Cb and R=>Cr tables are the same
  156402. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  156403. */
  156404. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  156405. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  156406. }
  156407. }
  156408. /*
  156409. * Convert some rows of samples to the JPEG colorspace.
  156410. *
  156411. * Note that we change from the application's interleaved-pixel format
  156412. * to our internal noninterleaved, one-plane-per-component format.
  156413. * The input buffer is therefore three times as wide as the output buffer.
  156414. *
  156415. * A starting row offset is provided only for the output buffer. The caller
  156416. * can easily adjust the passed input_buf value to accommodate any row
  156417. * offset required on that side.
  156418. */
  156419. METHODDEF(void)
  156420. rgb_ycc_convert (j_compress_ptr cinfo,
  156421. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  156422. JDIMENSION output_row, int num_rows)
  156423. {
  156424. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  156425. register int r, g, b;
  156426. register INT32 * ctab = cconvert->rgb_ycc_tab;
  156427. register JSAMPROW inptr;
  156428. register JSAMPROW outptr0, outptr1, outptr2;
  156429. register JDIMENSION col;
  156430. JDIMENSION num_cols = cinfo->image_width;
  156431. while (--num_rows >= 0) {
  156432. inptr = *input_buf++;
  156433. outptr0 = output_buf[0][output_row];
  156434. outptr1 = output_buf[1][output_row];
  156435. outptr2 = output_buf[2][output_row];
  156436. output_row++;
  156437. for (col = 0; col < num_cols; col++) {
  156438. r = GETJSAMPLE(inptr[RGB_RED]);
  156439. g = GETJSAMPLE(inptr[RGB_GREEN]);
  156440. b = GETJSAMPLE(inptr[RGB_BLUE]);
  156441. inptr += RGB_PIXELSIZE;
  156442. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  156443. * must be too; we do not need an explicit range-limiting operation.
  156444. * Hence the value being shifted is never negative, and we don't
  156445. * need the general RIGHT_SHIFT macro.
  156446. */
  156447. /* Y */
  156448. outptr0[col] = (JSAMPLE)
  156449. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  156450. >> SCALEBITS);
  156451. /* Cb */
  156452. outptr1[col] = (JSAMPLE)
  156453. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  156454. >> SCALEBITS);
  156455. /* Cr */
  156456. outptr2[col] = (JSAMPLE)
  156457. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  156458. >> SCALEBITS);
  156459. }
  156460. }
  156461. }
  156462. /**************** Cases other than RGB -> YCbCr **************/
  156463. /*
  156464. * Convert some rows of samples to the JPEG colorspace.
  156465. * This version handles RGB->grayscale conversion, which is the same
  156466. * as the RGB->Y portion of RGB->YCbCr.
  156467. * We assume rgb_ycc_start has been called (we only use the Y tables).
  156468. */
  156469. METHODDEF(void)
  156470. rgb_gray_convert (j_compress_ptr cinfo,
  156471. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  156472. JDIMENSION output_row, int num_rows)
  156473. {
  156474. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  156475. register int r, g, b;
  156476. register INT32 * ctab = cconvert->rgb_ycc_tab;
  156477. register JSAMPROW inptr;
  156478. register JSAMPROW outptr;
  156479. register JDIMENSION col;
  156480. JDIMENSION num_cols = cinfo->image_width;
  156481. while (--num_rows >= 0) {
  156482. inptr = *input_buf++;
  156483. outptr = output_buf[0][output_row];
  156484. output_row++;
  156485. for (col = 0; col < num_cols; col++) {
  156486. r = GETJSAMPLE(inptr[RGB_RED]);
  156487. g = GETJSAMPLE(inptr[RGB_GREEN]);
  156488. b = GETJSAMPLE(inptr[RGB_BLUE]);
  156489. inptr += RGB_PIXELSIZE;
  156490. /* Y */
  156491. outptr[col] = (JSAMPLE)
  156492. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  156493. >> SCALEBITS);
  156494. }
  156495. }
  156496. }
  156497. /*
  156498. * Convert some rows of samples to the JPEG colorspace.
  156499. * This version handles Adobe-style CMYK->YCCK conversion,
  156500. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  156501. * conversion as above, while passing K (black) unchanged.
  156502. * We assume rgb_ycc_start has been called.
  156503. */
  156504. METHODDEF(void)
  156505. cmyk_ycck_convert (j_compress_ptr cinfo,
  156506. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  156507. JDIMENSION output_row, int num_rows)
  156508. {
  156509. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  156510. register int r, g, b;
  156511. register INT32 * ctab = cconvert->rgb_ycc_tab;
  156512. register JSAMPROW inptr;
  156513. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  156514. register JDIMENSION col;
  156515. JDIMENSION num_cols = cinfo->image_width;
  156516. while (--num_rows >= 0) {
  156517. inptr = *input_buf++;
  156518. outptr0 = output_buf[0][output_row];
  156519. outptr1 = output_buf[1][output_row];
  156520. outptr2 = output_buf[2][output_row];
  156521. outptr3 = output_buf[3][output_row];
  156522. output_row++;
  156523. for (col = 0; col < num_cols; col++) {
  156524. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  156525. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  156526. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  156527. /* K passes through as-is */
  156528. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  156529. inptr += 4;
  156530. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  156531. * must be too; we do not need an explicit range-limiting operation.
  156532. * Hence the value being shifted is never negative, and we don't
  156533. * need the general RIGHT_SHIFT macro.
  156534. */
  156535. /* Y */
  156536. outptr0[col] = (JSAMPLE)
  156537. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  156538. >> SCALEBITS);
  156539. /* Cb */
  156540. outptr1[col] = (JSAMPLE)
  156541. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  156542. >> SCALEBITS);
  156543. /* Cr */
  156544. outptr2[col] = (JSAMPLE)
  156545. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  156546. >> SCALEBITS);
  156547. }
  156548. }
  156549. }
  156550. /*
  156551. * Convert some rows of samples to the JPEG colorspace.
  156552. * This version handles grayscale output with no conversion.
  156553. * The source can be either plain grayscale or YCbCr (since Y == gray).
  156554. */
  156555. METHODDEF(void)
  156556. grayscale_convert (j_compress_ptr cinfo,
  156557. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  156558. JDIMENSION output_row, int num_rows)
  156559. {
  156560. register JSAMPROW inptr;
  156561. register JSAMPROW outptr;
  156562. register JDIMENSION col;
  156563. JDIMENSION num_cols = cinfo->image_width;
  156564. int instride = cinfo->input_components;
  156565. while (--num_rows >= 0) {
  156566. inptr = *input_buf++;
  156567. outptr = output_buf[0][output_row];
  156568. output_row++;
  156569. for (col = 0; col < num_cols; col++) {
  156570. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  156571. inptr += instride;
  156572. }
  156573. }
  156574. }
  156575. /*
  156576. * Convert some rows of samples to the JPEG colorspace.
  156577. * This version handles multi-component colorspaces without conversion.
  156578. * We assume input_components == num_components.
  156579. */
  156580. METHODDEF(void)
  156581. null_convert (j_compress_ptr cinfo,
  156582. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  156583. JDIMENSION output_row, int num_rows)
  156584. {
  156585. register JSAMPROW inptr;
  156586. register JSAMPROW outptr;
  156587. register JDIMENSION col;
  156588. register int ci;
  156589. int nc = cinfo->num_components;
  156590. JDIMENSION num_cols = cinfo->image_width;
  156591. while (--num_rows >= 0) {
  156592. /* It seems fastest to make a separate pass for each component. */
  156593. for (ci = 0; ci < nc; ci++) {
  156594. inptr = *input_buf;
  156595. outptr = output_buf[ci][output_row];
  156596. for (col = 0; col < num_cols; col++) {
  156597. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  156598. inptr += nc;
  156599. }
  156600. }
  156601. input_buf++;
  156602. output_row++;
  156603. }
  156604. }
  156605. /*
  156606. * Empty method for start_pass.
  156607. */
  156608. METHODDEF(void)
  156609. null_method (j_compress_ptr cinfo)
  156610. {
  156611. /* no work needed */
  156612. }
  156613. /*
  156614. * Module initialization routine for input colorspace conversion.
  156615. */
  156616. GLOBAL(void)
  156617. jinit_color_converter (j_compress_ptr cinfo)
  156618. {
  156619. my_cconvert_ptr cconvert;
  156620. cconvert = (my_cconvert_ptr)
  156621. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156622. SIZEOF(my_color_converter));
  156623. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  156624. /* set start_pass to null method until we find out differently */
  156625. cconvert->pub.start_pass = null_method;
  156626. /* Make sure input_components agrees with in_color_space */
  156627. switch (cinfo->in_color_space) {
  156628. case JCS_GRAYSCALE:
  156629. if (cinfo->input_components != 1)
  156630. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  156631. break;
  156632. case JCS_RGB:
  156633. #if RGB_PIXELSIZE != 3
  156634. if (cinfo->input_components != RGB_PIXELSIZE)
  156635. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  156636. break;
  156637. #endif /* else share code with YCbCr */
  156638. case JCS_YCbCr:
  156639. if (cinfo->input_components != 3)
  156640. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  156641. break;
  156642. case JCS_CMYK:
  156643. case JCS_YCCK:
  156644. if (cinfo->input_components != 4)
  156645. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  156646. break;
  156647. default: /* JCS_UNKNOWN can be anything */
  156648. if (cinfo->input_components < 1)
  156649. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  156650. break;
  156651. }
  156652. /* Check num_components, set conversion method based on requested space */
  156653. switch (cinfo->jpeg_color_space) {
  156654. case JCS_GRAYSCALE:
  156655. if (cinfo->num_components != 1)
  156656. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  156657. if (cinfo->in_color_space == JCS_GRAYSCALE)
  156658. cconvert->pub.color_convert = grayscale_convert;
  156659. else if (cinfo->in_color_space == JCS_RGB) {
  156660. cconvert->pub.start_pass = rgb_ycc_start;
  156661. cconvert->pub.color_convert = rgb_gray_convert;
  156662. } else if (cinfo->in_color_space == JCS_YCbCr)
  156663. cconvert->pub.color_convert = grayscale_convert;
  156664. else
  156665. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  156666. break;
  156667. case JCS_RGB:
  156668. if (cinfo->num_components != 3)
  156669. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  156670. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  156671. cconvert->pub.color_convert = null_convert;
  156672. else
  156673. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  156674. break;
  156675. case JCS_YCbCr:
  156676. if (cinfo->num_components != 3)
  156677. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  156678. if (cinfo->in_color_space == JCS_RGB) {
  156679. cconvert->pub.start_pass = rgb_ycc_start;
  156680. cconvert->pub.color_convert = rgb_ycc_convert;
  156681. } else if (cinfo->in_color_space == JCS_YCbCr)
  156682. cconvert->pub.color_convert = null_convert;
  156683. else
  156684. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  156685. break;
  156686. case JCS_CMYK:
  156687. if (cinfo->num_components != 4)
  156688. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  156689. if (cinfo->in_color_space == JCS_CMYK)
  156690. cconvert->pub.color_convert = null_convert;
  156691. else
  156692. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  156693. break;
  156694. case JCS_YCCK:
  156695. if (cinfo->num_components != 4)
  156696. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  156697. if (cinfo->in_color_space == JCS_CMYK) {
  156698. cconvert->pub.start_pass = rgb_ycc_start;
  156699. cconvert->pub.color_convert = cmyk_ycck_convert;
  156700. } else if (cinfo->in_color_space == JCS_YCCK)
  156701. cconvert->pub.color_convert = null_convert;
  156702. else
  156703. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  156704. break;
  156705. default: /* allow null conversion of JCS_UNKNOWN */
  156706. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  156707. cinfo->num_components != cinfo->input_components)
  156708. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  156709. cconvert->pub.color_convert = null_convert;
  156710. break;
  156711. }
  156712. }
  156713. /********* End of inlined file: jccolor.c *********/
  156714. #undef FIX
  156715. /********* Start of inlined file: jcdctmgr.c *********/
  156716. #define JPEG_INTERNALS
  156717. /********* Start of inlined file: jdct.h *********/
  156718. /*
  156719. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  156720. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  156721. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  156722. * implementations use an array of type FAST_FLOAT, instead.)
  156723. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  156724. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  156725. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  156726. * convention improves accuracy in integer implementations and saves some
  156727. * work in floating-point ones.
  156728. * Quantization of the output coefficients is done by jcdctmgr.c.
  156729. */
  156730. #ifndef __jdct_h__
  156731. #define __jdct_h__
  156732. #if BITS_IN_JSAMPLE == 8
  156733. typedef int DCTELEM; /* 16 or 32 bits is fine */
  156734. #else
  156735. typedef INT32 DCTELEM; /* must have 32 bits */
  156736. #endif
  156737. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  156738. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  156739. /*
  156740. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  156741. * to an output sample array. The routine must dequantize the input data as
  156742. * well as perform the IDCT; for dequantization, it uses the multiplier table
  156743. * pointed to by compptr->dct_table. The output data is to be placed into the
  156744. * sample array starting at a specified column. (Any row offset needed will
  156745. * be applied to the array pointer before it is passed to the IDCT code.)
  156746. * Note that the number of samples emitted by the IDCT routine is
  156747. * DCT_scaled_size * DCT_scaled_size.
  156748. */
  156749. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  156750. /*
  156751. * Each IDCT routine has its own ideas about the best dct_table element type.
  156752. */
  156753. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  156754. #if BITS_IN_JSAMPLE == 8
  156755. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  156756. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  156757. #else
  156758. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  156759. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  156760. #endif
  156761. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  156762. /*
  156763. * Each IDCT routine is responsible for range-limiting its results and
  156764. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  156765. * be quite far out of range if the input data is corrupt, so a bulletproof
  156766. * range-limiting step is required. We use a mask-and-table-lookup method
  156767. * to do the combined operations quickly. See the comments with
  156768. * prepare_range_limit_table (in jdmaster.c) for more info.
  156769. */
  156770. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  156771. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  156772. /* Short forms of external names for systems with brain-damaged linkers. */
  156773. #ifdef NEED_SHORT_EXTERNAL_NAMES
  156774. #define jpeg_fdct_islow jFDislow
  156775. #define jpeg_fdct_ifast jFDifast
  156776. #define jpeg_fdct_float jFDfloat
  156777. #define jpeg_idct_islow jRDislow
  156778. #define jpeg_idct_ifast jRDifast
  156779. #define jpeg_idct_float jRDfloat
  156780. #define jpeg_idct_4x4 jRD4x4
  156781. #define jpeg_idct_2x2 jRD2x2
  156782. #define jpeg_idct_1x1 jRD1x1
  156783. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  156784. /* Extern declarations for the forward and inverse DCT routines. */
  156785. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  156786. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  156787. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  156788. EXTERN(void) jpeg_idct_islow
  156789. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156790. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156791. EXTERN(void) jpeg_idct_ifast
  156792. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156793. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156794. EXTERN(void) jpeg_idct_float
  156795. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156796. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156797. EXTERN(void) jpeg_idct_4x4
  156798. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156799. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156800. EXTERN(void) jpeg_idct_2x2
  156801. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156802. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156803. EXTERN(void) jpeg_idct_1x1
  156804. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156805. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156806. /*
  156807. * Macros for handling fixed-point arithmetic; these are used by many
  156808. * but not all of the DCT/IDCT modules.
  156809. *
  156810. * All values are expected to be of type INT32.
  156811. * Fractional constants are scaled left by CONST_BITS bits.
  156812. * CONST_BITS is defined within each module using these macros,
  156813. * and may differ from one module to the next.
  156814. */
  156815. #define ONE ((INT32) 1)
  156816. #define CONST_SCALE (ONE << CONST_BITS)
  156817. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  156818. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  156819. * thus causing a lot of useless floating-point operations at run time.
  156820. */
  156821. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  156822. /* Descale and correctly round an INT32 value that's scaled by N bits.
  156823. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  156824. * the fudge factor is correct for either sign of X.
  156825. */
  156826. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  156827. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  156828. * This macro is used only when the two inputs will actually be no more than
  156829. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  156830. * full 32x32 multiply. This provides a useful speedup on many machines.
  156831. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  156832. * in C, but some C compilers will do the right thing if you provide the
  156833. * correct combination of casts.
  156834. */
  156835. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  156836. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  156837. #endif
  156838. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  156839. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  156840. #endif
  156841. #ifndef MULTIPLY16C16 /* default definition */
  156842. #define MULTIPLY16C16(var,const) ((var) * (const))
  156843. #endif
  156844. /* Same except both inputs are variables. */
  156845. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  156846. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  156847. #endif
  156848. #ifndef MULTIPLY16V16 /* default definition */
  156849. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  156850. #endif
  156851. #endif
  156852. /********* End of inlined file: jdct.h *********/
  156853. /* Private declarations for DCT subsystem */
  156854. /* Private subobject for this module */
  156855. typedef struct {
  156856. struct jpeg_forward_dct pub; /* public fields */
  156857. /* Pointer to the DCT routine actually in use */
  156858. forward_DCT_method_ptr do_dct;
  156859. /* The actual post-DCT divisors --- not identical to the quant table
  156860. * entries, because of scaling (especially for an unnormalized DCT).
  156861. * Each table is given in normal array order.
  156862. */
  156863. DCTELEM * divisors[NUM_QUANT_TBLS];
  156864. #ifdef DCT_FLOAT_SUPPORTED
  156865. /* Same as above for the floating-point case. */
  156866. float_DCT_method_ptr do_float_dct;
  156867. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  156868. #endif
  156869. } my_fdct_controller;
  156870. typedef my_fdct_controller * my_fdct_ptr;
  156871. /*
  156872. * Initialize for a processing pass.
  156873. * Verify that all referenced Q-tables are present, and set up
  156874. * the divisor table for each one.
  156875. * In the current implementation, DCT of all components is done during
  156876. * the first pass, even if only some components will be output in the
  156877. * first scan. Hence all components should be examined here.
  156878. */
  156879. METHODDEF(void)
  156880. start_pass_fdctmgr (j_compress_ptr cinfo)
  156881. {
  156882. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  156883. int ci, qtblno, i;
  156884. jpeg_component_info *compptr;
  156885. JQUANT_TBL * qtbl;
  156886. DCTELEM * dtbl;
  156887. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  156888. ci++, compptr++) {
  156889. qtblno = compptr->quant_tbl_no;
  156890. /* Make sure specified quantization table is present */
  156891. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  156892. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  156893. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  156894. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  156895. /* Compute divisors for this quant table */
  156896. /* We may do this more than once for same table, but it's not a big deal */
  156897. switch (cinfo->dct_method) {
  156898. #ifdef DCT_ISLOW_SUPPORTED
  156899. case JDCT_ISLOW:
  156900. /* For LL&M IDCT method, divisors are equal to raw quantization
  156901. * coefficients multiplied by 8 (to counteract scaling).
  156902. */
  156903. if (fdct->divisors[qtblno] == NULL) {
  156904. fdct->divisors[qtblno] = (DCTELEM *)
  156905. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156906. DCTSIZE2 * SIZEOF(DCTELEM));
  156907. }
  156908. dtbl = fdct->divisors[qtblno];
  156909. for (i = 0; i < DCTSIZE2; i++) {
  156910. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  156911. }
  156912. break;
  156913. #endif
  156914. #ifdef DCT_IFAST_SUPPORTED
  156915. case JDCT_IFAST:
  156916. {
  156917. /* For AA&N IDCT method, divisors are equal to quantization
  156918. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  156919. * scalefactor[0] = 1
  156920. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  156921. * We apply a further scale factor of 8.
  156922. */
  156923. #define CONST_BITS 14
  156924. static const INT16 aanscales[DCTSIZE2] = {
  156925. /* precomputed values scaled up by 14 bits */
  156926. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  156927. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  156928. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  156929. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  156930. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  156931. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  156932. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  156933. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  156934. };
  156935. SHIFT_TEMPS
  156936. if (fdct->divisors[qtblno] == NULL) {
  156937. fdct->divisors[qtblno] = (DCTELEM *)
  156938. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156939. DCTSIZE2 * SIZEOF(DCTELEM));
  156940. }
  156941. dtbl = fdct->divisors[qtblno];
  156942. for (i = 0; i < DCTSIZE2; i++) {
  156943. dtbl[i] = (DCTELEM)
  156944. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  156945. (INT32) aanscales[i]),
  156946. CONST_BITS-3);
  156947. }
  156948. }
  156949. break;
  156950. #endif
  156951. #ifdef DCT_FLOAT_SUPPORTED
  156952. case JDCT_FLOAT:
  156953. {
  156954. /* For float AA&N IDCT method, divisors are equal to quantization
  156955. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  156956. * scalefactor[0] = 1
  156957. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  156958. * We apply a further scale factor of 8.
  156959. * What's actually stored is 1/divisor so that the inner loop can
  156960. * use a multiplication rather than a division.
  156961. */
  156962. FAST_FLOAT * fdtbl;
  156963. int row, col;
  156964. static const double aanscalefactor[DCTSIZE] = {
  156965. 1.0, 1.387039845, 1.306562965, 1.175875602,
  156966. 1.0, 0.785694958, 0.541196100, 0.275899379
  156967. };
  156968. if (fdct->float_divisors[qtblno] == NULL) {
  156969. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  156970. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156971. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  156972. }
  156973. fdtbl = fdct->float_divisors[qtblno];
  156974. i = 0;
  156975. for (row = 0; row < DCTSIZE; row++) {
  156976. for (col = 0; col < DCTSIZE; col++) {
  156977. fdtbl[i] = (FAST_FLOAT)
  156978. (1.0 / (((double) qtbl->quantval[i] *
  156979. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  156980. i++;
  156981. }
  156982. }
  156983. }
  156984. break;
  156985. #endif
  156986. default:
  156987. ERREXIT(cinfo, JERR_NOT_COMPILED);
  156988. break;
  156989. }
  156990. }
  156991. }
  156992. /*
  156993. * Perform forward DCT on one or more blocks of a component.
  156994. *
  156995. * The input samples are taken from the sample_data[] array starting at
  156996. * position start_row/start_col, and moving to the right for any additional
  156997. * blocks. The quantized coefficients are returned in coef_blocks[].
  156998. */
  156999. METHODDEF(void)
  157000. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  157001. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  157002. JDIMENSION start_row, JDIMENSION start_col,
  157003. JDIMENSION num_blocks)
  157004. /* This version is used for integer DCT implementations. */
  157005. {
  157006. /* This routine is heavily used, so it's worth coding it tightly. */
  157007. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  157008. forward_DCT_method_ptr do_dct = fdct->do_dct;
  157009. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  157010. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  157011. JDIMENSION bi;
  157012. sample_data += start_row; /* fold in the vertical offset once */
  157013. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  157014. /* Load data into workspace, applying unsigned->signed conversion */
  157015. { register DCTELEM *workspaceptr;
  157016. register JSAMPROW elemptr;
  157017. register int elemr;
  157018. workspaceptr = workspace;
  157019. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  157020. elemptr = sample_data[elemr] + start_col;
  157021. #if DCTSIZE == 8 /* unroll the inner loop */
  157022. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157023. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157024. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157025. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157026. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157027. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157028. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157029. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157030. #else
  157031. { register int elemc;
  157032. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  157033. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157034. }
  157035. }
  157036. #endif
  157037. }
  157038. }
  157039. /* Perform the DCT */
  157040. (*do_dct) (workspace);
  157041. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  157042. { register DCTELEM temp, qval;
  157043. register int i;
  157044. register JCOEFPTR output_ptr = coef_blocks[bi];
  157045. for (i = 0; i < DCTSIZE2; i++) {
  157046. qval = divisors[i];
  157047. temp = workspace[i];
  157048. /* Divide the coefficient value by qval, ensuring proper rounding.
  157049. * Since C does not specify the direction of rounding for negative
  157050. * quotients, we have to force the dividend positive for portability.
  157051. *
  157052. * In most files, at least half of the output values will be zero
  157053. * (at default quantization settings, more like three-quarters...)
  157054. * so we should ensure that this case is fast. On many machines,
  157055. * a comparison is enough cheaper than a divide to make a special test
  157056. * a win. Since both inputs will be nonnegative, we need only test
  157057. * for a < b to discover whether a/b is 0.
  157058. * If your machine's division is fast enough, define FAST_DIVIDE.
  157059. */
  157060. #ifdef FAST_DIVIDE
  157061. #define DIVIDE_BY(a,b) a /= b
  157062. #else
  157063. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  157064. #endif
  157065. if (temp < 0) {
  157066. temp = -temp;
  157067. temp += qval>>1; /* for rounding */
  157068. DIVIDE_BY(temp, qval);
  157069. temp = -temp;
  157070. } else {
  157071. temp += qval>>1; /* for rounding */
  157072. DIVIDE_BY(temp, qval);
  157073. }
  157074. output_ptr[i] = (JCOEF) temp;
  157075. }
  157076. }
  157077. }
  157078. }
  157079. #ifdef DCT_FLOAT_SUPPORTED
  157080. METHODDEF(void)
  157081. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  157082. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  157083. JDIMENSION start_row, JDIMENSION start_col,
  157084. JDIMENSION num_blocks)
  157085. /* This version is used for floating-point DCT implementations. */
  157086. {
  157087. /* This routine is heavily used, so it's worth coding it tightly. */
  157088. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  157089. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  157090. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  157091. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  157092. JDIMENSION bi;
  157093. sample_data += start_row; /* fold in the vertical offset once */
  157094. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  157095. /* Load data into workspace, applying unsigned->signed conversion */
  157096. { register FAST_FLOAT *workspaceptr;
  157097. register JSAMPROW elemptr;
  157098. register int elemr;
  157099. workspaceptr = workspace;
  157100. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  157101. elemptr = sample_data[elemr] + start_col;
  157102. #if DCTSIZE == 8 /* unroll the inner loop */
  157103. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157104. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157105. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157106. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157107. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157108. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157109. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157110. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157111. #else
  157112. { register int elemc;
  157113. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  157114. *workspaceptr++ = (FAST_FLOAT)
  157115. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157116. }
  157117. }
  157118. #endif
  157119. }
  157120. }
  157121. /* Perform the DCT */
  157122. (*do_dct) (workspace);
  157123. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  157124. { register FAST_FLOAT temp;
  157125. register int i;
  157126. register JCOEFPTR output_ptr = coef_blocks[bi];
  157127. for (i = 0; i < DCTSIZE2; i++) {
  157128. /* Apply the quantization and scaling factor */
  157129. temp = workspace[i] * divisors[i];
  157130. /* Round to nearest integer.
  157131. * Since C does not specify the direction of rounding for negative
  157132. * quotients, we have to force the dividend positive for portability.
  157133. * The maximum coefficient size is +-16K (for 12-bit data), so this
  157134. * code should work for either 16-bit or 32-bit ints.
  157135. */
  157136. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  157137. }
  157138. }
  157139. }
  157140. }
  157141. #endif /* DCT_FLOAT_SUPPORTED */
  157142. /*
  157143. * Initialize FDCT manager.
  157144. */
  157145. GLOBAL(void)
  157146. jinit_forward_dct (j_compress_ptr cinfo)
  157147. {
  157148. my_fdct_ptr fdct;
  157149. int i;
  157150. fdct = (my_fdct_ptr)
  157151. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157152. SIZEOF(my_fdct_controller));
  157153. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  157154. fdct->pub.start_pass = start_pass_fdctmgr;
  157155. switch (cinfo->dct_method) {
  157156. #ifdef DCT_ISLOW_SUPPORTED
  157157. case JDCT_ISLOW:
  157158. fdct->pub.forward_DCT = forward_DCT;
  157159. fdct->do_dct = jpeg_fdct_islow;
  157160. break;
  157161. #endif
  157162. #ifdef DCT_IFAST_SUPPORTED
  157163. case JDCT_IFAST:
  157164. fdct->pub.forward_DCT = forward_DCT;
  157165. fdct->do_dct = jpeg_fdct_ifast;
  157166. break;
  157167. #endif
  157168. #ifdef DCT_FLOAT_SUPPORTED
  157169. case JDCT_FLOAT:
  157170. fdct->pub.forward_DCT = forward_DCT_float;
  157171. fdct->do_float_dct = jpeg_fdct_float;
  157172. break;
  157173. #endif
  157174. default:
  157175. ERREXIT(cinfo, JERR_NOT_COMPILED);
  157176. break;
  157177. }
  157178. /* Mark divisor tables unallocated */
  157179. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  157180. fdct->divisors[i] = NULL;
  157181. #ifdef DCT_FLOAT_SUPPORTED
  157182. fdct->float_divisors[i] = NULL;
  157183. #endif
  157184. }
  157185. }
  157186. /********* End of inlined file: jcdctmgr.c *********/
  157187. #undef CONST_BITS
  157188. /********* Start of inlined file: jchuff.c *********/
  157189. #define JPEG_INTERNALS
  157190. /********* Start of inlined file: jchuff.h *********/
  157191. /* The legal range of a DCT coefficient is
  157192. * -1024 .. +1023 for 8-bit data;
  157193. * -16384 .. +16383 for 12-bit data.
  157194. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  157195. */
  157196. #ifndef _jchuff_h_
  157197. #define _jchuff_h_
  157198. #if BITS_IN_JSAMPLE == 8
  157199. #define MAX_COEF_BITS 10
  157200. #else
  157201. #define MAX_COEF_BITS 14
  157202. #endif
  157203. /* Derived data constructed for each Huffman table */
  157204. typedef struct {
  157205. unsigned int ehufco[256]; /* code for each symbol */
  157206. char ehufsi[256]; /* length of code for each symbol */
  157207. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  157208. } c_derived_tbl;
  157209. /* Short forms of external names for systems with brain-damaged linkers. */
  157210. #ifdef NEED_SHORT_EXTERNAL_NAMES
  157211. #define jpeg_make_c_derived_tbl jMkCDerived
  157212. #define jpeg_gen_optimal_table jGenOptTbl
  157213. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  157214. /* Expand a Huffman table definition into the derived format */
  157215. EXTERN(void) jpeg_make_c_derived_tbl
  157216. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  157217. c_derived_tbl ** pdtbl));
  157218. /* Generate an optimal table definition given the specified counts */
  157219. EXTERN(void) jpeg_gen_optimal_table
  157220. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  157221. #endif
  157222. /********* End of inlined file: jchuff.h *********/
  157223. /* Declarations shared with jcphuff.c */
  157224. /* Expanded entropy encoder object for Huffman encoding.
  157225. *
  157226. * The savable_state subrecord contains fields that change within an MCU,
  157227. * but must not be updated permanently until we complete the MCU.
  157228. */
  157229. typedef struct {
  157230. INT32 put_buffer; /* current bit-accumulation buffer */
  157231. int put_bits; /* # of bits now in it */
  157232. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  157233. } savable_state;
  157234. /* This macro is to work around compilers with missing or broken
  157235. * structure assignment. You'll need to fix this code if you have
  157236. * such a compiler and you change MAX_COMPS_IN_SCAN.
  157237. */
  157238. #ifndef NO_STRUCT_ASSIGN
  157239. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  157240. #else
  157241. #if MAX_COMPS_IN_SCAN == 4
  157242. #define ASSIGN_STATE(dest,src) \
  157243. ((dest).put_buffer = (src).put_buffer, \
  157244. (dest).put_bits = (src).put_bits, \
  157245. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  157246. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  157247. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  157248. (dest).last_dc_val[3] = (src).last_dc_val[3])
  157249. #endif
  157250. #endif
  157251. typedef struct {
  157252. struct jpeg_entropy_encoder pub; /* public fields */
  157253. savable_state saved; /* Bit buffer & DC state at start of MCU */
  157254. /* These fields are NOT loaded into local working state. */
  157255. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  157256. int next_restart_num; /* next restart number to write (0-7) */
  157257. /* Pointers to derived tables (these workspaces have image lifespan) */
  157258. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  157259. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  157260. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  157261. long * dc_count_ptrs[NUM_HUFF_TBLS];
  157262. long * ac_count_ptrs[NUM_HUFF_TBLS];
  157263. #endif
  157264. } huff_entropy_encoder;
  157265. typedef huff_entropy_encoder * huff_entropy_ptr;
  157266. /* Working state while writing an MCU.
  157267. * This struct contains all the fields that are needed by subroutines.
  157268. */
  157269. typedef struct {
  157270. JOCTET * next_output_byte; /* => next byte to write in buffer */
  157271. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  157272. savable_state cur; /* Current bit buffer & DC state */
  157273. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  157274. } working_state;
  157275. /* Forward declarations */
  157276. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  157277. JBLOCKROW *MCU_data));
  157278. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  157279. #ifdef ENTROPY_OPT_SUPPORTED
  157280. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  157281. JBLOCKROW *MCU_data));
  157282. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  157283. #endif
  157284. /*
  157285. * Initialize for a Huffman-compressed scan.
  157286. * If gather_statistics is TRUE, we do not output anything during the scan,
  157287. * just count the Huffman symbols used and generate Huffman code tables.
  157288. */
  157289. METHODDEF(void)
  157290. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  157291. {
  157292. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  157293. int ci, dctbl, actbl;
  157294. jpeg_component_info * compptr;
  157295. if (gather_statistics) {
  157296. #ifdef ENTROPY_OPT_SUPPORTED
  157297. entropy->pub.encode_mcu = encode_mcu_gather;
  157298. entropy->pub.finish_pass = finish_pass_gather;
  157299. #else
  157300. ERREXIT(cinfo, JERR_NOT_COMPILED);
  157301. #endif
  157302. } else {
  157303. entropy->pub.encode_mcu = encode_mcu_huff;
  157304. entropy->pub.finish_pass = finish_pass_huff;
  157305. }
  157306. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157307. compptr = cinfo->cur_comp_info[ci];
  157308. dctbl = compptr->dc_tbl_no;
  157309. actbl = compptr->ac_tbl_no;
  157310. if (gather_statistics) {
  157311. #ifdef ENTROPY_OPT_SUPPORTED
  157312. /* Check for invalid table indexes */
  157313. /* (make_c_derived_tbl does this in the other path) */
  157314. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  157315. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  157316. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  157317. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  157318. /* Allocate and zero the statistics tables */
  157319. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  157320. if (entropy->dc_count_ptrs[dctbl] == NULL)
  157321. entropy->dc_count_ptrs[dctbl] = (long *)
  157322. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157323. 257 * SIZEOF(long));
  157324. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  157325. if (entropy->ac_count_ptrs[actbl] == NULL)
  157326. entropy->ac_count_ptrs[actbl] = (long *)
  157327. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157328. 257 * SIZEOF(long));
  157329. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  157330. #endif
  157331. } else {
  157332. /* Compute derived values for Huffman tables */
  157333. /* We may do this more than once for a table, but it's not expensive */
  157334. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  157335. & entropy->dc_derived_tbls[dctbl]);
  157336. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  157337. & entropy->ac_derived_tbls[actbl]);
  157338. }
  157339. /* Initialize DC predictions to 0 */
  157340. entropy->saved.last_dc_val[ci] = 0;
  157341. }
  157342. /* Initialize bit buffer to empty */
  157343. entropy->saved.put_buffer = 0;
  157344. entropy->saved.put_bits = 0;
  157345. /* Initialize restart stuff */
  157346. entropy->restarts_to_go = cinfo->restart_interval;
  157347. entropy->next_restart_num = 0;
  157348. }
  157349. /*
  157350. * Compute the derived values for a Huffman table.
  157351. * This routine also performs some validation checks on the table.
  157352. *
  157353. * Note this is also used by jcphuff.c.
  157354. */
  157355. GLOBAL(void)
  157356. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  157357. c_derived_tbl ** pdtbl)
  157358. {
  157359. JHUFF_TBL *htbl;
  157360. c_derived_tbl *dtbl;
  157361. int p, i, l, lastp, si, maxsymbol;
  157362. char huffsize[257];
  157363. unsigned int huffcode[257];
  157364. unsigned int code;
  157365. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  157366. * paralleling the order of the symbols themselves in htbl->huffval[].
  157367. */
  157368. /* Find the input Huffman table */
  157369. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  157370. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  157371. htbl =
  157372. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  157373. if (htbl == NULL)
  157374. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  157375. /* Allocate a workspace if we haven't already done so. */
  157376. if (*pdtbl == NULL)
  157377. *pdtbl = (c_derived_tbl *)
  157378. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157379. SIZEOF(c_derived_tbl));
  157380. dtbl = *pdtbl;
  157381. /* Figure C.1: make table of Huffman code length for each symbol */
  157382. p = 0;
  157383. for (l = 1; l <= 16; l++) {
  157384. i = (int) htbl->bits[l];
  157385. if (i < 0 || p + i > 256) /* protect against table overrun */
  157386. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  157387. while (i--)
  157388. huffsize[p++] = (char) l;
  157389. }
  157390. huffsize[p] = 0;
  157391. lastp = p;
  157392. /* Figure C.2: generate the codes themselves */
  157393. /* We also validate that the counts represent a legal Huffman code tree. */
  157394. code = 0;
  157395. si = huffsize[0];
  157396. p = 0;
  157397. while (huffsize[p]) {
  157398. while (((int) huffsize[p]) == si) {
  157399. huffcode[p++] = code;
  157400. code++;
  157401. }
  157402. /* code is now 1 more than the last code used for codelength si; but
  157403. * it must still fit in si bits, since no code is allowed to be all ones.
  157404. */
  157405. if (((INT32) code) >= (((INT32) 1) << si))
  157406. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  157407. code <<= 1;
  157408. si++;
  157409. }
  157410. /* Figure C.3: generate encoding tables */
  157411. /* These are code and size indexed by symbol value */
  157412. /* Set all codeless symbols to have code length 0;
  157413. * this lets us detect duplicate VAL entries here, and later
  157414. * allows emit_bits to detect any attempt to emit such symbols.
  157415. */
  157416. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  157417. /* This is also a convenient place to check for out-of-range
  157418. * and duplicated VAL entries. We allow 0..255 for AC symbols
  157419. * but only 0..15 for DC. (We could constrain them further
  157420. * based on data depth and mode, but this seems enough.)
  157421. */
  157422. maxsymbol = isDC ? 15 : 255;
  157423. for (p = 0; p < lastp; p++) {
  157424. i = htbl->huffval[p];
  157425. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  157426. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  157427. dtbl->ehufco[i] = huffcode[p];
  157428. dtbl->ehufsi[i] = huffsize[p];
  157429. }
  157430. }
  157431. /* Outputting bytes to the file */
  157432. /* Emit a byte, taking 'action' if must suspend. */
  157433. #define emit_byte(state,val,action) \
  157434. { *(state)->next_output_byte++ = (JOCTET) (val); \
  157435. if (--(state)->free_in_buffer == 0) \
  157436. if (! dump_buffer(state)) \
  157437. { action; } }
  157438. LOCAL(boolean)
  157439. dump_buffer (working_state * state)
  157440. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  157441. {
  157442. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  157443. if (! (*dest->empty_output_buffer) (state->cinfo))
  157444. return FALSE;
  157445. /* After a successful buffer dump, must reset buffer pointers */
  157446. state->next_output_byte = dest->next_output_byte;
  157447. state->free_in_buffer = dest->free_in_buffer;
  157448. return TRUE;
  157449. }
  157450. /* Outputting bits to the file */
  157451. /* Only the right 24 bits of put_buffer are used; the valid bits are
  157452. * left-justified in this part. At most 16 bits can be passed to emit_bits
  157453. * in one call, and we never retain more than 7 bits in put_buffer
  157454. * between calls, so 24 bits are sufficient.
  157455. */
  157456. INLINE
  157457. LOCAL(boolean)
  157458. emit_bits (working_state * state, unsigned int code, int size)
  157459. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  157460. {
  157461. /* This routine is heavily used, so it's worth coding tightly. */
  157462. register INT32 put_buffer = (INT32) code;
  157463. register int put_bits = state->cur.put_bits;
  157464. /* if size is 0, caller used an invalid Huffman table entry */
  157465. if (size == 0)
  157466. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  157467. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  157468. put_bits += size; /* new number of bits in buffer */
  157469. put_buffer <<= 24 - put_bits; /* align incoming bits */
  157470. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  157471. while (put_bits >= 8) {
  157472. int c = (int) ((put_buffer >> 16) & 0xFF);
  157473. emit_byte(state, c, return FALSE);
  157474. if (c == 0xFF) { /* need to stuff a zero byte? */
  157475. emit_byte(state, 0, return FALSE);
  157476. }
  157477. put_buffer <<= 8;
  157478. put_bits -= 8;
  157479. }
  157480. state->cur.put_buffer = put_buffer; /* update state variables */
  157481. state->cur.put_bits = put_bits;
  157482. return TRUE;
  157483. }
  157484. LOCAL(boolean)
  157485. flush_bits (working_state * state)
  157486. {
  157487. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  157488. return FALSE;
  157489. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  157490. state->cur.put_bits = 0;
  157491. return TRUE;
  157492. }
  157493. /* Encode a single block's worth of coefficients */
  157494. LOCAL(boolean)
  157495. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  157496. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  157497. {
  157498. register int temp, temp2;
  157499. register int nbits;
  157500. register int k, r, i;
  157501. /* Encode the DC coefficient difference per section F.1.2.1 */
  157502. temp = temp2 = block[0] - last_dc_val;
  157503. if (temp < 0) {
  157504. temp = -temp; /* temp is abs value of input */
  157505. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  157506. /* This code assumes we are on a two's complement machine */
  157507. temp2--;
  157508. }
  157509. /* Find the number of bits needed for the magnitude of the coefficient */
  157510. nbits = 0;
  157511. while (temp) {
  157512. nbits++;
  157513. temp >>= 1;
  157514. }
  157515. /* Check for out-of-range coefficient values.
  157516. * Since we're encoding a difference, the range limit is twice as much.
  157517. */
  157518. if (nbits > MAX_COEF_BITS+1)
  157519. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  157520. /* Emit the Huffman-coded symbol for the number of bits */
  157521. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  157522. return FALSE;
  157523. /* Emit that number of bits of the value, if positive, */
  157524. /* or the complement of its magnitude, if negative. */
  157525. if (nbits) /* emit_bits rejects calls with size 0 */
  157526. if (! emit_bits(state, (unsigned int) temp2, nbits))
  157527. return FALSE;
  157528. /* Encode the AC coefficients per section F.1.2.2 */
  157529. r = 0; /* r = run length of zeros */
  157530. for (k = 1; k < DCTSIZE2; k++) {
  157531. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  157532. r++;
  157533. } else {
  157534. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  157535. while (r > 15) {
  157536. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  157537. return FALSE;
  157538. r -= 16;
  157539. }
  157540. temp2 = temp;
  157541. if (temp < 0) {
  157542. temp = -temp; /* temp is abs value of input */
  157543. /* This code assumes we are on a two's complement machine */
  157544. temp2--;
  157545. }
  157546. /* Find the number of bits needed for the magnitude of the coefficient */
  157547. nbits = 1; /* there must be at least one 1 bit */
  157548. while ((temp >>= 1))
  157549. nbits++;
  157550. /* Check for out-of-range coefficient values */
  157551. if (nbits > MAX_COEF_BITS)
  157552. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  157553. /* Emit Huffman symbol for run length / number of bits */
  157554. i = (r << 4) + nbits;
  157555. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  157556. return FALSE;
  157557. /* Emit that number of bits of the value, if positive, */
  157558. /* or the complement of its magnitude, if negative. */
  157559. if (! emit_bits(state, (unsigned int) temp2, nbits))
  157560. return FALSE;
  157561. r = 0;
  157562. }
  157563. }
  157564. /* If the last coef(s) were zero, emit an end-of-block code */
  157565. if (r > 0)
  157566. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  157567. return FALSE;
  157568. return TRUE;
  157569. }
  157570. /*
  157571. * Emit a restart marker & resynchronize predictions.
  157572. */
  157573. LOCAL(boolean)
  157574. emit_restart (working_state * state, int restart_num)
  157575. {
  157576. int ci;
  157577. if (! flush_bits(state))
  157578. return FALSE;
  157579. emit_byte(state, 0xFF, return FALSE);
  157580. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  157581. /* Re-initialize DC predictions to 0 */
  157582. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  157583. state->cur.last_dc_val[ci] = 0;
  157584. /* The restart counter is not updated until we successfully write the MCU. */
  157585. return TRUE;
  157586. }
  157587. /*
  157588. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  157589. */
  157590. METHODDEF(boolean)
  157591. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  157592. {
  157593. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  157594. working_state state;
  157595. int blkn, ci;
  157596. jpeg_component_info * compptr;
  157597. /* Load up working state */
  157598. state.next_output_byte = cinfo->dest->next_output_byte;
  157599. state.free_in_buffer = cinfo->dest->free_in_buffer;
  157600. ASSIGN_STATE(state.cur, entropy->saved);
  157601. state.cinfo = cinfo;
  157602. /* Emit restart marker if needed */
  157603. if (cinfo->restart_interval) {
  157604. if (entropy->restarts_to_go == 0)
  157605. if (! emit_restart(&state, entropy->next_restart_num))
  157606. return FALSE;
  157607. }
  157608. /* Encode the MCU data blocks */
  157609. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  157610. ci = cinfo->MCU_membership[blkn];
  157611. compptr = cinfo->cur_comp_info[ci];
  157612. if (! encode_one_block(&state,
  157613. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  157614. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  157615. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  157616. return FALSE;
  157617. /* Update last_dc_val */
  157618. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  157619. }
  157620. /* Completed MCU, so update state */
  157621. cinfo->dest->next_output_byte = state.next_output_byte;
  157622. cinfo->dest->free_in_buffer = state.free_in_buffer;
  157623. ASSIGN_STATE(entropy->saved, state.cur);
  157624. /* Update restart-interval state too */
  157625. if (cinfo->restart_interval) {
  157626. if (entropy->restarts_to_go == 0) {
  157627. entropy->restarts_to_go = cinfo->restart_interval;
  157628. entropy->next_restart_num++;
  157629. entropy->next_restart_num &= 7;
  157630. }
  157631. entropy->restarts_to_go--;
  157632. }
  157633. return TRUE;
  157634. }
  157635. /*
  157636. * Finish up at the end of a Huffman-compressed scan.
  157637. */
  157638. METHODDEF(void)
  157639. finish_pass_huff (j_compress_ptr cinfo)
  157640. {
  157641. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  157642. working_state state;
  157643. /* Load up working state ... flush_bits needs it */
  157644. state.next_output_byte = cinfo->dest->next_output_byte;
  157645. state.free_in_buffer = cinfo->dest->free_in_buffer;
  157646. ASSIGN_STATE(state.cur, entropy->saved);
  157647. state.cinfo = cinfo;
  157648. /* Flush out the last data */
  157649. if (! flush_bits(&state))
  157650. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  157651. /* Update state */
  157652. cinfo->dest->next_output_byte = state.next_output_byte;
  157653. cinfo->dest->free_in_buffer = state.free_in_buffer;
  157654. ASSIGN_STATE(entropy->saved, state.cur);
  157655. }
  157656. /*
  157657. * Huffman coding optimization.
  157658. *
  157659. * We first scan the supplied data and count the number of uses of each symbol
  157660. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  157661. * Then we build a Huffman coding tree for the observed counts.
  157662. * Symbols which are not needed at all for the particular image are not
  157663. * assigned any code, which saves space in the DHT marker as well as in
  157664. * the compressed data.
  157665. */
  157666. #ifdef ENTROPY_OPT_SUPPORTED
  157667. /* Process a single block's worth of coefficients */
  157668. LOCAL(void)
  157669. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  157670. long dc_counts[], long ac_counts[])
  157671. {
  157672. register int temp;
  157673. register int nbits;
  157674. register int k, r;
  157675. /* Encode the DC coefficient difference per section F.1.2.1 */
  157676. temp = block[0] - last_dc_val;
  157677. if (temp < 0)
  157678. temp = -temp;
  157679. /* Find the number of bits needed for the magnitude of the coefficient */
  157680. nbits = 0;
  157681. while (temp) {
  157682. nbits++;
  157683. temp >>= 1;
  157684. }
  157685. /* Check for out-of-range coefficient values.
  157686. * Since we're encoding a difference, the range limit is twice as much.
  157687. */
  157688. if (nbits > MAX_COEF_BITS+1)
  157689. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  157690. /* Count the Huffman symbol for the number of bits */
  157691. dc_counts[nbits]++;
  157692. /* Encode the AC coefficients per section F.1.2.2 */
  157693. r = 0; /* r = run length of zeros */
  157694. for (k = 1; k < DCTSIZE2; k++) {
  157695. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  157696. r++;
  157697. } else {
  157698. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  157699. while (r > 15) {
  157700. ac_counts[0xF0]++;
  157701. r -= 16;
  157702. }
  157703. /* Find the number of bits needed for the magnitude of the coefficient */
  157704. if (temp < 0)
  157705. temp = -temp;
  157706. /* Find the number of bits needed for the magnitude of the coefficient */
  157707. nbits = 1; /* there must be at least one 1 bit */
  157708. while ((temp >>= 1))
  157709. nbits++;
  157710. /* Check for out-of-range coefficient values */
  157711. if (nbits > MAX_COEF_BITS)
  157712. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  157713. /* Count Huffman symbol for run length / number of bits */
  157714. ac_counts[(r << 4) + nbits]++;
  157715. r = 0;
  157716. }
  157717. }
  157718. /* If the last coef(s) were zero, emit an end-of-block code */
  157719. if (r > 0)
  157720. ac_counts[0]++;
  157721. }
  157722. /*
  157723. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  157724. * No data is actually output, so no suspension return is possible.
  157725. */
  157726. METHODDEF(boolean)
  157727. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  157728. {
  157729. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  157730. int blkn, ci;
  157731. jpeg_component_info * compptr;
  157732. /* Take care of restart intervals if needed */
  157733. if (cinfo->restart_interval) {
  157734. if (entropy->restarts_to_go == 0) {
  157735. /* Re-initialize DC predictions to 0 */
  157736. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  157737. entropy->saved.last_dc_val[ci] = 0;
  157738. /* Update restart state */
  157739. entropy->restarts_to_go = cinfo->restart_interval;
  157740. }
  157741. entropy->restarts_to_go--;
  157742. }
  157743. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  157744. ci = cinfo->MCU_membership[blkn];
  157745. compptr = cinfo->cur_comp_info[ci];
  157746. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  157747. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  157748. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  157749. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  157750. }
  157751. return TRUE;
  157752. }
  157753. /*
  157754. * Generate the best Huffman code table for the given counts, fill htbl.
  157755. * Note this is also used by jcphuff.c.
  157756. *
  157757. * The JPEG standard requires that no symbol be assigned a codeword of all
  157758. * one bits (so that padding bits added at the end of a compressed segment
  157759. * can't look like a valid code). Because of the canonical ordering of
  157760. * codewords, this just means that there must be an unused slot in the
  157761. * longest codeword length category. Section K.2 of the JPEG spec suggests
  157762. * reserving such a slot by pretending that symbol 256 is a valid symbol
  157763. * with count 1. In theory that's not optimal; giving it count zero but
  157764. * including it in the symbol set anyway should give a better Huffman code.
  157765. * But the theoretically better code actually seems to come out worse in
  157766. * practice, because it produces more all-ones bytes (which incur stuffed
  157767. * zero bytes in the final file). In any case the difference is tiny.
  157768. *
  157769. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  157770. * If some symbols have a very small but nonzero probability, the Huffman tree
  157771. * must be adjusted to meet the code length restriction. We currently use
  157772. * the adjustment method suggested in JPEG section K.2. This method is *not*
  157773. * optimal; it may not choose the best possible limited-length code. But
  157774. * typically only very-low-frequency symbols will be given less-than-optimal
  157775. * lengths, so the code is almost optimal. Experimental comparisons against
  157776. * an optimal limited-length-code algorithm indicate that the difference is
  157777. * microscopic --- usually less than a hundredth of a percent of total size.
  157778. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  157779. */
  157780. GLOBAL(void)
  157781. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  157782. {
  157783. #define MAX_CLEN 32 /* assumed maximum initial code length */
  157784. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  157785. int codesize[257]; /* codesize[k] = code length of symbol k */
  157786. int others[257]; /* next symbol in current branch of tree */
  157787. int c1, c2;
  157788. int p, i, j;
  157789. long v;
  157790. /* This algorithm is explained in section K.2 of the JPEG standard */
  157791. MEMZERO(bits, SIZEOF(bits));
  157792. MEMZERO(codesize, SIZEOF(codesize));
  157793. for (i = 0; i < 257; i++)
  157794. others[i] = -1; /* init links to empty */
  157795. freq[256] = 1; /* make sure 256 has a nonzero count */
  157796. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  157797. * that no real symbol is given code-value of all ones, because 256
  157798. * will be placed last in the largest codeword category.
  157799. */
  157800. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  157801. for (;;) {
  157802. /* Find the smallest nonzero frequency, set c1 = its symbol */
  157803. /* In case of ties, take the larger symbol number */
  157804. c1 = -1;
  157805. v = 1000000000L;
  157806. for (i = 0; i <= 256; i++) {
  157807. if (freq[i] && freq[i] <= v) {
  157808. v = freq[i];
  157809. c1 = i;
  157810. }
  157811. }
  157812. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  157813. /* In case of ties, take the larger symbol number */
  157814. c2 = -1;
  157815. v = 1000000000L;
  157816. for (i = 0; i <= 256; i++) {
  157817. if (freq[i] && freq[i] <= v && i != c1) {
  157818. v = freq[i];
  157819. c2 = i;
  157820. }
  157821. }
  157822. /* Done if we've merged everything into one frequency */
  157823. if (c2 < 0)
  157824. break;
  157825. /* Else merge the two counts/trees */
  157826. freq[c1] += freq[c2];
  157827. freq[c2] = 0;
  157828. /* Increment the codesize of everything in c1's tree branch */
  157829. codesize[c1]++;
  157830. while (others[c1] >= 0) {
  157831. c1 = others[c1];
  157832. codesize[c1]++;
  157833. }
  157834. others[c1] = c2; /* chain c2 onto c1's tree branch */
  157835. /* Increment the codesize of everything in c2's tree branch */
  157836. codesize[c2]++;
  157837. while (others[c2] >= 0) {
  157838. c2 = others[c2];
  157839. codesize[c2]++;
  157840. }
  157841. }
  157842. /* Now count the number of symbols of each code length */
  157843. for (i = 0; i <= 256; i++) {
  157844. if (codesize[i]) {
  157845. /* The JPEG standard seems to think that this can't happen, */
  157846. /* but I'm paranoid... */
  157847. if (codesize[i] > MAX_CLEN)
  157848. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  157849. bits[codesize[i]]++;
  157850. }
  157851. }
  157852. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  157853. * Huffman procedure assigned any such lengths, we must adjust the coding.
  157854. * Here is what the JPEG spec says about how this next bit works:
  157855. * Since symbols are paired for the longest Huffman code, the symbols are
  157856. * removed from this length category two at a time. The prefix for the pair
  157857. * (which is one bit shorter) is allocated to one of the pair; then,
  157858. * skipping the BITS entry for that prefix length, a code word from the next
  157859. * shortest nonzero BITS entry is converted into a prefix for two code words
  157860. * one bit longer.
  157861. */
  157862. for (i = MAX_CLEN; i > 16; i--) {
  157863. while (bits[i] > 0) {
  157864. j = i - 2; /* find length of new prefix to be used */
  157865. while (bits[j] == 0)
  157866. j--;
  157867. bits[i] -= 2; /* remove two symbols */
  157868. bits[i-1]++; /* one goes in this length */
  157869. bits[j+1] += 2; /* two new symbols in this length */
  157870. bits[j]--; /* symbol of this length is now a prefix */
  157871. }
  157872. }
  157873. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  157874. while (bits[i] == 0) /* find largest codelength still in use */
  157875. i--;
  157876. bits[i]--;
  157877. /* Return final symbol counts (only for lengths 0..16) */
  157878. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  157879. /* Return a list of the symbols sorted by code length */
  157880. /* It's not real clear to me why we don't need to consider the codelength
  157881. * changes made above, but the JPEG spec seems to think this works.
  157882. */
  157883. p = 0;
  157884. for (i = 1; i <= MAX_CLEN; i++) {
  157885. for (j = 0; j <= 255; j++) {
  157886. if (codesize[j] == i) {
  157887. htbl->huffval[p] = (UINT8) j;
  157888. p++;
  157889. }
  157890. }
  157891. }
  157892. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  157893. htbl->sent_table = FALSE;
  157894. }
  157895. /*
  157896. * Finish up a statistics-gathering pass and create the new Huffman tables.
  157897. */
  157898. METHODDEF(void)
  157899. finish_pass_gather (j_compress_ptr cinfo)
  157900. {
  157901. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  157902. int ci, dctbl, actbl;
  157903. jpeg_component_info * compptr;
  157904. JHUFF_TBL **htblptr;
  157905. boolean did_dc[NUM_HUFF_TBLS];
  157906. boolean did_ac[NUM_HUFF_TBLS];
  157907. /* It's important not to apply jpeg_gen_optimal_table more than once
  157908. * per table, because it clobbers the input frequency counts!
  157909. */
  157910. MEMZERO(did_dc, SIZEOF(did_dc));
  157911. MEMZERO(did_ac, SIZEOF(did_ac));
  157912. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157913. compptr = cinfo->cur_comp_info[ci];
  157914. dctbl = compptr->dc_tbl_no;
  157915. actbl = compptr->ac_tbl_no;
  157916. if (! did_dc[dctbl]) {
  157917. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  157918. if (*htblptr == NULL)
  157919. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  157920. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  157921. did_dc[dctbl] = TRUE;
  157922. }
  157923. if (! did_ac[actbl]) {
  157924. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  157925. if (*htblptr == NULL)
  157926. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  157927. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  157928. did_ac[actbl] = TRUE;
  157929. }
  157930. }
  157931. }
  157932. #endif /* ENTROPY_OPT_SUPPORTED */
  157933. /*
  157934. * Module initialization routine for Huffman entropy encoding.
  157935. */
  157936. GLOBAL(void)
  157937. jinit_huff_encoder (j_compress_ptr cinfo)
  157938. {
  157939. huff_entropy_ptr entropy;
  157940. int i;
  157941. entropy = (huff_entropy_ptr)
  157942. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157943. SIZEOF(huff_entropy_encoder));
  157944. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  157945. entropy->pub.start_pass = start_pass_huff;
  157946. /* Mark tables unallocated */
  157947. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  157948. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  157949. #ifdef ENTROPY_OPT_SUPPORTED
  157950. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  157951. #endif
  157952. }
  157953. }
  157954. /********* End of inlined file: jchuff.c *********/
  157955. #undef emit_byte
  157956. /********* Start of inlined file: jcinit.c *********/
  157957. #define JPEG_INTERNALS
  157958. /*
  157959. * Master selection of compression modules.
  157960. * This is done once at the start of processing an image. We determine
  157961. * which modules will be used and give them appropriate initialization calls.
  157962. */
  157963. GLOBAL(void)
  157964. jinit_compress_master (j_compress_ptr cinfo)
  157965. {
  157966. /* Initialize master control (includes parameter checking/processing) */
  157967. jinit_c_master_control(cinfo, FALSE /* full compression */);
  157968. /* Preprocessing */
  157969. if (! cinfo->raw_data_in) {
  157970. jinit_color_converter(cinfo);
  157971. jinit_downsampler(cinfo);
  157972. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  157973. }
  157974. /* Forward DCT */
  157975. jinit_forward_dct(cinfo);
  157976. /* Entropy encoding: either Huffman or arithmetic coding. */
  157977. if (cinfo->arith_code) {
  157978. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  157979. } else {
  157980. if (cinfo->progressive_mode) {
  157981. #ifdef C_PROGRESSIVE_SUPPORTED
  157982. jinit_phuff_encoder(cinfo);
  157983. #else
  157984. ERREXIT(cinfo, JERR_NOT_COMPILED);
  157985. #endif
  157986. } else
  157987. jinit_huff_encoder(cinfo);
  157988. }
  157989. /* Need a full-image coefficient buffer in any multi-pass mode. */
  157990. jinit_c_coef_controller(cinfo,
  157991. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  157992. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  157993. jinit_marker_writer(cinfo);
  157994. /* We can now tell the memory manager to allocate virtual arrays. */
  157995. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  157996. /* Write the datastream header (SOI) immediately.
  157997. * Frame and scan headers are postponed till later.
  157998. * This lets application insert special markers after the SOI.
  157999. */
  158000. (*cinfo->marker->write_file_header) (cinfo);
  158001. }
  158002. /********* End of inlined file: jcinit.c *********/
  158003. /********* Start of inlined file: jcmainct.c *********/
  158004. #define JPEG_INTERNALS
  158005. /* Note: currently, there is no operating mode in which a full-image buffer
  158006. * is needed at this step. If there were, that mode could not be used with
  158007. * "raw data" input, since this module is bypassed in that case. However,
  158008. * we've left the code here for possible use in special applications.
  158009. */
  158010. #undef FULL_MAIN_BUFFER_SUPPORTED
  158011. /* Private buffer controller object */
  158012. typedef struct {
  158013. struct jpeg_c_main_controller pub; /* public fields */
  158014. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  158015. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  158016. boolean suspended; /* remember if we suspended output */
  158017. J_BUF_MODE pass_mode; /* current operating mode */
  158018. /* If using just a strip buffer, this points to the entire set of buffers
  158019. * (we allocate one for each component). In the full-image case, this
  158020. * points to the currently accessible strips of the virtual arrays.
  158021. */
  158022. JSAMPARRAY buffer[MAX_COMPONENTS];
  158023. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158024. /* If using full-image storage, this array holds pointers to virtual-array
  158025. * control blocks for each component. Unused if not full-image storage.
  158026. */
  158027. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  158028. #endif
  158029. } my_main_controller;
  158030. typedef my_main_controller * my_main_ptr;
  158031. /* Forward declarations */
  158032. METHODDEF(void) process_data_simple_main
  158033. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  158034. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  158035. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158036. METHODDEF(void) process_data_buffer_main
  158037. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  158038. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  158039. #endif
  158040. /*
  158041. * Initialize for a processing pass.
  158042. */
  158043. METHODDEF(void)
  158044. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  158045. {
  158046. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  158047. /* Do nothing in raw-data mode. */
  158048. if (cinfo->raw_data_in)
  158049. return;
  158050. main_->cur_iMCU_row = 0; /* initialize counters */
  158051. main_->rowgroup_ctr = 0;
  158052. main_->suspended = FALSE;
  158053. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  158054. switch (pass_mode) {
  158055. case JBUF_PASS_THRU:
  158056. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158057. if (main_->whole_image[0] != NULL)
  158058. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158059. #endif
  158060. main_->pub.process_data = process_data_simple_main;
  158061. break;
  158062. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158063. case JBUF_SAVE_SOURCE:
  158064. case JBUF_CRANK_DEST:
  158065. case JBUF_SAVE_AND_PASS:
  158066. if (main_->whole_image[0] == NULL)
  158067. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158068. main_->pub.process_data = process_data_buffer_main;
  158069. break;
  158070. #endif
  158071. default:
  158072. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158073. break;
  158074. }
  158075. }
  158076. /*
  158077. * Process some data.
  158078. * This routine handles the simple pass-through mode,
  158079. * where we have only a strip buffer.
  158080. */
  158081. METHODDEF(void)
  158082. process_data_simple_main (j_compress_ptr cinfo,
  158083. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  158084. JDIMENSION in_rows_avail)
  158085. {
  158086. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  158087. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  158088. /* Read input data if we haven't filled the main buffer yet */
  158089. if (main_->rowgroup_ctr < DCTSIZE)
  158090. (*cinfo->prep->pre_process_data) (cinfo,
  158091. input_buf, in_row_ctr, in_rows_avail,
  158092. main_->buffer, &main_->rowgroup_ctr,
  158093. (JDIMENSION) DCTSIZE);
  158094. /* If we don't have a full iMCU row buffered, return to application for
  158095. * more data. Note that preprocessor will always pad to fill the iMCU row
  158096. * at the bottom of the image.
  158097. */
  158098. if (main_->rowgroup_ctr != DCTSIZE)
  158099. return;
  158100. /* Send the completed row to the compressor */
  158101. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  158102. /* If compressor did not consume the whole row, then we must need to
  158103. * suspend processing and return to the application. In this situation
  158104. * we pretend we didn't yet consume the last input row; otherwise, if
  158105. * it happened to be the last row of the image, the application would
  158106. * think we were done.
  158107. */
  158108. if (! main_->suspended) {
  158109. (*in_row_ctr)--;
  158110. main_->suspended = TRUE;
  158111. }
  158112. return;
  158113. }
  158114. /* We did finish the row. Undo our little suspension hack if a previous
  158115. * call suspended; then mark the main buffer empty.
  158116. */
  158117. if (main_->suspended) {
  158118. (*in_row_ctr)++;
  158119. main_->suspended = FALSE;
  158120. }
  158121. main_->rowgroup_ctr = 0;
  158122. main_->cur_iMCU_row++;
  158123. }
  158124. }
  158125. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158126. /*
  158127. * Process some data.
  158128. * This routine handles all of the modes that use a full-size buffer.
  158129. */
  158130. METHODDEF(void)
  158131. process_data_buffer_main (j_compress_ptr cinfo,
  158132. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  158133. JDIMENSION in_rows_avail)
  158134. {
  158135. my_main_ptr main = (my_main_ptr) cinfo->main;
  158136. int ci;
  158137. jpeg_component_info *compptr;
  158138. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  158139. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  158140. /* Realign the virtual buffers if at the start of an iMCU row. */
  158141. if (main->rowgroup_ctr == 0) {
  158142. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158143. ci++, compptr++) {
  158144. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  158145. ((j_common_ptr) cinfo, main->whole_image[ci],
  158146. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  158147. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  158148. }
  158149. /* In a read pass, pretend we just read some source data. */
  158150. if (! writing) {
  158151. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  158152. main->rowgroup_ctr = DCTSIZE;
  158153. }
  158154. }
  158155. /* If a write pass, read input data until the current iMCU row is full. */
  158156. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  158157. if (writing) {
  158158. (*cinfo->prep->pre_process_data) (cinfo,
  158159. input_buf, in_row_ctr, in_rows_avail,
  158160. main->buffer, &main->rowgroup_ctr,
  158161. (JDIMENSION) DCTSIZE);
  158162. /* Return to application if we need more data to fill the iMCU row. */
  158163. if (main->rowgroup_ctr < DCTSIZE)
  158164. return;
  158165. }
  158166. /* Emit data, unless this is a sink-only pass. */
  158167. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  158168. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  158169. /* If compressor did not consume the whole row, then we must need to
  158170. * suspend processing and return to the application. In this situation
  158171. * we pretend we didn't yet consume the last input row; otherwise, if
  158172. * it happened to be the last row of the image, the application would
  158173. * think we were done.
  158174. */
  158175. if (! main->suspended) {
  158176. (*in_row_ctr)--;
  158177. main->suspended = TRUE;
  158178. }
  158179. return;
  158180. }
  158181. /* We did finish the row. Undo our little suspension hack if a previous
  158182. * call suspended; then mark the main buffer empty.
  158183. */
  158184. if (main->suspended) {
  158185. (*in_row_ctr)++;
  158186. main->suspended = FALSE;
  158187. }
  158188. }
  158189. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  158190. main->rowgroup_ctr = 0;
  158191. main->cur_iMCU_row++;
  158192. }
  158193. }
  158194. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  158195. /*
  158196. * Initialize main buffer controller.
  158197. */
  158198. GLOBAL(void)
  158199. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  158200. {
  158201. my_main_ptr main_;
  158202. int ci;
  158203. jpeg_component_info *compptr;
  158204. main_ = (my_main_ptr)
  158205. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158206. SIZEOF(my_main_controller));
  158207. cinfo->main = (struct jpeg_c_main_controller *) main_;
  158208. main_->pub.start_pass = start_pass_main;
  158209. /* We don't need to create a buffer in raw-data mode. */
  158210. if (cinfo->raw_data_in)
  158211. return;
  158212. /* Create the buffer. It holds downsampled data, so each component
  158213. * may be of a different size.
  158214. */
  158215. if (need_full_buffer) {
  158216. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158217. /* Allocate a full-image virtual array for each component */
  158218. /* Note we pad the bottom to a multiple of the iMCU height */
  158219. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158220. ci++, compptr++) {
  158221. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  158222. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  158223. compptr->width_in_blocks * DCTSIZE,
  158224. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  158225. (long) compptr->v_samp_factor) * DCTSIZE,
  158226. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  158227. }
  158228. #else
  158229. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158230. #endif
  158231. } else {
  158232. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158233. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  158234. #endif
  158235. /* Allocate a strip buffer for each component */
  158236. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158237. ci++, compptr++) {
  158238. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  158239. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158240. compptr->width_in_blocks * DCTSIZE,
  158241. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  158242. }
  158243. }
  158244. }
  158245. /********* End of inlined file: jcmainct.c *********/
  158246. /********* Start of inlined file: jcmarker.c *********/
  158247. #define JPEG_INTERNALS
  158248. /* Private state */
  158249. typedef struct {
  158250. struct jpeg_marker_writer pub; /* public fields */
  158251. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  158252. } my_marker_writer;
  158253. typedef my_marker_writer * my_marker_ptr;
  158254. /*
  158255. * Basic output routines.
  158256. *
  158257. * Note that we do not support suspension while writing a marker.
  158258. * Therefore, an application using suspension must ensure that there is
  158259. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  158260. * calling jpeg_start_compress, and enough space to write the trailing EOI
  158261. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  158262. * modes are not supported at all with suspension, so those two are the only
  158263. * points where markers will be written.
  158264. */
  158265. LOCAL(void)
  158266. emit_byte (j_compress_ptr cinfo, int val)
  158267. /* Emit a byte */
  158268. {
  158269. struct jpeg_destination_mgr * dest = cinfo->dest;
  158270. *(dest->next_output_byte)++ = (JOCTET) val;
  158271. if (--dest->free_in_buffer == 0) {
  158272. if (! (*dest->empty_output_buffer) (cinfo))
  158273. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  158274. }
  158275. }
  158276. LOCAL(void)
  158277. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  158278. /* Emit a marker code */
  158279. {
  158280. emit_byte(cinfo, 0xFF);
  158281. emit_byte(cinfo, (int) mark);
  158282. }
  158283. LOCAL(void)
  158284. emit_2bytes (j_compress_ptr cinfo, int value)
  158285. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  158286. {
  158287. emit_byte(cinfo, (value >> 8) & 0xFF);
  158288. emit_byte(cinfo, value & 0xFF);
  158289. }
  158290. /*
  158291. * Routines to write specific marker types.
  158292. */
  158293. LOCAL(int)
  158294. emit_dqt (j_compress_ptr cinfo, int index)
  158295. /* Emit a DQT marker */
  158296. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  158297. {
  158298. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  158299. int prec;
  158300. int i;
  158301. if (qtbl == NULL)
  158302. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  158303. prec = 0;
  158304. for (i = 0; i < DCTSIZE2; i++) {
  158305. if (qtbl->quantval[i] > 255)
  158306. prec = 1;
  158307. }
  158308. if (! qtbl->sent_table) {
  158309. emit_marker(cinfo, M_DQT);
  158310. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  158311. emit_byte(cinfo, index + (prec<<4));
  158312. for (i = 0; i < DCTSIZE2; i++) {
  158313. /* The table entries must be emitted in zigzag order. */
  158314. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  158315. if (prec)
  158316. emit_byte(cinfo, (int) (qval >> 8));
  158317. emit_byte(cinfo, (int) (qval & 0xFF));
  158318. }
  158319. qtbl->sent_table = TRUE;
  158320. }
  158321. return prec;
  158322. }
  158323. LOCAL(void)
  158324. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  158325. /* Emit a DHT marker */
  158326. {
  158327. JHUFF_TBL * htbl;
  158328. int length, i;
  158329. if (is_ac) {
  158330. htbl = cinfo->ac_huff_tbl_ptrs[index];
  158331. index += 0x10; /* output index has AC bit set */
  158332. } else {
  158333. htbl = cinfo->dc_huff_tbl_ptrs[index];
  158334. }
  158335. if (htbl == NULL)
  158336. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  158337. if (! htbl->sent_table) {
  158338. emit_marker(cinfo, M_DHT);
  158339. length = 0;
  158340. for (i = 1; i <= 16; i++)
  158341. length += htbl->bits[i];
  158342. emit_2bytes(cinfo, length + 2 + 1 + 16);
  158343. emit_byte(cinfo, index);
  158344. for (i = 1; i <= 16; i++)
  158345. emit_byte(cinfo, htbl->bits[i]);
  158346. for (i = 0; i < length; i++)
  158347. emit_byte(cinfo, htbl->huffval[i]);
  158348. htbl->sent_table = TRUE;
  158349. }
  158350. }
  158351. LOCAL(void)
  158352. emit_dac (j_compress_ptr cinfo)
  158353. /* Emit a DAC marker */
  158354. /* Since the useful info is so small, we want to emit all the tables in */
  158355. /* one DAC marker. Therefore this routine does its own scan of the table. */
  158356. {
  158357. #ifdef C_ARITH_CODING_SUPPORTED
  158358. char dc_in_use[NUM_ARITH_TBLS];
  158359. char ac_in_use[NUM_ARITH_TBLS];
  158360. int length, i;
  158361. jpeg_component_info *compptr;
  158362. for (i = 0; i < NUM_ARITH_TBLS; i++)
  158363. dc_in_use[i] = ac_in_use[i] = 0;
  158364. for (i = 0; i < cinfo->comps_in_scan; i++) {
  158365. compptr = cinfo->cur_comp_info[i];
  158366. dc_in_use[compptr->dc_tbl_no] = 1;
  158367. ac_in_use[compptr->ac_tbl_no] = 1;
  158368. }
  158369. length = 0;
  158370. for (i = 0; i < NUM_ARITH_TBLS; i++)
  158371. length += dc_in_use[i] + ac_in_use[i];
  158372. emit_marker(cinfo, M_DAC);
  158373. emit_2bytes(cinfo, length*2 + 2);
  158374. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  158375. if (dc_in_use[i]) {
  158376. emit_byte(cinfo, i);
  158377. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  158378. }
  158379. if (ac_in_use[i]) {
  158380. emit_byte(cinfo, i + 0x10);
  158381. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  158382. }
  158383. }
  158384. #endif /* C_ARITH_CODING_SUPPORTED */
  158385. }
  158386. LOCAL(void)
  158387. emit_dri (j_compress_ptr cinfo)
  158388. /* Emit a DRI marker */
  158389. {
  158390. emit_marker(cinfo, M_DRI);
  158391. emit_2bytes(cinfo, 4); /* fixed length */
  158392. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  158393. }
  158394. LOCAL(void)
  158395. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  158396. /* Emit a SOF marker */
  158397. {
  158398. int ci;
  158399. jpeg_component_info *compptr;
  158400. emit_marker(cinfo, code);
  158401. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  158402. /* Make sure image isn't bigger than SOF field can handle */
  158403. if ((long) cinfo->image_height > 65535L ||
  158404. (long) cinfo->image_width > 65535L)
  158405. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  158406. emit_byte(cinfo, cinfo->data_precision);
  158407. emit_2bytes(cinfo, (int) cinfo->image_height);
  158408. emit_2bytes(cinfo, (int) cinfo->image_width);
  158409. emit_byte(cinfo, cinfo->num_components);
  158410. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158411. ci++, compptr++) {
  158412. emit_byte(cinfo, compptr->component_id);
  158413. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  158414. emit_byte(cinfo, compptr->quant_tbl_no);
  158415. }
  158416. }
  158417. LOCAL(void)
  158418. emit_sos (j_compress_ptr cinfo)
  158419. /* Emit a SOS marker */
  158420. {
  158421. int i, td, ta;
  158422. jpeg_component_info *compptr;
  158423. emit_marker(cinfo, M_SOS);
  158424. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  158425. emit_byte(cinfo, cinfo->comps_in_scan);
  158426. for (i = 0; i < cinfo->comps_in_scan; i++) {
  158427. compptr = cinfo->cur_comp_info[i];
  158428. emit_byte(cinfo, compptr->component_id);
  158429. td = compptr->dc_tbl_no;
  158430. ta = compptr->ac_tbl_no;
  158431. if (cinfo->progressive_mode) {
  158432. /* Progressive mode: only DC or only AC tables are used in one scan;
  158433. * furthermore, Huffman coding of DC refinement uses no table at all.
  158434. * We emit 0 for unused field(s); this is recommended by the P&M text
  158435. * but does not seem to be specified in the standard.
  158436. */
  158437. if (cinfo->Ss == 0) {
  158438. ta = 0; /* DC scan */
  158439. if (cinfo->Ah != 0 && !cinfo->arith_code)
  158440. td = 0; /* no DC table either */
  158441. } else {
  158442. td = 0; /* AC scan */
  158443. }
  158444. }
  158445. emit_byte(cinfo, (td << 4) + ta);
  158446. }
  158447. emit_byte(cinfo, cinfo->Ss);
  158448. emit_byte(cinfo, cinfo->Se);
  158449. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  158450. }
  158451. LOCAL(void)
  158452. emit_jfif_app0 (j_compress_ptr cinfo)
  158453. /* Emit a JFIF-compliant APP0 marker */
  158454. {
  158455. /*
  158456. * Length of APP0 block (2 bytes)
  158457. * Block ID (4 bytes - ASCII "JFIF")
  158458. * Zero byte (1 byte to terminate the ID string)
  158459. * Version Major, Minor (2 bytes - major first)
  158460. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  158461. * Xdpu (2 bytes - dots per unit horizontal)
  158462. * Ydpu (2 bytes - dots per unit vertical)
  158463. * Thumbnail X size (1 byte)
  158464. * Thumbnail Y size (1 byte)
  158465. */
  158466. emit_marker(cinfo, M_APP0);
  158467. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  158468. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  158469. emit_byte(cinfo, 0x46);
  158470. emit_byte(cinfo, 0x49);
  158471. emit_byte(cinfo, 0x46);
  158472. emit_byte(cinfo, 0);
  158473. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  158474. emit_byte(cinfo, cinfo->JFIF_minor_version);
  158475. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  158476. emit_2bytes(cinfo, (int) cinfo->X_density);
  158477. emit_2bytes(cinfo, (int) cinfo->Y_density);
  158478. emit_byte(cinfo, 0); /* No thumbnail image */
  158479. emit_byte(cinfo, 0);
  158480. }
  158481. LOCAL(void)
  158482. emit_adobe_app14 (j_compress_ptr cinfo)
  158483. /* Emit an Adobe APP14 marker */
  158484. {
  158485. /*
  158486. * Length of APP14 block (2 bytes)
  158487. * Block ID (5 bytes - ASCII "Adobe")
  158488. * Version Number (2 bytes - currently 100)
  158489. * Flags0 (2 bytes - currently 0)
  158490. * Flags1 (2 bytes - currently 0)
  158491. * Color transform (1 byte)
  158492. *
  158493. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  158494. * now in circulation seem to use Version = 100, so that's what we write.
  158495. *
  158496. * We write the color transform byte as 1 if the JPEG color space is
  158497. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  158498. * whether the encoder performed a transformation, which is pretty useless.
  158499. */
  158500. emit_marker(cinfo, M_APP14);
  158501. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  158502. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  158503. emit_byte(cinfo, 0x64);
  158504. emit_byte(cinfo, 0x6F);
  158505. emit_byte(cinfo, 0x62);
  158506. emit_byte(cinfo, 0x65);
  158507. emit_2bytes(cinfo, 100); /* Version */
  158508. emit_2bytes(cinfo, 0); /* Flags0 */
  158509. emit_2bytes(cinfo, 0); /* Flags1 */
  158510. switch (cinfo->jpeg_color_space) {
  158511. case JCS_YCbCr:
  158512. emit_byte(cinfo, 1); /* Color transform = 1 */
  158513. break;
  158514. case JCS_YCCK:
  158515. emit_byte(cinfo, 2); /* Color transform = 2 */
  158516. break;
  158517. default:
  158518. emit_byte(cinfo, 0); /* Color transform = 0 */
  158519. break;
  158520. }
  158521. }
  158522. /*
  158523. * These routines allow writing an arbitrary marker with parameters.
  158524. * The only intended use is to emit COM or APPn markers after calling
  158525. * write_file_header and before calling write_frame_header.
  158526. * Other uses are not guaranteed to produce desirable results.
  158527. * Counting the parameter bytes properly is the caller's responsibility.
  158528. */
  158529. METHODDEF(void)
  158530. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  158531. /* Emit an arbitrary marker header */
  158532. {
  158533. if (datalen > (unsigned int) 65533) /* safety check */
  158534. ERREXIT(cinfo, JERR_BAD_LENGTH);
  158535. emit_marker(cinfo, (JPEG_MARKER) marker);
  158536. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  158537. }
  158538. METHODDEF(void)
  158539. write_marker_byte (j_compress_ptr cinfo, int val)
  158540. /* Emit one byte of marker parameters following write_marker_header */
  158541. {
  158542. emit_byte(cinfo, val);
  158543. }
  158544. /*
  158545. * Write datastream header.
  158546. * This consists of an SOI and optional APPn markers.
  158547. * We recommend use of the JFIF marker, but not the Adobe marker,
  158548. * when using YCbCr or grayscale data. The JFIF marker should NOT
  158549. * be used for any other JPEG colorspace. The Adobe marker is helpful
  158550. * to distinguish RGB, CMYK, and YCCK colorspaces.
  158551. * Note that an application can write additional header markers after
  158552. * jpeg_start_compress returns.
  158553. */
  158554. METHODDEF(void)
  158555. write_file_header (j_compress_ptr cinfo)
  158556. {
  158557. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  158558. emit_marker(cinfo, M_SOI); /* first the SOI */
  158559. /* SOI is defined to reset restart interval to 0 */
  158560. marker->last_restart_interval = 0;
  158561. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  158562. emit_jfif_app0(cinfo);
  158563. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  158564. emit_adobe_app14(cinfo);
  158565. }
  158566. /*
  158567. * Write frame header.
  158568. * This consists of DQT and SOFn markers.
  158569. * Note that we do not emit the SOF until we have emitted the DQT(s).
  158570. * This avoids compatibility problems with incorrect implementations that
  158571. * try to error-check the quant table numbers as soon as they see the SOF.
  158572. */
  158573. METHODDEF(void)
  158574. write_frame_header (j_compress_ptr cinfo)
  158575. {
  158576. int ci, prec;
  158577. boolean is_baseline;
  158578. jpeg_component_info *compptr;
  158579. /* Emit DQT for each quantization table.
  158580. * Note that emit_dqt() suppresses any duplicate tables.
  158581. */
  158582. prec = 0;
  158583. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158584. ci++, compptr++) {
  158585. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  158586. }
  158587. /* now prec is nonzero iff there are any 16-bit quant tables. */
  158588. /* Check for a non-baseline specification.
  158589. * Note we assume that Huffman table numbers won't be changed later.
  158590. */
  158591. if (cinfo->arith_code || cinfo->progressive_mode ||
  158592. cinfo->data_precision != 8) {
  158593. is_baseline = FALSE;
  158594. } else {
  158595. is_baseline = TRUE;
  158596. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158597. ci++, compptr++) {
  158598. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  158599. is_baseline = FALSE;
  158600. }
  158601. if (prec && is_baseline) {
  158602. is_baseline = FALSE;
  158603. /* If it's baseline except for quantizer size, warn the user */
  158604. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  158605. }
  158606. }
  158607. /* Emit the proper SOF marker */
  158608. if (cinfo->arith_code) {
  158609. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  158610. } else {
  158611. if (cinfo->progressive_mode)
  158612. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  158613. else if (is_baseline)
  158614. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  158615. else
  158616. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  158617. }
  158618. }
  158619. /*
  158620. * Write scan header.
  158621. * This consists of DHT or DAC markers, optional DRI, and SOS.
  158622. * Compressed data will be written following the SOS.
  158623. */
  158624. METHODDEF(void)
  158625. write_scan_header (j_compress_ptr cinfo)
  158626. {
  158627. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  158628. int i;
  158629. jpeg_component_info *compptr;
  158630. if (cinfo->arith_code) {
  158631. /* Emit arith conditioning info. We may have some duplication
  158632. * if the file has multiple scans, but it's so small it's hardly
  158633. * worth worrying about.
  158634. */
  158635. emit_dac(cinfo);
  158636. } else {
  158637. /* Emit Huffman tables.
  158638. * Note that emit_dht() suppresses any duplicate tables.
  158639. */
  158640. for (i = 0; i < cinfo->comps_in_scan; i++) {
  158641. compptr = cinfo->cur_comp_info[i];
  158642. if (cinfo->progressive_mode) {
  158643. /* Progressive mode: only DC or only AC tables are used in one scan */
  158644. if (cinfo->Ss == 0) {
  158645. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  158646. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  158647. } else {
  158648. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  158649. }
  158650. } else {
  158651. /* Sequential mode: need both DC and AC tables */
  158652. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  158653. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  158654. }
  158655. }
  158656. }
  158657. /* Emit DRI if required --- note that DRI value could change for each scan.
  158658. * We avoid wasting space with unnecessary DRIs, however.
  158659. */
  158660. if (cinfo->restart_interval != marker->last_restart_interval) {
  158661. emit_dri(cinfo);
  158662. marker->last_restart_interval = cinfo->restart_interval;
  158663. }
  158664. emit_sos(cinfo);
  158665. }
  158666. /*
  158667. * Write datastream trailer.
  158668. */
  158669. METHODDEF(void)
  158670. write_file_trailer (j_compress_ptr cinfo)
  158671. {
  158672. emit_marker(cinfo, M_EOI);
  158673. }
  158674. /*
  158675. * Write an abbreviated table-specification datastream.
  158676. * This consists of SOI, DQT and DHT tables, and EOI.
  158677. * Any table that is defined and not marked sent_table = TRUE will be
  158678. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  158679. */
  158680. METHODDEF(void)
  158681. write_tables_only (j_compress_ptr cinfo)
  158682. {
  158683. int i;
  158684. emit_marker(cinfo, M_SOI);
  158685. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  158686. if (cinfo->quant_tbl_ptrs[i] != NULL)
  158687. (void) emit_dqt(cinfo, i);
  158688. }
  158689. if (! cinfo->arith_code) {
  158690. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  158691. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  158692. emit_dht(cinfo, i, FALSE);
  158693. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  158694. emit_dht(cinfo, i, TRUE);
  158695. }
  158696. }
  158697. emit_marker(cinfo, M_EOI);
  158698. }
  158699. /*
  158700. * Initialize the marker writer module.
  158701. */
  158702. GLOBAL(void)
  158703. jinit_marker_writer (j_compress_ptr cinfo)
  158704. {
  158705. my_marker_ptr marker;
  158706. /* Create the subobject */
  158707. marker = (my_marker_ptr)
  158708. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158709. SIZEOF(my_marker_writer));
  158710. cinfo->marker = (struct jpeg_marker_writer *) marker;
  158711. /* Initialize method pointers */
  158712. marker->pub.write_file_header = write_file_header;
  158713. marker->pub.write_frame_header = write_frame_header;
  158714. marker->pub.write_scan_header = write_scan_header;
  158715. marker->pub.write_file_trailer = write_file_trailer;
  158716. marker->pub.write_tables_only = write_tables_only;
  158717. marker->pub.write_marker_header = write_marker_header;
  158718. marker->pub.write_marker_byte = write_marker_byte;
  158719. /* Initialize private state */
  158720. marker->last_restart_interval = 0;
  158721. }
  158722. /********* End of inlined file: jcmarker.c *********/
  158723. /********* Start of inlined file: jcmaster.c *********/
  158724. #define JPEG_INTERNALS
  158725. /* Private state */
  158726. typedef enum {
  158727. main_pass, /* input data, also do first output step */
  158728. huff_opt_pass, /* Huffman code optimization pass */
  158729. output_pass /* data output pass */
  158730. } c_pass_type;
  158731. typedef struct {
  158732. struct jpeg_comp_master pub; /* public fields */
  158733. c_pass_type pass_type; /* the type of the current pass */
  158734. int pass_number; /* # of passes completed */
  158735. int total_passes; /* total # of passes needed */
  158736. int scan_number; /* current index in scan_info[] */
  158737. } my_comp_master;
  158738. typedef my_comp_master * my_master_ptr;
  158739. /*
  158740. * Support routines that do various essential calculations.
  158741. */
  158742. LOCAL(void)
  158743. initial_setup (j_compress_ptr cinfo)
  158744. /* Do computations that are needed before master selection phase */
  158745. {
  158746. int ci;
  158747. jpeg_component_info *compptr;
  158748. long samplesperrow;
  158749. JDIMENSION jd_samplesperrow;
  158750. /* Sanity check on image dimensions */
  158751. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  158752. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  158753. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  158754. /* Make sure image isn't bigger than I can handle */
  158755. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  158756. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  158757. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  158758. /* Width of an input scanline must be representable as JDIMENSION. */
  158759. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  158760. jd_samplesperrow = (JDIMENSION) samplesperrow;
  158761. if ((long) jd_samplesperrow != samplesperrow)
  158762. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  158763. /* For now, precision must match compiled-in value... */
  158764. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  158765. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  158766. /* Check that number of components won't exceed internal array sizes */
  158767. if (cinfo->num_components > MAX_COMPONENTS)
  158768. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  158769. MAX_COMPONENTS);
  158770. /* Compute maximum sampling factors; check factor validity */
  158771. cinfo->max_h_samp_factor = 1;
  158772. cinfo->max_v_samp_factor = 1;
  158773. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158774. ci++, compptr++) {
  158775. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  158776. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  158777. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  158778. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  158779. compptr->h_samp_factor);
  158780. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  158781. compptr->v_samp_factor);
  158782. }
  158783. /* Compute dimensions of components */
  158784. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158785. ci++, compptr++) {
  158786. /* Fill in the correct component_index value; don't rely on application */
  158787. compptr->component_index = ci;
  158788. /* For compression, we never do DCT scaling. */
  158789. compptr->DCT_scaled_size = DCTSIZE;
  158790. /* Size in DCT blocks */
  158791. compptr->width_in_blocks = (JDIMENSION)
  158792. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  158793. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  158794. compptr->height_in_blocks = (JDIMENSION)
  158795. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  158796. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  158797. /* Size in samples */
  158798. compptr->downsampled_width = (JDIMENSION)
  158799. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  158800. (long) cinfo->max_h_samp_factor);
  158801. compptr->downsampled_height = (JDIMENSION)
  158802. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  158803. (long) cinfo->max_v_samp_factor);
  158804. /* Mark component needed (this flag isn't actually used for compression) */
  158805. compptr->component_needed = TRUE;
  158806. }
  158807. /* Compute number of fully interleaved MCU rows (number of times that
  158808. * main controller will call coefficient controller).
  158809. */
  158810. cinfo->total_iMCU_rows = (JDIMENSION)
  158811. jdiv_round_up((long) cinfo->image_height,
  158812. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  158813. }
  158814. #ifdef C_MULTISCAN_FILES_SUPPORTED
  158815. LOCAL(void)
  158816. validate_script (j_compress_ptr cinfo)
  158817. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  158818. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  158819. */
  158820. {
  158821. const jpeg_scan_info * scanptr;
  158822. int scanno, ncomps, ci, coefi, thisi;
  158823. int Ss, Se, Ah, Al;
  158824. boolean component_sent[MAX_COMPONENTS];
  158825. #ifdef C_PROGRESSIVE_SUPPORTED
  158826. int * last_bitpos_ptr;
  158827. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  158828. /* -1 until that coefficient has been seen; then last Al for it */
  158829. #endif
  158830. if (cinfo->num_scans <= 0)
  158831. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  158832. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  158833. * for progressive JPEG, no scan can have this.
  158834. */
  158835. scanptr = cinfo->scan_info;
  158836. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  158837. #ifdef C_PROGRESSIVE_SUPPORTED
  158838. cinfo->progressive_mode = TRUE;
  158839. last_bitpos_ptr = & last_bitpos[0][0];
  158840. for (ci = 0; ci < cinfo->num_components; ci++)
  158841. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  158842. *last_bitpos_ptr++ = -1;
  158843. #else
  158844. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158845. #endif
  158846. } else {
  158847. cinfo->progressive_mode = FALSE;
  158848. for (ci = 0; ci < cinfo->num_components; ci++)
  158849. component_sent[ci] = FALSE;
  158850. }
  158851. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  158852. /* Validate component indexes */
  158853. ncomps = scanptr->comps_in_scan;
  158854. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  158855. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  158856. for (ci = 0; ci < ncomps; ci++) {
  158857. thisi = scanptr->component_index[ci];
  158858. if (thisi < 0 || thisi >= cinfo->num_components)
  158859. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  158860. /* Components must appear in SOF order within each scan */
  158861. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  158862. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  158863. }
  158864. /* Validate progression parameters */
  158865. Ss = scanptr->Ss;
  158866. Se = scanptr->Se;
  158867. Ah = scanptr->Ah;
  158868. Al = scanptr->Al;
  158869. if (cinfo->progressive_mode) {
  158870. #ifdef C_PROGRESSIVE_SUPPORTED
  158871. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  158872. * seems wrong: the upper bound ought to depend on data precision.
  158873. * Perhaps they really meant 0..N+1 for N-bit precision.
  158874. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  158875. * out-of-range reconstructed DC values during the first DC scan,
  158876. * which might cause problems for some decoders.
  158877. */
  158878. #if BITS_IN_JSAMPLE == 8
  158879. #define MAX_AH_AL 10
  158880. #else
  158881. #define MAX_AH_AL 13
  158882. #endif
  158883. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  158884. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  158885. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158886. if (Ss == 0) {
  158887. if (Se != 0) /* DC and AC together not OK */
  158888. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158889. } else {
  158890. if (ncomps != 1) /* AC scans must be for only one component */
  158891. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158892. }
  158893. for (ci = 0; ci < ncomps; ci++) {
  158894. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  158895. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  158896. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158897. for (coefi = Ss; coefi <= Se; coefi++) {
  158898. if (last_bitpos_ptr[coefi] < 0) {
  158899. /* first scan of this coefficient */
  158900. if (Ah != 0)
  158901. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158902. } else {
  158903. /* not first scan */
  158904. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  158905. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158906. }
  158907. last_bitpos_ptr[coefi] = Al;
  158908. }
  158909. }
  158910. #endif
  158911. } else {
  158912. /* For sequential JPEG, all progression parameters must be these: */
  158913. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  158914. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158915. /* Make sure components are not sent twice */
  158916. for (ci = 0; ci < ncomps; ci++) {
  158917. thisi = scanptr->component_index[ci];
  158918. if (component_sent[thisi])
  158919. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  158920. component_sent[thisi] = TRUE;
  158921. }
  158922. }
  158923. }
  158924. /* Now verify that everything got sent. */
  158925. if (cinfo->progressive_mode) {
  158926. #ifdef C_PROGRESSIVE_SUPPORTED
  158927. /* For progressive mode, we only check that at least some DC data
  158928. * got sent for each component; the spec does not require that all bits
  158929. * of all coefficients be transmitted. Would it be wiser to enforce
  158930. * transmission of all coefficient bits??
  158931. */
  158932. for (ci = 0; ci < cinfo->num_components; ci++) {
  158933. if (last_bitpos[ci][0] < 0)
  158934. ERREXIT(cinfo, JERR_MISSING_DATA);
  158935. }
  158936. #endif
  158937. } else {
  158938. for (ci = 0; ci < cinfo->num_components; ci++) {
  158939. if (! component_sent[ci])
  158940. ERREXIT(cinfo, JERR_MISSING_DATA);
  158941. }
  158942. }
  158943. }
  158944. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  158945. LOCAL(void)
  158946. select_scan_parameters (j_compress_ptr cinfo)
  158947. /* Set up the scan parameters for the current scan */
  158948. {
  158949. int ci;
  158950. #ifdef C_MULTISCAN_FILES_SUPPORTED
  158951. if (cinfo->scan_info != NULL) {
  158952. /* Prepare for current scan --- the script is already validated */
  158953. my_master_ptr master = (my_master_ptr) cinfo->master;
  158954. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  158955. cinfo->comps_in_scan = scanptr->comps_in_scan;
  158956. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  158957. cinfo->cur_comp_info[ci] =
  158958. &cinfo->comp_info[scanptr->component_index[ci]];
  158959. }
  158960. cinfo->Ss = scanptr->Ss;
  158961. cinfo->Se = scanptr->Se;
  158962. cinfo->Ah = scanptr->Ah;
  158963. cinfo->Al = scanptr->Al;
  158964. }
  158965. else
  158966. #endif
  158967. {
  158968. /* Prepare for single sequential-JPEG scan containing all components */
  158969. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  158970. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  158971. MAX_COMPS_IN_SCAN);
  158972. cinfo->comps_in_scan = cinfo->num_components;
  158973. for (ci = 0; ci < cinfo->num_components; ci++) {
  158974. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  158975. }
  158976. cinfo->Ss = 0;
  158977. cinfo->Se = DCTSIZE2-1;
  158978. cinfo->Ah = 0;
  158979. cinfo->Al = 0;
  158980. }
  158981. }
  158982. LOCAL(void)
  158983. per_scan_setup (j_compress_ptr cinfo)
  158984. /* Do computations that are needed before processing a JPEG scan */
  158985. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  158986. {
  158987. int ci, mcublks, tmp;
  158988. jpeg_component_info *compptr;
  158989. if (cinfo->comps_in_scan == 1) {
  158990. /* Noninterleaved (single-component) scan */
  158991. compptr = cinfo->cur_comp_info[0];
  158992. /* Overall image size in MCUs */
  158993. cinfo->MCUs_per_row = compptr->width_in_blocks;
  158994. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  158995. /* For noninterleaved scan, always one block per MCU */
  158996. compptr->MCU_width = 1;
  158997. compptr->MCU_height = 1;
  158998. compptr->MCU_blocks = 1;
  158999. compptr->MCU_sample_width = DCTSIZE;
  159000. compptr->last_col_width = 1;
  159001. /* For noninterleaved scans, it is convenient to define last_row_height
  159002. * as the number of block rows present in the last iMCU row.
  159003. */
  159004. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  159005. if (tmp == 0) tmp = compptr->v_samp_factor;
  159006. compptr->last_row_height = tmp;
  159007. /* Prepare array describing MCU composition */
  159008. cinfo->blocks_in_MCU = 1;
  159009. cinfo->MCU_membership[0] = 0;
  159010. } else {
  159011. /* Interleaved (multi-component) scan */
  159012. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  159013. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  159014. MAX_COMPS_IN_SCAN);
  159015. /* Overall image size in MCUs */
  159016. cinfo->MCUs_per_row = (JDIMENSION)
  159017. jdiv_round_up((long) cinfo->image_width,
  159018. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  159019. cinfo->MCU_rows_in_scan = (JDIMENSION)
  159020. jdiv_round_up((long) cinfo->image_height,
  159021. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  159022. cinfo->blocks_in_MCU = 0;
  159023. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159024. compptr = cinfo->cur_comp_info[ci];
  159025. /* Sampling factors give # of blocks of component in each MCU */
  159026. compptr->MCU_width = compptr->h_samp_factor;
  159027. compptr->MCU_height = compptr->v_samp_factor;
  159028. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  159029. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  159030. /* Figure number of non-dummy blocks in last MCU column & row */
  159031. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  159032. if (tmp == 0) tmp = compptr->MCU_width;
  159033. compptr->last_col_width = tmp;
  159034. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  159035. if (tmp == 0) tmp = compptr->MCU_height;
  159036. compptr->last_row_height = tmp;
  159037. /* Prepare array describing MCU composition */
  159038. mcublks = compptr->MCU_blocks;
  159039. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  159040. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  159041. while (mcublks-- > 0) {
  159042. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  159043. }
  159044. }
  159045. }
  159046. /* Convert restart specified in rows to actual MCU count. */
  159047. /* Note that count must fit in 16 bits, so we provide limiting. */
  159048. if (cinfo->restart_in_rows > 0) {
  159049. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  159050. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  159051. }
  159052. }
  159053. /*
  159054. * Per-pass setup.
  159055. * This is called at the beginning of each pass. We determine which modules
  159056. * will be active during this pass and give them appropriate start_pass calls.
  159057. * We also set is_last_pass to indicate whether any more passes will be
  159058. * required.
  159059. */
  159060. METHODDEF(void)
  159061. prepare_for_pass (j_compress_ptr cinfo)
  159062. {
  159063. my_master_ptr master = (my_master_ptr) cinfo->master;
  159064. switch (master->pass_type) {
  159065. case main_pass:
  159066. /* Initial pass: will collect input data, and do either Huffman
  159067. * optimization or data output for the first scan.
  159068. */
  159069. select_scan_parameters(cinfo);
  159070. per_scan_setup(cinfo);
  159071. if (! cinfo->raw_data_in) {
  159072. (*cinfo->cconvert->start_pass) (cinfo);
  159073. (*cinfo->downsample->start_pass) (cinfo);
  159074. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  159075. }
  159076. (*cinfo->fdct->start_pass) (cinfo);
  159077. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  159078. (*cinfo->coef->start_pass) (cinfo,
  159079. (master->total_passes > 1 ?
  159080. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  159081. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  159082. if (cinfo->optimize_coding) {
  159083. /* No immediate data output; postpone writing frame/scan headers */
  159084. master->pub.call_pass_startup = FALSE;
  159085. } else {
  159086. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  159087. master->pub.call_pass_startup = TRUE;
  159088. }
  159089. break;
  159090. #ifdef ENTROPY_OPT_SUPPORTED
  159091. case huff_opt_pass:
  159092. /* Do Huffman optimization for a scan after the first one. */
  159093. select_scan_parameters(cinfo);
  159094. per_scan_setup(cinfo);
  159095. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  159096. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  159097. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  159098. master->pub.call_pass_startup = FALSE;
  159099. break;
  159100. }
  159101. /* Special case: Huffman DC refinement scans need no Huffman table
  159102. * and therefore we can skip the optimization pass for them.
  159103. */
  159104. master->pass_type = output_pass;
  159105. master->pass_number++;
  159106. /*FALLTHROUGH*/
  159107. #endif
  159108. case output_pass:
  159109. /* Do a data-output pass. */
  159110. /* We need not repeat per-scan setup if prior optimization pass did it. */
  159111. if (! cinfo->optimize_coding) {
  159112. select_scan_parameters(cinfo);
  159113. per_scan_setup(cinfo);
  159114. }
  159115. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  159116. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  159117. /* We emit frame/scan headers now */
  159118. if (master->scan_number == 0)
  159119. (*cinfo->marker->write_frame_header) (cinfo);
  159120. (*cinfo->marker->write_scan_header) (cinfo);
  159121. master->pub.call_pass_startup = FALSE;
  159122. break;
  159123. default:
  159124. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159125. }
  159126. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  159127. /* Set up progress monitor's pass info if present */
  159128. if (cinfo->progress != NULL) {
  159129. cinfo->progress->completed_passes = master->pass_number;
  159130. cinfo->progress->total_passes = master->total_passes;
  159131. }
  159132. }
  159133. /*
  159134. * Special start-of-pass hook.
  159135. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  159136. * In single-pass processing, we need this hook because we don't want to
  159137. * write frame/scan headers during jpeg_start_compress; we want to let the
  159138. * application write COM markers etc. between jpeg_start_compress and the
  159139. * jpeg_write_scanlines loop.
  159140. * In multi-pass processing, this routine is not used.
  159141. */
  159142. METHODDEF(void)
  159143. pass_startup (j_compress_ptr cinfo)
  159144. {
  159145. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  159146. (*cinfo->marker->write_frame_header) (cinfo);
  159147. (*cinfo->marker->write_scan_header) (cinfo);
  159148. }
  159149. /*
  159150. * Finish up at end of pass.
  159151. */
  159152. METHODDEF(void)
  159153. finish_pass_master (j_compress_ptr cinfo)
  159154. {
  159155. my_master_ptr master = (my_master_ptr) cinfo->master;
  159156. /* The entropy coder always needs an end-of-pass call,
  159157. * either to analyze statistics or to flush its output buffer.
  159158. */
  159159. (*cinfo->entropy->finish_pass) (cinfo);
  159160. /* Update state for next pass */
  159161. switch (master->pass_type) {
  159162. case main_pass:
  159163. /* next pass is either output of scan 0 (after optimization)
  159164. * or output of scan 1 (if no optimization).
  159165. */
  159166. master->pass_type = output_pass;
  159167. if (! cinfo->optimize_coding)
  159168. master->scan_number++;
  159169. break;
  159170. case huff_opt_pass:
  159171. /* next pass is always output of current scan */
  159172. master->pass_type = output_pass;
  159173. break;
  159174. case output_pass:
  159175. /* next pass is either optimization or output of next scan */
  159176. if (cinfo->optimize_coding)
  159177. master->pass_type = huff_opt_pass;
  159178. master->scan_number++;
  159179. break;
  159180. }
  159181. master->pass_number++;
  159182. }
  159183. /*
  159184. * Initialize master compression control.
  159185. */
  159186. GLOBAL(void)
  159187. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  159188. {
  159189. my_master_ptr master;
  159190. master = (my_master_ptr)
  159191. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159192. SIZEOF(my_comp_master));
  159193. cinfo->master = (struct jpeg_comp_master *) master;
  159194. master->pub.prepare_for_pass = prepare_for_pass;
  159195. master->pub.pass_startup = pass_startup;
  159196. master->pub.finish_pass = finish_pass_master;
  159197. master->pub.is_last_pass = FALSE;
  159198. /* Validate parameters, determine derived values */
  159199. initial_setup(cinfo);
  159200. if (cinfo->scan_info != NULL) {
  159201. #ifdef C_MULTISCAN_FILES_SUPPORTED
  159202. validate_script(cinfo);
  159203. #else
  159204. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159205. #endif
  159206. } else {
  159207. cinfo->progressive_mode = FALSE;
  159208. cinfo->num_scans = 1;
  159209. }
  159210. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  159211. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  159212. /* Initialize my private state */
  159213. if (transcode_only) {
  159214. /* no main pass in transcoding */
  159215. if (cinfo->optimize_coding)
  159216. master->pass_type = huff_opt_pass;
  159217. else
  159218. master->pass_type = output_pass;
  159219. } else {
  159220. /* for normal compression, first pass is always this type: */
  159221. master->pass_type = main_pass;
  159222. }
  159223. master->scan_number = 0;
  159224. master->pass_number = 0;
  159225. if (cinfo->optimize_coding)
  159226. master->total_passes = cinfo->num_scans * 2;
  159227. else
  159228. master->total_passes = cinfo->num_scans;
  159229. }
  159230. /********* End of inlined file: jcmaster.c *********/
  159231. /********* Start of inlined file: jcomapi.c *********/
  159232. #define JPEG_INTERNALS
  159233. /*
  159234. * Abort processing of a JPEG compression or decompression operation,
  159235. * but don't destroy the object itself.
  159236. *
  159237. * For this, we merely clean up all the nonpermanent memory pools.
  159238. * Note that temp files (virtual arrays) are not allowed to belong to
  159239. * the permanent pool, so we will be able to close all temp files here.
  159240. * Closing a data source or destination, if necessary, is the application's
  159241. * responsibility.
  159242. */
  159243. GLOBAL(void)
  159244. jpeg_abort (j_common_ptr cinfo)
  159245. {
  159246. int pool;
  159247. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  159248. if (cinfo->mem == NULL)
  159249. return;
  159250. /* Releasing pools in reverse order might help avoid fragmentation
  159251. * with some (brain-damaged) malloc libraries.
  159252. */
  159253. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  159254. (*cinfo->mem->free_pool) (cinfo, pool);
  159255. }
  159256. /* Reset overall state for possible reuse of object */
  159257. if (cinfo->is_decompressor) {
  159258. cinfo->global_state = DSTATE_START;
  159259. /* Try to keep application from accessing now-deleted marker list.
  159260. * A bit kludgy to do it here, but this is the most central place.
  159261. */
  159262. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  159263. } else {
  159264. cinfo->global_state = CSTATE_START;
  159265. }
  159266. }
  159267. /*
  159268. * Destruction of a JPEG object.
  159269. *
  159270. * Everything gets deallocated except the master jpeg_compress_struct itself
  159271. * and the error manager struct. Both of these are supplied by the application
  159272. * and must be freed, if necessary, by the application. (Often they are on
  159273. * the stack and so don't need to be freed anyway.)
  159274. * Closing a data source or destination, if necessary, is the application's
  159275. * responsibility.
  159276. */
  159277. GLOBAL(void)
  159278. jpeg_destroy (j_common_ptr cinfo)
  159279. {
  159280. /* We need only tell the memory manager to release everything. */
  159281. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  159282. if (cinfo->mem != NULL)
  159283. (*cinfo->mem->self_destruct) (cinfo);
  159284. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  159285. cinfo->global_state = 0; /* mark it destroyed */
  159286. }
  159287. /*
  159288. * Convenience routines for allocating quantization and Huffman tables.
  159289. * (Would jutils.c be a more reasonable place to put these?)
  159290. */
  159291. GLOBAL(JQUANT_TBL *)
  159292. jpeg_alloc_quant_table (j_common_ptr cinfo)
  159293. {
  159294. JQUANT_TBL *tbl;
  159295. tbl = (JQUANT_TBL *)
  159296. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  159297. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  159298. return tbl;
  159299. }
  159300. GLOBAL(JHUFF_TBL *)
  159301. jpeg_alloc_huff_table (j_common_ptr cinfo)
  159302. {
  159303. JHUFF_TBL *tbl;
  159304. tbl = (JHUFF_TBL *)
  159305. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  159306. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  159307. return tbl;
  159308. }
  159309. /********* End of inlined file: jcomapi.c *********/
  159310. /********* Start of inlined file: jcparam.c *********/
  159311. #define JPEG_INTERNALS
  159312. /*
  159313. * Quantization table setup routines
  159314. */
  159315. GLOBAL(void)
  159316. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  159317. const unsigned int *basic_table,
  159318. int scale_factor, boolean force_baseline)
  159319. /* Define a quantization table equal to the basic_table times
  159320. * a scale factor (given as a percentage).
  159321. * If force_baseline is TRUE, the computed quantization table entries
  159322. * are limited to 1..255 for JPEG baseline compatibility.
  159323. */
  159324. {
  159325. JQUANT_TBL ** qtblptr;
  159326. int i;
  159327. long temp;
  159328. /* Safety check to ensure start_compress not called yet. */
  159329. if (cinfo->global_state != CSTATE_START)
  159330. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  159331. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  159332. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  159333. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  159334. if (*qtblptr == NULL)
  159335. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  159336. for (i = 0; i < DCTSIZE2; i++) {
  159337. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  159338. /* limit the values to the valid range */
  159339. if (temp <= 0L) temp = 1L;
  159340. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  159341. if (force_baseline && temp > 255L)
  159342. temp = 255L; /* limit to baseline range if requested */
  159343. (*qtblptr)->quantval[i] = (UINT16) temp;
  159344. }
  159345. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  159346. (*qtblptr)->sent_table = FALSE;
  159347. }
  159348. GLOBAL(void)
  159349. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  159350. boolean force_baseline)
  159351. /* Set or change the 'quality' (quantization) setting, using default tables
  159352. * and a straight percentage-scaling quality scale. In most cases it's better
  159353. * to use jpeg_set_quality (below); this entry point is provided for
  159354. * applications that insist on a linear percentage scaling.
  159355. */
  159356. {
  159357. /* These are the sample quantization tables given in JPEG spec section K.1.
  159358. * The spec says that the values given produce "good" quality, and
  159359. * when divided by 2, "very good" quality.
  159360. */
  159361. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  159362. 16, 11, 10, 16, 24, 40, 51, 61,
  159363. 12, 12, 14, 19, 26, 58, 60, 55,
  159364. 14, 13, 16, 24, 40, 57, 69, 56,
  159365. 14, 17, 22, 29, 51, 87, 80, 62,
  159366. 18, 22, 37, 56, 68, 109, 103, 77,
  159367. 24, 35, 55, 64, 81, 104, 113, 92,
  159368. 49, 64, 78, 87, 103, 121, 120, 101,
  159369. 72, 92, 95, 98, 112, 100, 103, 99
  159370. };
  159371. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  159372. 17, 18, 24, 47, 99, 99, 99, 99,
  159373. 18, 21, 26, 66, 99, 99, 99, 99,
  159374. 24, 26, 56, 99, 99, 99, 99, 99,
  159375. 47, 66, 99, 99, 99, 99, 99, 99,
  159376. 99, 99, 99, 99, 99, 99, 99, 99,
  159377. 99, 99, 99, 99, 99, 99, 99, 99,
  159378. 99, 99, 99, 99, 99, 99, 99, 99,
  159379. 99, 99, 99, 99, 99, 99, 99, 99
  159380. };
  159381. /* Set up two quantization tables using the specified scaling */
  159382. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  159383. scale_factor, force_baseline);
  159384. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  159385. scale_factor, force_baseline);
  159386. }
  159387. GLOBAL(int)
  159388. jpeg_quality_scaling (int quality)
  159389. /* Convert a user-specified quality rating to a percentage scaling factor
  159390. * for an underlying quantization table, using our recommended scaling curve.
  159391. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  159392. */
  159393. {
  159394. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  159395. if (quality <= 0) quality = 1;
  159396. if (quality > 100) quality = 100;
  159397. /* The basic table is used as-is (scaling 100) for a quality of 50.
  159398. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  159399. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  159400. * to make all the table entries 1 (hence, minimum quantization loss).
  159401. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  159402. */
  159403. if (quality < 50)
  159404. quality = 5000 / quality;
  159405. else
  159406. quality = 200 - quality*2;
  159407. return quality;
  159408. }
  159409. GLOBAL(void)
  159410. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  159411. /* Set or change the 'quality' (quantization) setting, using default tables.
  159412. * This is the standard quality-adjusting entry point for typical user
  159413. * interfaces; only those who want detailed control over quantization tables
  159414. * would use the preceding three routines directly.
  159415. */
  159416. {
  159417. /* Convert user 0-100 rating to percentage scaling */
  159418. quality = jpeg_quality_scaling(quality);
  159419. /* Set up standard quality tables */
  159420. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  159421. }
  159422. /*
  159423. * Huffman table setup routines
  159424. */
  159425. LOCAL(void)
  159426. add_huff_table (j_compress_ptr cinfo,
  159427. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  159428. /* Define a Huffman table */
  159429. {
  159430. int nsymbols, len;
  159431. if (*htblptr == NULL)
  159432. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  159433. /* Copy the number-of-symbols-of-each-code-length counts */
  159434. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  159435. /* Validate the counts. We do this here mainly so we can copy the right
  159436. * number of symbols from the val[] array, without risking marching off
  159437. * the end of memory. jchuff.c will do a more thorough test later.
  159438. */
  159439. nsymbols = 0;
  159440. for (len = 1; len <= 16; len++)
  159441. nsymbols += bits[len];
  159442. if (nsymbols < 1 || nsymbols > 256)
  159443. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  159444. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  159445. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  159446. (*htblptr)->sent_table = FALSE;
  159447. }
  159448. LOCAL(void)
  159449. std_huff_tables (j_compress_ptr cinfo)
  159450. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  159451. /* IMPORTANT: these are only valid for 8-bit data precision! */
  159452. {
  159453. static const UINT8 bits_dc_luminance[17] =
  159454. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  159455. static const UINT8 val_dc_luminance[] =
  159456. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  159457. static const UINT8 bits_dc_chrominance[17] =
  159458. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  159459. static const UINT8 val_dc_chrominance[] =
  159460. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  159461. static const UINT8 bits_ac_luminance[17] =
  159462. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  159463. static const UINT8 val_ac_luminance[] =
  159464. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  159465. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  159466. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  159467. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  159468. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  159469. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  159470. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  159471. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  159472. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  159473. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  159474. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  159475. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  159476. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  159477. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  159478. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  159479. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  159480. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  159481. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  159482. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  159483. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  159484. 0xf9, 0xfa };
  159485. static const UINT8 bits_ac_chrominance[17] =
  159486. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  159487. static const UINT8 val_ac_chrominance[] =
  159488. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  159489. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  159490. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  159491. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  159492. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  159493. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  159494. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  159495. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  159496. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  159497. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  159498. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  159499. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  159500. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  159501. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  159502. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  159503. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  159504. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  159505. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  159506. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  159507. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  159508. 0xf9, 0xfa };
  159509. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  159510. bits_dc_luminance, val_dc_luminance);
  159511. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  159512. bits_ac_luminance, val_ac_luminance);
  159513. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  159514. bits_dc_chrominance, val_dc_chrominance);
  159515. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  159516. bits_ac_chrominance, val_ac_chrominance);
  159517. }
  159518. /*
  159519. * Default parameter setup for compression.
  159520. *
  159521. * Applications that don't choose to use this routine must do their
  159522. * own setup of all these parameters. Alternately, you can call this
  159523. * to establish defaults and then alter parameters selectively. This
  159524. * is the recommended approach since, if we add any new parameters,
  159525. * your code will still work (they'll be set to reasonable defaults).
  159526. */
  159527. GLOBAL(void)
  159528. jpeg_set_defaults (j_compress_ptr cinfo)
  159529. {
  159530. int i;
  159531. /* Safety check to ensure start_compress not called yet. */
  159532. if (cinfo->global_state != CSTATE_START)
  159533. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  159534. /* Allocate comp_info array large enough for maximum component count.
  159535. * Array is made permanent in case application wants to compress
  159536. * multiple images at same param settings.
  159537. */
  159538. if (cinfo->comp_info == NULL)
  159539. cinfo->comp_info = (jpeg_component_info *)
  159540. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  159541. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  159542. /* Initialize everything not dependent on the color space */
  159543. cinfo->data_precision = BITS_IN_JSAMPLE;
  159544. /* Set up two quantization tables using default quality of 75 */
  159545. jpeg_set_quality(cinfo, 75, TRUE);
  159546. /* Set up two Huffman tables */
  159547. std_huff_tables(cinfo);
  159548. /* Initialize default arithmetic coding conditioning */
  159549. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  159550. cinfo->arith_dc_L[i] = 0;
  159551. cinfo->arith_dc_U[i] = 1;
  159552. cinfo->arith_ac_K[i] = 5;
  159553. }
  159554. /* Default is no multiple-scan output */
  159555. cinfo->scan_info = NULL;
  159556. cinfo->num_scans = 0;
  159557. /* Expect normal source image, not raw downsampled data */
  159558. cinfo->raw_data_in = FALSE;
  159559. /* Use Huffman coding, not arithmetic coding, by default */
  159560. cinfo->arith_code = FALSE;
  159561. /* By default, don't do extra passes to optimize entropy coding */
  159562. cinfo->optimize_coding = FALSE;
  159563. /* The standard Huffman tables are only valid for 8-bit data precision.
  159564. * If the precision is higher, force optimization on so that usable
  159565. * tables will be computed. This test can be removed if default tables
  159566. * are supplied that are valid for the desired precision.
  159567. */
  159568. if (cinfo->data_precision > 8)
  159569. cinfo->optimize_coding = TRUE;
  159570. /* By default, use the simpler non-cosited sampling alignment */
  159571. cinfo->CCIR601_sampling = FALSE;
  159572. /* No input smoothing */
  159573. cinfo->smoothing_factor = 0;
  159574. /* DCT algorithm preference */
  159575. cinfo->dct_method = JDCT_DEFAULT;
  159576. /* No restart markers */
  159577. cinfo->restart_interval = 0;
  159578. cinfo->restart_in_rows = 0;
  159579. /* Fill in default JFIF marker parameters. Note that whether the marker
  159580. * will actually be written is determined by jpeg_set_colorspace.
  159581. *
  159582. * By default, the library emits JFIF version code 1.01.
  159583. * An application that wants to emit JFIF 1.02 extension markers should set
  159584. * JFIF_minor_version to 2. We could probably get away with just defaulting
  159585. * to 1.02, but there may still be some decoders in use that will complain
  159586. * about that; saying 1.01 should minimize compatibility problems.
  159587. */
  159588. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  159589. cinfo->JFIF_minor_version = 1;
  159590. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  159591. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  159592. cinfo->Y_density = 1;
  159593. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  159594. jpeg_default_colorspace(cinfo);
  159595. }
  159596. /*
  159597. * Select an appropriate JPEG colorspace for in_color_space.
  159598. */
  159599. GLOBAL(void)
  159600. jpeg_default_colorspace (j_compress_ptr cinfo)
  159601. {
  159602. switch (cinfo->in_color_space) {
  159603. case JCS_GRAYSCALE:
  159604. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  159605. break;
  159606. case JCS_RGB:
  159607. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  159608. break;
  159609. case JCS_YCbCr:
  159610. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  159611. break;
  159612. case JCS_CMYK:
  159613. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  159614. break;
  159615. case JCS_YCCK:
  159616. jpeg_set_colorspace(cinfo, JCS_YCCK);
  159617. break;
  159618. case JCS_UNKNOWN:
  159619. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  159620. break;
  159621. default:
  159622. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159623. }
  159624. }
  159625. /*
  159626. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  159627. */
  159628. GLOBAL(void)
  159629. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  159630. {
  159631. jpeg_component_info * compptr;
  159632. int ci;
  159633. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  159634. (compptr = &cinfo->comp_info[index], \
  159635. compptr->component_id = (id), \
  159636. compptr->h_samp_factor = (hsamp), \
  159637. compptr->v_samp_factor = (vsamp), \
  159638. compptr->quant_tbl_no = (quant), \
  159639. compptr->dc_tbl_no = (dctbl), \
  159640. compptr->ac_tbl_no = (actbl) )
  159641. /* Safety check to ensure start_compress not called yet. */
  159642. if (cinfo->global_state != CSTATE_START)
  159643. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  159644. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  159645. * tables 1 for chrominance components.
  159646. */
  159647. cinfo->jpeg_color_space = colorspace;
  159648. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  159649. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  159650. switch (colorspace) {
  159651. case JCS_GRAYSCALE:
  159652. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  159653. cinfo->num_components = 1;
  159654. /* JFIF specifies component ID 1 */
  159655. SET_COMP(0, 1, 1,1, 0, 0,0);
  159656. break;
  159657. case JCS_RGB:
  159658. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  159659. cinfo->num_components = 3;
  159660. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  159661. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  159662. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  159663. break;
  159664. case JCS_YCbCr:
  159665. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  159666. cinfo->num_components = 3;
  159667. /* JFIF specifies component IDs 1,2,3 */
  159668. /* We default to 2x2 subsamples of chrominance */
  159669. SET_COMP(0, 1, 2,2, 0, 0,0);
  159670. SET_COMP(1, 2, 1,1, 1, 1,1);
  159671. SET_COMP(2, 3, 1,1, 1, 1,1);
  159672. break;
  159673. case JCS_CMYK:
  159674. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  159675. cinfo->num_components = 4;
  159676. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  159677. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  159678. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  159679. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  159680. break;
  159681. case JCS_YCCK:
  159682. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  159683. cinfo->num_components = 4;
  159684. SET_COMP(0, 1, 2,2, 0, 0,0);
  159685. SET_COMP(1, 2, 1,1, 1, 1,1);
  159686. SET_COMP(2, 3, 1,1, 1, 1,1);
  159687. SET_COMP(3, 4, 2,2, 0, 0,0);
  159688. break;
  159689. case JCS_UNKNOWN:
  159690. cinfo->num_components = cinfo->input_components;
  159691. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  159692. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  159693. MAX_COMPONENTS);
  159694. for (ci = 0; ci < cinfo->num_components; ci++) {
  159695. SET_COMP(ci, ci, 1,1, 0, 0,0);
  159696. }
  159697. break;
  159698. default:
  159699. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159700. }
  159701. }
  159702. #ifdef C_PROGRESSIVE_SUPPORTED
  159703. LOCAL(jpeg_scan_info *)
  159704. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  159705. int Ss, int Se, int Ah, int Al)
  159706. /* Support routine: generate one scan for specified component */
  159707. {
  159708. scanptr->comps_in_scan = 1;
  159709. scanptr->component_index[0] = ci;
  159710. scanptr->Ss = Ss;
  159711. scanptr->Se = Se;
  159712. scanptr->Ah = Ah;
  159713. scanptr->Al = Al;
  159714. scanptr++;
  159715. return scanptr;
  159716. }
  159717. LOCAL(jpeg_scan_info *)
  159718. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  159719. int Ss, int Se, int Ah, int Al)
  159720. /* Support routine: generate one scan for each component */
  159721. {
  159722. int ci;
  159723. for (ci = 0; ci < ncomps; ci++) {
  159724. scanptr->comps_in_scan = 1;
  159725. scanptr->component_index[0] = ci;
  159726. scanptr->Ss = Ss;
  159727. scanptr->Se = Se;
  159728. scanptr->Ah = Ah;
  159729. scanptr->Al = Al;
  159730. scanptr++;
  159731. }
  159732. return scanptr;
  159733. }
  159734. LOCAL(jpeg_scan_info *)
  159735. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  159736. /* Support routine: generate interleaved DC scan if possible, else N scans */
  159737. {
  159738. int ci;
  159739. if (ncomps <= MAX_COMPS_IN_SCAN) {
  159740. /* Single interleaved DC scan */
  159741. scanptr->comps_in_scan = ncomps;
  159742. for (ci = 0; ci < ncomps; ci++)
  159743. scanptr->component_index[ci] = ci;
  159744. scanptr->Ss = scanptr->Se = 0;
  159745. scanptr->Ah = Ah;
  159746. scanptr->Al = Al;
  159747. scanptr++;
  159748. } else {
  159749. /* Noninterleaved DC scan for each component */
  159750. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  159751. }
  159752. return scanptr;
  159753. }
  159754. /*
  159755. * Create a recommended progressive-JPEG script.
  159756. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  159757. */
  159758. GLOBAL(void)
  159759. jpeg_simple_progression (j_compress_ptr cinfo)
  159760. {
  159761. int ncomps = cinfo->num_components;
  159762. int nscans;
  159763. jpeg_scan_info * scanptr;
  159764. /* Safety check to ensure start_compress not called yet. */
  159765. if (cinfo->global_state != CSTATE_START)
  159766. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  159767. /* Figure space needed for script. Calculation must match code below! */
  159768. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  159769. /* Custom script for YCbCr color images. */
  159770. nscans = 10;
  159771. } else {
  159772. /* All-purpose script for other color spaces. */
  159773. if (ncomps > MAX_COMPS_IN_SCAN)
  159774. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  159775. else
  159776. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  159777. }
  159778. /* Allocate space for script.
  159779. * We need to put it in the permanent pool in case the application performs
  159780. * multiple compressions without changing the settings. To avoid a memory
  159781. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  159782. * object, we try to re-use previously allocated space, and we allocate
  159783. * enough space to handle YCbCr even if initially asked for grayscale.
  159784. */
  159785. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  159786. cinfo->script_space_size = MAX(nscans, 10);
  159787. cinfo->script_space = (jpeg_scan_info *)
  159788. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  159789. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  159790. }
  159791. scanptr = cinfo->script_space;
  159792. cinfo->scan_info = scanptr;
  159793. cinfo->num_scans = nscans;
  159794. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  159795. /* Custom script for YCbCr color images. */
  159796. /* Initial DC scan */
  159797. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  159798. /* Initial AC scan: get some luma data out in a hurry */
  159799. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  159800. /* Chroma data is too small to be worth expending many scans on */
  159801. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  159802. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  159803. /* Complete spectral selection for luma AC */
  159804. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  159805. /* Refine next bit of luma AC */
  159806. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  159807. /* Finish DC successive approximation */
  159808. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  159809. /* Finish AC successive approximation */
  159810. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  159811. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  159812. /* Luma bottom bit comes last since it's usually largest scan */
  159813. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  159814. } else {
  159815. /* All-purpose script for other color spaces. */
  159816. /* Successive approximation first pass */
  159817. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  159818. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  159819. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  159820. /* Successive approximation second pass */
  159821. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  159822. /* Successive approximation final pass */
  159823. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  159824. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  159825. }
  159826. }
  159827. #endif /* C_PROGRESSIVE_SUPPORTED */
  159828. /********* End of inlined file: jcparam.c *********/
  159829. /********* Start of inlined file: jcphuff.c *********/
  159830. #define JPEG_INTERNALS
  159831. #ifdef C_PROGRESSIVE_SUPPORTED
  159832. /* Expanded entropy encoder object for progressive Huffman encoding. */
  159833. typedef struct {
  159834. struct jpeg_entropy_encoder pub; /* public fields */
  159835. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  159836. boolean gather_statistics;
  159837. /* Bit-level coding status.
  159838. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  159839. */
  159840. JOCTET * next_output_byte; /* => next byte to write in buffer */
  159841. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  159842. INT32 put_buffer; /* current bit-accumulation buffer */
  159843. int put_bits; /* # of bits now in it */
  159844. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  159845. /* Coding status for DC components */
  159846. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  159847. /* Coding status for AC components */
  159848. int ac_tbl_no; /* the table number of the single component */
  159849. unsigned int EOBRUN; /* run length of EOBs */
  159850. unsigned int BE; /* # of buffered correction bits before MCU */
  159851. char * bit_buffer; /* buffer for correction bits (1 per char) */
  159852. /* packing correction bits tightly would save some space but cost time... */
  159853. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  159854. int next_restart_num; /* next restart number to write (0-7) */
  159855. /* Pointers to derived tables (these workspaces have image lifespan).
  159856. * Since any one scan codes only DC or only AC, we only need one set
  159857. * of tables, not one for DC and one for AC.
  159858. */
  159859. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  159860. /* Statistics tables for optimization; again, one set is enough */
  159861. long * count_ptrs[NUM_HUFF_TBLS];
  159862. } phuff_entropy_encoder;
  159863. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  159864. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  159865. * buffer can hold. Larger sizes may slightly improve compression, but
  159866. * 1000 is already well into the realm of overkill.
  159867. * The minimum safe size is 64 bits.
  159868. */
  159869. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  159870. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  159871. * We assume that int right shift is unsigned if INT32 right shift is,
  159872. * which should be safe.
  159873. */
  159874. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  159875. #define ISHIFT_TEMPS int ishift_temp;
  159876. #define IRIGHT_SHIFT(x,shft) \
  159877. ((ishift_temp = (x)) < 0 ? \
  159878. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  159879. (ishift_temp >> (shft)))
  159880. #else
  159881. #define ISHIFT_TEMPS
  159882. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  159883. #endif
  159884. /* Forward declarations */
  159885. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  159886. JBLOCKROW *MCU_data));
  159887. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  159888. JBLOCKROW *MCU_data));
  159889. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  159890. JBLOCKROW *MCU_data));
  159891. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  159892. JBLOCKROW *MCU_data));
  159893. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  159894. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  159895. /*
  159896. * Initialize for a Huffman-compressed scan using progressive JPEG.
  159897. */
  159898. METHODDEF(void)
  159899. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  159900. {
  159901. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  159902. boolean is_DC_band;
  159903. int ci, tbl;
  159904. jpeg_component_info * compptr;
  159905. entropy->cinfo = cinfo;
  159906. entropy->gather_statistics = gather_statistics;
  159907. is_DC_band = (cinfo->Ss == 0);
  159908. /* We assume jcmaster.c already validated the scan parameters. */
  159909. /* Select execution routines */
  159910. if (cinfo->Ah == 0) {
  159911. if (is_DC_band)
  159912. entropy->pub.encode_mcu = encode_mcu_DC_first;
  159913. else
  159914. entropy->pub.encode_mcu = encode_mcu_AC_first;
  159915. } else {
  159916. if (is_DC_band)
  159917. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  159918. else {
  159919. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  159920. /* AC refinement needs a correction bit buffer */
  159921. if (entropy->bit_buffer == NULL)
  159922. entropy->bit_buffer = (char *)
  159923. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159924. MAX_CORR_BITS * SIZEOF(char));
  159925. }
  159926. }
  159927. if (gather_statistics)
  159928. entropy->pub.finish_pass = finish_pass_gather_phuff;
  159929. else
  159930. entropy->pub.finish_pass = finish_pass_phuff;
  159931. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  159932. * for AC coefficients.
  159933. */
  159934. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159935. compptr = cinfo->cur_comp_info[ci];
  159936. /* Initialize DC predictions to 0 */
  159937. entropy->last_dc_val[ci] = 0;
  159938. /* Get table index */
  159939. if (is_DC_band) {
  159940. if (cinfo->Ah != 0) /* DC refinement needs no table */
  159941. continue;
  159942. tbl = compptr->dc_tbl_no;
  159943. } else {
  159944. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  159945. }
  159946. if (gather_statistics) {
  159947. /* Check for invalid table index */
  159948. /* (make_c_derived_tbl does this in the other path) */
  159949. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  159950. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  159951. /* Allocate and zero the statistics tables */
  159952. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  159953. if (entropy->count_ptrs[tbl] == NULL)
  159954. entropy->count_ptrs[tbl] = (long *)
  159955. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159956. 257 * SIZEOF(long));
  159957. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  159958. } else {
  159959. /* Compute derived values for Huffman table */
  159960. /* We may do this more than once for a table, but it's not expensive */
  159961. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  159962. & entropy->derived_tbls[tbl]);
  159963. }
  159964. }
  159965. /* Initialize AC stuff */
  159966. entropy->EOBRUN = 0;
  159967. entropy->BE = 0;
  159968. /* Initialize bit buffer to empty */
  159969. entropy->put_buffer = 0;
  159970. entropy->put_bits = 0;
  159971. /* Initialize restart stuff */
  159972. entropy->restarts_to_go = cinfo->restart_interval;
  159973. entropy->next_restart_num = 0;
  159974. }
  159975. /* Outputting bytes to the file.
  159976. * NB: these must be called only when actually outputting,
  159977. * that is, entropy->gather_statistics == FALSE.
  159978. */
  159979. /* Emit a byte */
  159980. #define emit_byte(entropy,val) \
  159981. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  159982. if (--(entropy)->free_in_buffer == 0) \
  159983. dump_buffer_p(entropy); }
  159984. LOCAL(void)
  159985. dump_buffer_p (phuff_entropy_ptr entropy)
  159986. /* Empty the output buffer; we do not support suspension in this module. */
  159987. {
  159988. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  159989. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  159990. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  159991. /* After a successful buffer dump, must reset buffer pointers */
  159992. entropy->next_output_byte = dest->next_output_byte;
  159993. entropy->free_in_buffer = dest->free_in_buffer;
  159994. }
  159995. /* Outputting bits to the file */
  159996. /* Only the right 24 bits of put_buffer are used; the valid bits are
  159997. * left-justified in this part. At most 16 bits can be passed to emit_bits
  159998. * in one call, and we never retain more than 7 bits in put_buffer
  159999. * between calls, so 24 bits are sufficient.
  160000. */
  160001. INLINE
  160002. LOCAL(void)
  160003. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  160004. /* Emit some bits, unless we are in gather mode */
  160005. {
  160006. /* This routine is heavily used, so it's worth coding tightly. */
  160007. register INT32 put_buffer = (INT32) code;
  160008. register int put_bits = entropy->put_bits;
  160009. /* if size is 0, caller used an invalid Huffman table entry */
  160010. if (size == 0)
  160011. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  160012. if (entropy->gather_statistics)
  160013. return; /* do nothing if we're only getting stats */
  160014. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  160015. put_bits += size; /* new number of bits in buffer */
  160016. put_buffer <<= 24 - put_bits; /* align incoming bits */
  160017. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  160018. while (put_bits >= 8) {
  160019. int c = (int) ((put_buffer >> 16) & 0xFF);
  160020. emit_byte(entropy, c);
  160021. if (c == 0xFF) { /* need to stuff a zero byte? */
  160022. emit_byte(entropy, 0);
  160023. }
  160024. put_buffer <<= 8;
  160025. put_bits -= 8;
  160026. }
  160027. entropy->put_buffer = put_buffer; /* update variables */
  160028. entropy->put_bits = put_bits;
  160029. }
  160030. LOCAL(void)
  160031. flush_bits_p (phuff_entropy_ptr entropy)
  160032. {
  160033. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  160034. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  160035. entropy->put_bits = 0;
  160036. }
  160037. /*
  160038. * Emit (or just count) a Huffman symbol.
  160039. */
  160040. INLINE
  160041. LOCAL(void)
  160042. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  160043. {
  160044. if (entropy->gather_statistics)
  160045. entropy->count_ptrs[tbl_no][symbol]++;
  160046. else {
  160047. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  160048. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  160049. }
  160050. }
  160051. /*
  160052. * Emit bits from a correction bit buffer.
  160053. */
  160054. LOCAL(void)
  160055. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  160056. unsigned int nbits)
  160057. {
  160058. if (entropy->gather_statistics)
  160059. return; /* no real work */
  160060. while (nbits > 0) {
  160061. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  160062. bufstart++;
  160063. nbits--;
  160064. }
  160065. }
  160066. /*
  160067. * Emit any pending EOBRUN symbol.
  160068. */
  160069. LOCAL(void)
  160070. emit_eobrun (phuff_entropy_ptr entropy)
  160071. {
  160072. register int temp, nbits;
  160073. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  160074. temp = entropy->EOBRUN;
  160075. nbits = 0;
  160076. while ((temp >>= 1))
  160077. nbits++;
  160078. /* safety check: shouldn't happen given limited correction-bit buffer */
  160079. if (nbits > 14)
  160080. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  160081. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  160082. if (nbits)
  160083. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  160084. entropy->EOBRUN = 0;
  160085. /* Emit any buffered correction bits */
  160086. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  160087. entropy->BE = 0;
  160088. }
  160089. }
  160090. /*
  160091. * Emit a restart marker & resynchronize predictions.
  160092. */
  160093. LOCAL(void)
  160094. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  160095. {
  160096. int ci;
  160097. emit_eobrun(entropy);
  160098. if (! entropy->gather_statistics) {
  160099. flush_bits_p(entropy);
  160100. emit_byte(entropy, 0xFF);
  160101. emit_byte(entropy, JPEG_RST0 + restart_num);
  160102. }
  160103. if (entropy->cinfo->Ss == 0) {
  160104. /* Re-initialize DC predictions to 0 */
  160105. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  160106. entropy->last_dc_val[ci] = 0;
  160107. } else {
  160108. /* Re-initialize all AC-related fields to 0 */
  160109. entropy->EOBRUN = 0;
  160110. entropy->BE = 0;
  160111. }
  160112. }
  160113. /*
  160114. * MCU encoding for DC initial scan (either spectral selection,
  160115. * or first pass of successive approximation).
  160116. */
  160117. METHODDEF(boolean)
  160118. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160119. {
  160120. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160121. register int temp, temp2;
  160122. register int nbits;
  160123. int blkn, ci;
  160124. int Al = cinfo->Al;
  160125. JBLOCKROW block;
  160126. jpeg_component_info * compptr;
  160127. ISHIFT_TEMPS
  160128. entropy->next_output_byte = cinfo->dest->next_output_byte;
  160129. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  160130. /* Emit restart marker if needed */
  160131. if (cinfo->restart_interval)
  160132. if (entropy->restarts_to_go == 0)
  160133. emit_restart_p(entropy, entropy->next_restart_num);
  160134. /* Encode the MCU data blocks */
  160135. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  160136. block = MCU_data[blkn];
  160137. ci = cinfo->MCU_membership[blkn];
  160138. compptr = cinfo->cur_comp_info[ci];
  160139. /* Compute the DC value after the required point transform by Al.
  160140. * This is simply an arithmetic right shift.
  160141. */
  160142. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  160143. /* DC differences are figured on the point-transformed values. */
  160144. temp = temp2 - entropy->last_dc_val[ci];
  160145. entropy->last_dc_val[ci] = temp2;
  160146. /* Encode the DC coefficient difference per section G.1.2.1 */
  160147. temp2 = temp;
  160148. if (temp < 0) {
  160149. temp = -temp; /* temp is abs value of input */
  160150. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  160151. /* This code assumes we are on a two's complement machine */
  160152. temp2--;
  160153. }
  160154. /* Find the number of bits needed for the magnitude of the coefficient */
  160155. nbits = 0;
  160156. while (temp) {
  160157. nbits++;
  160158. temp >>= 1;
  160159. }
  160160. /* Check for out-of-range coefficient values.
  160161. * Since we're encoding a difference, the range limit is twice as much.
  160162. */
  160163. if (nbits > MAX_COEF_BITS+1)
  160164. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  160165. /* Count/emit the Huffman-coded symbol for the number of bits */
  160166. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  160167. /* Emit that number of bits of the value, if positive, */
  160168. /* or the complement of its magnitude, if negative. */
  160169. if (nbits) /* emit_bits rejects calls with size 0 */
  160170. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  160171. }
  160172. cinfo->dest->next_output_byte = entropy->next_output_byte;
  160173. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  160174. /* Update restart-interval state too */
  160175. if (cinfo->restart_interval) {
  160176. if (entropy->restarts_to_go == 0) {
  160177. entropy->restarts_to_go = cinfo->restart_interval;
  160178. entropy->next_restart_num++;
  160179. entropy->next_restart_num &= 7;
  160180. }
  160181. entropy->restarts_to_go--;
  160182. }
  160183. return TRUE;
  160184. }
  160185. /*
  160186. * MCU encoding for AC initial scan (either spectral selection,
  160187. * or first pass of successive approximation).
  160188. */
  160189. METHODDEF(boolean)
  160190. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160191. {
  160192. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160193. register int temp, temp2;
  160194. register int nbits;
  160195. register int r, k;
  160196. int Se = cinfo->Se;
  160197. int Al = cinfo->Al;
  160198. JBLOCKROW block;
  160199. entropy->next_output_byte = cinfo->dest->next_output_byte;
  160200. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  160201. /* Emit restart marker if needed */
  160202. if (cinfo->restart_interval)
  160203. if (entropy->restarts_to_go == 0)
  160204. emit_restart_p(entropy, entropy->next_restart_num);
  160205. /* Encode the MCU data block */
  160206. block = MCU_data[0];
  160207. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  160208. r = 0; /* r = run length of zeros */
  160209. for (k = cinfo->Ss; k <= Se; k++) {
  160210. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  160211. r++;
  160212. continue;
  160213. }
  160214. /* We must apply the point transform by Al. For AC coefficients this
  160215. * is an integer division with rounding towards 0. To do this portably
  160216. * in C, we shift after obtaining the absolute value; so the code is
  160217. * interwoven with finding the abs value (temp) and output bits (temp2).
  160218. */
  160219. if (temp < 0) {
  160220. temp = -temp; /* temp is abs value of input */
  160221. temp >>= Al; /* apply the point transform */
  160222. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  160223. temp2 = ~temp;
  160224. } else {
  160225. temp >>= Al; /* apply the point transform */
  160226. temp2 = temp;
  160227. }
  160228. /* Watch out for case that nonzero coef is zero after point transform */
  160229. if (temp == 0) {
  160230. r++;
  160231. continue;
  160232. }
  160233. /* Emit any pending EOBRUN */
  160234. if (entropy->EOBRUN > 0)
  160235. emit_eobrun(entropy);
  160236. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  160237. while (r > 15) {
  160238. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  160239. r -= 16;
  160240. }
  160241. /* Find the number of bits needed for the magnitude of the coefficient */
  160242. nbits = 1; /* there must be at least one 1 bit */
  160243. while ((temp >>= 1))
  160244. nbits++;
  160245. /* Check for out-of-range coefficient values */
  160246. if (nbits > MAX_COEF_BITS)
  160247. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  160248. /* Count/emit Huffman symbol for run length / number of bits */
  160249. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  160250. /* Emit that number of bits of the value, if positive, */
  160251. /* or the complement of its magnitude, if negative. */
  160252. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  160253. r = 0; /* reset zero run length */
  160254. }
  160255. if (r > 0) { /* If there are trailing zeroes, */
  160256. entropy->EOBRUN++; /* count an EOB */
  160257. if (entropy->EOBRUN == 0x7FFF)
  160258. emit_eobrun(entropy); /* force it out to avoid overflow */
  160259. }
  160260. cinfo->dest->next_output_byte = entropy->next_output_byte;
  160261. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  160262. /* Update restart-interval state too */
  160263. if (cinfo->restart_interval) {
  160264. if (entropy->restarts_to_go == 0) {
  160265. entropy->restarts_to_go = cinfo->restart_interval;
  160266. entropy->next_restart_num++;
  160267. entropy->next_restart_num &= 7;
  160268. }
  160269. entropy->restarts_to_go--;
  160270. }
  160271. return TRUE;
  160272. }
  160273. /*
  160274. * MCU encoding for DC successive approximation refinement scan.
  160275. * Note: we assume such scans can be multi-component, although the spec
  160276. * is not very clear on the point.
  160277. */
  160278. METHODDEF(boolean)
  160279. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160280. {
  160281. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160282. register int temp;
  160283. int blkn;
  160284. int Al = cinfo->Al;
  160285. JBLOCKROW block;
  160286. entropy->next_output_byte = cinfo->dest->next_output_byte;
  160287. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  160288. /* Emit restart marker if needed */
  160289. if (cinfo->restart_interval)
  160290. if (entropy->restarts_to_go == 0)
  160291. emit_restart_p(entropy, entropy->next_restart_num);
  160292. /* Encode the MCU data blocks */
  160293. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  160294. block = MCU_data[blkn];
  160295. /* We simply emit the Al'th bit of the DC coefficient value. */
  160296. temp = (*block)[0];
  160297. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  160298. }
  160299. cinfo->dest->next_output_byte = entropy->next_output_byte;
  160300. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  160301. /* Update restart-interval state too */
  160302. if (cinfo->restart_interval) {
  160303. if (entropy->restarts_to_go == 0) {
  160304. entropy->restarts_to_go = cinfo->restart_interval;
  160305. entropy->next_restart_num++;
  160306. entropy->next_restart_num &= 7;
  160307. }
  160308. entropy->restarts_to_go--;
  160309. }
  160310. return TRUE;
  160311. }
  160312. /*
  160313. * MCU encoding for AC successive approximation refinement scan.
  160314. */
  160315. METHODDEF(boolean)
  160316. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160317. {
  160318. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160319. register int temp;
  160320. register int r, k;
  160321. int EOB;
  160322. char *BR_buffer;
  160323. unsigned int BR;
  160324. int Se = cinfo->Se;
  160325. int Al = cinfo->Al;
  160326. JBLOCKROW block;
  160327. int absvalues[DCTSIZE2];
  160328. entropy->next_output_byte = cinfo->dest->next_output_byte;
  160329. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  160330. /* Emit restart marker if needed */
  160331. if (cinfo->restart_interval)
  160332. if (entropy->restarts_to_go == 0)
  160333. emit_restart_p(entropy, entropy->next_restart_num);
  160334. /* Encode the MCU data block */
  160335. block = MCU_data[0];
  160336. /* It is convenient to make a pre-pass to determine the transformed
  160337. * coefficients' absolute values and the EOB position.
  160338. */
  160339. EOB = 0;
  160340. for (k = cinfo->Ss; k <= Se; k++) {
  160341. temp = (*block)[jpeg_natural_order[k]];
  160342. /* We must apply the point transform by Al. For AC coefficients this
  160343. * is an integer division with rounding towards 0. To do this portably
  160344. * in C, we shift after obtaining the absolute value.
  160345. */
  160346. if (temp < 0)
  160347. temp = -temp; /* temp is abs value of input */
  160348. temp >>= Al; /* apply the point transform */
  160349. absvalues[k] = temp; /* save abs value for main pass */
  160350. if (temp == 1)
  160351. EOB = k; /* EOB = index of last newly-nonzero coef */
  160352. }
  160353. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  160354. r = 0; /* r = run length of zeros */
  160355. BR = 0; /* BR = count of buffered bits added now */
  160356. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  160357. for (k = cinfo->Ss; k <= Se; k++) {
  160358. if ((temp = absvalues[k]) == 0) {
  160359. r++;
  160360. continue;
  160361. }
  160362. /* Emit any required ZRLs, but not if they can be folded into EOB */
  160363. while (r > 15 && k <= EOB) {
  160364. /* emit any pending EOBRUN and the BE correction bits */
  160365. emit_eobrun(entropy);
  160366. /* Emit ZRL */
  160367. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  160368. r -= 16;
  160369. /* Emit buffered correction bits that must be associated with ZRL */
  160370. emit_buffered_bits(entropy, BR_buffer, BR);
  160371. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  160372. BR = 0;
  160373. }
  160374. /* If the coef was previously nonzero, it only needs a correction bit.
  160375. * NOTE: a straight translation of the spec's figure G.7 would suggest
  160376. * that we also need to test r > 15. But if r > 15, we can only get here
  160377. * if k > EOB, which implies that this coefficient is not 1.
  160378. */
  160379. if (temp > 1) {
  160380. /* The correction bit is the next bit of the absolute value. */
  160381. BR_buffer[BR++] = (char) (temp & 1);
  160382. continue;
  160383. }
  160384. /* Emit any pending EOBRUN and the BE correction bits */
  160385. emit_eobrun(entropy);
  160386. /* Count/emit Huffman symbol for run length / number of bits */
  160387. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  160388. /* Emit output bit for newly-nonzero coef */
  160389. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  160390. emit_bits_p(entropy, (unsigned int) temp, 1);
  160391. /* Emit buffered correction bits that must be associated with this code */
  160392. emit_buffered_bits(entropy, BR_buffer, BR);
  160393. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  160394. BR = 0;
  160395. r = 0; /* reset zero run length */
  160396. }
  160397. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  160398. entropy->EOBRUN++; /* count an EOB */
  160399. entropy->BE += BR; /* concat my correction bits to older ones */
  160400. /* We force out the EOB if we risk either:
  160401. * 1. overflow of the EOB counter;
  160402. * 2. overflow of the correction bit buffer during the next MCU.
  160403. */
  160404. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  160405. emit_eobrun(entropy);
  160406. }
  160407. cinfo->dest->next_output_byte = entropy->next_output_byte;
  160408. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  160409. /* Update restart-interval state too */
  160410. if (cinfo->restart_interval) {
  160411. if (entropy->restarts_to_go == 0) {
  160412. entropy->restarts_to_go = cinfo->restart_interval;
  160413. entropy->next_restart_num++;
  160414. entropy->next_restart_num &= 7;
  160415. }
  160416. entropy->restarts_to_go--;
  160417. }
  160418. return TRUE;
  160419. }
  160420. /*
  160421. * Finish up at the end of a Huffman-compressed progressive scan.
  160422. */
  160423. METHODDEF(void)
  160424. finish_pass_phuff (j_compress_ptr cinfo)
  160425. {
  160426. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160427. entropy->next_output_byte = cinfo->dest->next_output_byte;
  160428. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  160429. /* Flush out any buffered data */
  160430. emit_eobrun(entropy);
  160431. flush_bits_p(entropy);
  160432. cinfo->dest->next_output_byte = entropy->next_output_byte;
  160433. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  160434. }
  160435. /*
  160436. * Finish up a statistics-gathering pass and create the new Huffman tables.
  160437. */
  160438. METHODDEF(void)
  160439. finish_pass_gather_phuff (j_compress_ptr cinfo)
  160440. {
  160441. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160442. boolean is_DC_band;
  160443. int ci, tbl;
  160444. jpeg_component_info * compptr;
  160445. JHUFF_TBL **htblptr;
  160446. boolean did[NUM_HUFF_TBLS];
  160447. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  160448. emit_eobrun(entropy);
  160449. is_DC_band = (cinfo->Ss == 0);
  160450. /* It's important not to apply jpeg_gen_optimal_table more than once
  160451. * per table, because it clobbers the input frequency counts!
  160452. */
  160453. MEMZERO(did, SIZEOF(did));
  160454. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160455. compptr = cinfo->cur_comp_info[ci];
  160456. if (is_DC_band) {
  160457. if (cinfo->Ah != 0) /* DC refinement needs no table */
  160458. continue;
  160459. tbl = compptr->dc_tbl_no;
  160460. } else {
  160461. tbl = compptr->ac_tbl_no;
  160462. }
  160463. if (! did[tbl]) {
  160464. if (is_DC_band)
  160465. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  160466. else
  160467. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  160468. if (*htblptr == NULL)
  160469. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  160470. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  160471. did[tbl] = TRUE;
  160472. }
  160473. }
  160474. }
  160475. /*
  160476. * Module initialization routine for progressive Huffman entropy encoding.
  160477. */
  160478. GLOBAL(void)
  160479. jinit_phuff_encoder (j_compress_ptr cinfo)
  160480. {
  160481. phuff_entropy_ptr entropy;
  160482. int i;
  160483. entropy = (phuff_entropy_ptr)
  160484. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160485. SIZEOF(phuff_entropy_encoder));
  160486. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  160487. entropy->pub.start_pass = start_pass_phuff;
  160488. /* Mark tables unallocated */
  160489. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160490. entropy->derived_tbls[i] = NULL;
  160491. entropy->count_ptrs[i] = NULL;
  160492. }
  160493. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  160494. }
  160495. #endif /* C_PROGRESSIVE_SUPPORTED */
  160496. /********* End of inlined file: jcphuff.c *********/
  160497. /********* Start of inlined file: jcprepct.c *********/
  160498. #define JPEG_INTERNALS
  160499. /* At present, jcsample.c can request context rows only for smoothing.
  160500. * In the future, we might also need context rows for CCIR601 sampling
  160501. * or other more-complex downsampling procedures. The code to support
  160502. * context rows should be compiled only if needed.
  160503. */
  160504. #ifdef INPUT_SMOOTHING_SUPPORTED
  160505. #define CONTEXT_ROWS_SUPPORTED
  160506. #endif
  160507. /*
  160508. * For the simple (no-context-row) case, we just need to buffer one
  160509. * row group's worth of pixels for the downsampling step. At the bottom of
  160510. * the image, we pad to a full row group by replicating the last pixel row.
  160511. * The downsampler's last output row is then replicated if needed to pad
  160512. * out to a full iMCU row.
  160513. *
  160514. * When providing context rows, we must buffer three row groups' worth of
  160515. * pixels. Three row groups are physically allocated, but the row pointer
  160516. * arrays are made five row groups high, with the extra pointers above and
  160517. * below "wrapping around" to point to the last and first real row groups.
  160518. * This allows the downsampler to access the proper context rows.
  160519. * At the top and bottom of the image, we create dummy context rows by
  160520. * copying the first or last real pixel row. This copying could be avoided
  160521. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  160522. * trouble on the compression side.
  160523. */
  160524. /* Private buffer controller object */
  160525. typedef struct {
  160526. struct jpeg_c_prep_controller pub; /* public fields */
  160527. /* Downsampling input buffer. This buffer holds color-converted data
  160528. * until we have enough to do a downsample step.
  160529. */
  160530. JSAMPARRAY color_buf[MAX_COMPONENTS];
  160531. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  160532. int next_buf_row; /* index of next row to store in color_buf */
  160533. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  160534. int this_row_group; /* starting row index of group to process */
  160535. int next_buf_stop; /* downsample when we reach this index */
  160536. #endif
  160537. } my_prep_controller;
  160538. typedef my_prep_controller * my_prep_ptr;
  160539. /*
  160540. * Initialize for a processing pass.
  160541. */
  160542. METHODDEF(void)
  160543. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  160544. {
  160545. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  160546. if (pass_mode != JBUF_PASS_THRU)
  160547. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160548. /* Initialize total-height counter for detecting bottom of image */
  160549. prep->rows_to_go = cinfo->image_height;
  160550. /* Mark the conversion buffer empty */
  160551. prep->next_buf_row = 0;
  160552. #ifdef CONTEXT_ROWS_SUPPORTED
  160553. /* Preset additional state variables for context mode.
  160554. * These aren't used in non-context mode, so we needn't test which mode.
  160555. */
  160556. prep->this_row_group = 0;
  160557. /* Set next_buf_stop to stop after two row groups have been read in. */
  160558. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  160559. #endif
  160560. }
  160561. /*
  160562. * Expand an image vertically from height input_rows to height output_rows,
  160563. * by duplicating the bottom row.
  160564. */
  160565. LOCAL(void)
  160566. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  160567. int input_rows, int output_rows)
  160568. {
  160569. register int row;
  160570. for (row = input_rows; row < output_rows; row++) {
  160571. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  160572. 1, num_cols);
  160573. }
  160574. }
  160575. /*
  160576. * Process some data in the simple no-context case.
  160577. *
  160578. * Preprocessor output data is counted in "row groups". A row group
  160579. * is defined to be v_samp_factor sample rows of each component.
  160580. * Downsampling will produce this much data from each max_v_samp_factor
  160581. * input rows.
  160582. */
  160583. METHODDEF(void)
  160584. pre_process_data (j_compress_ptr cinfo,
  160585. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160586. JDIMENSION in_rows_avail,
  160587. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  160588. JDIMENSION out_row_groups_avail)
  160589. {
  160590. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  160591. int numrows, ci;
  160592. JDIMENSION inrows;
  160593. jpeg_component_info * compptr;
  160594. while (*in_row_ctr < in_rows_avail &&
  160595. *out_row_group_ctr < out_row_groups_avail) {
  160596. /* Do color conversion to fill the conversion buffer. */
  160597. inrows = in_rows_avail - *in_row_ctr;
  160598. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  160599. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  160600. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  160601. prep->color_buf,
  160602. (JDIMENSION) prep->next_buf_row,
  160603. numrows);
  160604. *in_row_ctr += numrows;
  160605. prep->next_buf_row += numrows;
  160606. prep->rows_to_go -= numrows;
  160607. /* If at bottom of image, pad to fill the conversion buffer. */
  160608. if (prep->rows_to_go == 0 &&
  160609. prep->next_buf_row < cinfo->max_v_samp_factor) {
  160610. for (ci = 0; ci < cinfo->num_components; ci++) {
  160611. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  160612. prep->next_buf_row, cinfo->max_v_samp_factor);
  160613. }
  160614. prep->next_buf_row = cinfo->max_v_samp_factor;
  160615. }
  160616. /* If we've filled the conversion buffer, empty it. */
  160617. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  160618. (*cinfo->downsample->downsample) (cinfo,
  160619. prep->color_buf, (JDIMENSION) 0,
  160620. output_buf, *out_row_group_ctr);
  160621. prep->next_buf_row = 0;
  160622. (*out_row_group_ctr)++;
  160623. }
  160624. /* If at bottom of image, pad the output to a full iMCU height.
  160625. * Note we assume the caller is providing a one-iMCU-height output buffer!
  160626. */
  160627. if (prep->rows_to_go == 0 &&
  160628. *out_row_group_ctr < out_row_groups_avail) {
  160629. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160630. ci++, compptr++) {
  160631. expand_bottom_edge(output_buf[ci],
  160632. compptr->width_in_blocks * DCTSIZE,
  160633. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  160634. (int) (out_row_groups_avail * compptr->v_samp_factor));
  160635. }
  160636. *out_row_group_ctr = out_row_groups_avail;
  160637. break; /* can exit outer loop without test */
  160638. }
  160639. }
  160640. }
  160641. #ifdef CONTEXT_ROWS_SUPPORTED
  160642. /*
  160643. * Process some data in the context case.
  160644. */
  160645. METHODDEF(void)
  160646. pre_process_context (j_compress_ptr cinfo,
  160647. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160648. JDIMENSION in_rows_avail,
  160649. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  160650. JDIMENSION out_row_groups_avail)
  160651. {
  160652. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  160653. int numrows, ci;
  160654. int buf_height = cinfo->max_v_samp_factor * 3;
  160655. JDIMENSION inrows;
  160656. while (*out_row_group_ctr < out_row_groups_avail) {
  160657. if (*in_row_ctr < in_rows_avail) {
  160658. /* Do color conversion to fill the conversion buffer. */
  160659. inrows = in_rows_avail - *in_row_ctr;
  160660. numrows = prep->next_buf_stop - prep->next_buf_row;
  160661. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  160662. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  160663. prep->color_buf,
  160664. (JDIMENSION) prep->next_buf_row,
  160665. numrows);
  160666. /* Pad at top of image, if first time through */
  160667. if (prep->rows_to_go == cinfo->image_height) {
  160668. for (ci = 0; ci < cinfo->num_components; ci++) {
  160669. int row;
  160670. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  160671. jcopy_sample_rows(prep->color_buf[ci], 0,
  160672. prep->color_buf[ci], -row,
  160673. 1, cinfo->image_width);
  160674. }
  160675. }
  160676. }
  160677. *in_row_ctr += numrows;
  160678. prep->next_buf_row += numrows;
  160679. prep->rows_to_go -= numrows;
  160680. } else {
  160681. /* Return for more data, unless we are at the bottom of the image. */
  160682. if (prep->rows_to_go != 0)
  160683. break;
  160684. /* When at bottom of image, pad to fill the conversion buffer. */
  160685. if (prep->next_buf_row < prep->next_buf_stop) {
  160686. for (ci = 0; ci < cinfo->num_components; ci++) {
  160687. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  160688. prep->next_buf_row, prep->next_buf_stop);
  160689. }
  160690. prep->next_buf_row = prep->next_buf_stop;
  160691. }
  160692. }
  160693. /* If we've gotten enough data, downsample a row group. */
  160694. if (prep->next_buf_row == prep->next_buf_stop) {
  160695. (*cinfo->downsample->downsample) (cinfo,
  160696. prep->color_buf,
  160697. (JDIMENSION) prep->this_row_group,
  160698. output_buf, *out_row_group_ctr);
  160699. (*out_row_group_ctr)++;
  160700. /* Advance pointers with wraparound as necessary. */
  160701. prep->this_row_group += cinfo->max_v_samp_factor;
  160702. if (prep->this_row_group >= buf_height)
  160703. prep->this_row_group = 0;
  160704. if (prep->next_buf_row >= buf_height)
  160705. prep->next_buf_row = 0;
  160706. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  160707. }
  160708. }
  160709. }
  160710. /*
  160711. * Create the wrapped-around downsampling input buffer needed for context mode.
  160712. */
  160713. LOCAL(void)
  160714. create_context_buffer (j_compress_ptr cinfo)
  160715. {
  160716. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  160717. int rgroup_height = cinfo->max_v_samp_factor;
  160718. int ci, i;
  160719. jpeg_component_info * compptr;
  160720. JSAMPARRAY true_buffer, fake_buffer;
  160721. /* Grab enough space for fake row pointers for all the components;
  160722. * we need five row groups' worth of pointers for each component.
  160723. */
  160724. fake_buffer = (JSAMPARRAY)
  160725. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160726. (cinfo->num_components * 5 * rgroup_height) *
  160727. SIZEOF(JSAMPROW));
  160728. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160729. ci++, compptr++) {
  160730. /* Allocate the actual buffer space (3 row groups) for this component.
  160731. * We make the buffer wide enough to allow the downsampler to edge-expand
  160732. * horizontally within the buffer, if it so chooses.
  160733. */
  160734. true_buffer = (*cinfo->mem->alloc_sarray)
  160735. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160736. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  160737. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  160738. (JDIMENSION) (3 * rgroup_height));
  160739. /* Copy true buffer row pointers into the middle of the fake row array */
  160740. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  160741. 3 * rgroup_height * SIZEOF(JSAMPROW));
  160742. /* Fill in the above and below wraparound pointers */
  160743. for (i = 0; i < rgroup_height; i++) {
  160744. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  160745. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  160746. }
  160747. prep->color_buf[ci] = fake_buffer + rgroup_height;
  160748. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  160749. }
  160750. }
  160751. #endif /* CONTEXT_ROWS_SUPPORTED */
  160752. /*
  160753. * Initialize preprocessing controller.
  160754. */
  160755. GLOBAL(void)
  160756. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  160757. {
  160758. my_prep_ptr prep;
  160759. int ci;
  160760. jpeg_component_info * compptr;
  160761. if (need_full_buffer) /* safety check */
  160762. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160763. prep = (my_prep_ptr)
  160764. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160765. SIZEOF(my_prep_controller));
  160766. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  160767. prep->pub.start_pass = start_pass_prep;
  160768. /* Allocate the color conversion buffer.
  160769. * We make the buffer wide enough to allow the downsampler to edge-expand
  160770. * horizontally within the buffer, if it so chooses.
  160771. */
  160772. if (cinfo->downsample->need_context_rows) {
  160773. /* Set up to provide context rows */
  160774. #ifdef CONTEXT_ROWS_SUPPORTED
  160775. prep->pub.pre_process_data = pre_process_context;
  160776. create_context_buffer(cinfo);
  160777. #else
  160778. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160779. #endif
  160780. } else {
  160781. /* No context, just make it tall enough for one row group */
  160782. prep->pub.pre_process_data = pre_process_data;
  160783. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160784. ci++, compptr++) {
  160785. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  160786. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160787. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  160788. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  160789. (JDIMENSION) cinfo->max_v_samp_factor);
  160790. }
  160791. }
  160792. }
  160793. /********* End of inlined file: jcprepct.c *********/
  160794. /********* Start of inlined file: jcsample.c *********/
  160795. #define JPEG_INTERNALS
  160796. /* Pointer to routine to downsample a single component */
  160797. typedef JMETHOD(void, downsample1_ptr,
  160798. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160799. JSAMPARRAY input_data, JSAMPARRAY output_data));
  160800. /* Private subobject */
  160801. typedef struct {
  160802. struct jpeg_downsampler pub; /* public fields */
  160803. /* Downsampling method pointers, one per component */
  160804. downsample1_ptr methods[MAX_COMPONENTS];
  160805. } my_downsampler;
  160806. typedef my_downsampler * my_downsample_ptr;
  160807. /*
  160808. * Initialize for a downsampling pass.
  160809. */
  160810. METHODDEF(void)
  160811. start_pass_downsample (j_compress_ptr cinfo)
  160812. {
  160813. /* no work for now */
  160814. }
  160815. /*
  160816. * Expand a component horizontally from width input_cols to width output_cols,
  160817. * by duplicating the rightmost samples.
  160818. */
  160819. LOCAL(void)
  160820. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  160821. JDIMENSION input_cols, JDIMENSION output_cols)
  160822. {
  160823. register JSAMPROW ptr;
  160824. register JSAMPLE pixval;
  160825. register int count;
  160826. int row;
  160827. int numcols = (int) (output_cols - input_cols);
  160828. if (numcols > 0) {
  160829. for (row = 0; row < num_rows; row++) {
  160830. ptr = image_data[row] + input_cols;
  160831. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  160832. for (count = numcols; count > 0; count--)
  160833. *ptr++ = pixval;
  160834. }
  160835. }
  160836. }
  160837. /*
  160838. * Do downsampling for a whole row group (all components).
  160839. *
  160840. * In this version we simply downsample each component independently.
  160841. */
  160842. METHODDEF(void)
  160843. sep_downsample (j_compress_ptr cinfo,
  160844. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160845. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  160846. {
  160847. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  160848. int ci;
  160849. jpeg_component_info * compptr;
  160850. JSAMPARRAY in_ptr, out_ptr;
  160851. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160852. ci++, compptr++) {
  160853. in_ptr = input_buf[ci] + in_row_index;
  160854. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  160855. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  160856. }
  160857. }
  160858. /*
  160859. * Downsample pixel values of a single component.
  160860. * One row group is processed per call.
  160861. * This version handles arbitrary integral sampling ratios, without smoothing.
  160862. * Note that this version is not actually used for customary sampling ratios.
  160863. */
  160864. METHODDEF(void)
  160865. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160866. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160867. {
  160868. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  160869. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  160870. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  160871. JSAMPROW inptr, outptr;
  160872. INT32 outvalue;
  160873. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  160874. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  160875. numpix = h_expand * v_expand;
  160876. numpix2 = numpix/2;
  160877. /* Expand input data enough to let all the output samples be generated
  160878. * by the standard loop. Special-casing padded output would be more
  160879. * efficient.
  160880. */
  160881. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  160882. cinfo->image_width, output_cols * h_expand);
  160883. inrow = 0;
  160884. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  160885. outptr = output_data[outrow];
  160886. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  160887. outcol++, outcol_h += h_expand) {
  160888. outvalue = 0;
  160889. for (v = 0; v < v_expand; v++) {
  160890. inptr = input_data[inrow+v] + outcol_h;
  160891. for (h = 0; h < h_expand; h++) {
  160892. outvalue += (INT32) GETJSAMPLE(*inptr++);
  160893. }
  160894. }
  160895. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  160896. }
  160897. inrow += v_expand;
  160898. }
  160899. }
  160900. /*
  160901. * Downsample pixel values of a single component.
  160902. * This version handles the special case of a full-size component,
  160903. * without smoothing.
  160904. */
  160905. METHODDEF(void)
  160906. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160907. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160908. {
  160909. /* Copy the data */
  160910. jcopy_sample_rows(input_data, 0, output_data, 0,
  160911. cinfo->max_v_samp_factor, cinfo->image_width);
  160912. /* Edge-expand */
  160913. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  160914. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  160915. }
  160916. /*
  160917. * Downsample pixel values of a single component.
  160918. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  160919. * without smoothing.
  160920. *
  160921. * A note about the "bias" calculations: when rounding fractional values to
  160922. * integer, we do not want to always round 0.5 up to the next integer.
  160923. * If we did that, we'd introduce a noticeable bias towards larger values.
  160924. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  160925. * alternate pixel locations (a simple ordered dither pattern).
  160926. */
  160927. METHODDEF(void)
  160928. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160929. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160930. {
  160931. int outrow;
  160932. JDIMENSION outcol;
  160933. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  160934. register JSAMPROW inptr, outptr;
  160935. register int bias;
  160936. /* Expand input data enough to let all the output samples be generated
  160937. * by the standard loop. Special-casing padded output would be more
  160938. * efficient.
  160939. */
  160940. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  160941. cinfo->image_width, output_cols * 2);
  160942. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  160943. outptr = output_data[outrow];
  160944. inptr = input_data[outrow];
  160945. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  160946. for (outcol = 0; outcol < output_cols; outcol++) {
  160947. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  160948. + bias) >> 1);
  160949. bias ^= 1; /* 0=>1, 1=>0 */
  160950. inptr += 2;
  160951. }
  160952. }
  160953. }
  160954. /*
  160955. * Downsample pixel values of a single component.
  160956. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  160957. * without smoothing.
  160958. */
  160959. METHODDEF(void)
  160960. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160961. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160962. {
  160963. int inrow, outrow;
  160964. JDIMENSION outcol;
  160965. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  160966. register JSAMPROW inptr0, inptr1, outptr;
  160967. register int bias;
  160968. /* Expand input data enough to let all the output samples be generated
  160969. * by the standard loop. Special-casing padded output would be more
  160970. * efficient.
  160971. */
  160972. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  160973. cinfo->image_width, output_cols * 2);
  160974. inrow = 0;
  160975. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  160976. outptr = output_data[outrow];
  160977. inptr0 = input_data[inrow];
  160978. inptr1 = input_data[inrow+1];
  160979. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  160980. for (outcol = 0; outcol < output_cols; outcol++) {
  160981. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  160982. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  160983. + bias) >> 2);
  160984. bias ^= 3; /* 1=>2, 2=>1 */
  160985. inptr0 += 2; inptr1 += 2;
  160986. }
  160987. inrow += 2;
  160988. }
  160989. }
  160990. #ifdef INPUT_SMOOTHING_SUPPORTED
  160991. /*
  160992. * Downsample pixel values of a single component.
  160993. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  160994. * with smoothing. One row of context is required.
  160995. */
  160996. METHODDEF(void)
  160997. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160998. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160999. {
  161000. int inrow, outrow;
  161001. JDIMENSION colctr;
  161002. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  161003. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  161004. INT32 membersum, neighsum, memberscale, neighscale;
  161005. /* Expand input data enough to let all the output samples be generated
  161006. * by the standard loop. Special-casing padded output would be more
  161007. * efficient.
  161008. */
  161009. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  161010. cinfo->image_width, output_cols * 2);
  161011. /* We don't bother to form the individual "smoothed" input pixel values;
  161012. * we can directly compute the output which is the average of the four
  161013. * smoothed values. Each of the four member pixels contributes a fraction
  161014. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  161015. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  161016. * output. The four corner-adjacent neighbor pixels contribute a fraction
  161017. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  161018. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  161019. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  161020. * factors are scaled by 2^16 = 65536.
  161021. * Also recall that SF = smoothing_factor / 1024.
  161022. */
  161023. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  161024. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  161025. inrow = 0;
  161026. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  161027. outptr = output_data[outrow];
  161028. inptr0 = input_data[inrow];
  161029. inptr1 = input_data[inrow+1];
  161030. above_ptr = input_data[inrow-1];
  161031. below_ptr = input_data[inrow+2];
  161032. /* Special case for first column: pretend column -1 is same as column 0 */
  161033. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  161034. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  161035. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  161036. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  161037. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  161038. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  161039. neighsum += neighsum;
  161040. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  161041. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  161042. membersum = membersum * memberscale + neighsum * neighscale;
  161043. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  161044. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  161045. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  161046. /* sum of pixels directly mapped to this output element */
  161047. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  161048. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  161049. /* sum of edge-neighbor pixels */
  161050. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  161051. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  161052. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  161053. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  161054. /* The edge-neighbors count twice as much as corner-neighbors */
  161055. neighsum += neighsum;
  161056. /* Add in the corner-neighbors */
  161057. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  161058. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  161059. /* form final output scaled up by 2^16 */
  161060. membersum = membersum * memberscale + neighsum * neighscale;
  161061. /* round, descale and output it */
  161062. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  161063. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  161064. }
  161065. /* Special case for last column */
  161066. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  161067. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  161068. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  161069. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  161070. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  161071. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  161072. neighsum += neighsum;
  161073. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  161074. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  161075. membersum = membersum * memberscale + neighsum * neighscale;
  161076. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  161077. inrow += 2;
  161078. }
  161079. }
  161080. /*
  161081. * Downsample pixel values of a single component.
  161082. * This version handles the special case of a full-size component,
  161083. * with smoothing. One row of context is required.
  161084. */
  161085. METHODDEF(void)
  161086. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  161087. JSAMPARRAY input_data, JSAMPARRAY output_data)
  161088. {
  161089. int outrow;
  161090. JDIMENSION colctr;
  161091. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  161092. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  161093. INT32 membersum, neighsum, memberscale, neighscale;
  161094. int colsum, lastcolsum, nextcolsum;
  161095. /* Expand input data enough to let all the output samples be generated
  161096. * by the standard loop. Special-casing padded output would be more
  161097. * efficient.
  161098. */
  161099. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  161100. cinfo->image_width, output_cols);
  161101. /* Each of the eight neighbor pixels contributes a fraction SF to the
  161102. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  161103. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  161104. * Also recall that SF = smoothing_factor / 1024.
  161105. */
  161106. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  161107. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  161108. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  161109. outptr = output_data[outrow];
  161110. inptr = input_data[outrow];
  161111. above_ptr = input_data[outrow-1];
  161112. below_ptr = input_data[outrow+1];
  161113. /* Special case for first column */
  161114. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  161115. GETJSAMPLE(*inptr);
  161116. membersum = GETJSAMPLE(*inptr++);
  161117. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  161118. GETJSAMPLE(*inptr);
  161119. neighsum = colsum + (colsum - membersum) + nextcolsum;
  161120. membersum = membersum * memberscale + neighsum * neighscale;
  161121. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  161122. lastcolsum = colsum; colsum = nextcolsum;
  161123. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  161124. membersum = GETJSAMPLE(*inptr++);
  161125. above_ptr++; below_ptr++;
  161126. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  161127. GETJSAMPLE(*inptr);
  161128. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  161129. membersum = membersum * memberscale + neighsum * neighscale;
  161130. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  161131. lastcolsum = colsum; colsum = nextcolsum;
  161132. }
  161133. /* Special case for last column */
  161134. membersum = GETJSAMPLE(*inptr);
  161135. neighsum = lastcolsum + (colsum - membersum) + colsum;
  161136. membersum = membersum * memberscale + neighsum * neighscale;
  161137. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  161138. }
  161139. }
  161140. #endif /* INPUT_SMOOTHING_SUPPORTED */
  161141. /*
  161142. * Module initialization routine for downsampling.
  161143. * Note that we must select a routine for each component.
  161144. */
  161145. GLOBAL(void)
  161146. jinit_downsampler (j_compress_ptr cinfo)
  161147. {
  161148. my_downsample_ptr downsample;
  161149. int ci;
  161150. jpeg_component_info * compptr;
  161151. boolean smoothok = TRUE;
  161152. downsample = (my_downsample_ptr)
  161153. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161154. SIZEOF(my_downsampler));
  161155. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  161156. downsample->pub.start_pass = start_pass_downsample;
  161157. downsample->pub.downsample = sep_downsample;
  161158. downsample->pub.need_context_rows = FALSE;
  161159. if (cinfo->CCIR601_sampling)
  161160. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  161161. /* Verify we can handle the sampling factors, and set up method pointers */
  161162. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161163. ci++, compptr++) {
  161164. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  161165. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  161166. #ifdef INPUT_SMOOTHING_SUPPORTED
  161167. if (cinfo->smoothing_factor) {
  161168. downsample->methods[ci] = fullsize_smooth_downsample;
  161169. downsample->pub.need_context_rows = TRUE;
  161170. } else
  161171. #endif
  161172. downsample->methods[ci] = fullsize_downsample;
  161173. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  161174. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  161175. smoothok = FALSE;
  161176. downsample->methods[ci] = h2v1_downsample;
  161177. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  161178. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  161179. #ifdef INPUT_SMOOTHING_SUPPORTED
  161180. if (cinfo->smoothing_factor) {
  161181. downsample->methods[ci] = h2v2_smooth_downsample;
  161182. downsample->pub.need_context_rows = TRUE;
  161183. } else
  161184. #endif
  161185. downsample->methods[ci] = h2v2_downsample;
  161186. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  161187. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  161188. smoothok = FALSE;
  161189. downsample->methods[ci] = int_downsample;
  161190. } else
  161191. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  161192. }
  161193. #ifdef INPUT_SMOOTHING_SUPPORTED
  161194. if (cinfo->smoothing_factor && !smoothok)
  161195. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  161196. #endif
  161197. }
  161198. /********* End of inlined file: jcsample.c *********/
  161199. /********* Start of inlined file: jctrans.c *********/
  161200. #define JPEG_INTERNALS
  161201. /* Forward declarations */
  161202. LOCAL(void) transencode_master_selection
  161203. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  161204. LOCAL(void) transencode_coef_controller
  161205. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  161206. /*
  161207. * Compression initialization for writing raw-coefficient data.
  161208. * Before calling this, all parameters and a data destination must be set up.
  161209. * Call jpeg_finish_compress() to actually write the data.
  161210. *
  161211. * The number of passed virtual arrays must match cinfo->num_components.
  161212. * Note that the virtual arrays need not be filled or even realized at
  161213. * the time write_coefficients is called; indeed, if the virtual arrays
  161214. * were requested from this compression object's memory manager, they
  161215. * typically will be realized during this routine and filled afterwards.
  161216. */
  161217. GLOBAL(void)
  161218. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  161219. {
  161220. if (cinfo->global_state != CSTATE_START)
  161221. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161222. /* Mark all tables to be written */
  161223. jpeg_suppress_tables(cinfo, FALSE);
  161224. /* (Re)initialize error mgr and destination modules */
  161225. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161226. (*cinfo->dest->init_destination) (cinfo);
  161227. /* Perform master selection of active modules */
  161228. transencode_master_selection(cinfo, coef_arrays);
  161229. /* Wait for jpeg_finish_compress() call */
  161230. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  161231. cinfo->global_state = CSTATE_WRCOEFS;
  161232. }
  161233. /*
  161234. * Initialize the compression object with default parameters,
  161235. * then copy from the source object all parameters needed for lossless
  161236. * transcoding. Parameters that can be varied without loss (such as
  161237. * scan script and Huffman optimization) are left in their default states.
  161238. */
  161239. GLOBAL(void)
  161240. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  161241. j_compress_ptr dstinfo)
  161242. {
  161243. JQUANT_TBL ** qtblptr;
  161244. jpeg_component_info *incomp, *outcomp;
  161245. JQUANT_TBL *c_quant, *slot_quant;
  161246. int tblno, ci, coefi;
  161247. /* Safety check to ensure start_compress not called yet. */
  161248. if (dstinfo->global_state != CSTATE_START)
  161249. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  161250. /* Copy fundamental image dimensions */
  161251. dstinfo->image_width = srcinfo->image_width;
  161252. dstinfo->image_height = srcinfo->image_height;
  161253. dstinfo->input_components = srcinfo->num_components;
  161254. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  161255. /* Initialize all parameters to default values */
  161256. jpeg_set_defaults(dstinfo);
  161257. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  161258. * Fix it to get the right header markers for the image colorspace.
  161259. */
  161260. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  161261. dstinfo->data_precision = srcinfo->data_precision;
  161262. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  161263. /* Copy the source's quantization tables. */
  161264. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  161265. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  161266. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  161267. if (*qtblptr == NULL)
  161268. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  161269. MEMCOPY((*qtblptr)->quantval,
  161270. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  161271. SIZEOF((*qtblptr)->quantval));
  161272. (*qtblptr)->sent_table = FALSE;
  161273. }
  161274. }
  161275. /* Copy the source's per-component info.
  161276. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  161277. */
  161278. dstinfo->num_components = srcinfo->num_components;
  161279. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  161280. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  161281. MAX_COMPONENTS);
  161282. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  161283. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  161284. outcomp->component_id = incomp->component_id;
  161285. outcomp->h_samp_factor = incomp->h_samp_factor;
  161286. outcomp->v_samp_factor = incomp->v_samp_factor;
  161287. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  161288. /* Make sure saved quantization table for component matches the qtable
  161289. * slot. If not, the input file re-used this qtable slot.
  161290. * IJG encoder currently cannot duplicate this.
  161291. */
  161292. tblno = outcomp->quant_tbl_no;
  161293. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  161294. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  161295. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  161296. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  161297. c_quant = incomp->quant_table;
  161298. if (c_quant != NULL) {
  161299. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  161300. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  161301. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  161302. }
  161303. }
  161304. /* Note: we do not copy the source's Huffman table assignments;
  161305. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  161306. */
  161307. }
  161308. /* Also copy JFIF version and resolution information, if available.
  161309. * Strictly speaking this isn't "critical" info, but it's nearly
  161310. * always appropriate to copy it if available. In particular,
  161311. * if the application chooses to copy JFIF 1.02 extension markers from
  161312. * the source file, we need to copy the version to make sure we don't
  161313. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  161314. * We will *not*, however, copy version info from mislabeled "2.01" files.
  161315. */
  161316. if (srcinfo->saw_JFIF_marker) {
  161317. if (srcinfo->JFIF_major_version == 1) {
  161318. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  161319. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  161320. }
  161321. dstinfo->density_unit = srcinfo->density_unit;
  161322. dstinfo->X_density = srcinfo->X_density;
  161323. dstinfo->Y_density = srcinfo->Y_density;
  161324. }
  161325. }
  161326. /*
  161327. * Master selection of compression modules for transcoding.
  161328. * This substitutes for jcinit.c's initialization of the full compressor.
  161329. */
  161330. LOCAL(void)
  161331. transencode_master_selection (j_compress_ptr cinfo,
  161332. jvirt_barray_ptr * coef_arrays)
  161333. {
  161334. /* Although we don't actually use input_components for transcoding,
  161335. * jcmaster.c's initial_setup will complain if input_components is 0.
  161336. */
  161337. cinfo->input_components = 1;
  161338. /* Initialize master control (includes parameter checking/processing) */
  161339. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  161340. /* Entropy encoding: either Huffman or arithmetic coding. */
  161341. if (cinfo->arith_code) {
  161342. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  161343. } else {
  161344. if (cinfo->progressive_mode) {
  161345. #ifdef C_PROGRESSIVE_SUPPORTED
  161346. jinit_phuff_encoder(cinfo);
  161347. #else
  161348. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161349. #endif
  161350. } else
  161351. jinit_huff_encoder(cinfo);
  161352. }
  161353. /* We need a special coefficient buffer controller. */
  161354. transencode_coef_controller(cinfo, coef_arrays);
  161355. jinit_marker_writer(cinfo);
  161356. /* We can now tell the memory manager to allocate virtual arrays. */
  161357. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  161358. /* Write the datastream header (SOI, JFIF) immediately.
  161359. * Frame and scan headers are postponed till later.
  161360. * This lets application insert special markers after the SOI.
  161361. */
  161362. (*cinfo->marker->write_file_header) (cinfo);
  161363. }
  161364. /*
  161365. * The rest of this file is a special implementation of the coefficient
  161366. * buffer controller. This is similar to jccoefct.c, but it handles only
  161367. * output from presupplied virtual arrays. Furthermore, we generate any
  161368. * dummy padding blocks on-the-fly rather than expecting them to be present
  161369. * in the arrays.
  161370. */
  161371. /* Private buffer controller object */
  161372. typedef struct {
  161373. struct jpeg_c_coef_controller pub; /* public fields */
  161374. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161375. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161376. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161377. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161378. /* Virtual block array for each component. */
  161379. jvirt_barray_ptr * whole_image;
  161380. /* Workspace for constructing dummy blocks at right/bottom edges. */
  161381. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  161382. } my_coef_controller2;
  161383. typedef my_coef_controller2 * my_coef_ptr2;
  161384. LOCAL(void)
  161385. start_iMCU_row2 (j_compress_ptr cinfo)
  161386. /* Reset within-iMCU-row counters for a new row */
  161387. {
  161388. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  161389. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161390. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161391. * But at the bottom of the image, process only what's left.
  161392. */
  161393. if (cinfo->comps_in_scan > 1) {
  161394. coef->MCU_rows_per_iMCU_row = 1;
  161395. } else {
  161396. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161397. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161398. else
  161399. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161400. }
  161401. coef->mcu_ctr = 0;
  161402. coef->MCU_vert_offset = 0;
  161403. }
  161404. /*
  161405. * Initialize for a processing pass.
  161406. */
  161407. METHODDEF(void)
  161408. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161409. {
  161410. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  161411. if (pass_mode != JBUF_CRANK_DEST)
  161412. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161413. coef->iMCU_row_num = 0;
  161414. start_iMCU_row2(cinfo);
  161415. }
  161416. /*
  161417. * Process some data.
  161418. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161419. * per call, ie, v_samp_factor block rows for each component in the scan.
  161420. * The data is obtained from the virtual arrays and fed to the entropy coder.
  161421. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161422. *
  161423. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  161424. */
  161425. METHODDEF(boolean)
  161426. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161427. {
  161428. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  161429. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161430. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161431. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161432. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  161433. JDIMENSION start_col;
  161434. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  161435. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161436. JBLOCKROW buffer_ptr;
  161437. jpeg_component_info *compptr;
  161438. /* Align the virtual buffers for the components used in this scan. */
  161439. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161440. compptr = cinfo->cur_comp_info[ci];
  161441. buffer[ci] = (*cinfo->mem->access_virt_barray)
  161442. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  161443. coef->iMCU_row_num * compptr->v_samp_factor,
  161444. (JDIMENSION) compptr->v_samp_factor, FALSE);
  161445. }
  161446. /* Loop to process one whole iMCU row */
  161447. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161448. yoffset++) {
  161449. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  161450. MCU_col_num++) {
  161451. /* Construct list of pointers to DCT blocks belonging to this MCU */
  161452. blkn = 0; /* index of current DCT block within MCU */
  161453. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161454. compptr = cinfo->cur_comp_info[ci];
  161455. start_col = MCU_col_num * compptr->MCU_width;
  161456. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161457. : compptr->last_col_width;
  161458. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161459. if (coef->iMCU_row_num < last_iMCU_row ||
  161460. yindex+yoffset < compptr->last_row_height) {
  161461. /* Fill in pointers to real blocks in this row */
  161462. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  161463. for (xindex = 0; xindex < blockcnt; xindex++)
  161464. MCU_buffer[blkn++] = buffer_ptr++;
  161465. } else {
  161466. /* At bottom of image, need a whole row of dummy blocks */
  161467. xindex = 0;
  161468. }
  161469. /* Fill in any dummy blocks needed in this row.
  161470. * Dummy blocks are filled in the same way as in jccoefct.c:
  161471. * all zeroes in the AC entries, DC entries equal to previous
  161472. * block's DC value. The init routine has already zeroed the
  161473. * AC entries, so we need only set the DC entries correctly.
  161474. */
  161475. for (; xindex < compptr->MCU_width; xindex++) {
  161476. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  161477. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  161478. blkn++;
  161479. }
  161480. }
  161481. }
  161482. /* Try to write the MCU. */
  161483. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  161484. /* Suspension forced; update state counters and exit */
  161485. coef->MCU_vert_offset = yoffset;
  161486. coef->mcu_ctr = MCU_col_num;
  161487. return FALSE;
  161488. }
  161489. }
  161490. /* Completed an MCU row, but perhaps not an iMCU row */
  161491. coef->mcu_ctr = 0;
  161492. }
  161493. /* Completed the iMCU row, advance counters for next one */
  161494. coef->iMCU_row_num++;
  161495. start_iMCU_row2(cinfo);
  161496. return TRUE;
  161497. }
  161498. /*
  161499. * Initialize coefficient buffer controller.
  161500. *
  161501. * Each passed coefficient array must be the right size for that
  161502. * coefficient: width_in_blocks wide and height_in_blocks high,
  161503. * with unitheight at least v_samp_factor.
  161504. */
  161505. LOCAL(void)
  161506. transencode_coef_controller (j_compress_ptr cinfo,
  161507. jvirt_barray_ptr * coef_arrays)
  161508. {
  161509. my_coef_ptr2 coef;
  161510. JBLOCKROW buffer;
  161511. int i;
  161512. coef = (my_coef_ptr2)
  161513. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161514. SIZEOF(my_coef_controller2));
  161515. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  161516. coef->pub.start_pass = start_pass_coef2;
  161517. coef->pub.compress_data = compress_output2;
  161518. /* Save pointer to virtual arrays */
  161519. coef->whole_image = coef_arrays;
  161520. /* Allocate and pre-zero space for dummy DCT blocks. */
  161521. buffer = (JBLOCKROW)
  161522. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161523. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  161524. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  161525. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  161526. coef->dummy_buffer[i] = buffer + i;
  161527. }
  161528. }
  161529. /********* End of inlined file: jctrans.c *********/
  161530. /********* Start of inlined file: jdapistd.c *********/
  161531. #define JPEG_INTERNALS
  161532. /* Forward declarations */
  161533. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  161534. /*
  161535. * Decompression initialization.
  161536. * jpeg_read_header must be completed before calling this.
  161537. *
  161538. * If a multipass operating mode was selected, this will do all but the
  161539. * last pass, and thus may take a great deal of time.
  161540. *
  161541. * Returns FALSE if suspended. The return value need be inspected only if
  161542. * a suspending data source is used.
  161543. */
  161544. GLOBAL(boolean)
  161545. jpeg_start_decompress (j_decompress_ptr cinfo)
  161546. {
  161547. if (cinfo->global_state == DSTATE_READY) {
  161548. /* First call: initialize master control, select active modules */
  161549. jinit_master_decompress(cinfo);
  161550. if (cinfo->buffered_image) {
  161551. /* No more work here; expecting jpeg_start_output next */
  161552. cinfo->global_state = DSTATE_BUFIMAGE;
  161553. return TRUE;
  161554. }
  161555. cinfo->global_state = DSTATE_PRELOAD;
  161556. }
  161557. if (cinfo->global_state == DSTATE_PRELOAD) {
  161558. /* If file has multiple scans, absorb them all into the coef buffer */
  161559. if (cinfo->inputctl->has_multiple_scans) {
  161560. #ifdef D_MULTISCAN_FILES_SUPPORTED
  161561. for (;;) {
  161562. int retcode;
  161563. /* Call progress monitor hook if present */
  161564. if (cinfo->progress != NULL)
  161565. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161566. /* Absorb some more input */
  161567. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  161568. if (retcode == JPEG_SUSPENDED)
  161569. return FALSE;
  161570. if (retcode == JPEG_REACHED_EOI)
  161571. break;
  161572. /* Advance progress counter if appropriate */
  161573. if (cinfo->progress != NULL &&
  161574. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  161575. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  161576. /* jdmaster underestimated number of scans; ratchet up one scan */
  161577. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  161578. }
  161579. }
  161580. }
  161581. #else
  161582. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161583. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  161584. }
  161585. cinfo->output_scan_number = cinfo->input_scan_number;
  161586. } else if (cinfo->global_state != DSTATE_PRESCAN)
  161587. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161588. /* Perform any dummy output passes, and set up for the final pass */
  161589. return output_pass_setup(cinfo);
  161590. }
  161591. /*
  161592. * Set up for an output pass, and perform any dummy pass(es) needed.
  161593. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  161594. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  161595. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  161596. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  161597. */
  161598. LOCAL(boolean)
  161599. output_pass_setup (j_decompress_ptr cinfo)
  161600. {
  161601. if (cinfo->global_state != DSTATE_PRESCAN) {
  161602. /* First call: do pass setup */
  161603. (*cinfo->master->prepare_for_output_pass) (cinfo);
  161604. cinfo->output_scanline = 0;
  161605. cinfo->global_state = DSTATE_PRESCAN;
  161606. }
  161607. /* Loop over any required dummy passes */
  161608. while (cinfo->master->is_dummy_pass) {
  161609. #ifdef QUANT_2PASS_SUPPORTED
  161610. /* Crank through the dummy pass */
  161611. while (cinfo->output_scanline < cinfo->output_height) {
  161612. JDIMENSION last_scanline;
  161613. /* Call progress monitor hook if present */
  161614. if (cinfo->progress != NULL) {
  161615. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  161616. cinfo->progress->pass_limit = (long) cinfo->output_height;
  161617. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161618. }
  161619. /* Process some data */
  161620. last_scanline = cinfo->output_scanline;
  161621. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  161622. &cinfo->output_scanline, (JDIMENSION) 0);
  161623. if (cinfo->output_scanline == last_scanline)
  161624. return FALSE; /* No progress made, must suspend */
  161625. }
  161626. /* Finish up dummy pass, and set up for another one */
  161627. (*cinfo->master->finish_output_pass) (cinfo);
  161628. (*cinfo->master->prepare_for_output_pass) (cinfo);
  161629. cinfo->output_scanline = 0;
  161630. #else
  161631. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161632. #endif /* QUANT_2PASS_SUPPORTED */
  161633. }
  161634. /* Ready for application to drive output pass through
  161635. * jpeg_read_scanlines or jpeg_read_raw_data.
  161636. */
  161637. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  161638. return TRUE;
  161639. }
  161640. /*
  161641. * Read some scanlines of data from the JPEG decompressor.
  161642. *
  161643. * The return value will be the number of lines actually read.
  161644. * This may be less than the number requested in several cases,
  161645. * including bottom of image, data source suspension, and operating
  161646. * modes that emit multiple scanlines at a time.
  161647. *
  161648. * Note: we warn about excess calls to jpeg_read_scanlines() since
  161649. * this likely signals an application programmer error. However,
  161650. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  161651. */
  161652. GLOBAL(JDIMENSION)
  161653. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  161654. JDIMENSION max_lines)
  161655. {
  161656. JDIMENSION row_ctr;
  161657. if (cinfo->global_state != DSTATE_SCANNING)
  161658. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161659. if (cinfo->output_scanline >= cinfo->output_height) {
  161660. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161661. return 0;
  161662. }
  161663. /* Call progress monitor hook if present */
  161664. if (cinfo->progress != NULL) {
  161665. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  161666. cinfo->progress->pass_limit = (long) cinfo->output_height;
  161667. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161668. }
  161669. /* Process some data */
  161670. row_ctr = 0;
  161671. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  161672. cinfo->output_scanline += row_ctr;
  161673. return row_ctr;
  161674. }
  161675. /*
  161676. * Alternate entry point to read raw data.
  161677. * Processes exactly one iMCU row per call, unless suspended.
  161678. */
  161679. GLOBAL(JDIMENSION)
  161680. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  161681. JDIMENSION max_lines)
  161682. {
  161683. JDIMENSION lines_per_iMCU_row;
  161684. if (cinfo->global_state != DSTATE_RAW_OK)
  161685. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161686. if (cinfo->output_scanline >= cinfo->output_height) {
  161687. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161688. return 0;
  161689. }
  161690. /* Call progress monitor hook if present */
  161691. if (cinfo->progress != NULL) {
  161692. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  161693. cinfo->progress->pass_limit = (long) cinfo->output_height;
  161694. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161695. }
  161696. /* Verify that at least one iMCU row can be returned. */
  161697. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  161698. if (max_lines < lines_per_iMCU_row)
  161699. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161700. /* Decompress directly into user's buffer. */
  161701. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  161702. return 0; /* suspension forced, can do nothing more */
  161703. /* OK, we processed one iMCU row. */
  161704. cinfo->output_scanline += lines_per_iMCU_row;
  161705. return lines_per_iMCU_row;
  161706. }
  161707. /* Additional entry points for buffered-image mode. */
  161708. #ifdef D_MULTISCAN_FILES_SUPPORTED
  161709. /*
  161710. * Initialize for an output pass in buffered-image mode.
  161711. */
  161712. GLOBAL(boolean)
  161713. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  161714. {
  161715. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  161716. cinfo->global_state != DSTATE_PRESCAN)
  161717. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161718. /* Limit scan number to valid range */
  161719. if (scan_number <= 0)
  161720. scan_number = 1;
  161721. if (cinfo->inputctl->eoi_reached &&
  161722. scan_number > cinfo->input_scan_number)
  161723. scan_number = cinfo->input_scan_number;
  161724. cinfo->output_scan_number = scan_number;
  161725. /* Perform any dummy output passes, and set up for the real pass */
  161726. return output_pass_setup(cinfo);
  161727. }
  161728. /*
  161729. * Finish up after an output pass in buffered-image mode.
  161730. *
  161731. * Returns FALSE if suspended. The return value need be inspected only if
  161732. * a suspending data source is used.
  161733. */
  161734. GLOBAL(boolean)
  161735. jpeg_finish_output (j_decompress_ptr cinfo)
  161736. {
  161737. if ((cinfo->global_state == DSTATE_SCANNING ||
  161738. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  161739. /* Terminate this pass. */
  161740. /* We do not require the whole pass to have been completed. */
  161741. (*cinfo->master->finish_output_pass) (cinfo);
  161742. cinfo->global_state = DSTATE_BUFPOST;
  161743. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  161744. /* BUFPOST = repeat call after a suspension, anything else is error */
  161745. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161746. }
  161747. /* Read markers looking for SOS or EOI */
  161748. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  161749. ! cinfo->inputctl->eoi_reached) {
  161750. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  161751. return FALSE; /* Suspend, come back later */
  161752. }
  161753. cinfo->global_state = DSTATE_BUFIMAGE;
  161754. return TRUE;
  161755. }
  161756. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  161757. /********* End of inlined file: jdapistd.c *********/
  161758. /********* Start of inlined file: jdapimin.c *********/
  161759. #define JPEG_INTERNALS
  161760. /*
  161761. * Initialization of a JPEG decompression object.
  161762. * The error manager must already be set up (in case memory manager fails).
  161763. */
  161764. GLOBAL(void)
  161765. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  161766. {
  161767. int i;
  161768. /* Guard against version mismatches between library and caller. */
  161769. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161770. if (version != JPEG_LIB_VERSION)
  161771. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161772. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  161773. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161774. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  161775. /* For debugging purposes, we zero the whole master structure.
  161776. * But the application has already set the err pointer, and may have set
  161777. * client_data, so we have to save and restore those fields.
  161778. * Note: if application hasn't set client_data, tools like Purify may
  161779. * complain here.
  161780. */
  161781. {
  161782. struct jpeg_error_mgr * err = cinfo->err;
  161783. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161784. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  161785. cinfo->err = err;
  161786. cinfo->client_data = client_data;
  161787. }
  161788. cinfo->is_decompressor = TRUE;
  161789. /* Initialize a memory manager instance for this object */
  161790. jinit_memory_mgr((j_common_ptr) cinfo);
  161791. /* Zero out pointers to permanent structures. */
  161792. cinfo->progress = NULL;
  161793. cinfo->src = NULL;
  161794. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161795. cinfo->quant_tbl_ptrs[i] = NULL;
  161796. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161797. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161798. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161799. }
  161800. /* Initialize marker processor so application can override methods
  161801. * for COM, APPn markers before calling jpeg_read_header.
  161802. */
  161803. cinfo->marker_list = NULL;
  161804. jinit_marker_reader(cinfo);
  161805. /* And initialize the overall input controller. */
  161806. jinit_input_controller(cinfo);
  161807. /* OK, I'm ready */
  161808. cinfo->global_state = DSTATE_START;
  161809. }
  161810. /*
  161811. * Destruction of a JPEG decompression object
  161812. */
  161813. GLOBAL(void)
  161814. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  161815. {
  161816. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161817. }
  161818. /*
  161819. * Abort processing of a JPEG decompression operation,
  161820. * but don't destroy the object itself.
  161821. */
  161822. GLOBAL(void)
  161823. jpeg_abort_decompress (j_decompress_ptr cinfo)
  161824. {
  161825. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161826. }
  161827. /*
  161828. * Set default decompression parameters.
  161829. */
  161830. LOCAL(void)
  161831. default_decompress_parms (j_decompress_ptr cinfo)
  161832. {
  161833. /* Guess the input colorspace, and set output colorspace accordingly. */
  161834. /* (Wish JPEG committee had provided a real way to specify this...) */
  161835. /* Note application may override our guesses. */
  161836. switch (cinfo->num_components) {
  161837. case 1:
  161838. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  161839. cinfo->out_color_space = JCS_GRAYSCALE;
  161840. break;
  161841. case 3:
  161842. if (cinfo->saw_JFIF_marker) {
  161843. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  161844. } else if (cinfo->saw_Adobe_marker) {
  161845. switch (cinfo->Adobe_transform) {
  161846. case 0:
  161847. cinfo->jpeg_color_space = JCS_RGB;
  161848. break;
  161849. case 1:
  161850. cinfo->jpeg_color_space = JCS_YCbCr;
  161851. break;
  161852. default:
  161853. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  161854. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  161855. break;
  161856. }
  161857. } else {
  161858. /* Saw no special markers, try to guess from the component IDs */
  161859. int cid0 = cinfo->comp_info[0].component_id;
  161860. int cid1 = cinfo->comp_info[1].component_id;
  161861. int cid2 = cinfo->comp_info[2].component_id;
  161862. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  161863. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  161864. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  161865. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  161866. else {
  161867. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  161868. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  161869. }
  161870. }
  161871. /* Always guess RGB is proper output colorspace. */
  161872. cinfo->out_color_space = JCS_RGB;
  161873. break;
  161874. case 4:
  161875. if (cinfo->saw_Adobe_marker) {
  161876. switch (cinfo->Adobe_transform) {
  161877. case 0:
  161878. cinfo->jpeg_color_space = JCS_CMYK;
  161879. break;
  161880. case 2:
  161881. cinfo->jpeg_color_space = JCS_YCCK;
  161882. break;
  161883. default:
  161884. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  161885. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  161886. break;
  161887. }
  161888. } else {
  161889. /* No special markers, assume straight CMYK. */
  161890. cinfo->jpeg_color_space = JCS_CMYK;
  161891. }
  161892. cinfo->out_color_space = JCS_CMYK;
  161893. break;
  161894. default:
  161895. cinfo->jpeg_color_space = JCS_UNKNOWN;
  161896. cinfo->out_color_space = JCS_UNKNOWN;
  161897. break;
  161898. }
  161899. /* Set defaults for other decompression parameters. */
  161900. cinfo->scale_num = 1; /* 1:1 scaling */
  161901. cinfo->scale_denom = 1;
  161902. cinfo->output_gamma = 1.0;
  161903. cinfo->buffered_image = FALSE;
  161904. cinfo->raw_data_out = FALSE;
  161905. cinfo->dct_method = JDCT_DEFAULT;
  161906. cinfo->do_fancy_upsampling = TRUE;
  161907. cinfo->do_block_smoothing = TRUE;
  161908. cinfo->quantize_colors = FALSE;
  161909. /* We set these in case application only sets quantize_colors. */
  161910. cinfo->dither_mode = JDITHER_FS;
  161911. #ifdef QUANT_2PASS_SUPPORTED
  161912. cinfo->two_pass_quantize = TRUE;
  161913. #else
  161914. cinfo->two_pass_quantize = FALSE;
  161915. #endif
  161916. cinfo->desired_number_of_colors = 256;
  161917. cinfo->colormap = NULL;
  161918. /* Initialize for no mode change in buffered-image mode. */
  161919. cinfo->enable_1pass_quant = FALSE;
  161920. cinfo->enable_external_quant = FALSE;
  161921. cinfo->enable_2pass_quant = FALSE;
  161922. }
  161923. /*
  161924. * Decompression startup: read start of JPEG datastream to see what's there.
  161925. * Need only initialize JPEG object and supply a data source before calling.
  161926. *
  161927. * This routine will read as far as the first SOS marker (ie, actual start of
  161928. * compressed data), and will save all tables and parameters in the JPEG
  161929. * object. It will also initialize the decompression parameters to default
  161930. * values, and finally return JPEG_HEADER_OK. On return, the application may
  161931. * adjust the decompression parameters and then call jpeg_start_decompress.
  161932. * (Or, if the application only wanted to determine the image parameters,
  161933. * the data need not be decompressed. In that case, call jpeg_abort or
  161934. * jpeg_destroy to release any temporary space.)
  161935. * If an abbreviated (tables only) datastream is presented, the routine will
  161936. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  161937. * re-use the JPEG object to read the abbreviated image datastream(s).
  161938. * It is unnecessary (but OK) to call jpeg_abort in this case.
  161939. * The JPEG_SUSPENDED return code only occurs if the data source module
  161940. * requests suspension of the decompressor. In this case the application
  161941. * should load more source data and then re-call jpeg_read_header to resume
  161942. * processing.
  161943. * If a non-suspending data source is used and require_image is TRUE, then the
  161944. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  161945. *
  161946. * This routine is now just a front end to jpeg_consume_input, with some
  161947. * extra error checking.
  161948. */
  161949. GLOBAL(int)
  161950. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  161951. {
  161952. int retcode;
  161953. if (cinfo->global_state != DSTATE_START &&
  161954. cinfo->global_state != DSTATE_INHEADER)
  161955. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161956. retcode = jpeg_consume_input(cinfo);
  161957. switch (retcode) {
  161958. case JPEG_REACHED_SOS:
  161959. retcode = JPEG_HEADER_OK;
  161960. break;
  161961. case JPEG_REACHED_EOI:
  161962. if (require_image) /* Complain if application wanted an image */
  161963. ERREXIT(cinfo, JERR_NO_IMAGE);
  161964. /* Reset to start state; it would be safer to require the application to
  161965. * call jpeg_abort, but we can't change it now for compatibility reasons.
  161966. * A side effect is to free any temporary memory (there shouldn't be any).
  161967. */
  161968. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  161969. retcode = JPEG_HEADER_TABLES_ONLY;
  161970. break;
  161971. case JPEG_SUSPENDED:
  161972. /* no work */
  161973. break;
  161974. }
  161975. return retcode;
  161976. }
  161977. /*
  161978. * Consume data in advance of what the decompressor requires.
  161979. * This can be called at any time once the decompressor object has
  161980. * been created and a data source has been set up.
  161981. *
  161982. * This routine is essentially a state machine that handles a couple
  161983. * of critical state-transition actions, namely initial setup and
  161984. * transition from header scanning to ready-for-start_decompress.
  161985. * All the actual input is done via the input controller's consume_input
  161986. * method.
  161987. */
  161988. GLOBAL(int)
  161989. jpeg_consume_input (j_decompress_ptr cinfo)
  161990. {
  161991. int retcode = JPEG_SUSPENDED;
  161992. /* NB: every possible DSTATE value should be listed in this switch */
  161993. switch (cinfo->global_state) {
  161994. case DSTATE_START:
  161995. /* Start-of-datastream actions: reset appropriate modules */
  161996. (*cinfo->inputctl->reset_input_controller) (cinfo);
  161997. /* Initialize application's data source module */
  161998. (*cinfo->src->init_source) (cinfo);
  161999. cinfo->global_state = DSTATE_INHEADER;
  162000. /*FALLTHROUGH*/
  162001. case DSTATE_INHEADER:
  162002. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  162003. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  162004. /* Set up default parameters based on header data */
  162005. default_decompress_parms(cinfo);
  162006. /* Set global state: ready for start_decompress */
  162007. cinfo->global_state = DSTATE_READY;
  162008. }
  162009. break;
  162010. case DSTATE_READY:
  162011. /* Can't advance past first SOS until start_decompress is called */
  162012. retcode = JPEG_REACHED_SOS;
  162013. break;
  162014. case DSTATE_PRELOAD:
  162015. case DSTATE_PRESCAN:
  162016. case DSTATE_SCANNING:
  162017. case DSTATE_RAW_OK:
  162018. case DSTATE_BUFIMAGE:
  162019. case DSTATE_BUFPOST:
  162020. case DSTATE_STOPPING:
  162021. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  162022. break;
  162023. default:
  162024. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162025. }
  162026. return retcode;
  162027. }
  162028. /*
  162029. * Have we finished reading the input file?
  162030. */
  162031. GLOBAL(boolean)
  162032. jpeg_input_complete (j_decompress_ptr cinfo)
  162033. {
  162034. /* Check for valid jpeg object */
  162035. if (cinfo->global_state < DSTATE_START ||
  162036. cinfo->global_state > DSTATE_STOPPING)
  162037. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162038. return cinfo->inputctl->eoi_reached;
  162039. }
  162040. /*
  162041. * Is there more than one scan?
  162042. */
  162043. GLOBAL(boolean)
  162044. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  162045. {
  162046. /* Only valid after jpeg_read_header completes */
  162047. if (cinfo->global_state < DSTATE_READY ||
  162048. cinfo->global_state > DSTATE_STOPPING)
  162049. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162050. return cinfo->inputctl->has_multiple_scans;
  162051. }
  162052. /*
  162053. * Finish JPEG decompression.
  162054. *
  162055. * This will normally just verify the file trailer and release temp storage.
  162056. *
  162057. * Returns FALSE if suspended. The return value need be inspected only if
  162058. * a suspending data source is used.
  162059. */
  162060. GLOBAL(boolean)
  162061. jpeg_finish_decompress (j_decompress_ptr cinfo)
  162062. {
  162063. if ((cinfo->global_state == DSTATE_SCANNING ||
  162064. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  162065. /* Terminate final pass of non-buffered mode */
  162066. if (cinfo->output_scanline < cinfo->output_height)
  162067. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  162068. (*cinfo->master->finish_output_pass) (cinfo);
  162069. cinfo->global_state = DSTATE_STOPPING;
  162070. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  162071. /* Finishing after a buffered-image operation */
  162072. cinfo->global_state = DSTATE_STOPPING;
  162073. } else if (cinfo->global_state != DSTATE_STOPPING) {
  162074. /* STOPPING = repeat call after a suspension, anything else is error */
  162075. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162076. }
  162077. /* Read until EOI */
  162078. while (! cinfo->inputctl->eoi_reached) {
  162079. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  162080. return FALSE; /* Suspend, come back later */
  162081. }
  162082. /* Do final cleanup */
  162083. (*cinfo->src->term_source) (cinfo);
  162084. /* We can use jpeg_abort to release memory and reset global_state */
  162085. jpeg_abort((j_common_ptr) cinfo);
  162086. return TRUE;
  162087. }
  162088. /********* End of inlined file: jdapimin.c *********/
  162089. /********* Start of inlined file: jdatasrc.c *********/
  162090. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  162091. /********* Start of inlined file: jerror.h *********/
  162092. /*
  162093. * To define the enum list of message codes, include this file without
  162094. * defining macro JMESSAGE. To create a message string table, include it
  162095. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  162096. */
  162097. #ifndef JMESSAGE
  162098. #ifndef JERROR_H
  162099. /* First time through, define the enum list */
  162100. #define JMAKE_ENUM_LIST
  162101. #else
  162102. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  162103. #define JMESSAGE(code,string)
  162104. #endif /* JERROR_H */
  162105. #endif /* JMESSAGE */
  162106. #ifdef JMAKE_ENUM_LIST
  162107. typedef enum {
  162108. #define JMESSAGE(code,string) code ,
  162109. #endif /* JMAKE_ENUM_LIST */
  162110. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  162111. /* For maintenance convenience, list is alphabetical by message code name */
  162112. JMESSAGE(JERR_ARITH_NOTIMPL,
  162113. "Sorry, there are legal restrictions on arithmetic coding")
  162114. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  162115. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  162116. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  162117. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  162118. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  162119. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  162120. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  162121. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  162122. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  162123. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  162124. JMESSAGE(JERR_BAD_LIB_VERSION,
  162125. "Wrong JPEG library version: library is %d, caller expects %d")
  162126. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  162127. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  162128. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  162129. JMESSAGE(JERR_BAD_PROGRESSION,
  162130. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  162131. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  162132. "Invalid progressive parameters at scan script entry %d")
  162133. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  162134. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  162135. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  162136. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  162137. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  162138. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  162139. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  162140. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  162141. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  162142. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  162143. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  162144. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  162145. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  162146. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  162147. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  162148. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  162149. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  162150. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  162151. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  162152. JMESSAGE(JERR_FILE_READ, "Input file read error")
  162153. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  162154. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  162155. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  162156. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  162157. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  162158. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  162159. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  162160. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  162161. "Cannot transcode due to multiple use of quantization table %d")
  162162. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  162163. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  162164. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  162165. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  162166. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  162167. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  162168. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  162169. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  162170. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  162171. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  162172. JMESSAGE(JERR_QUANT_COMPONENTS,
  162173. "Cannot quantize more than %d color components")
  162174. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  162175. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  162176. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  162177. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  162178. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  162179. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  162180. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  162181. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  162182. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  162183. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  162184. JMESSAGE(JERR_TFILE_WRITE,
  162185. "Write failed on temporary file --- out of disk space?")
  162186. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  162187. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  162188. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  162189. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  162190. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  162191. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  162192. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  162193. JMESSAGE(JMSG_VERSION, JVERSION)
  162194. JMESSAGE(JTRC_16BIT_TABLES,
  162195. "Caution: quantization tables are too coarse for baseline JPEG")
  162196. JMESSAGE(JTRC_ADOBE,
  162197. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  162198. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  162199. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  162200. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  162201. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  162202. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  162203. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  162204. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  162205. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  162206. JMESSAGE(JTRC_EOI, "End Of Image")
  162207. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  162208. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  162209. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  162210. "Warning: thumbnail image size does not match data length %u")
  162211. JMESSAGE(JTRC_JFIF_EXTENSION,
  162212. "JFIF extension marker: type 0x%02x, length %u")
  162213. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  162214. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  162215. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  162216. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  162217. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  162218. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  162219. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  162220. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  162221. JMESSAGE(JTRC_RST, "RST%d")
  162222. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  162223. "Smoothing not supported with nonstandard sampling ratios")
  162224. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  162225. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  162226. JMESSAGE(JTRC_SOI, "Start of Image")
  162227. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  162228. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  162229. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  162230. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  162231. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  162232. JMESSAGE(JTRC_THUMB_JPEG,
  162233. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  162234. JMESSAGE(JTRC_THUMB_PALETTE,
  162235. "JFIF extension marker: palette thumbnail image, length %u")
  162236. JMESSAGE(JTRC_THUMB_RGB,
  162237. "JFIF extension marker: RGB thumbnail image, length %u")
  162238. JMESSAGE(JTRC_UNKNOWN_IDS,
  162239. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  162240. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  162241. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  162242. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  162243. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  162244. "Inconsistent progression sequence for component %d coefficient %d")
  162245. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  162246. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  162247. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  162248. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  162249. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  162250. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  162251. JMESSAGE(JWRN_MUST_RESYNC,
  162252. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  162253. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  162254. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  162255. #ifdef JMAKE_ENUM_LIST
  162256. JMSG_LASTMSGCODE
  162257. } J_MESSAGE_CODE;
  162258. #undef JMAKE_ENUM_LIST
  162259. #endif /* JMAKE_ENUM_LIST */
  162260. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  162261. #undef JMESSAGE
  162262. #ifndef JERROR_H
  162263. #define JERROR_H
  162264. /* Macros to simplify using the error and trace message stuff */
  162265. /* The first parameter is either type of cinfo pointer */
  162266. /* Fatal errors (print message and exit) */
  162267. #define ERREXIT(cinfo,code) \
  162268. ((cinfo)->err->msg_code = (code), \
  162269. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162270. #define ERREXIT1(cinfo,code,p1) \
  162271. ((cinfo)->err->msg_code = (code), \
  162272. (cinfo)->err->msg_parm.i[0] = (p1), \
  162273. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162274. #define ERREXIT2(cinfo,code,p1,p2) \
  162275. ((cinfo)->err->msg_code = (code), \
  162276. (cinfo)->err->msg_parm.i[0] = (p1), \
  162277. (cinfo)->err->msg_parm.i[1] = (p2), \
  162278. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162279. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  162280. ((cinfo)->err->msg_code = (code), \
  162281. (cinfo)->err->msg_parm.i[0] = (p1), \
  162282. (cinfo)->err->msg_parm.i[1] = (p2), \
  162283. (cinfo)->err->msg_parm.i[2] = (p3), \
  162284. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162285. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  162286. ((cinfo)->err->msg_code = (code), \
  162287. (cinfo)->err->msg_parm.i[0] = (p1), \
  162288. (cinfo)->err->msg_parm.i[1] = (p2), \
  162289. (cinfo)->err->msg_parm.i[2] = (p3), \
  162290. (cinfo)->err->msg_parm.i[3] = (p4), \
  162291. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162292. #define ERREXITS(cinfo,code,str) \
  162293. ((cinfo)->err->msg_code = (code), \
  162294. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  162295. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162296. #define MAKESTMT(stuff) do { stuff } while (0)
  162297. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  162298. #define WARNMS(cinfo,code) \
  162299. ((cinfo)->err->msg_code = (code), \
  162300. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  162301. #define WARNMS1(cinfo,code,p1) \
  162302. ((cinfo)->err->msg_code = (code), \
  162303. (cinfo)->err->msg_parm.i[0] = (p1), \
  162304. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  162305. #define WARNMS2(cinfo,code,p1,p2) \
  162306. ((cinfo)->err->msg_code = (code), \
  162307. (cinfo)->err->msg_parm.i[0] = (p1), \
  162308. (cinfo)->err->msg_parm.i[1] = (p2), \
  162309. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  162310. /* Informational/debugging messages */
  162311. #define TRACEMS(cinfo,lvl,code) \
  162312. ((cinfo)->err->msg_code = (code), \
  162313. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  162314. #define TRACEMS1(cinfo,lvl,code,p1) \
  162315. ((cinfo)->err->msg_code = (code), \
  162316. (cinfo)->err->msg_parm.i[0] = (p1), \
  162317. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  162318. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  162319. ((cinfo)->err->msg_code = (code), \
  162320. (cinfo)->err->msg_parm.i[0] = (p1), \
  162321. (cinfo)->err->msg_parm.i[1] = (p2), \
  162322. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  162323. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  162324. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  162325. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  162326. (cinfo)->err->msg_code = (code); \
  162327. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  162328. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  162329. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  162330. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  162331. (cinfo)->err->msg_code = (code); \
  162332. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  162333. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  162334. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  162335. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  162336. _mp[4] = (p5); \
  162337. (cinfo)->err->msg_code = (code); \
  162338. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  162339. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  162340. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  162341. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  162342. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  162343. (cinfo)->err->msg_code = (code); \
  162344. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  162345. #define TRACEMSS(cinfo,lvl,code,str) \
  162346. ((cinfo)->err->msg_code = (code), \
  162347. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  162348. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  162349. #endif /* JERROR_H */
  162350. /********* End of inlined file: jerror.h *********/
  162351. /* Expanded data source object for stdio input */
  162352. typedef struct {
  162353. struct jpeg_source_mgr pub; /* public fields */
  162354. FILE * infile; /* source stream */
  162355. JOCTET * buffer; /* start of buffer */
  162356. boolean start_of_file; /* have we gotten any data yet? */
  162357. } my_source_mgr;
  162358. typedef my_source_mgr * my_src_ptr;
  162359. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  162360. /*
  162361. * Initialize source --- called by jpeg_read_header
  162362. * before any data is actually read.
  162363. */
  162364. METHODDEF(void)
  162365. init_source (j_decompress_ptr cinfo)
  162366. {
  162367. my_src_ptr src = (my_src_ptr) cinfo->src;
  162368. /* We reset the empty-input-file flag for each image,
  162369. * but we don't clear the input buffer.
  162370. * This is correct behavior for reading a series of images from one source.
  162371. */
  162372. src->start_of_file = TRUE;
  162373. }
  162374. /*
  162375. * Fill the input buffer --- called whenever buffer is emptied.
  162376. *
  162377. * In typical applications, this should read fresh data into the buffer
  162378. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  162379. * reset the pointer & count to the start of the buffer, and return TRUE
  162380. * indicating that the buffer has been reloaded. It is not necessary to
  162381. * fill the buffer entirely, only to obtain at least one more byte.
  162382. *
  162383. * There is no such thing as an EOF return. If the end of the file has been
  162384. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  162385. * the buffer. In most cases, generating a warning message and inserting a
  162386. * fake EOI marker is the best course of action --- this will allow the
  162387. * decompressor to output however much of the image is there. However,
  162388. * the resulting error message is misleading if the real problem is an empty
  162389. * input file, so we handle that case specially.
  162390. *
  162391. * In applications that need to be able to suspend compression due to input
  162392. * not being available yet, a FALSE return indicates that no more data can be
  162393. * obtained right now, but more may be forthcoming later. In this situation,
  162394. * the decompressor will return to its caller (with an indication of the
  162395. * number of scanlines it has read, if any). The application should resume
  162396. * decompression after it has loaded more data into the input buffer. Note
  162397. * that there are substantial restrictions on the use of suspension --- see
  162398. * the documentation.
  162399. *
  162400. * When suspending, the decompressor will back up to a convenient restart point
  162401. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  162402. * indicate where the restart point will be if the current call returns FALSE.
  162403. * Data beyond this point must be rescanned after resumption, so move it to
  162404. * the front of the buffer rather than discarding it.
  162405. */
  162406. METHODDEF(boolean)
  162407. fill_input_buffer (j_decompress_ptr cinfo)
  162408. {
  162409. my_src_ptr src = (my_src_ptr) cinfo->src;
  162410. size_t nbytes;
  162411. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  162412. if (nbytes <= 0) {
  162413. if (src->start_of_file) /* Treat empty input file as fatal error */
  162414. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  162415. WARNMS(cinfo, JWRN_JPEG_EOF);
  162416. /* Insert a fake EOI marker */
  162417. src->buffer[0] = (JOCTET) 0xFF;
  162418. src->buffer[1] = (JOCTET) JPEG_EOI;
  162419. nbytes = 2;
  162420. }
  162421. src->pub.next_input_byte = src->buffer;
  162422. src->pub.bytes_in_buffer = nbytes;
  162423. src->start_of_file = FALSE;
  162424. return TRUE;
  162425. }
  162426. /*
  162427. * Skip data --- used to skip over a potentially large amount of
  162428. * uninteresting data (such as an APPn marker).
  162429. *
  162430. * Writers of suspendable-input applications must note that skip_input_data
  162431. * is not granted the right to give a suspension return. If the skip extends
  162432. * beyond the data currently in the buffer, the buffer can be marked empty so
  162433. * that the next read will cause a fill_input_buffer call that can suspend.
  162434. * Arranging for additional bytes to be discarded before reloading the input
  162435. * buffer is the application writer's problem.
  162436. */
  162437. METHODDEF(void)
  162438. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  162439. {
  162440. my_src_ptr src = (my_src_ptr) cinfo->src;
  162441. /* Just a dumb implementation for now. Could use fseek() except
  162442. * it doesn't work on pipes. Not clear that being smart is worth
  162443. * any trouble anyway --- large skips are infrequent.
  162444. */
  162445. if (num_bytes > 0) {
  162446. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  162447. num_bytes -= (long) src->pub.bytes_in_buffer;
  162448. (void) fill_input_buffer(cinfo);
  162449. /* note we assume that fill_input_buffer will never return FALSE,
  162450. * so suspension need not be handled.
  162451. */
  162452. }
  162453. src->pub.next_input_byte += (size_t) num_bytes;
  162454. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  162455. }
  162456. }
  162457. /*
  162458. * An additional method that can be provided by data source modules is the
  162459. * resync_to_restart method for error recovery in the presence of RST markers.
  162460. * For the moment, this source module just uses the default resync method
  162461. * provided by the JPEG library. That method assumes that no backtracking
  162462. * is possible.
  162463. */
  162464. /*
  162465. * Terminate source --- called by jpeg_finish_decompress
  162466. * after all data has been read. Often a no-op.
  162467. *
  162468. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  162469. * application must deal with any cleanup that should happen even
  162470. * for error exit.
  162471. */
  162472. METHODDEF(void)
  162473. term_source (j_decompress_ptr cinfo)
  162474. {
  162475. /* no work necessary here */
  162476. }
  162477. /*
  162478. * Prepare for input from a stdio stream.
  162479. * The caller must have already opened the stream, and is responsible
  162480. * for closing it after finishing decompression.
  162481. */
  162482. GLOBAL(void)
  162483. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  162484. {
  162485. my_src_ptr src;
  162486. /* The source object and input buffer are made permanent so that a series
  162487. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  162488. * only before the first one. (If we discarded the buffer at the end of
  162489. * one image, we'd likely lose the start of the next one.)
  162490. * This makes it unsafe to use this manager and a different source
  162491. * manager serially with the same JPEG object. Caveat programmer.
  162492. */
  162493. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  162494. cinfo->src = (struct jpeg_source_mgr *)
  162495. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  162496. SIZEOF(my_source_mgr));
  162497. src = (my_src_ptr) cinfo->src;
  162498. src->buffer = (JOCTET *)
  162499. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  162500. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  162501. }
  162502. src = (my_src_ptr) cinfo->src;
  162503. src->pub.init_source = init_source;
  162504. src->pub.fill_input_buffer = fill_input_buffer;
  162505. src->pub.skip_input_data = skip_input_data;
  162506. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  162507. src->pub.term_source = term_source;
  162508. src->infile = infile;
  162509. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  162510. src->pub.next_input_byte = NULL; /* until buffer loaded */
  162511. }
  162512. /********* End of inlined file: jdatasrc.c *********/
  162513. /********* Start of inlined file: jdcoefct.c *********/
  162514. #define JPEG_INTERNALS
  162515. /* Block smoothing is only applicable for progressive JPEG, so: */
  162516. #ifndef D_PROGRESSIVE_SUPPORTED
  162517. #undef BLOCK_SMOOTHING_SUPPORTED
  162518. #endif
  162519. /* Private buffer controller object */
  162520. typedef struct {
  162521. struct jpeg_d_coef_controller pub; /* public fields */
  162522. /* These variables keep track of the current location of the input side. */
  162523. /* cinfo->input_iMCU_row is also used for this. */
  162524. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  162525. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  162526. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  162527. /* The output side's location is represented by cinfo->output_iMCU_row. */
  162528. /* In single-pass modes, it's sufficient to buffer just one MCU.
  162529. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  162530. * and let the entropy decoder write into that workspace each time.
  162531. * (On 80x86, the workspace is FAR even though it's not really very big;
  162532. * this is to keep the module interfaces unchanged when a large coefficient
  162533. * buffer is necessary.)
  162534. * In multi-pass modes, this array points to the current MCU's blocks
  162535. * within the virtual arrays; it is used only by the input side.
  162536. */
  162537. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  162538. #ifdef D_MULTISCAN_FILES_SUPPORTED
  162539. /* In multi-pass modes, we need a virtual block array for each component. */
  162540. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  162541. #endif
  162542. #ifdef BLOCK_SMOOTHING_SUPPORTED
  162543. /* When doing block smoothing, we latch coefficient Al values here */
  162544. int * coef_bits_latch;
  162545. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  162546. #endif
  162547. } my_coef_controller3;
  162548. typedef my_coef_controller3 * my_coef_ptr3;
  162549. /* Forward declarations */
  162550. METHODDEF(int) decompress_onepass
  162551. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  162552. #ifdef D_MULTISCAN_FILES_SUPPORTED
  162553. METHODDEF(int) decompress_data
  162554. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  162555. #endif
  162556. #ifdef BLOCK_SMOOTHING_SUPPORTED
  162557. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  162558. METHODDEF(int) decompress_smooth_data
  162559. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  162560. #endif
  162561. LOCAL(void)
  162562. start_iMCU_row3 (j_decompress_ptr cinfo)
  162563. /* Reset within-iMCU-row counters for a new row (input side) */
  162564. {
  162565. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162566. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  162567. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  162568. * But at the bottom of the image, process only what's left.
  162569. */
  162570. if (cinfo->comps_in_scan > 1) {
  162571. coef->MCU_rows_per_iMCU_row = 1;
  162572. } else {
  162573. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  162574. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  162575. else
  162576. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  162577. }
  162578. coef->MCU_ctr = 0;
  162579. coef->MCU_vert_offset = 0;
  162580. }
  162581. /*
  162582. * Initialize for an input processing pass.
  162583. */
  162584. METHODDEF(void)
  162585. start_input_pass (j_decompress_ptr cinfo)
  162586. {
  162587. cinfo->input_iMCU_row = 0;
  162588. start_iMCU_row3(cinfo);
  162589. }
  162590. /*
  162591. * Initialize for an output processing pass.
  162592. */
  162593. METHODDEF(void)
  162594. start_output_pass (j_decompress_ptr cinfo)
  162595. {
  162596. #ifdef BLOCK_SMOOTHING_SUPPORTED
  162597. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162598. /* If multipass, check to see whether to use block smoothing on this pass */
  162599. if (coef->pub.coef_arrays != NULL) {
  162600. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  162601. coef->pub.decompress_data = decompress_smooth_data;
  162602. else
  162603. coef->pub.decompress_data = decompress_data;
  162604. }
  162605. #endif
  162606. cinfo->output_iMCU_row = 0;
  162607. }
  162608. /*
  162609. * Decompress and return some data in the single-pass case.
  162610. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  162611. * Input and output must run in lockstep since we have only a one-MCU buffer.
  162612. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  162613. *
  162614. * NB: output_buf contains a plane for each component in image,
  162615. * which we index according to the component's SOF position.
  162616. */
  162617. METHODDEF(int)
  162618. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  162619. {
  162620. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162621. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162622. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  162623. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162624. int blkn, ci, xindex, yindex, yoffset, useful_width;
  162625. JSAMPARRAY output_ptr;
  162626. JDIMENSION start_col, output_col;
  162627. jpeg_component_info *compptr;
  162628. inverse_DCT_method_ptr inverse_DCT;
  162629. /* Loop to process as much as one whole iMCU row */
  162630. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162631. yoffset++) {
  162632. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  162633. MCU_col_num++) {
  162634. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  162635. jzero_far((void FAR *) coef->MCU_buffer[0],
  162636. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  162637. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  162638. /* Suspension forced; update state counters and exit */
  162639. coef->MCU_vert_offset = yoffset;
  162640. coef->MCU_ctr = MCU_col_num;
  162641. return JPEG_SUSPENDED;
  162642. }
  162643. /* Determine where data should go in output_buf and do the IDCT thing.
  162644. * We skip dummy blocks at the right and bottom edges (but blkn gets
  162645. * incremented past them!). Note the inner loop relies on having
  162646. * allocated the MCU_buffer[] blocks sequentially.
  162647. */
  162648. blkn = 0; /* index of current DCT block within MCU */
  162649. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162650. compptr = cinfo->cur_comp_info[ci];
  162651. /* Don't bother to IDCT an uninteresting component. */
  162652. if (! compptr->component_needed) {
  162653. blkn += compptr->MCU_blocks;
  162654. continue;
  162655. }
  162656. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  162657. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162658. : compptr->last_col_width;
  162659. output_ptr = output_buf[compptr->component_index] +
  162660. yoffset * compptr->DCT_scaled_size;
  162661. start_col = MCU_col_num * compptr->MCU_sample_width;
  162662. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162663. if (cinfo->input_iMCU_row < last_iMCU_row ||
  162664. yoffset+yindex < compptr->last_row_height) {
  162665. output_col = start_col;
  162666. for (xindex = 0; xindex < useful_width; xindex++) {
  162667. (*inverse_DCT) (cinfo, compptr,
  162668. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  162669. output_ptr, output_col);
  162670. output_col += compptr->DCT_scaled_size;
  162671. }
  162672. }
  162673. blkn += compptr->MCU_width;
  162674. output_ptr += compptr->DCT_scaled_size;
  162675. }
  162676. }
  162677. }
  162678. /* Completed an MCU row, but perhaps not an iMCU row */
  162679. coef->MCU_ctr = 0;
  162680. }
  162681. /* Completed the iMCU row, advance counters for next one */
  162682. cinfo->output_iMCU_row++;
  162683. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  162684. start_iMCU_row3(cinfo);
  162685. return JPEG_ROW_COMPLETED;
  162686. }
  162687. /* Completed the scan */
  162688. (*cinfo->inputctl->finish_input_pass) (cinfo);
  162689. return JPEG_SCAN_COMPLETED;
  162690. }
  162691. /*
  162692. * Dummy consume-input routine for single-pass operation.
  162693. */
  162694. METHODDEF(int)
  162695. dummy_consume_data (j_decompress_ptr cinfo)
  162696. {
  162697. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  162698. }
  162699. #ifdef D_MULTISCAN_FILES_SUPPORTED
  162700. /*
  162701. * Consume input data and store it in the full-image coefficient buffer.
  162702. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  162703. * ie, v_samp_factor block rows for each component in the scan.
  162704. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  162705. */
  162706. METHODDEF(int)
  162707. consume_data (j_decompress_ptr cinfo)
  162708. {
  162709. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162710. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162711. int blkn, ci, xindex, yindex, yoffset;
  162712. JDIMENSION start_col;
  162713. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162714. JBLOCKROW buffer_ptr;
  162715. jpeg_component_info *compptr;
  162716. /* Align the virtual buffers for the components used in this scan. */
  162717. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162718. compptr = cinfo->cur_comp_info[ci];
  162719. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162720. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162721. cinfo->input_iMCU_row * compptr->v_samp_factor,
  162722. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162723. /* Note: entropy decoder expects buffer to be zeroed,
  162724. * but this is handled automatically by the memory manager
  162725. * because we requested a pre-zeroed array.
  162726. */
  162727. }
  162728. /* Loop to process one whole iMCU row */
  162729. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162730. yoffset++) {
  162731. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162732. MCU_col_num++) {
  162733. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162734. blkn = 0; /* index of current DCT block within MCU */
  162735. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162736. compptr = cinfo->cur_comp_info[ci];
  162737. start_col = MCU_col_num * compptr->MCU_width;
  162738. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162739. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162740. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162741. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162742. }
  162743. }
  162744. }
  162745. /* Try to fetch the MCU. */
  162746. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  162747. /* Suspension forced; update state counters and exit */
  162748. coef->MCU_vert_offset = yoffset;
  162749. coef->MCU_ctr = MCU_col_num;
  162750. return JPEG_SUSPENDED;
  162751. }
  162752. }
  162753. /* Completed an MCU row, but perhaps not an iMCU row */
  162754. coef->MCU_ctr = 0;
  162755. }
  162756. /* Completed the iMCU row, advance counters for next one */
  162757. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  162758. start_iMCU_row3(cinfo);
  162759. return JPEG_ROW_COMPLETED;
  162760. }
  162761. /* Completed the scan */
  162762. (*cinfo->inputctl->finish_input_pass) (cinfo);
  162763. return JPEG_SCAN_COMPLETED;
  162764. }
  162765. /*
  162766. * Decompress and return some data in the multi-pass case.
  162767. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  162768. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  162769. *
  162770. * NB: output_buf contains a plane for each component in image.
  162771. */
  162772. METHODDEF(int)
  162773. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  162774. {
  162775. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162776. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162777. JDIMENSION block_num;
  162778. int ci, block_row, block_rows;
  162779. JBLOCKARRAY buffer;
  162780. JBLOCKROW buffer_ptr;
  162781. JSAMPARRAY output_ptr;
  162782. JDIMENSION output_col;
  162783. jpeg_component_info *compptr;
  162784. inverse_DCT_method_ptr inverse_DCT;
  162785. /* Force some input to be done if we are getting ahead of the input. */
  162786. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  162787. (cinfo->input_scan_number == cinfo->output_scan_number &&
  162788. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  162789. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  162790. return JPEG_SUSPENDED;
  162791. }
  162792. /* OK, output from the virtual arrays. */
  162793. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162794. ci++, compptr++) {
  162795. /* Don't bother to IDCT an uninteresting component. */
  162796. if (! compptr->component_needed)
  162797. continue;
  162798. /* Align the virtual buffer for this component. */
  162799. buffer = (*cinfo->mem->access_virt_barray)
  162800. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162801. cinfo->output_iMCU_row * compptr->v_samp_factor,
  162802. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162803. /* Count non-dummy DCT block rows in this iMCU row. */
  162804. if (cinfo->output_iMCU_row < last_iMCU_row)
  162805. block_rows = compptr->v_samp_factor;
  162806. else {
  162807. /* NB: can't use last_row_height here; it is input-side-dependent! */
  162808. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162809. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162810. }
  162811. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  162812. output_ptr = output_buf[ci];
  162813. /* Loop over all DCT blocks to be processed. */
  162814. for (block_row = 0; block_row < block_rows; block_row++) {
  162815. buffer_ptr = buffer[block_row];
  162816. output_col = 0;
  162817. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  162818. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  162819. output_ptr, output_col);
  162820. buffer_ptr++;
  162821. output_col += compptr->DCT_scaled_size;
  162822. }
  162823. output_ptr += compptr->DCT_scaled_size;
  162824. }
  162825. }
  162826. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  162827. return JPEG_ROW_COMPLETED;
  162828. return JPEG_SCAN_COMPLETED;
  162829. }
  162830. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  162831. #ifdef BLOCK_SMOOTHING_SUPPORTED
  162832. /*
  162833. * This code applies interblock smoothing as described by section K.8
  162834. * of the JPEG standard: the first 5 AC coefficients are estimated from
  162835. * the DC values of a DCT block and its 8 neighboring blocks.
  162836. * We apply smoothing only for progressive JPEG decoding, and only if
  162837. * the coefficients it can estimate are not yet known to full precision.
  162838. */
  162839. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  162840. #define Q01_POS 1
  162841. #define Q10_POS 8
  162842. #define Q20_POS 16
  162843. #define Q11_POS 9
  162844. #define Q02_POS 2
  162845. /*
  162846. * Determine whether block smoothing is applicable and safe.
  162847. * We also latch the current states of the coef_bits[] entries for the
  162848. * AC coefficients; otherwise, if the input side of the decompressor
  162849. * advances into a new scan, we might think the coefficients are known
  162850. * more accurately than they really are.
  162851. */
  162852. LOCAL(boolean)
  162853. smoothing_ok (j_decompress_ptr cinfo)
  162854. {
  162855. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162856. boolean smoothing_useful = FALSE;
  162857. int ci, coefi;
  162858. jpeg_component_info *compptr;
  162859. JQUANT_TBL * qtable;
  162860. int * coef_bits;
  162861. int * coef_bits_latch;
  162862. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  162863. return FALSE;
  162864. /* Allocate latch area if not already done */
  162865. if (coef->coef_bits_latch == NULL)
  162866. coef->coef_bits_latch = (int *)
  162867. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162868. cinfo->num_components *
  162869. (SAVED_COEFS * SIZEOF(int)));
  162870. coef_bits_latch = coef->coef_bits_latch;
  162871. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162872. ci++, compptr++) {
  162873. /* All components' quantization values must already be latched. */
  162874. if ((qtable = compptr->quant_table) == NULL)
  162875. return FALSE;
  162876. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  162877. if (qtable->quantval[0] == 0 ||
  162878. qtable->quantval[Q01_POS] == 0 ||
  162879. qtable->quantval[Q10_POS] == 0 ||
  162880. qtable->quantval[Q20_POS] == 0 ||
  162881. qtable->quantval[Q11_POS] == 0 ||
  162882. qtable->quantval[Q02_POS] == 0)
  162883. return FALSE;
  162884. /* DC values must be at least partly known for all components. */
  162885. coef_bits = cinfo->coef_bits[ci];
  162886. if (coef_bits[0] < 0)
  162887. return FALSE;
  162888. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  162889. for (coefi = 1; coefi <= 5; coefi++) {
  162890. coef_bits_latch[coefi] = coef_bits[coefi];
  162891. if (coef_bits[coefi] != 0)
  162892. smoothing_useful = TRUE;
  162893. }
  162894. coef_bits_latch += SAVED_COEFS;
  162895. }
  162896. return smoothing_useful;
  162897. }
  162898. /*
  162899. * Variant of decompress_data for use when doing block smoothing.
  162900. */
  162901. METHODDEF(int)
  162902. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  162903. {
  162904. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162905. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162906. JDIMENSION block_num, last_block_column;
  162907. int ci, block_row, block_rows, access_rows;
  162908. JBLOCKARRAY buffer;
  162909. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  162910. JSAMPARRAY output_ptr;
  162911. JDIMENSION output_col;
  162912. jpeg_component_info *compptr;
  162913. inverse_DCT_method_ptr inverse_DCT;
  162914. boolean first_row, last_row;
  162915. JBLOCK workspace;
  162916. int *coef_bits;
  162917. JQUANT_TBL *quanttbl;
  162918. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  162919. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  162920. int Al, pred;
  162921. /* Force some input to be done if we are getting ahead of the input. */
  162922. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  162923. ! cinfo->inputctl->eoi_reached) {
  162924. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  162925. /* If input is working on current scan, we ordinarily want it to
  162926. * have completed the current row. But if input scan is DC,
  162927. * we want it to keep one row ahead so that next block row's DC
  162928. * values are up to date.
  162929. */
  162930. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  162931. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  162932. break;
  162933. }
  162934. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  162935. return JPEG_SUSPENDED;
  162936. }
  162937. /* OK, output from the virtual arrays. */
  162938. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162939. ci++, compptr++) {
  162940. /* Don't bother to IDCT an uninteresting component. */
  162941. if (! compptr->component_needed)
  162942. continue;
  162943. /* Count non-dummy DCT block rows in this iMCU row. */
  162944. if (cinfo->output_iMCU_row < last_iMCU_row) {
  162945. block_rows = compptr->v_samp_factor;
  162946. access_rows = block_rows * 2; /* this and next iMCU row */
  162947. last_row = FALSE;
  162948. } else {
  162949. /* NB: can't use last_row_height here; it is input-side-dependent! */
  162950. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162951. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162952. access_rows = block_rows; /* this iMCU row only */
  162953. last_row = TRUE;
  162954. }
  162955. /* Align the virtual buffer for this component. */
  162956. if (cinfo->output_iMCU_row > 0) {
  162957. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  162958. buffer = (*cinfo->mem->access_virt_barray)
  162959. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162960. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  162961. (JDIMENSION) access_rows, FALSE);
  162962. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  162963. first_row = FALSE;
  162964. } else {
  162965. buffer = (*cinfo->mem->access_virt_barray)
  162966. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162967. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  162968. first_row = TRUE;
  162969. }
  162970. /* Fetch component-dependent info */
  162971. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  162972. quanttbl = compptr->quant_table;
  162973. Q00 = quanttbl->quantval[0];
  162974. Q01 = quanttbl->quantval[Q01_POS];
  162975. Q10 = quanttbl->quantval[Q10_POS];
  162976. Q20 = quanttbl->quantval[Q20_POS];
  162977. Q11 = quanttbl->quantval[Q11_POS];
  162978. Q02 = quanttbl->quantval[Q02_POS];
  162979. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  162980. output_ptr = output_buf[ci];
  162981. /* Loop over all DCT blocks to be processed. */
  162982. for (block_row = 0; block_row < block_rows; block_row++) {
  162983. buffer_ptr = buffer[block_row];
  162984. if (first_row && block_row == 0)
  162985. prev_block_row = buffer_ptr;
  162986. else
  162987. prev_block_row = buffer[block_row-1];
  162988. if (last_row && block_row == block_rows-1)
  162989. next_block_row = buffer_ptr;
  162990. else
  162991. next_block_row = buffer[block_row+1];
  162992. /* We fetch the surrounding DC values using a sliding-register approach.
  162993. * Initialize all nine here so as to do the right thing on narrow pics.
  162994. */
  162995. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  162996. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  162997. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  162998. output_col = 0;
  162999. last_block_column = compptr->width_in_blocks - 1;
  163000. for (block_num = 0; block_num <= last_block_column; block_num++) {
  163001. /* Fetch current DCT block into workspace so we can modify it. */
  163002. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  163003. /* Update DC values */
  163004. if (block_num < last_block_column) {
  163005. DC3 = (int) prev_block_row[1][0];
  163006. DC6 = (int) buffer_ptr[1][0];
  163007. DC9 = (int) next_block_row[1][0];
  163008. }
  163009. /* Compute coefficient estimates per K.8.
  163010. * An estimate is applied only if coefficient is still zero,
  163011. * and is not known to be fully accurate.
  163012. */
  163013. /* AC01 */
  163014. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  163015. num = 36 * Q00 * (DC4 - DC6);
  163016. if (num >= 0) {
  163017. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  163018. if (Al > 0 && pred >= (1<<Al))
  163019. pred = (1<<Al)-1;
  163020. } else {
  163021. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  163022. if (Al > 0 && pred >= (1<<Al))
  163023. pred = (1<<Al)-1;
  163024. pred = -pred;
  163025. }
  163026. workspace[1] = (JCOEF) pred;
  163027. }
  163028. /* AC10 */
  163029. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  163030. num = 36 * Q00 * (DC2 - DC8);
  163031. if (num >= 0) {
  163032. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  163033. if (Al > 0 && pred >= (1<<Al))
  163034. pred = (1<<Al)-1;
  163035. } else {
  163036. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  163037. if (Al > 0 && pred >= (1<<Al))
  163038. pred = (1<<Al)-1;
  163039. pred = -pred;
  163040. }
  163041. workspace[8] = (JCOEF) pred;
  163042. }
  163043. /* AC20 */
  163044. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  163045. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  163046. if (num >= 0) {
  163047. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  163048. if (Al > 0 && pred >= (1<<Al))
  163049. pred = (1<<Al)-1;
  163050. } else {
  163051. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  163052. if (Al > 0 && pred >= (1<<Al))
  163053. pred = (1<<Al)-1;
  163054. pred = -pred;
  163055. }
  163056. workspace[16] = (JCOEF) pred;
  163057. }
  163058. /* AC11 */
  163059. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  163060. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  163061. if (num >= 0) {
  163062. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  163063. if (Al > 0 && pred >= (1<<Al))
  163064. pred = (1<<Al)-1;
  163065. } else {
  163066. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  163067. if (Al > 0 && pred >= (1<<Al))
  163068. pred = (1<<Al)-1;
  163069. pred = -pred;
  163070. }
  163071. workspace[9] = (JCOEF) pred;
  163072. }
  163073. /* AC02 */
  163074. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  163075. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  163076. if (num >= 0) {
  163077. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  163078. if (Al > 0 && pred >= (1<<Al))
  163079. pred = (1<<Al)-1;
  163080. } else {
  163081. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  163082. if (Al > 0 && pred >= (1<<Al))
  163083. pred = (1<<Al)-1;
  163084. pred = -pred;
  163085. }
  163086. workspace[2] = (JCOEF) pred;
  163087. }
  163088. /* OK, do the IDCT */
  163089. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  163090. output_ptr, output_col);
  163091. /* Advance for next column */
  163092. DC1 = DC2; DC2 = DC3;
  163093. DC4 = DC5; DC5 = DC6;
  163094. DC7 = DC8; DC8 = DC9;
  163095. buffer_ptr++, prev_block_row++, next_block_row++;
  163096. output_col += compptr->DCT_scaled_size;
  163097. }
  163098. output_ptr += compptr->DCT_scaled_size;
  163099. }
  163100. }
  163101. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  163102. return JPEG_ROW_COMPLETED;
  163103. return JPEG_SCAN_COMPLETED;
  163104. }
  163105. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  163106. /*
  163107. * Initialize coefficient buffer controller.
  163108. */
  163109. GLOBAL(void)
  163110. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  163111. {
  163112. my_coef_ptr3 coef;
  163113. coef = (my_coef_ptr3)
  163114. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163115. SIZEOF(my_coef_controller3));
  163116. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  163117. coef->pub.start_input_pass = start_input_pass;
  163118. coef->pub.start_output_pass = start_output_pass;
  163119. #ifdef BLOCK_SMOOTHING_SUPPORTED
  163120. coef->coef_bits_latch = NULL;
  163121. #endif
  163122. /* Create the coefficient buffer. */
  163123. if (need_full_buffer) {
  163124. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163125. /* Allocate a full-image virtual array for each component, */
  163126. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  163127. /* Note we ask for a pre-zeroed array. */
  163128. int ci, access_rows;
  163129. jpeg_component_info *compptr;
  163130. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163131. ci++, compptr++) {
  163132. access_rows = compptr->v_samp_factor;
  163133. #ifdef BLOCK_SMOOTHING_SUPPORTED
  163134. /* If block smoothing could be used, need a bigger window */
  163135. if (cinfo->progressive_mode)
  163136. access_rows *= 3;
  163137. #endif
  163138. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  163139. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  163140. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  163141. (long) compptr->h_samp_factor),
  163142. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  163143. (long) compptr->v_samp_factor),
  163144. (JDIMENSION) access_rows);
  163145. }
  163146. coef->pub.consume_data = consume_data;
  163147. coef->pub.decompress_data = decompress_data;
  163148. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  163149. #else
  163150. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163151. #endif
  163152. } else {
  163153. /* We only need a single-MCU buffer. */
  163154. JBLOCKROW buffer;
  163155. int i;
  163156. buffer = (JBLOCKROW)
  163157. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163158. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  163159. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  163160. coef->MCU_buffer[i] = buffer + i;
  163161. }
  163162. coef->pub.consume_data = dummy_consume_data;
  163163. coef->pub.decompress_data = decompress_onepass;
  163164. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  163165. }
  163166. }
  163167. /********* End of inlined file: jdcoefct.c *********/
  163168. #undef FIX
  163169. /********* Start of inlined file: jdcolor.c *********/
  163170. #define JPEG_INTERNALS
  163171. /* Private subobject */
  163172. typedef struct {
  163173. struct jpeg_color_deconverter pub; /* public fields */
  163174. /* Private state for YCC->RGB conversion */
  163175. int * Cr_r_tab; /* => table for Cr to R conversion */
  163176. int * Cb_b_tab; /* => table for Cb to B conversion */
  163177. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  163178. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  163179. } my_color_deconverter2;
  163180. typedef my_color_deconverter2 * my_cconvert_ptr2;
  163181. /**************** YCbCr -> RGB conversion: most common case **************/
  163182. /*
  163183. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  163184. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  163185. * The conversion equations to be implemented are therefore
  163186. * R = Y + 1.40200 * Cr
  163187. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  163188. * B = Y + 1.77200 * Cb
  163189. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  163190. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  163191. *
  163192. * To avoid floating-point arithmetic, we represent the fractional constants
  163193. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  163194. * the products by 2^16, with appropriate rounding, to get the correct answer.
  163195. * Notice that Y, being an integral input, does not contribute any fraction
  163196. * so it need not participate in the rounding.
  163197. *
  163198. * For even more speed, we avoid doing any multiplications in the inner loop
  163199. * by precalculating the constants times Cb and Cr for all possible values.
  163200. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  163201. * for 12-bit samples it is still acceptable. It's not very reasonable for
  163202. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  163203. * colorspace anyway.
  163204. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  163205. * values for the G calculation are left scaled up, since we must add them
  163206. * together before rounding.
  163207. */
  163208. #define SCALEBITS 16 /* speediest right-shift on some machines */
  163209. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  163210. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  163211. /*
  163212. * Initialize tables for YCC->RGB colorspace conversion.
  163213. */
  163214. LOCAL(void)
  163215. build_ycc_rgb_table (j_decompress_ptr cinfo)
  163216. {
  163217. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  163218. int i;
  163219. INT32 x;
  163220. SHIFT_TEMPS
  163221. cconvert->Cr_r_tab = (int *)
  163222. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163223. (MAXJSAMPLE+1) * SIZEOF(int));
  163224. cconvert->Cb_b_tab = (int *)
  163225. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163226. (MAXJSAMPLE+1) * SIZEOF(int));
  163227. cconvert->Cr_g_tab = (INT32 *)
  163228. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163229. (MAXJSAMPLE+1) * SIZEOF(INT32));
  163230. cconvert->Cb_g_tab = (INT32 *)
  163231. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163232. (MAXJSAMPLE+1) * SIZEOF(INT32));
  163233. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  163234. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  163235. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  163236. /* Cr=>R value is nearest int to 1.40200 * x */
  163237. cconvert->Cr_r_tab[i] = (int)
  163238. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  163239. /* Cb=>B value is nearest int to 1.77200 * x */
  163240. cconvert->Cb_b_tab[i] = (int)
  163241. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  163242. /* Cr=>G value is scaled-up -0.71414 * x */
  163243. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  163244. /* Cb=>G value is scaled-up -0.34414 * x */
  163245. /* We also add in ONE_HALF so that need not do it in inner loop */
  163246. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  163247. }
  163248. }
  163249. /*
  163250. * Convert some rows of samples to the output colorspace.
  163251. *
  163252. * Note that we change from noninterleaved, one-plane-per-component format
  163253. * to interleaved-pixel format. The output buffer is therefore three times
  163254. * as wide as the input buffer.
  163255. * A starting row offset is provided only for the input buffer. The caller
  163256. * can easily adjust the passed output_buf value to accommodate any row
  163257. * offset required on that side.
  163258. */
  163259. METHODDEF(void)
  163260. ycc_rgb_convert (j_decompress_ptr cinfo,
  163261. JSAMPIMAGE input_buf, JDIMENSION input_row,
  163262. JSAMPARRAY output_buf, int num_rows)
  163263. {
  163264. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  163265. register int y, cb, cr;
  163266. register JSAMPROW outptr;
  163267. register JSAMPROW inptr0, inptr1, inptr2;
  163268. register JDIMENSION col;
  163269. JDIMENSION num_cols = cinfo->output_width;
  163270. /* copy these pointers into registers if possible */
  163271. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  163272. register int * Crrtab = cconvert->Cr_r_tab;
  163273. register int * Cbbtab = cconvert->Cb_b_tab;
  163274. register INT32 * Crgtab = cconvert->Cr_g_tab;
  163275. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  163276. SHIFT_TEMPS
  163277. while (--num_rows >= 0) {
  163278. inptr0 = input_buf[0][input_row];
  163279. inptr1 = input_buf[1][input_row];
  163280. inptr2 = input_buf[2][input_row];
  163281. input_row++;
  163282. outptr = *output_buf++;
  163283. for (col = 0; col < num_cols; col++) {
  163284. y = GETJSAMPLE(inptr0[col]);
  163285. cb = GETJSAMPLE(inptr1[col]);
  163286. cr = GETJSAMPLE(inptr2[col]);
  163287. /* Range-limiting is essential due to noise introduced by DCT losses. */
  163288. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  163289. outptr[RGB_GREEN] = range_limit[y +
  163290. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  163291. SCALEBITS))];
  163292. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  163293. outptr += RGB_PIXELSIZE;
  163294. }
  163295. }
  163296. }
  163297. /**************** Cases other than YCbCr -> RGB **************/
  163298. /*
  163299. * Color conversion for no colorspace change: just copy the data,
  163300. * converting from separate-planes to interleaved representation.
  163301. */
  163302. METHODDEF(void)
  163303. null_convert2 (j_decompress_ptr cinfo,
  163304. JSAMPIMAGE input_buf, JDIMENSION input_row,
  163305. JSAMPARRAY output_buf, int num_rows)
  163306. {
  163307. register JSAMPROW inptr, outptr;
  163308. register JDIMENSION count;
  163309. register int num_components = cinfo->num_components;
  163310. JDIMENSION num_cols = cinfo->output_width;
  163311. int ci;
  163312. while (--num_rows >= 0) {
  163313. for (ci = 0; ci < num_components; ci++) {
  163314. inptr = input_buf[ci][input_row];
  163315. outptr = output_buf[0] + ci;
  163316. for (count = num_cols; count > 0; count--) {
  163317. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  163318. outptr += num_components;
  163319. }
  163320. }
  163321. input_row++;
  163322. output_buf++;
  163323. }
  163324. }
  163325. /*
  163326. * Color conversion for grayscale: just copy the data.
  163327. * This also works for YCbCr -> grayscale conversion, in which
  163328. * we just copy the Y (luminance) component and ignore chrominance.
  163329. */
  163330. METHODDEF(void)
  163331. grayscale_convert2 (j_decompress_ptr cinfo,
  163332. JSAMPIMAGE input_buf, JDIMENSION input_row,
  163333. JSAMPARRAY output_buf, int num_rows)
  163334. {
  163335. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  163336. num_rows, cinfo->output_width);
  163337. }
  163338. /*
  163339. * Convert grayscale to RGB: just duplicate the graylevel three times.
  163340. * This is provided to support applications that don't want to cope
  163341. * with grayscale as a separate case.
  163342. */
  163343. METHODDEF(void)
  163344. gray_rgb_convert (j_decompress_ptr cinfo,
  163345. JSAMPIMAGE input_buf, JDIMENSION input_row,
  163346. JSAMPARRAY output_buf, int num_rows)
  163347. {
  163348. register JSAMPROW inptr, outptr;
  163349. register JDIMENSION col;
  163350. JDIMENSION num_cols = cinfo->output_width;
  163351. while (--num_rows >= 0) {
  163352. inptr = input_buf[0][input_row++];
  163353. outptr = *output_buf++;
  163354. for (col = 0; col < num_cols; col++) {
  163355. /* We can dispense with GETJSAMPLE() here */
  163356. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  163357. outptr += RGB_PIXELSIZE;
  163358. }
  163359. }
  163360. }
  163361. /*
  163362. * Adobe-style YCCK->CMYK conversion.
  163363. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  163364. * conversion as above, while passing K (black) unchanged.
  163365. * We assume build_ycc_rgb_table has been called.
  163366. */
  163367. METHODDEF(void)
  163368. ycck_cmyk_convert (j_decompress_ptr cinfo,
  163369. JSAMPIMAGE input_buf, JDIMENSION input_row,
  163370. JSAMPARRAY output_buf, int num_rows)
  163371. {
  163372. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  163373. register int y, cb, cr;
  163374. register JSAMPROW outptr;
  163375. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  163376. register JDIMENSION col;
  163377. JDIMENSION num_cols = cinfo->output_width;
  163378. /* copy these pointers into registers if possible */
  163379. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  163380. register int * Crrtab = cconvert->Cr_r_tab;
  163381. register int * Cbbtab = cconvert->Cb_b_tab;
  163382. register INT32 * Crgtab = cconvert->Cr_g_tab;
  163383. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  163384. SHIFT_TEMPS
  163385. while (--num_rows >= 0) {
  163386. inptr0 = input_buf[0][input_row];
  163387. inptr1 = input_buf[1][input_row];
  163388. inptr2 = input_buf[2][input_row];
  163389. inptr3 = input_buf[3][input_row];
  163390. input_row++;
  163391. outptr = *output_buf++;
  163392. for (col = 0; col < num_cols; col++) {
  163393. y = GETJSAMPLE(inptr0[col]);
  163394. cb = GETJSAMPLE(inptr1[col]);
  163395. cr = GETJSAMPLE(inptr2[col]);
  163396. /* Range-limiting is essential due to noise introduced by DCT losses. */
  163397. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  163398. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  163399. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  163400. SCALEBITS)))];
  163401. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  163402. /* K passes through unchanged */
  163403. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  163404. outptr += 4;
  163405. }
  163406. }
  163407. }
  163408. /*
  163409. * Empty method for start_pass.
  163410. */
  163411. METHODDEF(void)
  163412. start_pass_dcolor (j_decompress_ptr cinfo)
  163413. {
  163414. /* no work needed */
  163415. }
  163416. /*
  163417. * Module initialization routine for output colorspace conversion.
  163418. */
  163419. GLOBAL(void)
  163420. jinit_color_deconverter (j_decompress_ptr cinfo)
  163421. {
  163422. my_cconvert_ptr2 cconvert;
  163423. int ci;
  163424. cconvert = (my_cconvert_ptr2)
  163425. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163426. SIZEOF(my_color_deconverter2));
  163427. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  163428. cconvert->pub.start_pass = start_pass_dcolor;
  163429. /* Make sure num_components agrees with jpeg_color_space */
  163430. switch (cinfo->jpeg_color_space) {
  163431. case JCS_GRAYSCALE:
  163432. if (cinfo->num_components != 1)
  163433. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  163434. break;
  163435. case JCS_RGB:
  163436. case JCS_YCbCr:
  163437. if (cinfo->num_components != 3)
  163438. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  163439. break;
  163440. case JCS_CMYK:
  163441. case JCS_YCCK:
  163442. if (cinfo->num_components != 4)
  163443. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  163444. break;
  163445. default: /* JCS_UNKNOWN can be anything */
  163446. if (cinfo->num_components < 1)
  163447. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  163448. break;
  163449. }
  163450. /* Set out_color_components and conversion method based on requested space.
  163451. * Also clear the component_needed flags for any unused components,
  163452. * so that earlier pipeline stages can avoid useless computation.
  163453. */
  163454. switch (cinfo->out_color_space) {
  163455. case JCS_GRAYSCALE:
  163456. cinfo->out_color_components = 1;
  163457. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  163458. cinfo->jpeg_color_space == JCS_YCbCr) {
  163459. cconvert->pub.color_convert = grayscale_convert2;
  163460. /* For color->grayscale conversion, only the Y (0) component is needed */
  163461. for (ci = 1; ci < cinfo->num_components; ci++)
  163462. cinfo->comp_info[ci].component_needed = FALSE;
  163463. } else
  163464. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  163465. break;
  163466. case JCS_RGB:
  163467. cinfo->out_color_components = RGB_PIXELSIZE;
  163468. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  163469. cconvert->pub.color_convert = ycc_rgb_convert;
  163470. build_ycc_rgb_table(cinfo);
  163471. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  163472. cconvert->pub.color_convert = gray_rgb_convert;
  163473. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  163474. cconvert->pub.color_convert = null_convert2;
  163475. } else
  163476. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  163477. break;
  163478. case JCS_CMYK:
  163479. cinfo->out_color_components = 4;
  163480. if (cinfo->jpeg_color_space == JCS_YCCK) {
  163481. cconvert->pub.color_convert = ycck_cmyk_convert;
  163482. build_ycc_rgb_table(cinfo);
  163483. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  163484. cconvert->pub.color_convert = null_convert2;
  163485. } else
  163486. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  163487. break;
  163488. default:
  163489. /* Permit null conversion to same output space */
  163490. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  163491. cinfo->out_color_components = cinfo->num_components;
  163492. cconvert->pub.color_convert = null_convert2;
  163493. } else /* unsupported non-null conversion */
  163494. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  163495. break;
  163496. }
  163497. if (cinfo->quantize_colors)
  163498. cinfo->output_components = 1; /* single colormapped output component */
  163499. else
  163500. cinfo->output_components = cinfo->out_color_components;
  163501. }
  163502. /********* End of inlined file: jdcolor.c *********/
  163503. #undef FIX
  163504. /********* Start of inlined file: jddctmgr.c *********/
  163505. #define JPEG_INTERNALS
  163506. /*
  163507. * The decompressor input side (jdinput.c) saves away the appropriate
  163508. * quantization table for each component at the start of the first scan
  163509. * involving that component. (This is necessary in order to correctly
  163510. * decode files that reuse Q-table slots.)
  163511. * When we are ready to make an output pass, the saved Q-table is converted
  163512. * to a multiplier table that will actually be used by the IDCT routine.
  163513. * The multiplier table contents are IDCT-method-dependent. To support
  163514. * application changes in IDCT method between scans, we can remake the
  163515. * multiplier tables if necessary.
  163516. * In buffered-image mode, the first output pass may occur before any data
  163517. * has been seen for some components, and thus before their Q-tables have
  163518. * been saved away. To handle this case, multiplier tables are preset
  163519. * to zeroes; the result of the IDCT will be a neutral gray level.
  163520. */
  163521. /* Private subobject for this module */
  163522. typedef struct {
  163523. struct jpeg_inverse_dct pub; /* public fields */
  163524. /* This array contains the IDCT method code that each multiplier table
  163525. * is currently set up for, or -1 if it's not yet set up.
  163526. * The actual multiplier tables are pointed to by dct_table in the
  163527. * per-component comp_info structures.
  163528. */
  163529. int cur_method[MAX_COMPONENTS];
  163530. } my_idct_controller;
  163531. typedef my_idct_controller * my_idct_ptr;
  163532. /* Allocated multiplier tables: big enough for any supported variant */
  163533. typedef union {
  163534. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  163535. #ifdef DCT_IFAST_SUPPORTED
  163536. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  163537. #endif
  163538. #ifdef DCT_FLOAT_SUPPORTED
  163539. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  163540. #endif
  163541. } multiplier_table;
  163542. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  163543. * so be sure to compile that code if either ISLOW or SCALING is requested.
  163544. */
  163545. #ifdef DCT_ISLOW_SUPPORTED
  163546. #define PROVIDE_ISLOW_TABLES
  163547. #else
  163548. #ifdef IDCT_SCALING_SUPPORTED
  163549. #define PROVIDE_ISLOW_TABLES
  163550. #endif
  163551. #endif
  163552. /*
  163553. * Prepare for an output pass.
  163554. * Here we select the proper IDCT routine for each component and build
  163555. * a matching multiplier table.
  163556. */
  163557. METHODDEF(void)
  163558. start_pass (j_decompress_ptr cinfo)
  163559. {
  163560. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  163561. int ci, i;
  163562. jpeg_component_info *compptr;
  163563. int method = 0;
  163564. inverse_DCT_method_ptr method_ptr = NULL;
  163565. JQUANT_TBL * qtbl;
  163566. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163567. ci++, compptr++) {
  163568. /* Select the proper IDCT routine for this component's scaling */
  163569. switch (compptr->DCT_scaled_size) {
  163570. #ifdef IDCT_SCALING_SUPPORTED
  163571. case 1:
  163572. method_ptr = jpeg_idct_1x1;
  163573. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  163574. break;
  163575. case 2:
  163576. method_ptr = jpeg_idct_2x2;
  163577. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  163578. break;
  163579. case 4:
  163580. method_ptr = jpeg_idct_4x4;
  163581. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  163582. break;
  163583. #endif
  163584. case DCTSIZE:
  163585. switch (cinfo->dct_method) {
  163586. #ifdef DCT_ISLOW_SUPPORTED
  163587. case JDCT_ISLOW:
  163588. method_ptr = jpeg_idct_islow;
  163589. method = JDCT_ISLOW;
  163590. break;
  163591. #endif
  163592. #ifdef DCT_IFAST_SUPPORTED
  163593. case JDCT_IFAST:
  163594. method_ptr = jpeg_idct_ifast;
  163595. method = JDCT_IFAST;
  163596. break;
  163597. #endif
  163598. #ifdef DCT_FLOAT_SUPPORTED
  163599. case JDCT_FLOAT:
  163600. method_ptr = jpeg_idct_float;
  163601. method = JDCT_FLOAT;
  163602. break;
  163603. #endif
  163604. default:
  163605. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163606. break;
  163607. }
  163608. break;
  163609. default:
  163610. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  163611. break;
  163612. }
  163613. idct->pub.inverse_DCT[ci] = method_ptr;
  163614. /* Create multiplier table from quant table.
  163615. * However, we can skip this if the component is uninteresting
  163616. * or if we already built the table. Also, if no quant table
  163617. * has yet been saved for the component, we leave the
  163618. * multiplier table all-zero; we'll be reading zeroes from the
  163619. * coefficient controller's buffer anyway.
  163620. */
  163621. if (! compptr->component_needed || idct->cur_method[ci] == method)
  163622. continue;
  163623. qtbl = compptr->quant_table;
  163624. if (qtbl == NULL) /* happens if no data yet for component */
  163625. continue;
  163626. idct->cur_method[ci] = method;
  163627. switch (method) {
  163628. #ifdef PROVIDE_ISLOW_TABLES
  163629. case JDCT_ISLOW:
  163630. {
  163631. /* For LL&M IDCT method, multipliers are equal to raw quantization
  163632. * coefficients, but are stored as ints to ensure access efficiency.
  163633. */
  163634. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  163635. for (i = 0; i < DCTSIZE2; i++) {
  163636. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  163637. }
  163638. }
  163639. break;
  163640. #endif
  163641. #ifdef DCT_IFAST_SUPPORTED
  163642. case JDCT_IFAST:
  163643. {
  163644. /* For AA&N IDCT method, multipliers are equal to quantization
  163645. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163646. * scalefactor[0] = 1
  163647. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163648. * For integer operation, the multiplier table is to be scaled by
  163649. * IFAST_SCALE_BITS.
  163650. */
  163651. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  163652. #define CONST_BITS 14
  163653. static const INT16 aanscales[DCTSIZE2] = {
  163654. /* precomputed values scaled up by 14 bits */
  163655. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163656. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  163657. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  163658. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  163659. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163660. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  163661. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  163662. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  163663. };
  163664. SHIFT_TEMPS
  163665. for (i = 0; i < DCTSIZE2; i++) {
  163666. ifmtbl[i] = (IFAST_MULT_TYPE)
  163667. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  163668. (INT32) aanscales[i]),
  163669. CONST_BITS-IFAST_SCALE_BITS);
  163670. }
  163671. }
  163672. break;
  163673. #endif
  163674. #ifdef DCT_FLOAT_SUPPORTED
  163675. case JDCT_FLOAT:
  163676. {
  163677. /* For float AA&N IDCT method, multipliers are equal to quantization
  163678. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163679. * scalefactor[0] = 1
  163680. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163681. */
  163682. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  163683. int row, col;
  163684. static const double aanscalefactor[DCTSIZE] = {
  163685. 1.0, 1.387039845, 1.306562965, 1.175875602,
  163686. 1.0, 0.785694958, 0.541196100, 0.275899379
  163687. };
  163688. i = 0;
  163689. for (row = 0; row < DCTSIZE; row++) {
  163690. for (col = 0; col < DCTSIZE; col++) {
  163691. fmtbl[i] = (FLOAT_MULT_TYPE)
  163692. ((double) qtbl->quantval[i] *
  163693. aanscalefactor[row] * aanscalefactor[col]);
  163694. i++;
  163695. }
  163696. }
  163697. }
  163698. break;
  163699. #endif
  163700. default:
  163701. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163702. break;
  163703. }
  163704. }
  163705. }
  163706. /*
  163707. * Initialize IDCT manager.
  163708. */
  163709. GLOBAL(void)
  163710. jinit_inverse_dct (j_decompress_ptr cinfo)
  163711. {
  163712. my_idct_ptr idct;
  163713. int ci;
  163714. jpeg_component_info *compptr;
  163715. idct = (my_idct_ptr)
  163716. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163717. SIZEOF(my_idct_controller));
  163718. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  163719. idct->pub.start_pass = start_pass;
  163720. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163721. ci++, compptr++) {
  163722. /* Allocate and pre-zero a multiplier table for each component */
  163723. compptr->dct_table =
  163724. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163725. SIZEOF(multiplier_table));
  163726. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  163727. /* Mark multiplier table not yet set up for any method */
  163728. idct->cur_method[ci] = -1;
  163729. }
  163730. }
  163731. /********* End of inlined file: jddctmgr.c *********/
  163732. #undef CONST_BITS
  163733. #undef ASSIGN_STATE
  163734. /********* Start of inlined file: jdhuff.c *********/
  163735. #define JPEG_INTERNALS
  163736. /********* Start of inlined file: jdhuff.h *********/
  163737. /* Short forms of external names for systems with brain-damaged linkers. */
  163738. #ifndef __jdhuff_h__
  163739. #define __jdhuff_h__
  163740. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163741. #define jpeg_make_d_derived_tbl jMkDDerived
  163742. #define jpeg_fill_bit_buffer jFilBitBuf
  163743. #define jpeg_huff_decode jHufDecode
  163744. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163745. /* Derived data constructed for each Huffman table */
  163746. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  163747. typedef struct {
  163748. /* Basic tables: (element [0] of each array is unused) */
  163749. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  163750. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  163751. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  163752. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  163753. * the smallest code of length k; so given a code of length k, the
  163754. * corresponding symbol is huffval[code + valoffset[k]]
  163755. */
  163756. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  163757. JHUFF_TBL *pub;
  163758. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  163759. * the input data stream. If the next Huffman code is no more
  163760. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  163761. * the corresponding symbol directly from these tables.
  163762. */
  163763. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  163764. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  163765. } d_derived_tbl;
  163766. /* Expand a Huffman table definition into the derived format */
  163767. EXTERN(void) jpeg_make_d_derived_tbl
  163768. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  163769. d_derived_tbl ** pdtbl));
  163770. /*
  163771. * Fetching the next N bits from the input stream is a time-critical operation
  163772. * for the Huffman decoders. We implement it with a combination of inline
  163773. * macros and out-of-line subroutines. Note that N (the number of bits
  163774. * demanded at one time) never exceeds 15 for JPEG use.
  163775. *
  163776. * We read source bytes into get_buffer and dole out bits as needed.
  163777. * If get_buffer already contains enough bits, they are fetched in-line
  163778. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  163779. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  163780. * as full as possible (not just to the number of bits needed; this
  163781. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  163782. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  163783. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  163784. * at least the requested number of bits --- dummy zeroes are inserted if
  163785. * necessary.
  163786. */
  163787. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  163788. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  163789. /* If long is > 32 bits on your machine, and shifting/masking longs is
  163790. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  163791. * appropriately should be a win. Unfortunately we can't define the size
  163792. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  163793. * because not all machines measure sizeof in 8-bit bytes.
  163794. */
  163795. typedef struct { /* Bitreading state saved across MCUs */
  163796. bit_buf_type get_buffer; /* current bit-extraction buffer */
  163797. int bits_left; /* # of unused bits in it */
  163798. } bitread_perm_state;
  163799. typedef struct { /* Bitreading working state within an MCU */
  163800. /* Current data source location */
  163801. /* We need a copy, rather than munging the original, in case of suspension */
  163802. const JOCTET * next_input_byte; /* => next byte to read from source */
  163803. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  163804. /* Bit input buffer --- note these values are kept in register variables,
  163805. * not in this struct, inside the inner loops.
  163806. */
  163807. bit_buf_type get_buffer; /* current bit-extraction buffer */
  163808. int bits_left; /* # of unused bits in it */
  163809. /* Pointer needed by jpeg_fill_bit_buffer. */
  163810. j_decompress_ptr cinfo; /* back link to decompress master record */
  163811. } bitread_working_state;
  163812. /* Macros to declare and load/save bitread local variables. */
  163813. #define BITREAD_STATE_VARS \
  163814. register bit_buf_type get_buffer; \
  163815. register int bits_left; \
  163816. bitread_working_state br_state
  163817. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  163818. br_state.cinfo = cinfop; \
  163819. br_state.next_input_byte = cinfop->src->next_input_byte; \
  163820. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  163821. get_buffer = permstate.get_buffer; \
  163822. bits_left = permstate.bits_left;
  163823. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  163824. cinfop->src->next_input_byte = br_state.next_input_byte; \
  163825. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  163826. permstate.get_buffer = get_buffer; \
  163827. permstate.bits_left = bits_left
  163828. /*
  163829. * These macros provide the in-line portion of bit fetching.
  163830. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  163831. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  163832. * The variables get_buffer and bits_left are assumed to be locals,
  163833. * but the state struct might not be (jpeg_huff_decode needs this).
  163834. * CHECK_BIT_BUFFER(state,n,action);
  163835. * Ensure there are N bits in get_buffer; if suspend, take action.
  163836. * val = GET_BITS(n);
  163837. * Fetch next N bits.
  163838. * val = PEEK_BITS(n);
  163839. * Fetch next N bits without removing them from the buffer.
  163840. * DROP_BITS(n);
  163841. * Discard next N bits.
  163842. * The value N should be a simple variable, not an expression, because it
  163843. * is evaluated multiple times.
  163844. */
  163845. #define CHECK_BIT_BUFFER(state,nbits,action) \
  163846. { if (bits_left < (nbits)) { \
  163847. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  163848. { action; } \
  163849. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  163850. #define GET_BITS(nbits) \
  163851. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  163852. #define PEEK_BITS(nbits) \
  163853. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  163854. #define DROP_BITS(nbits) \
  163855. (bits_left -= (nbits))
  163856. /* Load up the bit buffer to a depth of at least nbits */
  163857. EXTERN(boolean) jpeg_fill_bit_buffer
  163858. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  163859. register int bits_left, int nbits));
  163860. /*
  163861. * Code for extracting next Huffman-coded symbol from input bit stream.
  163862. * Again, this is time-critical and we make the main paths be macros.
  163863. *
  163864. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  163865. * without looping. Usually, more than 95% of the Huffman codes will be 8
  163866. * or fewer bits long. The few overlength codes are handled with a loop,
  163867. * which need not be inline code.
  163868. *
  163869. * Notes about the HUFF_DECODE macro:
  163870. * 1. Near the end of the data segment, we may fail to get enough bits
  163871. * for a lookahead. In that case, we do it the hard way.
  163872. * 2. If the lookahead table contains no entry, the next code must be
  163873. * more than HUFF_LOOKAHEAD bits long.
  163874. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  163875. */
  163876. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  163877. { register int nb, look; \
  163878. if (bits_left < HUFF_LOOKAHEAD) { \
  163879. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  163880. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  163881. if (bits_left < HUFF_LOOKAHEAD) { \
  163882. nb = 1; goto slowlabel; \
  163883. } \
  163884. } \
  163885. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  163886. if ((nb = htbl->look_nbits[look]) != 0) { \
  163887. DROP_BITS(nb); \
  163888. result = htbl->look_sym[look]; \
  163889. } else { \
  163890. nb = HUFF_LOOKAHEAD+1; \
  163891. slowlabel: \
  163892. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  163893. { failaction; } \
  163894. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  163895. } \
  163896. }
  163897. /* Out-of-line case for Huffman code fetching */
  163898. EXTERN(int) jpeg_huff_decode
  163899. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  163900. register int bits_left, d_derived_tbl * htbl, int min_bits));
  163901. #endif
  163902. /********* End of inlined file: jdhuff.h *********/
  163903. /* Declarations shared with jdphuff.c */
  163904. /*
  163905. * Expanded entropy decoder object for Huffman decoding.
  163906. *
  163907. * The savable_state subrecord contains fields that change within an MCU,
  163908. * but must not be updated permanently until we complete the MCU.
  163909. */
  163910. typedef struct {
  163911. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163912. } savable_state2;
  163913. /* This macro is to work around compilers with missing or broken
  163914. * structure assignment. You'll need to fix this code if you have
  163915. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163916. */
  163917. #ifndef NO_STRUCT_ASSIGN
  163918. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163919. #else
  163920. #if MAX_COMPS_IN_SCAN == 4
  163921. #define ASSIGN_STATE(dest,src) \
  163922. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  163923. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163924. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163925. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163926. #endif
  163927. #endif
  163928. typedef struct {
  163929. struct jpeg_entropy_decoder pub; /* public fields */
  163930. /* These fields are loaded into local variables at start of each MCU.
  163931. * In case of suspension, we exit WITHOUT updating them.
  163932. */
  163933. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  163934. savable_state2 saved; /* Other state at start of MCU */
  163935. /* These fields are NOT loaded into local working state. */
  163936. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163937. /* Pointers to derived tables (these workspaces have image lifespan) */
  163938. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163939. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163940. /* Precalculated info set up by start_pass for use in decode_mcu: */
  163941. /* Pointers to derived tables to be used for each block within an MCU */
  163942. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  163943. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  163944. /* Whether we care about the DC and AC coefficient values for each block */
  163945. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  163946. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  163947. } huff_entropy_decoder2;
  163948. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  163949. /*
  163950. * Initialize for a Huffman-compressed scan.
  163951. */
  163952. METHODDEF(void)
  163953. start_pass_huff_decoder (j_decompress_ptr cinfo)
  163954. {
  163955. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  163956. int ci, blkn, dctbl, actbl;
  163957. jpeg_component_info * compptr;
  163958. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  163959. * This ought to be an error condition, but we make it a warning because
  163960. * there are some baseline files out there with all zeroes in these bytes.
  163961. */
  163962. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  163963. cinfo->Ah != 0 || cinfo->Al != 0)
  163964. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  163965. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163966. compptr = cinfo->cur_comp_info[ci];
  163967. dctbl = compptr->dc_tbl_no;
  163968. actbl = compptr->ac_tbl_no;
  163969. /* Compute derived values for Huffman tables */
  163970. /* We may do this more than once for a table, but it's not expensive */
  163971. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  163972. & entropy->dc_derived_tbls[dctbl]);
  163973. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  163974. & entropy->ac_derived_tbls[actbl]);
  163975. /* Initialize DC predictions to 0 */
  163976. entropy->saved.last_dc_val[ci] = 0;
  163977. }
  163978. /* Precalculate decoding info for each block in an MCU of this scan */
  163979. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163980. ci = cinfo->MCU_membership[blkn];
  163981. compptr = cinfo->cur_comp_info[ci];
  163982. /* Precalculate which table to use for each block */
  163983. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  163984. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  163985. /* Decide whether we really care about the coefficient values */
  163986. if (compptr->component_needed) {
  163987. entropy->dc_needed[blkn] = TRUE;
  163988. /* we don't need the ACs if producing a 1/8th-size image */
  163989. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  163990. } else {
  163991. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  163992. }
  163993. }
  163994. /* Initialize bitread state variables */
  163995. entropy->bitstate.bits_left = 0;
  163996. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  163997. entropy->pub.insufficient_data = FALSE;
  163998. /* Initialize restart counter */
  163999. entropy->restarts_to_go = cinfo->restart_interval;
  164000. }
  164001. /*
  164002. * Compute the derived values for a Huffman table.
  164003. * This routine also performs some validation checks on the table.
  164004. *
  164005. * Note this is also used by jdphuff.c.
  164006. */
  164007. GLOBAL(void)
  164008. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  164009. d_derived_tbl ** pdtbl)
  164010. {
  164011. JHUFF_TBL *htbl;
  164012. d_derived_tbl *dtbl;
  164013. int p, i, l, si, numsymbols;
  164014. int lookbits, ctr;
  164015. char huffsize[257];
  164016. unsigned int huffcode[257];
  164017. unsigned int code;
  164018. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  164019. * paralleling the order of the symbols themselves in htbl->huffval[].
  164020. */
  164021. /* Find the input Huffman table */
  164022. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  164023. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  164024. htbl =
  164025. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  164026. if (htbl == NULL)
  164027. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  164028. /* Allocate a workspace if we haven't already done so. */
  164029. if (*pdtbl == NULL)
  164030. *pdtbl = (d_derived_tbl *)
  164031. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164032. SIZEOF(d_derived_tbl));
  164033. dtbl = *pdtbl;
  164034. dtbl->pub = htbl; /* fill in back link */
  164035. /* Figure C.1: make table of Huffman code length for each symbol */
  164036. p = 0;
  164037. for (l = 1; l <= 16; l++) {
  164038. i = (int) htbl->bits[l];
  164039. if (i < 0 || p + i > 256) /* protect against table overrun */
  164040. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164041. while (i--)
  164042. huffsize[p++] = (char) l;
  164043. }
  164044. huffsize[p] = 0;
  164045. numsymbols = p;
  164046. /* Figure C.2: generate the codes themselves */
  164047. /* We also validate that the counts represent a legal Huffman code tree. */
  164048. code = 0;
  164049. si = huffsize[0];
  164050. p = 0;
  164051. while (huffsize[p]) {
  164052. while (((int) huffsize[p]) == si) {
  164053. huffcode[p++] = code;
  164054. code++;
  164055. }
  164056. /* code is now 1 more than the last code used for codelength si; but
  164057. * it must still fit in si bits, since no code is allowed to be all ones.
  164058. */
  164059. if (((INT32) code) >= (((INT32) 1) << si))
  164060. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164061. code <<= 1;
  164062. si++;
  164063. }
  164064. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  164065. p = 0;
  164066. for (l = 1; l <= 16; l++) {
  164067. if (htbl->bits[l]) {
  164068. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  164069. * minus the minimum code of length l
  164070. */
  164071. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  164072. p += htbl->bits[l];
  164073. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  164074. } else {
  164075. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  164076. }
  164077. }
  164078. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  164079. /* Compute lookahead tables to speed up decoding.
  164080. * First we set all the table entries to 0, indicating "too long";
  164081. * then we iterate through the Huffman codes that are short enough and
  164082. * fill in all the entries that correspond to bit sequences starting
  164083. * with that code.
  164084. */
  164085. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  164086. p = 0;
  164087. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  164088. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  164089. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  164090. /* Generate left-justified code followed by all possible bit sequences */
  164091. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  164092. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  164093. dtbl->look_nbits[lookbits] = l;
  164094. dtbl->look_sym[lookbits] = htbl->huffval[p];
  164095. lookbits++;
  164096. }
  164097. }
  164098. }
  164099. /* Validate symbols as being reasonable.
  164100. * For AC tables, we make no check, but accept all byte values 0..255.
  164101. * For DC tables, we require the symbols to be in range 0..15.
  164102. * (Tighter bounds could be applied depending on the data depth and mode,
  164103. * but this is sufficient to ensure safe decoding.)
  164104. */
  164105. if (isDC) {
  164106. for (i = 0; i < numsymbols; i++) {
  164107. int sym = htbl->huffval[i];
  164108. if (sym < 0 || sym > 15)
  164109. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164110. }
  164111. }
  164112. }
  164113. /*
  164114. * Out-of-line code for bit fetching (shared with jdphuff.c).
  164115. * See jdhuff.h for info about usage.
  164116. * Note: current values of get_buffer and bits_left are passed as parameters,
  164117. * but are returned in the corresponding fields of the state struct.
  164118. *
  164119. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  164120. * of get_buffer to be used. (On machines with wider words, an even larger
  164121. * buffer could be used.) However, on some machines 32-bit shifts are
  164122. * quite slow and take time proportional to the number of places shifted.
  164123. * (This is true with most PC compilers, for instance.) In this case it may
  164124. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  164125. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  164126. */
  164127. #ifdef SLOW_SHIFT_32
  164128. #define MIN_GET_BITS 15 /* minimum allowable value */
  164129. #else
  164130. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  164131. #endif
  164132. GLOBAL(boolean)
  164133. jpeg_fill_bit_buffer (bitread_working_state * state,
  164134. register bit_buf_type get_buffer, register int bits_left,
  164135. int nbits)
  164136. /* Load up the bit buffer to a depth of at least nbits */
  164137. {
  164138. /* Copy heavily used state fields into locals (hopefully registers) */
  164139. register const JOCTET * next_input_byte = state->next_input_byte;
  164140. register size_t bytes_in_buffer = state->bytes_in_buffer;
  164141. j_decompress_ptr cinfo = state->cinfo;
  164142. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  164143. /* (It is assumed that no request will be for more than that many bits.) */
  164144. /* We fail to do so only if we hit a marker or are forced to suspend. */
  164145. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  164146. while (bits_left < MIN_GET_BITS) {
  164147. register int c;
  164148. /* Attempt to read a byte */
  164149. if (bytes_in_buffer == 0) {
  164150. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  164151. return FALSE;
  164152. next_input_byte = cinfo->src->next_input_byte;
  164153. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  164154. }
  164155. bytes_in_buffer--;
  164156. c = GETJOCTET(*next_input_byte++);
  164157. /* If it's 0xFF, check and discard stuffed zero byte */
  164158. if (c == 0xFF) {
  164159. /* Loop here to discard any padding FF's on terminating marker,
  164160. * so that we can save a valid unread_marker value. NOTE: we will
  164161. * accept multiple FF's followed by a 0 as meaning a single FF data
  164162. * byte. This data pattern is not valid according to the standard.
  164163. */
  164164. do {
  164165. if (bytes_in_buffer == 0) {
  164166. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  164167. return FALSE;
  164168. next_input_byte = cinfo->src->next_input_byte;
  164169. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  164170. }
  164171. bytes_in_buffer--;
  164172. c = GETJOCTET(*next_input_byte++);
  164173. } while (c == 0xFF);
  164174. if (c == 0) {
  164175. /* Found FF/00, which represents an FF data byte */
  164176. c = 0xFF;
  164177. } else {
  164178. /* Oops, it's actually a marker indicating end of compressed data.
  164179. * Save the marker code for later use.
  164180. * Fine point: it might appear that we should save the marker into
  164181. * bitread working state, not straight into permanent state. But
  164182. * once we have hit a marker, we cannot need to suspend within the
  164183. * current MCU, because we will read no more bytes from the data
  164184. * source. So it is OK to update permanent state right away.
  164185. */
  164186. cinfo->unread_marker = c;
  164187. /* See if we need to insert some fake zero bits. */
  164188. goto no_more_bytes;
  164189. }
  164190. }
  164191. /* OK, load c into get_buffer */
  164192. get_buffer = (get_buffer << 8) | c;
  164193. bits_left += 8;
  164194. } /* end while */
  164195. } else {
  164196. no_more_bytes:
  164197. /* We get here if we've read the marker that terminates the compressed
  164198. * data segment. There should be enough bits in the buffer register
  164199. * to satisfy the request; if so, no problem.
  164200. */
  164201. if (nbits > bits_left) {
  164202. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  164203. * the data stream, so that we can produce some kind of image.
  164204. * We use a nonvolatile flag to ensure that only one warning message
  164205. * appears per data segment.
  164206. */
  164207. if (! cinfo->entropy->insufficient_data) {
  164208. WARNMS(cinfo, JWRN_HIT_MARKER);
  164209. cinfo->entropy->insufficient_data = TRUE;
  164210. }
  164211. /* Fill the buffer with zero bits */
  164212. get_buffer <<= MIN_GET_BITS - bits_left;
  164213. bits_left = MIN_GET_BITS;
  164214. }
  164215. }
  164216. /* Unload the local registers */
  164217. state->next_input_byte = next_input_byte;
  164218. state->bytes_in_buffer = bytes_in_buffer;
  164219. state->get_buffer = get_buffer;
  164220. state->bits_left = bits_left;
  164221. return TRUE;
  164222. }
  164223. /*
  164224. * Out-of-line code for Huffman code decoding.
  164225. * See jdhuff.h for info about usage.
  164226. */
  164227. GLOBAL(int)
  164228. jpeg_huff_decode (bitread_working_state * state,
  164229. register bit_buf_type get_buffer, register int bits_left,
  164230. d_derived_tbl * htbl, int min_bits)
  164231. {
  164232. register int l = min_bits;
  164233. register INT32 code;
  164234. /* HUFF_DECODE has determined that the code is at least min_bits */
  164235. /* bits long, so fetch that many bits in one swoop. */
  164236. CHECK_BIT_BUFFER(*state, l, return -1);
  164237. code = GET_BITS(l);
  164238. /* Collect the rest of the Huffman code one bit at a time. */
  164239. /* This is per Figure F.16 in the JPEG spec. */
  164240. while (code > htbl->maxcode[l]) {
  164241. code <<= 1;
  164242. CHECK_BIT_BUFFER(*state, 1, return -1);
  164243. code |= GET_BITS(1);
  164244. l++;
  164245. }
  164246. /* Unload the local registers */
  164247. state->get_buffer = get_buffer;
  164248. state->bits_left = bits_left;
  164249. /* With garbage input we may reach the sentinel value l = 17. */
  164250. if (l > 16) {
  164251. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  164252. return 0; /* fake a zero as the safest result */
  164253. }
  164254. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  164255. }
  164256. /*
  164257. * Check for a restart marker & resynchronize decoder.
  164258. * Returns FALSE if must suspend.
  164259. */
  164260. LOCAL(boolean)
  164261. process_restart (j_decompress_ptr cinfo)
  164262. {
  164263. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  164264. int ci;
  164265. /* Throw away any unused bits remaining in bit buffer; */
  164266. /* include any full bytes in next_marker's count of discarded bytes */
  164267. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  164268. entropy->bitstate.bits_left = 0;
  164269. /* Advance past the RSTn marker */
  164270. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  164271. return FALSE;
  164272. /* Re-initialize DC predictions to 0 */
  164273. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  164274. entropy->saved.last_dc_val[ci] = 0;
  164275. /* Reset restart counter */
  164276. entropy->restarts_to_go = cinfo->restart_interval;
  164277. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  164278. * against a marker. In that case we will end up treating the next data
  164279. * segment as empty, and we can avoid producing bogus output pixels by
  164280. * leaving the flag set.
  164281. */
  164282. if (cinfo->unread_marker == 0)
  164283. entropy->pub.insufficient_data = FALSE;
  164284. return TRUE;
  164285. }
  164286. /*
  164287. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  164288. * The coefficients are reordered from zigzag order into natural array order,
  164289. * but are not dequantized.
  164290. *
  164291. * The i'th block of the MCU is stored into the block pointed to by
  164292. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  164293. * (Wholesale zeroing is usually a little faster than retail...)
  164294. *
  164295. * Returns FALSE if data source requested suspension. In that case no
  164296. * changes have been made to permanent state. (Exception: some output
  164297. * coefficients may already have been assigned. This is harmless for
  164298. * this module, since we'll just re-assign them on the next call.)
  164299. */
  164300. METHODDEF(boolean)
  164301. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  164302. {
  164303. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  164304. int blkn;
  164305. BITREAD_STATE_VARS;
  164306. savable_state2 state;
  164307. /* Process restart marker if needed; may have to suspend */
  164308. if (cinfo->restart_interval) {
  164309. if (entropy->restarts_to_go == 0)
  164310. if (! process_restart(cinfo))
  164311. return FALSE;
  164312. }
  164313. /* If we've run out of data, just leave the MCU set to zeroes.
  164314. * This way, we return uniform gray for the remainder of the segment.
  164315. */
  164316. if (! entropy->pub.insufficient_data) {
  164317. /* Load up working state */
  164318. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  164319. ASSIGN_STATE(state, entropy->saved);
  164320. /* Outer loop handles each block in the MCU */
  164321. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  164322. JBLOCKROW block = MCU_data[blkn];
  164323. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  164324. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  164325. register int s, k, r;
  164326. /* Decode a single block's worth of coefficients */
  164327. /* Section F.2.2.1: decode the DC coefficient difference */
  164328. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  164329. if (s) {
  164330. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  164331. r = GET_BITS(s);
  164332. s = HUFF_EXTEND(r, s);
  164333. }
  164334. if (entropy->dc_needed[blkn]) {
  164335. /* Convert DC difference to actual value, update last_dc_val */
  164336. int ci = cinfo->MCU_membership[blkn];
  164337. s += state.last_dc_val[ci];
  164338. state.last_dc_val[ci] = s;
  164339. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  164340. (*block)[0] = (JCOEF) s;
  164341. }
  164342. if (entropy->ac_needed[blkn]) {
  164343. /* Section F.2.2.2: decode the AC coefficients */
  164344. /* Since zeroes are skipped, output area must be cleared beforehand */
  164345. for (k = 1; k < DCTSIZE2; k++) {
  164346. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  164347. r = s >> 4;
  164348. s &= 15;
  164349. if (s) {
  164350. k += r;
  164351. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  164352. r = GET_BITS(s);
  164353. s = HUFF_EXTEND(r, s);
  164354. /* Output coefficient in natural (dezigzagged) order.
  164355. * Note: the extra entries in jpeg_natural_order[] will save us
  164356. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  164357. */
  164358. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  164359. } else {
  164360. if (r != 15)
  164361. break;
  164362. k += 15;
  164363. }
  164364. }
  164365. } else {
  164366. /* Section F.2.2.2: decode the AC coefficients */
  164367. /* In this path we just discard the values */
  164368. for (k = 1; k < DCTSIZE2; k++) {
  164369. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  164370. r = s >> 4;
  164371. s &= 15;
  164372. if (s) {
  164373. k += r;
  164374. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  164375. DROP_BITS(s);
  164376. } else {
  164377. if (r != 15)
  164378. break;
  164379. k += 15;
  164380. }
  164381. }
  164382. }
  164383. }
  164384. /* Completed MCU, so update state */
  164385. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  164386. ASSIGN_STATE(entropy->saved, state);
  164387. }
  164388. /* Account for restart interval (no-op if not using restarts) */
  164389. entropy->restarts_to_go--;
  164390. return TRUE;
  164391. }
  164392. /*
  164393. * Module initialization routine for Huffman entropy decoding.
  164394. */
  164395. GLOBAL(void)
  164396. jinit_huff_decoder (j_decompress_ptr cinfo)
  164397. {
  164398. huff_entropy_ptr2 entropy;
  164399. int i;
  164400. entropy = (huff_entropy_ptr2)
  164401. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164402. SIZEOF(huff_entropy_decoder2));
  164403. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  164404. entropy->pub.start_pass = start_pass_huff_decoder;
  164405. entropy->pub.decode_mcu = decode_mcu;
  164406. /* Mark tables unallocated */
  164407. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164408. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  164409. }
  164410. }
  164411. /********* End of inlined file: jdhuff.c *********/
  164412. /********* Start of inlined file: jdinput.c *********/
  164413. #define JPEG_INTERNALS
  164414. /* Private state */
  164415. typedef struct {
  164416. struct jpeg_input_controller pub; /* public fields */
  164417. boolean inheaders; /* TRUE until first SOS is reached */
  164418. } my_input_controller;
  164419. typedef my_input_controller * my_inputctl_ptr;
  164420. /* Forward declarations */
  164421. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  164422. /*
  164423. * Routines to calculate various quantities related to the size of the image.
  164424. */
  164425. LOCAL(void)
  164426. initial_setup2 (j_decompress_ptr cinfo)
  164427. /* Called once, when first SOS marker is reached */
  164428. {
  164429. int ci;
  164430. jpeg_component_info *compptr;
  164431. /* Make sure image isn't bigger than I can handle */
  164432. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164433. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164434. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164435. /* For now, precision must match compiled-in value... */
  164436. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164437. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164438. /* Check that number of components won't exceed internal array sizes */
  164439. if (cinfo->num_components > MAX_COMPONENTS)
  164440. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164441. MAX_COMPONENTS);
  164442. /* Compute maximum sampling factors; check factor validity */
  164443. cinfo->max_h_samp_factor = 1;
  164444. cinfo->max_v_samp_factor = 1;
  164445. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164446. ci++, compptr++) {
  164447. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164448. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164449. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164450. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164451. compptr->h_samp_factor);
  164452. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164453. compptr->v_samp_factor);
  164454. }
  164455. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  164456. * In the full decompressor, this will be overridden by jdmaster.c;
  164457. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  164458. */
  164459. cinfo->min_DCT_scaled_size = DCTSIZE;
  164460. /* Compute dimensions of components */
  164461. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164462. ci++, compptr++) {
  164463. compptr->DCT_scaled_size = DCTSIZE;
  164464. /* Size in DCT blocks */
  164465. compptr->width_in_blocks = (JDIMENSION)
  164466. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164467. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164468. compptr->height_in_blocks = (JDIMENSION)
  164469. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164470. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164471. /* downsampled_width and downsampled_height will also be overridden by
  164472. * jdmaster.c if we are doing full decompression. The transcoder library
  164473. * doesn't use these values, but the calling application might.
  164474. */
  164475. /* Size in samples */
  164476. compptr->downsampled_width = (JDIMENSION)
  164477. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164478. (long) cinfo->max_h_samp_factor);
  164479. compptr->downsampled_height = (JDIMENSION)
  164480. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164481. (long) cinfo->max_v_samp_factor);
  164482. /* Mark component needed, until color conversion says otherwise */
  164483. compptr->component_needed = TRUE;
  164484. /* Mark no quantization table yet saved for component */
  164485. compptr->quant_table = NULL;
  164486. }
  164487. /* Compute number of fully interleaved MCU rows. */
  164488. cinfo->total_iMCU_rows = (JDIMENSION)
  164489. jdiv_round_up((long) cinfo->image_height,
  164490. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164491. /* Decide whether file contains multiple scans */
  164492. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  164493. cinfo->inputctl->has_multiple_scans = TRUE;
  164494. else
  164495. cinfo->inputctl->has_multiple_scans = FALSE;
  164496. }
  164497. LOCAL(void)
  164498. per_scan_setup2 (j_decompress_ptr cinfo)
  164499. /* Do computations that are needed before processing a JPEG scan */
  164500. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  164501. {
  164502. int ci, mcublks, tmp;
  164503. jpeg_component_info *compptr;
  164504. if (cinfo->comps_in_scan == 1) {
  164505. /* Noninterleaved (single-component) scan */
  164506. compptr = cinfo->cur_comp_info[0];
  164507. /* Overall image size in MCUs */
  164508. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164509. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164510. /* For noninterleaved scan, always one block per MCU */
  164511. compptr->MCU_width = 1;
  164512. compptr->MCU_height = 1;
  164513. compptr->MCU_blocks = 1;
  164514. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  164515. compptr->last_col_width = 1;
  164516. /* For noninterleaved scans, it is convenient to define last_row_height
  164517. * as the number of block rows present in the last iMCU row.
  164518. */
  164519. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164520. if (tmp == 0) tmp = compptr->v_samp_factor;
  164521. compptr->last_row_height = tmp;
  164522. /* Prepare array describing MCU composition */
  164523. cinfo->blocks_in_MCU = 1;
  164524. cinfo->MCU_membership[0] = 0;
  164525. } else {
  164526. /* Interleaved (multi-component) scan */
  164527. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164528. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164529. MAX_COMPS_IN_SCAN);
  164530. /* Overall image size in MCUs */
  164531. cinfo->MCUs_per_row = (JDIMENSION)
  164532. jdiv_round_up((long) cinfo->image_width,
  164533. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164534. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164535. jdiv_round_up((long) cinfo->image_height,
  164536. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164537. cinfo->blocks_in_MCU = 0;
  164538. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164539. compptr = cinfo->cur_comp_info[ci];
  164540. /* Sampling factors give # of blocks of component in each MCU */
  164541. compptr->MCU_width = compptr->h_samp_factor;
  164542. compptr->MCU_height = compptr->v_samp_factor;
  164543. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164544. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  164545. /* Figure number of non-dummy blocks in last MCU column & row */
  164546. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164547. if (tmp == 0) tmp = compptr->MCU_width;
  164548. compptr->last_col_width = tmp;
  164549. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164550. if (tmp == 0) tmp = compptr->MCU_height;
  164551. compptr->last_row_height = tmp;
  164552. /* Prepare array describing MCU composition */
  164553. mcublks = compptr->MCU_blocks;
  164554. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  164555. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164556. while (mcublks-- > 0) {
  164557. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164558. }
  164559. }
  164560. }
  164561. }
  164562. /*
  164563. * Save away a copy of the Q-table referenced by each component present
  164564. * in the current scan, unless already saved during a prior scan.
  164565. *
  164566. * In a multiple-scan JPEG file, the encoder could assign different components
  164567. * the same Q-table slot number, but change table definitions between scans
  164568. * so that each component uses a different Q-table. (The IJG encoder is not
  164569. * currently capable of doing this, but other encoders might.) Since we want
  164570. * to be able to dequantize all the components at the end of the file, this
  164571. * means that we have to save away the table actually used for each component.
  164572. * We do this by copying the table at the start of the first scan containing
  164573. * the component.
  164574. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  164575. * slot between scans of a component using that slot. If the encoder does so
  164576. * anyway, this decoder will simply use the Q-table values that were current
  164577. * at the start of the first scan for the component.
  164578. *
  164579. * The decompressor output side looks only at the saved quant tables,
  164580. * not at the current Q-table slots.
  164581. */
  164582. LOCAL(void)
  164583. latch_quant_tables (j_decompress_ptr cinfo)
  164584. {
  164585. int ci, qtblno;
  164586. jpeg_component_info *compptr;
  164587. JQUANT_TBL * qtbl;
  164588. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164589. compptr = cinfo->cur_comp_info[ci];
  164590. /* No work if we already saved Q-table for this component */
  164591. if (compptr->quant_table != NULL)
  164592. continue;
  164593. /* Make sure specified quantization table is present */
  164594. qtblno = compptr->quant_tbl_no;
  164595. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  164596. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  164597. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  164598. /* OK, save away the quantization table */
  164599. qtbl = (JQUANT_TBL *)
  164600. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164601. SIZEOF(JQUANT_TBL));
  164602. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  164603. compptr->quant_table = qtbl;
  164604. }
  164605. }
  164606. /*
  164607. * Initialize the input modules to read a scan of compressed data.
  164608. * The first call to this is done by jdmaster.c after initializing
  164609. * the entire decompressor (during jpeg_start_decompress).
  164610. * Subsequent calls come from consume_markers, below.
  164611. */
  164612. METHODDEF(void)
  164613. start_input_pass2 (j_decompress_ptr cinfo)
  164614. {
  164615. per_scan_setup2(cinfo);
  164616. latch_quant_tables(cinfo);
  164617. (*cinfo->entropy->start_pass) (cinfo);
  164618. (*cinfo->coef->start_input_pass) (cinfo);
  164619. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  164620. }
  164621. /*
  164622. * Finish up after inputting a compressed-data scan.
  164623. * This is called by the coefficient controller after it's read all
  164624. * the expected data of the scan.
  164625. */
  164626. METHODDEF(void)
  164627. finish_input_pass (j_decompress_ptr cinfo)
  164628. {
  164629. cinfo->inputctl->consume_input = consume_markers;
  164630. }
  164631. /*
  164632. * Read JPEG markers before, between, or after compressed-data scans.
  164633. * Change state as necessary when a new scan is reached.
  164634. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  164635. *
  164636. * The consume_input method pointer points either here or to the
  164637. * coefficient controller's consume_data routine, depending on whether
  164638. * we are reading a compressed data segment or inter-segment markers.
  164639. */
  164640. METHODDEF(int)
  164641. consume_markers (j_decompress_ptr cinfo)
  164642. {
  164643. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  164644. int val;
  164645. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  164646. return JPEG_REACHED_EOI;
  164647. val = (*cinfo->marker->read_markers) (cinfo);
  164648. switch (val) {
  164649. case JPEG_REACHED_SOS: /* Found SOS */
  164650. if (inputctl->inheaders) { /* 1st SOS */
  164651. initial_setup2(cinfo);
  164652. inputctl->inheaders = FALSE;
  164653. /* Note: start_input_pass must be called by jdmaster.c
  164654. * before any more input can be consumed. jdapimin.c is
  164655. * responsible for enforcing this sequencing.
  164656. */
  164657. } else { /* 2nd or later SOS marker */
  164658. if (! inputctl->pub.has_multiple_scans)
  164659. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  164660. start_input_pass2(cinfo);
  164661. }
  164662. break;
  164663. case JPEG_REACHED_EOI: /* Found EOI */
  164664. inputctl->pub.eoi_reached = TRUE;
  164665. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  164666. if (cinfo->marker->saw_SOF)
  164667. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  164668. } else {
  164669. /* Prevent infinite loop in coef ctlr's decompress_data routine
  164670. * if user set output_scan_number larger than number of scans.
  164671. */
  164672. if (cinfo->output_scan_number > cinfo->input_scan_number)
  164673. cinfo->output_scan_number = cinfo->input_scan_number;
  164674. }
  164675. break;
  164676. case JPEG_SUSPENDED:
  164677. break;
  164678. }
  164679. return val;
  164680. }
  164681. /*
  164682. * Reset state to begin a fresh datastream.
  164683. */
  164684. METHODDEF(void)
  164685. reset_input_controller (j_decompress_ptr cinfo)
  164686. {
  164687. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  164688. inputctl->pub.consume_input = consume_markers;
  164689. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  164690. inputctl->pub.eoi_reached = FALSE;
  164691. inputctl->inheaders = TRUE;
  164692. /* Reset other modules */
  164693. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  164694. (*cinfo->marker->reset_marker_reader) (cinfo);
  164695. /* Reset progression state -- would be cleaner if entropy decoder did this */
  164696. cinfo->coef_bits = NULL;
  164697. }
  164698. /*
  164699. * Initialize the input controller module.
  164700. * This is called only once, when the decompression object is created.
  164701. */
  164702. GLOBAL(void)
  164703. jinit_input_controller (j_decompress_ptr cinfo)
  164704. {
  164705. my_inputctl_ptr inputctl;
  164706. /* Create subobject in permanent pool */
  164707. inputctl = (my_inputctl_ptr)
  164708. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164709. SIZEOF(my_input_controller));
  164710. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  164711. /* Initialize method pointers */
  164712. inputctl->pub.consume_input = consume_markers;
  164713. inputctl->pub.reset_input_controller = reset_input_controller;
  164714. inputctl->pub.start_input_pass = start_input_pass2;
  164715. inputctl->pub.finish_input_pass = finish_input_pass;
  164716. /* Initialize state: can't use reset_input_controller since we don't
  164717. * want to try to reset other modules yet.
  164718. */
  164719. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  164720. inputctl->pub.eoi_reached = FALSE;
  164721. inputctl->inheaders = TRUE;
  164722. }
  164723. /********* End of inlined file: jdinput.c *********/
  164724. /********* Start of inlined file: jdmainct.c *********/
  164725. #define JPEG_INTERNALS
  164726. /*
  164727. * In the current system design, the main buffer need never be a full-image
  164728. * buffer; any full-height buffers will be found inside the coefficient or
  164729. * postprocessing controllers. Nonetheless, the main controller is not
  164730. * trivial. Its responsibility is to provide context rows for upsampling/
  164731. * rescaling, and doing this in an efficient fashion is a bit tricky.
  164732. *
  164733. * Postprocessor input data is counted in "row groups". A row group
  164734. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  164735. * sample rows of each component. (We require DCT_scaled_size values to be
  164736. * chosen such that these numbers are integers. In practice DCT_scaled_size
  164737. * values will likely be powers of two, so we actually have the stronger
  164738. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  164739. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  164740. * row group (times any additional scale factor that the upsampler is
  164741. * applying).
  164742. *
  164743. * The coefficient controller will deliver data to us one iMCU row at a time;
  164744. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  164745. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  164746. * to one row of MCUs when the image is fully interleaved.) Note that the
  164747. * number of sample rows varies across components, but the number of row
  164748. * groups does not. Some garbage sample rows may be included in the last iMCU
  164749. * row at the bottom of the image.
  164750. *
  164751. * Depending on the vertical scaling algorithm used, the upsampler may need
  164752. * access to the sample row(s) above and below its current input row group.
  164753. * The upsampler is required to set need_context_rows TRUE at global selection
  164754. * time if so. When need_context_rows is FALSE, this controller can simply
  164755. * obtain one iMCU row at a time from the coefficient controller and dole it
  164756. * out as row groups to the postprocessor.
  164757. *
  164758. * When need_context_rows is TRUE, this controller guarantees that the buffer
  164759. * passed to postprocessing contains at least one row group's worth of samples
  164760. * above and below the row group(s) being processed. Note that the context
  164761. * rows "above" the first passed row group appear at negative row offsets in
  164762. * the passed buffer. At the top and bottom of the image, the required
  164763. * context rows are manufactured by duplicating the first or last real sample
  164764. * row; this avoids having special cases in the upsampling inner loops.
  164765. *
  164766. * The amount of context is fixed at one row group just because that's a
  164767. * convenient number for this controller to work with. The existing
  164768. * upsamplers really only need one sample row of context. An upsampler
  164769. * supporting arbitrary output rescaling might wish for more than one row
  164770. * group of context when shrinking the image; tough, we don't handle that.
  164771. * (This is justified by the assumption that downsizing will be handled mostly
  164772. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  164773. * the upsample step needn't be much less than one.)
  164774. *
  164775. * To provide the desired context, we have to retain the last two row groups
  164776. * of one iMCU row while reading in the next iMCU row. (The last row group
  164777. * can't be processed until we have another row group for its below-context,
  164778. * and so we have to save the next-to-last group too for its above-context.)
  164779. * We could do this most simply by copying data around in our buffer, but
  164780. * that'd be very slow. We can avoid copying any data by creating a rather
  164781. * strange pointer structure. Here's how it works. We allocate a workspace
  164782. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  164783. * of row groups per iMCU row). We create two sets of redundant pointers to
  164784. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  164785. * pointer lists look like this:
  164786. * M+1 M-1
  164787. * master pointer --> 0 master pointer --> 0
  164788. * 1 1
  164789. * ... ...
  164790. * M-3 M-3
  164791. * M-2 M
  164792. * M-1 M+1
  164793. * M M-2
  164794. * M+1 M-1
  164795. * 0 0
  164796. * We read alternate iMCU rows using each master pointer; thus the last two
  164797. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  164798. * The pointer lists are set up so that the required context rows appear to
  164799. * be adjacent to the proper places when we pass the pointer lists to the
  164800. * upsampler.
  164801. *
  164802. * The above pictures describe the normal state of the pointer lists.
  164803. * At top and bottom of the image, we diddle the pointer lists to duplicate
  164804. * the first or last sample row as necessary (this is cheaper than copying
  164805. * sample rows around).
  164806. *
  164807. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  164808. * situation each iMCU row provides only one row group so the buffering logic
  164809. * must be different (eg, we must read two iMCU rows before we can emit the
  164810. * first row group). For now, we simply do not support providing context
  164811. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  164812. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  164813. * want it quick and dirty, so a context-free upsampler is sufficient.
  164814. */
  164815. /* Private buffer controller object */
  164816. typedef struct {
  164817. struct jpeg_d_main_controller pub; /* public fields */
  164818. /* Pointer to allocated workspace (M or M+2 row groups). */
  164819. JSAMPARRAY buffer[MAX_COMPONENTS];
  164820. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  164821. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  164822. /* Remaining fields are only used in the context case. */
  164823. /* These are the master pointers to the funny-order pointer lists. */
  164824. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  164825. int whichptr; /* indicates which pointer set is now in use */
  164826. int context_state; /* process_data state machine status */
  164827. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  164828. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  164829. } my_main_controller4;
  164830. typedef my_main_controller4 * my_main_ptr4;
  164831. /* context_state values: */
  164832. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  164833. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  164834. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  164835. /* Forward declarations */
  164836. METHODDEF(void) process_data_simple_main2
  164837. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  164838. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  164839. METHODDEF(void) process_data_context_main
  164840. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  164841. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  164842. #ifdef QUANT_2PASS_SUPPORTED
  164843. METHODDEF(void) process_data_crank_post
  164844. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  164845. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  164846. #endif
  164847. LOCAL(void)
  164848. alloc_funny_pointers (j_decompress_ptr cinfo)
  164849. /* Allocate space for the funny pointer lists.
  164850. * This is done only once, not once per pass.
  164851. */
  164852. {
  164853. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164854. int ci, rgroup;
  164855. int M = cinfo->min_DCT_scaled_size;
  164856. jpeg_component_info *compptr;
  164857. JSAMPARRAY xbuf;
  164858. /* Get top-level space for component array pointers.
  164859. * We alloc both arrays with one call to save a few cycles.
  164860. */
  164861. main_->xbuffer[0] = (JSAMPIMAGE)
  164862. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164863. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  164864. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  164865. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164866. ci++, compptr++) {
  164867. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  164868. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  164869. /* Get space for pointer lists --- M+4 row groups in each list.
  164870. * We alloc both pointer lists with one call to save a few cycles.
  164871. */
  164872. xbuf = (JSAMPARRAY)
  164873. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164874. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  164875. xbuf += rgroup; /* want one row group at negative offsets */
  164876. main_->xbuffer[0][ci] = xbuf;
  164877. xbuf += rgroup * (M + 4);
  164878. main_->xbuffer[1][ci] = xbuf;
  164879. }
  164880. }
  164881. LOCAL(void)
  164882. make_funny_pointers (j_decompress_ptr cinfo)
  164883. /* Create the funny pointer lists discussed in the comments above.
  164884. * The actual workspace is already allocated (in main->buffer),
  164885. * and the space for the pointer lists is allocated too.
  164886. * This routine just fills in the curiously ordered lists.
  164887. * This will be repeated at the beginning of each pass.
  164888. */
  164889. {
  164890. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164891. int ci, i, rgroup;
  164892. int M = cinfo->min_DCT_scaled_size;
  164893. jpeg_component_info *compptr;
  164894. JSAMPARRAY buf, xbuf0, xbuf1;
  164895. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164896. ci++, compptr++) {
  164897. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  164898. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  164899. xbuf0 = main_->xbuffer[0][ci];
  164900. xbuf1 = main_->xbuffer[1][ci];
  164901. /* First copy the workspace pointers as-is */
  164902. buf = main_->buffer[ci];
  164903. for (i = 0; i < rgroup * (M + 2); i++) {
  164904. xbuf0[i] = xbuf1[i] = buf[i];
  164905. }
  164906. /* In the second list, put the last four row groups in swapped order */
  164907. for (i = 0; i < rgroup * 2; i++) {
  164908. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  164909. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  164910. }
  164911. /* The wraparound pointers at top and bottom will be filled later
  164912. * (see set_wraparound_pointers, below). Initially we want the "above"
  164913. * pointers to duplicate the first actual data line. This only needs
  164914. * to happen in xbuffer[0].
  164915. */
  164916. for (i = 0; i < rgroup; i++) {
  164917. xbuf0[i - rgroup] = xbuf0[0];
  164918. }
  164919. }
  164920. }
  164921. LOCAL(void)
  164922. set_wraparound_pointers (j_decompress_ptr cinfo)
  164923. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  164924. * This changes the pointer list state from top-of-image to the normal state.
  164925. */
  164926. {
  164927. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164928. int ci, i, rgroup;
  164929. int M = cinfo->min_DCT_scaled_size;
  164930. jpeg_component_info *compptr;
  164931. JSAMPARRAY xbuf0, xbuf1;
  164932. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164933. ci++, compptr++) {
  164934. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  164935. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  164936. xbuf0 = main_->xbuffer[0][ci];
  164937. xbuf1 = main_->xbuffer[1][ci];
  164938. for (i = 0; i < rgroup; i++) {
  164939. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  164940. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  164941. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  164942. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  164943. }
  164944. }
  164945. }
  164946. LOCAL(void)
  164947. set_bottom_pointers (j_decompress_ptr cinfo)
  164948. /* Change the pointer lists to duplicate the last sample row at the bottom
  164949. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  164950. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  164951. */
  164952. {
  164953. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164954. int ci, i, rgroup, iMCUheight, rows_left;
  164955. jpeg_component_info *compptr;
  164956. JSAMPARRAY xbuf;
  164957. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164958. ci++, compptr++) {
  164959. /* Count sample rows in one iMCU row and in one row group */
  164960. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  164961. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  164962. /* Count nondummy sample rows remaining for this component */
  164963. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  164964. if (rows_left == 0) rows_left = iMCUheight;
  164965. /* Count nondummy row groups. Should get same answer for each component,
  164966. * so we need only do it once.
  164967. */
  164968. if (ci == 0) {
  164969. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  164970. }
  164971. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  164972. * last partial rowgroup and ensures at least one full rowgroup of context.
  164973. */
  164974. xbuf = main_->xbuffer[main_->whichptr][ci];
  164975. for (i = 0; i < rgroup * 2; i++) {
  164976. xbuf[rows_left + i] = xbuf[rows_left-1];
  164977. }
  164978. }
  164979. }
  164980. /*
  164981. * Initialize for a processing pass.
  164982. */
  164983. METHODDEF(void)
  164984. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  164985. {
  164986. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164987. switch (pass_mode) {
  164988. case JBUF_PASS_THRU:
  164989. if (cinfo->upsample->need_context_rows) {
  164990. main_->pub.process_data = process_data_context_main;
  164991. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  164992. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  164993. main_->context_state = CTX_PREPARE_FOR_IMCU;
  164994. main_->iMCU_row_ctr = 0;
  164995. } else {
  164996. /* Simple case with no context needed */
  164997. main_->pub.process_data = process_data_simple_main2;
  164998. }
  164999. main_->buffer_full = FALSE; /* Mark buffer empty */
  165000. main_->rowgroup_ctr = 0;
  165001. break;
  165002. #ifdef QUANT_2PASS_SUPPORTED
  165003. case JBUF_CRANK_DEST:
  165004. /* For last pass of 2-pass quantization, just crank the postprocessor */
  165005. main_->pub.process_data = process_data_crank_post;
  165006. break;
  165007. #endif
  165008. default:
  165009. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165010. break;
  165011. }
  165012. }
  165013. /*
  165014. * Process some data.
  165015. * This handles the simple case where no context is required.
  165016. */
  165017. METHODDEF(void)
  165018. process_data_simple_main2 (j_decompress_ptr cinfo,
  165019. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  165020. JDIMENSION out_rows_avail)
  165021. {
  165022. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165023. JDIMENSION rowgroups_avail;
  165024. /* Read input data if we haven't filled the main buffer yet */
  165025. if (! main_->buffer_full) {
  165026. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  165027. return; /* suspension forced, can do nothing more */
  165028. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  165029. }
  165030. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  165031. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  165032. /* Note: at the bottom of the image, we may pass extra garbage row groups
  165033. * to the postprocessor. The postprocessor has to check for bottom
  165034. * of image anyway (at row resolution), so no point in us doing it too.
  165035. */
  165036. /* Feed the postprocessor */
  165037. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  165038. &main_->rowgroup_ctr, rowgroups_avail,
  165039. output_buf, out_row_ctr, out_rows_avail);
  165040. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  165041. if (main_->rowgroup_ctr >= rowgroups_avail) {
  165042. main_->buffer_full = FALSE;
  165043. main_->rowgroup_ctr = 0;
  165044. }
  165045. }
  165046. /*
  165047. * Process some data.
  165048. * This handles the case where context rows must be provided.
  165049. */
  165050. METHODDEF(void)
  165051. process_data_context_main (j_decompress_ptr cinfo,
  165052. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  165053. JDIMENSION out_rows_avail)
  165054. {
  165055. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165056. /* Read input data if we haven't filled the main buffer yet */
  165057. if (! main_->buffer_full) {
  165058. if (! (*cinfo->coef->decompress_data) (cinfo,
  165059. main_->xbuffer[main_->whichptr]))
  165060. return; /* suspension forced, can do nothing more */
  165061. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  165062. main_->iMCU_row_ctr++; /* count rows received */
  165063. }
  165064. /* Postprocessor typically will not swallow all the input data it is handed
  165065. * in one call (due to filling the output buffer first). Must be prepared
  165066. * to exit and restart. This switch lets us keep track of how far we got.
  165067. * Note that each case falls through to the next on successful completion.
  165068. */
  165069. switch (main_->context_state) {
  165070. case CTX_POSTPONED_ROW:
  165071. /* Call postprocessor using previously set pointers for postponed row */
  165072. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  165073. &main_->rowgroup_ctr, main_->rowgroups_avail,
  165074. output_buf, out_row_ctr, out_rows_avail);
  165075. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  165076. return; /* Need to suspend */
  165077. main_->context_state = CTX_PREPARE_FOR_IMCU;
  165078. if (*out_row_ctr >= out_rows_avail)
  165079. return; /* Postprocessor exactly filled output buf */
  165080. /*FALLTHROUGH*/
  165081. case CTX_PREPARE_FOR_IMCU:
  165082. /* Prepare to process first M-1 row groups of this iMCU row */
  165083. main_->rowgroup_ctr = 0;
  165084. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  165085. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  165086. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  165087. */
  165088. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  165089. set_bottom_pointers(cinfo);
  165090. main_->context_state = CTX_PROCESS_IMCU;
  165091. /*FALLTHROUGH*/
  165092. case CTX_PROCESS_IMCU:
  165093. /* Call postprocessor using previously set pointers */
  165094. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  165095. &main_->rowgroup_ctr, main_->rowgroups_avail,
  165096. output_buf, out_row_ctr, out_rows_avail);
  165097. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  165098. return; /* Need to suspend */
  165099. /* After the first iMCU, change wraparound pointers to normal state */
  165100. if (main_->iMCU_row_ctr == 1)
  165101. set_wraparound_pointers(cinfo);
  165102. /* Prepare to load new iMCU row using other xbuffer list */
  165103. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  165104. main_->buffer_full = FALSE;
  165105. /* Still need to process last row group of this iMCU row, */
  165106. /* which is saved at index M+1 of the other xbuffer */
  165107. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  165108. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  165109. main_->context_state = CTX_POSTPONED_ROW;
  165110. }
  165111. }
  165112. /*
  165113. * Process some data.
  165114. * Final pass of two-pass quantization: just call the postprocessor.
  165115. * Source data will be the postprocessor controller's internal buffer.
  165116. */
  165117. #ifdef QUANT_2PASS_SUPPORTED
  165118. METHODDEF(void)
  165119. process_data_crank_post (j_decompress_ptr cinfo,
  165120. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  165121. JDIMENSION out_rows_avail)
  165122. {
  165123. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  165124. (JDIMENSION *) NULL, (JDIMENSION) 0,
  165125. output_buf, out_row_ctr, out_rows_avail);
  165126. }
  165127. #endif /* QUANT_2PASS_SUPPORTED */
  165128. /*
  165129. * Initialize main buffer controller.
  165130. */
  165131. GLOBAL(void)
  165132. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  165133. {
  165134. my_main_ptr4 main_;
  165135. int ci, rgroup, ngroups;
  165136. jpeg_component_info *compptr;
  165137. main_ = (my_main_ptr4)
  165138. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165139. SIZEOF(my_main_controller4));
  165140. cinfo->main = (struct jpeg_d_main_controller *) main_;
  165141. main_->pub.start_pass = start_pass_main2;
  165142. if (need_full_buffer) /* shouldn't happen */
  165143. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165144. /* Allocate the workspace.
  165145. * ngroups is the number of row groups we need.
  165146. */
  165147. if (cinfo->upsample->need_context_rows) {
  165148. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  165149. ERREXIT(cinfo, JERR_NOTIMPL);
  165150. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  165151. ngroups = cinfo->min_DCT_scaled_size + 2;
  165152. } else {
  165153. ngroups = cinfo->min_DCT_scaled_size;
  165154. }
  165155. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165156. ci++, compptr++) {
  165157. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  165158. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  165159. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  165160. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165161. compptr->width_in_blocks * compptr->DCT_scaled_size,
  165162. (JDIMENSION) (rgroup * ngroups));
  165163. }
  165164. }
  165165. /********* End of inlined file: jdmainct.c *********/
  165166. /********* Start of inlined file: jdmarker.c *********/
  165167. #define JPEG_INTERNALS
  165168. /* Private state */
  165169. typedef struct {
  165170. struct jpeg_marker_reader pub; /* public fields */
  165171. /* Application-overridable marker processing methods */
  165172. jpeg_marker_parser_method process_COM;
  165173. jpeg_marker_parser_method process_APPn[16];
  165174. /* Limit on marker data length to save for each marker type */
  165175. unsigned int length_limit_COM;
  165176. unsigned int length_limit_APPn[16];
  165177. /* Status of COM/APPn marker saving */
  165178. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  165179. unsigned int bytes_read; /* data bytes read so far in marker */
  165180. /* Note: cur_marker is not linked into marker_list until it's all read. */
  165181. } my_marker_reader;
  165182. typedef my_marker_reader * my_marker_ptr2;
  165183. /*
  165184. * Macros for fetching data from the data source module.
  165185. *
  165186. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  165187. * the current restart point; we update them only when we have reached a
  165188. * suitable place to restart if a suspension occurs.
  165189. */
  165190. /* Declare and initialize local copies of input pointer/count */
  165191. #define INPUT_VARS(cinfo) \
  165192. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  165193. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  165194. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  165195. /* Unload the local copies --- do this only at a restart boundary */
  165196. #define INPUT_SYNC(cinfo) \
  165197. ( datasrc->next_input_byte = next_input_byte, \
  165198. datasrc->bytes_in_buffer = bytes_in_buffer )
  165199. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  165200. #define INPUT_RELOAD(cinfo) \
  165201. ( next_input_byte = datasrc->next_input_byte, \
  165202. bytes_in_buffer = datasrc->bytes_in_buffer )
  165203. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  165204. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  165205. * but we must reload the local copies after a successful fill.
  165206. */
  165207. #define MAKE_BYTE_AVAIL(cinfo,action) \
  165208. if (bytes_in_buffer == 0) { \
  165209. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  165210. { action; } \
  165211. INPUT_RELOAD(cinfo); \
  165212. }
  165213. /* Read a byte into variable V.
  165214. * If must suspend, take the specified action (typically "return FALSE").
  165215. */
  165216. #define INPUT_BYTE(cinfo,V,action) \
  165217. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  165218. bytes_in_buffer--; \
  165219. V = GETJOCTET(*next_input_byte++); )
  165220. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  165221. * V should be declared unsigned int or perhaps INT32.
  165222. */
  165223. #define INPUT_2BYTES(cinfo,V,action) \
  165224. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  165225. bytes_in_buffer--; \
  165226. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  165227. MAKE_BYTE_AVAIL(cinfo,action); \
  165228. bytes_in_buffer--; \
  165229. V += GETJOCTET(*next_input_byte++); )
  165230. /*
  165231. * Routines to process JPEG markers.
  165232. *
  165233. * Entry condition: JPEG marker itself has been read and its code saved
  165234. * in cinfo->unread_marker; input restart point is just after the marker.
  165235. *
  165236. * Exit: if return TRUE, have read and processed any parameters, and have
  165237. * updated the restart point to point after the parameters.
  165238. * If return FALSE, was forced to suspend before reaching end of
  165239. * marker parameters; restart point has not been moved. Same routine
  165240. * will be called again after application supplies more input data.
  165241. *
  165242. * This approach to suspension assumes that all of a marker's parameters
  165243. * can fit into a single input bufferload. This should hold for "normal"
  165244. * markers. Some COM/APPn markers might have large parameter segments
  165245. * that might not fit. If we are simply dropping such a marker, we use
  165246. * skip_input_data to get past it, and thereby put the problem on the
  165247. * source manager's shoulders. If we are saving the marker's contents
  165248. * into memory, we use a slightly different convention: when forced to
  165249. * suspend, the marker processor updates the restart point to the end of
  165250. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  165251. * On resumption, cinfo->unread_marker still contains the marker code,
  165252. * but the data source will point to the next chunk of marker data.
  165253. * The marker processor must retain internal state to deal with this.
  165254. *
  165255. * Note that we don't bother to avoid duplicate trace messages if a
  165256. * suspension occurs within marker parameters. Other side effects
  165257. * require more care.
  165258. */
  165259. LOCAL(boolean)
  165260. get_soi (j_decompress_ptr cinfo)
  165261. /* Process an SOI marker */
  165262. {
  165263. int i;
  165264. TRACEMS(cinfo, 1, JTRC_SOI);
  165265. if (cinfo->marker->saw_SOI)
  165266. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  165267. /* Reset all parameters that are defined to be reset by SOI */
  165268. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165269. cinfo->arith_dc_L[i] = 0;
  165270. cinfo->arith_dc_U[i] = 1;
  165271. cinfo->arith_ac_K[i] = 5;
  165272. }
  165273. cinfo->restart_interval = 0;
  165274. /* Set initial assumptions for colorspace etc */
  165275. cinfo->jpeg_color_space = JCS_UNKNOWN;
  165276. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  165277. cinfo->saw_JFIF_marker = FALSE;
  165278. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  165279. cinfo->JFIF_minor_version = 1;
  165280. cinfo->density_unit = 0;
  165281. cinfo->X_density = 1;
  165282. cinfo->Y_density = 1;
  165283. cinfo->saw_Adobe_marker = FALSE;
  165284. cinfo->Adobe_transform = 0;
  165285. cinfo->marker->saw_SOI = TRUE;
  165286. return TRUE;
  165287. }
  165288. LOCAL(boolean)
  165289. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  165290. /* Process a SOFn marker */
  165291. {
  165292. INT32 length;
  165293. int c, ci;
  165294. jpeg_component_info * compptr;
  165295. INPUT_VARS(cinfo);
  165296. cinfo->progressive_mode = is_prog;
  165297. cinfo->arith_code = is_arith;
  165298. INPUT_2BYTES(cinfo, length, return FALSE);
  165299. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  165300. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  165301. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  165302. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  165303. length -= 8;
  165304. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  165305. (int) cinfo->image_width, (int) cinfo->image_height,
  165306. cinfo->num_components);
  165307. if (cinfo->marker->saw_SOF)
  165308. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  165309. /* We don't support files in which the image height is initially specified */
  165310. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  165311. /* might as well have a general sanity check. */
  165312. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  165313. || cinfo->num_components <= 0)
  165314. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  165315. if (length != (cinfo->num_components * 3))
  165316. ERREXIT(cinfo, JERR_BAD_LENGTH);
  165317. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  165318. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  165319. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165320. cinfo->num_components * SIZEOF(jpeg_component_info));
  165321. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165322. ci++, compptr++) {
  165323. compptr->component_index = ci;
  165324. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  165325. INPUT_BYTE(cinfo, c, return FALSE);
  165326. compptr->h_samp_factor = (c >> 4) & 15;
  165327. compptr->v_samp_factor = (c ) & 15;
  165328. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  165329. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  165330. compptr->component_id, compptr->h_samp_factor,
  165331. compptr->v_samp_factor, compptr->quant_tbl_no);
  165332. }
  165333. cinfo->marker->saw_SOF = TRUE;
  165334. INPUT_SYNC(cinfo);
  165335. return TRUE;
  165336. }
  165337. LOCAL(boolean)
  165338. get_sos (j_decompress_ptr cinfo)
  165339. /* Process a SOS marker */
  165340. {
  165341. INT32 length;
  165342. int i, ci, n, c, cc;
  165343. jpeg_component_info * compptr;
  165344. INPUT_VARS(cinfo);
  165345. if (! cinfo->marker->saw_SOF)
  165346. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  165347. INPUT_2BYTES(cinfo, length, return FALSE);
  165348. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  165349. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  165350. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  165351. ERREXIT(cinfo, JERR_BAD_LENGTH);
  165352. cinfo->comps_in_scan = n;
  165353. /* Collect the component-spec parameters */
  165354. for (i = 0; i < n; i++) {
  165355. INPUT_BYTE(cinfo, cc, return FALSE);
  165356. INPUT_BYTE(cinfo, c, return FALSE);
  165357. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165358. ci++, compptr++) {
  165359. if (cc == compptr->component_id)
  165360. goto id_found;
  165361. }
  165362. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  165363. id_found:
  165364. cinfo->cur_comp_info[i] = compptr;
  165365. compptr->dc_tbl_no = (c >> 4) & 15;
  165366. compptr->ac_tbl_no = (c ) & 15;
  165367. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  165368. compptr->dc_tbl_no, compptr->ac_tbl_no);
  165369. }
  165370. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  165371. INPUT_BYTE(cinfo, c, return FALSE);
  165372. cinfo->Ss = c;
  165373. INPUT_BYTE(cinfo, c, return FALSE);
  165374. cinfo->Se = c;
  165375. INPUT_BYTE(cinfo, c, return FALSE);
  165376. cinfo->Ah = (c >> 4) & 15;
  165377. cinfo->Al = (c ) & 15;
  165378. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  165379. cinfo->Ah, cinfo->Al);
  165380. /* Prepare to scan data & restart markers */
  165381. cinfo->marker->next_restart_num = 0;
  165382. /* Count another SOS marker */
  165383. cinfo->input_scan_number++;
  165384. INPUT_SYNC(cinfo);
  165385. return TRUE;
  165386. }
  165387. #ifdef D_ARITH_CODING_SUPPORTED
  165388. LOCAL(boolean)
  165389. get_dac (j_decompress_ptr cinfo)
  165390. /* Process a DAC marker */
  165391. {
  165392. INT32 length;
  165393. int index, val;
  165394. INPUT_VARS(cinfo);
  165395. INPUT_2BYTES(cinfo, length, return FALSE);
  165396. length -= 2;
  165397. while (length > 0) {
  165398. INPUT_BYTE(cinfo, index, return FALSE);
  165399. INPUT_BYTE(cinfo, val, return FALSE);
  165400. length -= 2;
  165401. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  165402. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  165403. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  165404. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  165405. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  165406. } else { /* define DC table */
  165407. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  165408. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  165409. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  165410. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  165411. }
  165412. }
  165413. if (length != 0)
  165414. ERREXIT(cinfo, JERR_BAD_LENGTH);
  165415. INPUT_SYNC(cinfo);
  165416. return TRUE;
  165417. }
  165418. #else /* ! D_ARITH_CODING_SUPPORTED */
  165419. #define get_dac(cinfo) skip_variable(cinfo)
  165420. #endif /* D_ARITH_CODING_SUPPORTED */
  165421. LOCAL(boolean)
  165422. get_dht (j_decompress_ptr cinfo)
  165423. /* Process a DHT marker */
  165424. {
  165425. INT32 length;
  165426. UINT8 bits[17];
  165427. UINT8 huffval[256];
  165428. int i, index, count;
  165429. JHUFF_TBL **htblptr;
  165430. INPUT_VARS(cinfo);
  165431. INPUT_2BYTES(cinfo, length, return FALSE);
  165432. length -= 2;
  165433. while (length > 16) {
  165434. INPUT_BYTE(cinfo, index, return FALSE);
  165435. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  165436. bits[0] = 0;
  165437. count = 0;
  165438. for (i = 1; i <= 16; i++) {
  165439. INPUT_BYTE(cinfo, bits[i], return FALSE);
  165440. count += bits[i];
  165441. }
  165442. length -= 1 + 16;
  165443. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  165444. bits[1], bits[2], bits[3], bits[4],
  165445. bits[5], bits[6], bits[7], bits[8]);
  165446. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  165447. bits[9], bits[10], bits[11], bits[12],
  165448. bits[13], bits[14], bits[15], bits[16]);
  165449. /* Here we just do minimal validation of the counts to avoid walking
  165450. * off the end of our table space. jdhuff.c will check more carefully.
  165451. */
  165452. if (count > 256 || ((INT32) count) > length)
  165453. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165454. for (i = 0; i < count; i++)
  165455. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  165456. length -= count;
  165457. if (index & 0x10) { /* AC table definition */
  165458. index -= 0x10;
  165459. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  165460. } else { /* DC table definition */
  165461. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  165462. }
  165463. if (index < 0 || index >= NUM_HUFF_TBLS)
  165464. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  165465. if (*htblptr == NULL)
  165466. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165467. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165468. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  165469. }
  165470. if (length != 0)
  165471. ERREXIT(cinfo, JERR_BAD_LENGTH);
  165472. INPUT_SYNC(cinfo);
  165473. return TRUE;
  165474. }
  165475. LOCAL(boolean)
  165476. get_dqt (j_decompress_ptr cinfo)
  165477. /* Process a DQT marker */
  165478. {
  165479. INT32 length;
  165480. int n, i, prec;
  165481. unsigned int tmp;
  165482. JQUANT_TBL *quant_ptr;
  165483. INPUT_VARS(cinfo);
  165484. INPUT_2BYTES(cinfo, length, return FALSE);
  165485. length -= 2;
  165486. while (length > 0) {
  165487. INPUT_BYTE(cinfo, n, return FALSE);
  165488. prec = n >> 4;
  165489. n &= 0x0F;
  165490. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  165491. if (n >= NUM_QUANT_TBLS)
  165492. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  165493. if (cinfo->quant_tbl_ptrs[n] == NULL)
  165494. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165495. quant_ptr = cinfo->quant_tbl_ptrs[n];
  165496. for (i = 0; i < DCTSIZE2; i++) {
  165497. if (prec)
  165498. INPUT_2BYTES(cinfo, tmp, return FALSE);
  165499. else
  165500. INPUT_BYTE(cinfo, tmp, return FALSE);
  165501. /* We convert the zigzag-order table to natural array order. */
  165502. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  165503. }
  165504. if (cinfo->err->trace_level >= 2) {
  165505. for (i = 0; i < DCTSIZE2; i += 8) {
  165506. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  165507. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  165508. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  165509. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  165510. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  165511. }
  165512. }
  165513. length -= DCTSIZE2+1;
  165514. if (prec) length -= DCTSIZE2;
  165515. }
  165516. if (length != 0)
  165517. ERREXIT(cinfo, JERR_BAD_LENGTH);
  165518. INPUT_SYNC(cinfo);
  165519. return TRUE;
  165520. }
  165521. LOCAL(boolean)
  165522. get_dri (j_decompress_ptr cinfo)
  165523. /* Process a DRI marker */
  165524. {
  165525. INT32 length;
  165526. unsigned int tmp;
  165527. INPUT_VARS(cinfo);
  165528. INPUT_2BYTES(cinfo, length, return FALSE);
  165529. if (length != 4)
  165530. ERREXIT(cinfo, JERR_BAD_LENGTH);
  165531. INPUT_2BYTES(cinfo, tmp, return FALSE);
  165532. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  165533. cinfo->restart_interval = tmp;
  165534. INPUT_SYNC(cinfo);
  165535. return TRUE;
  165536. }
  165537. /*
  165538. * Routines for processing APPn and COM markers.
  165539. * These are either saved in memory or discarded, per application request.
  165540. * APP0 and APP14 are specially checked to see if they are
  165541. * JFIF and Adobe markers, respectively.
  165542. */
  165543. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  165544. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  165545. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  165546. LOCAL(void)
  165547. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  165548. unsigned int datalen, INT32 remaining)
  165549. /* Examine first few bytes from an APP0.
  165550. * Take appropriate action if it is a JFIF marker.
  165551. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  165552. */
  165553. {
  165554. INT32 totallen = (INT32) datalen + remaining;
  165555. if (datalen >= APP0_DATA_LEN &&
  165556. GETJOCTET(data[0]) == 0x4A &&
  165557. GETJOCTET(data[1]) == 0x46 &&
  165558. GETJOCTET(data[2]) == 0x49 &&
  165559. GETJOCTET(data[3]) == 0x46 &&
  165560. GETJOCTET(data[4]) == 0) {
  165561. /* Found JFIF APP0 marker: save info */
  165562. cinfo->saw_JFIF_marker = TRUE;
  165563. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  165564. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  165565. cinfo->density_unit = GETJOCTET(data[7]);
  165566. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  165567. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  165568. /* Check version.
  165569. * Major version must be 1, anything else signals an incompatible change.
  165570. * (We used to treat this as an error, but now it's a nonfatal warning,
  165571. * because some bozo at Hijaak couldn't read the spec.)
  165572. * Minor version should be 0..2, but process anyway if newer.
  165573. */
  165574. if (cinfo->JFIF_major_version != 1)
  165575. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  165576. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  165577. /* Generate trace messages */
  165578. TRACEMS5(cinfo, 1, JTRC_JFIF,
  165579. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  165580. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  165581. /* Validate thumbnail dimensions and issue appropriate messages */
  165582. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  165583. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  165584. GETJOCTET(data[12]), GETJOCTET(data[13]));
  165585. totallen -= APP0_DATA_LEN;
  165586. if (totallen !=
  165587. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  165588. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  165589. } else if (datalen >= 6 &&
  165590. GETJOCTET(data[0]) == 0x4A &&
  165591. GETJOCTET(data[1]) == 0x46 &&
  165592. GETJOCTET(data[2]) == 0x58 &&
  165593. GETJOCTET(data[3]) == 0x58 &&
  165594. GETJOCTET(data[4]) == 0) {
  165595. /* Found JFIF "JFXX" extension APP0 marker */
  165596. /* The library doesn't actually do anything with these,
  165597. * but we try to produce a helpful trace message.
  165598. */
  165599. switch (GETJOCTET(data[5])) {
  165600. case 0x10:
  165601. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  165602. break;
  165603. case 0x11:
  165604. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  165605. break;
  165606. case 0x13:
  165607. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  165608. break;
  165609. default:
  165610. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  165611. GETJOCTET(data[5]), (int) totallen);
  165612. break;
  165613. }
  165614. } else {
  165615. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  165616. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  165617. }
  165618. }
  165619. LOCAL(void)
  165620. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  165621. unsigned int datalen, INT32 remaining)
  165622. /* Examine first few bytes from an APP14.
  165623. * Take appropriate action if it is an Adobe marker.
  165624. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  165625. */
  165626. {
  165627. unsigned int version, flags0, flags1, transform;
  165628. if (datalen >= APP14_DATA_LEN &&
  165629. GETJOCTET(data[0]) == 0x41 &&
  165630. GETJOCTET(data[1]) == 0x64 &&
  165631. GETJOCTET(data[2]) == 0x6F &&
  165632. GETJOCTET(data[3]) == 0x62 &&
  165633. GETJOCTET(data[4]) == 0x65) {
  165634. /* Found Adobe APP14 marker */
  165635. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  165636. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  165637. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  165638. transform = GETJOCTET(data[11]);
  165639. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  165640. cinfo->saw_Adobe_marker = TRUE;
  165641. cinfo->Adobe_transform = (UINT8) transform;
  165642. } else {
  165643. /* Start of APP14 does not match "Adobe", or too short */
  165644. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  165645. }
  165646. }
  165647. METHODDEF(boolean)
  165648. get_interesting_appn (j_decompress_ptr cinfo)
  165649. /* Process an APP0 or APP14 marker without saving it */
  165650. {
  165651. INT32 length;
  165652. JOCTET b[APPN_DATA_LEN];
  165653. unsigned int i, numtoread;
  165654. INPUT_VARS(cinfo);
  165655. INPUT_2BYTES(cinfo, length, return FALSE);
  165656. length -= 2;
  165657. /* get the interesting part of the marker data */
  165658. if (length >= APPN_DATA_LEN)
  165659. numtoread = APPN_DATA_LEN;
  165660. else if (length > 0)
  165661. numtoread = (unsigned int) length;
  165662. else
  165663. numtoread = 0;
  165664. for (i = 0; i < numtoread; i++)
  165665. INPUT_BYTE(cinfo, b[i], return FALSE);
  165666. length -= numtoread;
  165667. /* process it */
  165668. switch (cinfo->unread_marker) {
  165669. case M_APP0:
  165670. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  165671. break;
  165672. case M_APP14:
  165673. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  165674. break;
  165675. default:
  165676. /* can't get here unless jpeg_save_markers chooses wrong processor */
  165677. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  165678. break;
  165679. }
  165680. /* skip any remaining data -- could be lots */
  165681. INPUT_SYNC(cinfo);
  165682. if (length > 0)
  165683. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  165684. return TRUE;
  165685. }
  165686. #ifdef SAVE_MARKERS_SUPPORTED
  165687. METHODDEF(boolean)
  165688. save_marker (j_decompress_ptr cinfo)
  165689. /* Save an APPn or COM marker into the marker list */
  165690. {
  165691. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  165692. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  165693. unsigned int bytes_read, data_length;
  165694. JOCTET FAR * data;
  165695. INT32 length = 0;
  165696. INPUT_VARS(cinfo);
  165697. if (cur_marker == NULL) {
  165698. /* begin reading a marker */
  165699. INPUT_2BYTES(cinfo, length, return FALSE);
  165700. length -= 2;
  165701. if (length >= 0) { /* watch out for bogus length word */
  165702. /* figure out how much we want to save */
  165703. unsigned int limit;
  165704. if (cinfo->unread_marker == (int) M_COM)
  165705. limit = marker->length_limit_COM;
  165706. else
  165707. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  165708. if ((unsigned int) length < limit)
  165709. limit = (unsigned int) length;
  165710. /* allocate and initialize the marker item */
  165711. cur_marker = (jpeg_saved_marker_ptr)
  165712. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165713. SIZEOF(struct jpeg_marker_struct) + limit);
  165714. cur_marker->next = NULL;
  165715. cur_marker->marker = (UINT8) cinfo->unread_marker;
  165716. cur_marker->original_length = (unsigned int) length;
  165717. cur_marker->data_length = limit;
  165718. /* data area is just beyond the jpeg_marker_struct */
  165719. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  165720. marker->cur_marker = cur_marker;
  165721. marker->bytes_read = 0;
  165722. bytes_read = 0;
  165723. data_length = limit;
  165724. } else {
  165725. /* deal with bogus length word */
  165726. bytes_read = data_length = 0;
  165727. data = NULL;
  165728. }
  165729. } else {
  165730. /* resume reading a marker */
  165731. bytes_read = marker->bytes_read;
  165732. data_length = cur_marker->data_length;
  165733. data = cur_marker->data + bytes_read;
  165734. }
  165735. while (bytes_read < data_length) {
  165736. INPUT_SYNC(cinfo); /* move the restart point to here */
  165737. marker->bytes_read = bytes_read;
  165738. /* If there's not at least one byte in buffer, suspend */
  165739. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  165740. /* Copy bytes with reasonable rapidity */
  165741. while (bytes_read < data_length && bytes_in_buffer > 0) {
  165742. *data++ = *next_input_byte++;
  165743. bytes_in_buffer--;
  165744. bytes_read++;
  165745. }
  165746. }
  165747. /* Done reading what we want to read */
  165748. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  165749. /* Add new marker to end of list */
  165750. if (cinfo->marker_list == NULL) {
  165751. cinfo->marker_list = cur_marker;
  165752. } else {
  165753. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  165754. while (prev->next != NULL)
  165755. prev = prev->next;
  165756. prev->next = cur_marker;
  165757. }
  165758. /* Reset pointer & calc remaining data length */
  165759. data = cur_marker->data;
  165760. length = cur_marker->original_length - data_length;
  165761. }
  165762. /* Reset to initial state for next marker */
  165763. marker->cur_marker = NULL;
  165764. /* Process the marker if interesting; else just make a generic trace msg */
  165765. switch (cinfo->unread_marker) {
  165766. case M_APP0:
  165767. examine_app0(cinfo, data, data_length, length);
  165768. break;
  165769. case M_APP14:
  165770. examine_app14(cinfo, data, data_length, length);
  165771. break;
  165772. default:
  165773. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  165774. (int) (data_length + length));
  165775. break;
  165776. }
  165777. /* skip any remaining data -- could be lots */
  165778. INPUT_SYNC(cinfo); /* do before skip_input_data */
  165779. if (length > 0)
  165780. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  165781. return TRUE;
  165782. }
  165783. #endif /* SAVE_MARKERS_SUPPORTED */
  165784. METHODDEF(boolean)
  165785. skip_variable (j_decompress_ptr cinfo)
  165786. /* Skip over an unknown or uninteresting variable-length marker */
  165787. {
  165788. INT32 length;
  165789. INPUT_VARS(cinfo);
  165790. INPUT_2BYTES(cinfo, length, return FALSE);
  165791. length -= 2;
  165792. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  165793. INPUT_SYNC(cinfo); /* do before skip_input_data */
  165794. if (length > 0)
  165795. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  165796. return TRUE;
  165797. }
  165798. /*
  165799. * Find the next JPEG marker, save it in cinfo->unread_marker.
  165800. * Returns FALSE if had to suspend before reaching a marker;
  165801. * in that case cinfo->unread_marker is unchanged.
  165802. *
  165803. * Note that the result might not be a valid marker code,
  165804. * but it will never be 0 or FF.
  165805. */
  165806. LOCAL(boolean)
  165807. next_marker (j_decompress_ptr cinfo)
  165808. {
  165809. int c;
  165810. INPUT_VARS(cinfo);
  165811. for (;;) {
  165812. INPUT_BYTE(cinfo, c, return FALSE);
  165813. /* Skip any non-FF bytes.
  165814. * This may look a bit inefficient, but it will not occur in a valid file.
  165815. * We sync after each discarded byte so that a suspending data source
  165816. * can discard the byte from its buffer.
  165817. */
  165818. while (c != 0xFF) {
  165819. cinfo->marker->discarded_bytes++;
  165820. INPUT_SYNC(cinfo);
  165821. INPUT_BYTE(cinfo, c, return FALSE);
  165822. }
  165823. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  165824. * pad bytes, so don't count them in discarded_bytes. We assume there
  165825. * will not be so many consecutive FF bytes as to overflow a suspending
  165826. * data source's input buffer.
  165827. */
  165828. do {
  165829. INPUT_BYTE(cinfo, c, return FALSE);
  165830. } while (c == 0xFF);
  165831. if (c != 0)
  165832. break; /* found a valid marker, exit loop */
  165833. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  165834. * Discard it and loop back to try again.
  165835. */
  165836. cinfo->marker->discarded_bytes += 2;
  165837. INPUT_SYNC(cinfo);
  165838. }
  165839. if (cinfo->marker->discarded_bytes != 0) {
  165840. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  165841. cinfo->marker->discarded_bytes = 0;
  165842. }
  165843. cinfo->unread_marker = c;
  165844. INPUT_SYNC(cinfo);
  165845. return TRUE;
  165846. }
  165847. LOCAL(boolean)
  165848. first_marker (j_decompress_ptr cinfo)
  165849. /* Like next_marker, but used to obtain the initial SOI marker. */
  165850. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  165851. * we might well scan an entire input file before realizing it ain't JPEG.
  165852. * If an application wants to process non-JFIF files, it must seek to the
  165853. * SOI before calling the JPEG library.
  165854. */
  165855. {
  165856. int c, c2;
  165857. INPUT_VARS(cinfo);
  165858. INPUT_BYTE(cinfo, c, return FALSE);
  165859. INPUT_BYTE(cinfo, c2, return FALSE);
  165860. if (c != 0xFF || c2 != (int) M_SOI)
  165861. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  165862. cinfo->unread_marker = c2;
  165863. INPUT_SYNC(cinfo);
  165864. return TRUE;
  165865. }
  165866. /*
  165867. * Read markers until SOS or EOI.
  165868. *
  165869. * Returns same codes as are defined for jpeg_consume_input:
  165870. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  165871. */
  165872. METHODDEF(int)
  165873. read_markers (j_decompress_ptr cinfo)
  165874. {
  165875. /* Outer loop repeats once for each marker. */
  165876. for (;;) {
  165877. /* Collect the marker proper, unless we already did. */
  165878. /* NB: first_marker() enforces the requirement that SOI appear first. */
  165879. if (cinfo->unread_marker == 0) {
  165880. if (! cinfo->marker->saw_SOI) {
  165881. if (! first_marker(cinfo))
  165882. return JPEG_SUSPENDED;
  165883. } else {
  165884. if (! next_marker(cinfo))
  165885. return JPEG_SUSPENDED;
  165886. }
  165887. }
  165888. /* At this point cinfo->unread_marker contains the marker code and the
  165889. * input point is just past the marker proper, but before any parameters.
  165890. * A suspension will cause us to return with this state still true.
  165891. */
  165892. switch (cinfo->unread_marker) {
  165893. case M_SOI:
  165894. if (! get_soi(cinfo))
  165895. return JPEG_SUSPENDED;
  165896. break;
  165897. case M_SOF0: /* Baseline */
  165898. case M_SOF1: /* Extended sequential, Huffman */
  165899. if (! get_sof(cinfo, FALSE, FALSE))
  165900. return JPEG_SUSPENDED;
  165901. break;
  165902. case M_SOF2: /* Progressive, Huffman */
  165903. if (! get_sof(cinfo, TRUE, FALSE))
  165904. return JPEG_SUSPENDED;
  165905. break;
  165906. case M_SOF9: /* Extended sequential, arithmetic */
  165907. if (! get_sof(cinfo, FALSE, TRUE))
  165908. return JPEG_SUSPENDED;
  165909. break;
  165910. case M_SOF10: /* Progressive, arithmetic */
  165911. if (! get_sof(cinfo, TRUE, TRUE))
  165912. return JPEG_SUSPENDED;
  165913. break;
  165914. /* Currently unsupported SOFn types */
  165915. case M_SOF3: /* Lossless, Huffman */
  165916. case M_SOF5: /* Differential sequential, Huffman */
  165917. case M_SOF6: /* Differential progressive, Huffman */
  165918. case M_SOF7: /* Differential lossless, Huffman */
  165919. case M_JPG: /* Reserved for JPEG extensions */
  165920. case M_SOF11: /* Lossless, arithmetic */
  165921. case M_SOF13: /* Differential sequential, arithmetic */
  165922. case M_SOF14: /* Differential progressive, arithmetic */
  165923. case M_SOF15: /* Differential lossless, arithmetic */
  165924. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  165925. break;
  165926. case M_SOS:
  165927. if (! get_sos(cinfo))
  165928. return JPEG_SUSPENDED;
  165929. cinfo->unread_marker = 0; /* processed the marker */
  165930. return JPEG_REACHED_SOS;
  165931. case M_EOI:
  165932. TRACEMS(cinfo, 1, JTRC_EOI);
  165933. cinfo->unread_marker = 0; /* processed the marker */
  165934. return JPEG_REACHED_EOI;
  165935. case M_DAC:
  165936. if (! get_dac(cinfo))
  165937. return JPEG_SUSPENDED;
  165938. break;
  165939. case M_DHT:
  165940. if (! get_dht(cinfo))
  165941. return JPEG_SUSPENDED;
  165942. break;
  165943. case M_DQT:
  165944. if (! get_dqt(cinfo))
  165945. return JPEG_SUSPENDED;
  165946. break;
  165947. case M_DRI:
  165948. if (! get_dri(cinfo))
  165949. return JPEG_SUSPENDED;
  165950. break;
  165951. case M_APP0:
  165952. case M_APP1:
  165953. case M_APP2:
  165954. case M_APP3:
  165955. case M_APP4:
  165956. case M_APP5:
  165957. case M_APP6:
  165958. case M_APP7:
  165959. case M_APP8:
  165960. case M_APP9:
  165961. case M_APP10:
  165962. case M_APP11:
  165963. case M_APP12:
  165964. case M_APP13:
  165965. case M_APP14:
  165966. case M_APP15:
  165967. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  165968. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  165969. return JPEG_SUSPENDED;
  165970. break;
  165971. case M_COM:
  165972. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  165973. return JPEG_SUSPENDED;
  165974. break;
  165975. case M_RST0: /* these are all parameterless */
  165976. case M_RST1:
  165977. case M_RST2:
  165978. case M_RST3:
  165979. case M_RST4:
  165980. case M_RST5:
  165981. case M_RST6:
  165982. case M_RST7:
  165983. case M_TEM:
  165984. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  165985. break;
  165986. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  165987. if (! skip_variable(cinfo))
  165988. return JPEG_SUSPENDED;
  165989. break;
  165990. default: /* must be DHP, EXP, JPGn, or RESn */
  165991. /* For now, we treat the reserved markers as fatal errors since they are
  165992. * likely to be used to signal incompatible JPEG Part 3 extensions.
  165993. * Once the JPEG 3 version-number marker is well defined, this code
  165994. * ought to change!
  165995. */
  165996. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  165997. break;
  165998. }
  165999. /* Successfully processed marker, so reset state variable */
  166000. cinfo->unread_marker = 0;
  166001. } /* end loop */
  166002. }
  166003. /*
  166004. * Read a restart marker, which is expected to appear next in the datastream;
  166005. * if the marker is not there, take appropriate recovery action.
  166006. * Returns FALSE if suspension is required.
  166007. *
  166008. * This is called by the entropy decoder after it has read an appropriate
  166009. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  166010. * has already read a marker from the data source. Under normal conditions
  166011. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  166012. * it holds a marker which the decoder will be unable to read past.
  166013. */
  166014. METHODDEF(boolean)
  166015. read_restart_marker (j_decompress_ptr cinfo)
  166016. {
  166017. /* Obtain a marker unless we already did. */
  166018. /* Note that next_marker will complain if it skips any data. */
  166019. if (cinfo->unread_marker == 0) {
  166020. if (! next_marker(cinfo))
  166021. return FALSE;
  166022. }
  166023. if (cinfo->unread_marker ==
  166024. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  166025. /* Normal case --- swallow the marker and let entropy decoder continue */
  166026. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  166027. cinfo->unread_marker = 0;
  166028. } else {
  166029. /* Uh-oh, the restart markers have been messed up. */
  166030. /* Let the data source manager determine how to resync. */
  166031. if (! (*cinfo->src->resync_to_restart) (cinfo,
  166032. cinfo->marker->next_restart_num))
  166033. return FALSE;
  166034. }
  166035. /* Update next-restart state */
  166036. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  166037. return TRUE;
  166038. }
  166039. /*
  166040. * This is the default resync_to_restart method for data source managers
  166041. * to use if they don't have any better approach. Some data source managers
  166042. * may be able to back up, or may have additional knowledge about the data
  166043. * which permits a more intelligent recovery strategy; such managers would
  166044. * presumably supply their own resync method.
  166045. *
  166046. * read_restart_marker calls resync_to_restart if it finds a marker other than
  166047. * the restart marker it was expecting. (This code is *not* used unless
  166048. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  166049. * the marker code actually found (might be anything, except 0 or FF).
  166050. * The desired restart marker number (0..7) is passed as a parameter.
  166051. * This routine is supposed to apply whatever error recovery strategy seems
  166052. * appropriate in order to position the input stream to the next data segment.
  166053. * Note that cinfo->unread_marker is treated as a marker appearing before
  166054. * the current data-source input point; usually it should be reset to zero
  166055. * before returning.
  166056. * Returns FALSE if suspension is required.
  166057. *
  166058. * This implementation is substantially constrained by wanting to treat the
  166059. * input as a data stream; this means we can't back up. Therefore, we have
  166060. * only the following actions to work with:
  166061. * 1. Simply discard the marker and let the entropy decoder resume at next
  166062. * byte of file.
  166063. * 2. Read forward until we find another marker, discarding intervening
  166064. * data. (In theory we could look ahead within the current bufferload,
  166065. * without having to discard data if we don't find the desired marker.
  166066. * This idea is not implemented here, in part because it makes behavior
  166067. * dependent on buffer size and chance buffer-boundary positions.)
  166068. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  166069. * This will cause the entropy decoder to process an empty data segment,
  166070. * inserting dummy zeroes, and then we will reprocess the marker.
  166071. *
  166072. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  166073. * appropriate if the found marker is a future restart marker (indicating
  166074. * that we have missed the desired restart marker, probably because it got
  166075. * corrupted).
  166076. * We apply #2 or #3 if the found marker is a restart marker no more than
  166077. * two counts behind or ahead of the expected one. We also apply #2 if the
  166078. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  166079. * If the found marker is a restart marker more than 2 counts away, we do #1
  166080. * (too much risk that the marker is erroneous; with luck we will be able to
  166081. * resync at some future point).
  166082. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  166083. * overrunning the end of a scan. An implementation limited to single-scan
  166084. * files might find it better to apply #2 for markers other than EOI, since
  166085. * any other marker would have to be bogus data in that case.
  166086. */
  166087. GLOBAL(boolean)
  166088. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  166089. {
  166090. int marker = cinfo->unread_marker;
  166091. int action = 1;
  166092. /* Always put up a warning. */
  166093. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  166094. /* Outer loop handles repeated decision after scanning forward. */
  166095. for (;;) {
  166096. if (marker < (int) M_SOF0)
  166097. action = 2; /* invalid marker */
  166098. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  166099. action = 3; /* valid non-restart marker */
  166100. else {
  166101. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  166102. marker == ((int) M_RST0 + ((desired+2) & 7)))
  166103. action = 3; /* one of the next two expected restarts */
  166104. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  166105. marker == ((int) M_RST0 + ((desired-2) & 7)))
  166106. action = 2; /* a prior restart, so advance */
  166107. else
  166108. action = 1; /* desired restart or too far away */
  166109. }
  166110. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  166111. switch (action) {
  166112. case 1:
  166113. /* Discard marker and let entropy decoder resume processing. */
  166114. cinfo->unread_marker = 0;
  166115. return TRUE;
  166116. case 2:
  166117. /* Scan to the next marker, and repeat the decision loop. */
  166118. if (! next_marker(cinfo))
  166119. return FALSE;
  166120. marker = cinfo->unread_marker;
  166121. break;
  166122. case 3:
  166123. /* Return without advancing past this marker. */
  166124. /* Entropy decoder will be forced to process an empty segment. */
  166125. return TRUE;
  166126. }
  166127. } /* end loop */
  166128. }
  166129. /*
  166130. * Reset marker processing state to begin a fresh datastream.
  166131. */
  166132. METHODDEF(void)
  166133. reset_marker_reader (j_decompress_ptr cinfo)
  166134. {
  166135. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  166136. cinfo->comp_info = NULL; /* until allocated by get_sof */
  166137. cinfo->input_scan_number = 0; /* no SOS seen yet */
  166138. cinfo->unread_marker = 0; /* no pending marker */
  166139. marker->pub.saw_SOI = FALSE; /* set internal state too */
  166140. marker->pub.saw_SOF = FALSE;
  166141. marker->pub.discarded_bytes = 0;
  166142. marker->cur_marker = NULL;
  166143. }
  166144. /*
  166145. * Initialize the marker reader module.
  166146. * This is called only once, when the decompression object is created.
  166147. */
  166148. GLOBAL(void)
  166149. jinit_marker_reader (j_decompress_ptr cinfo)
  166150. {
  166151. my_marker_ptr2 marker;
  166152. int i;
  166153. /* Create subobject in permanent pool */
  166154. marker = (my_marker_ptr2)
  166155. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  166156. SIZEOF(my_marker_reader));
  166157. cinfo->marker = (struct jpeg_marker_reader *) marker;
  166158. /* Initialize public method pointers */
  166159. marker->pub.reset_marker_reader = reset_marker_reader;
  166160. marker->pub.read_markers = read_markers;
  166161. marker->pub.read_restart_marker = read_restart_marker;
  166162. /* Initialize COM/APPn processing.
  166163. * By default, we examine and then discard APP0 and APP14,
  166164. * but simply discard COM and all other APPn.
  166165. */
  166166. marker->process_COM = skip_variable;
  166167. marker->length_limit_COM = 0;
  166168. for (i = 0; i < 16; i++) {
  166169. marker->process_APPn[i] = skip_variable;
  166170. marker->length_limit_APPn[i] = 0;
  166171. }
  166172. marker->process_APPn[0] = get_interesting_appn;
  166173. marker->process_APPn[14] = get_interesting_appn;
  166174. /* Reset marker processing state */
  166175. reset_marker_reader(cinfo);
  166176. }
  166177. /*
  166178. * Control saving of COM and APPn markers into marker_list.
  166179. */
  166180. #ifdef SAVE_MARKERS_SUPPORTED
  166181. GLOBAL(void)
  166182. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  166183. unsigned int length_limit)
  166184. {
  166185. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  166186. long maxlength;
  166187. jpeg_marker_parser_method processor;
  166188. /* Length limit mustn't be larger than what we can allocate
  166189. * (should only be a concern in a 16-bit environment).
  166190. */
  166191. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  166192. if (((long) length_limit) > maxlength)
  166193. length_limit = (unsigned int) maxlength;
  166194. /* Choose processor routine to use.
  166195. * APP0/APP14 have special requirements.
  166196. */
  166197. if (length_limit) {
  166198. processor = save_marker;
  166199. /* If saving APP0/APP14, save at least enough for our internal use. */
  166200. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  166201. length_limit = APP0_DATA_LEN;
  166202. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  166203. length_limit = APP14_DATA_LEN;
  166204. } else {
  166205. processor = skip_variable;
  166206. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  166207. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  166208. processor = get_interesting_appn;
  166209. }
  166210. if (marker_code == (int) M_COM) {
  166211. marker->process_COM = processor;
  166212. marker->length_limit_COM = length_limit;
  166213. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  166214. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  166215. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  166216. } else
  166217. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  166218. }
  166219. #endif /* SAVE_MARKERS_SUPPORTED */
  166220. /*
  166221. * Install a special processing method for COM or APPn markers.
  166222. */
  166223. GLOBAL(void)
  166224. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  166225. jpeg_marker_parser_method routine)
  166226. {
  166227. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  166228. if (marker_code == (int) M_COM)
  166229. marker->process_COM = routine;
  166230. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  166231. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  166232. else
  166233. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  166234. }
  166235. /********* End of inlined file: jdmarker.c *********/
  166236. /********* Start of inlined file: jdmaster.c *********/
  166237. #define JPEG_INTERNALS
  166238. /* Private state */
  166239. typedef struct {
  166240. struct jpeg_decomp_master pub; /* public fields */
  166241. int pass_number; /* # of passes completed */
  166242. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  166243. /* Saved references to initialized quantizer modules,
  166244. * in case we need to switch modes.
  166245. */
  166246. struct jpeg_color_quantizer * quantizer_1pass;
  166247. struct jpeg_color_quantizer * quantizer_2pass;
  166248. } my_decomp_master;
  166249. typedef my_decomp_master * my_master_ptr6;
  166250. /*
  166251. * Determine whether merged upsample/color conversion should be used.
  166252. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  166253. */
  166254. LOCAL(boolean)
  166255. use_merged_upsample (j_decompress_ptr cinfo)
  166256. {
  166257. #ifdef UPSAMPLE_MERGING_SUPPORTED
  166258. /* Merging is the equivalent of plain box-filter upsampling */
  166259. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  166260. return FALSE;
  166261. /* jdmerge.c only supports YCC=>RGB color conversion */
  166262. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  166263. cinfo->out_color_space != JCS_RGB ||
  166264. cinfo->out_color_components != RGB_PIXELSIZE)
  166265. return FALSE;
  166266. /* and it only handles 2h1v or 2h2v sampling ratios */
  166267. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  166268. cinfo->comp_info[1].h_samp_factor != 1 ||
  166269. cinfo->comp_info[2].h_samp_factor != 1 ||
  166270. cinfo->comp_info[0].v_samp_factor > 2 ||
  166271. cinfo->comp_info[1].v_samp_factor != 1 ||
  166272. cinfo->comp_info[2].v_samp_factor != 1)
  166273. return FALSE;
  166274. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  166275. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  166276. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  166277. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  166278. return FALSE;
  166279. /* ??? also need to test for upsample-time rescaling, when & if supported */
  166280. return TRUE; /* by golly, it'll work... */
  166281. #else
  166282. return FALSE;
  166283. #endif
  166284. }
  166285. /*
  166286. * Compute output image dimensions and related values.
  166287. * NOTE: this is exported for possible use by application.
  166288. * Hence it mustn't do anything that can't be done twice.
  166289. * Also note that it may be called before the master module is initialized!
  166290. */
  166291. GLOBAL(void)
  166292. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  166293. /* Do computations that are needed before master selection phase */
  166294. {
  166295. #ifdef IDCT_SCALING_SUPPORTED
  166296. int ci;
  166297. jpeg_component_info *compptr;
  166298. #endif
  166299. /* Prevent application from calling me at wrong times */
  166300. if (cinfo->global_state != DSTATE_READY)
  166301. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166302. #ifdef IDCT_SCALING_SUPPORTED
  166303. /* Compute actual output image dimensions and DCT scaling choices. */
  166304. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  166305. /* Provide 1/8 scaling */
  166306. cinfo->output_width = (JDIMENSION)
  166307. jdiv_round_up((long) cinfo->image_width, 8L);
  166308. cinfo->output_height = (JDIMENSION)
  166309. jdiv_round_up((long) cinfo->image_height, 8L);
  166310. cinfo->min_DCT_scaled_size = 1;
  166311. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  166312. /* Provide 1/4 scaling */
  166313. cinfo->output_width = (JDIMENSION)
  166314. jdiv_round_up((long) cinfo->image_width, 4L);
  166315. cinfo->output_height = (JDIMENSION)
  166316. jdiv_round_up((long) cinfo->image_height, 4L);
  166317. cinfo->min_DCT_scaled_size = 2;
  166318. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  166319. /* Provide 1/2 scaling */
  166320. cinfo->output_width = (JDIMENSION)
  166321. jdiv_round_up((long) cinfo->image_width, 2L);
  166322. cinfo->output_height = (JDIMENSION)
  166323. jdiv_round_up((long) cinfo->image_height, 2L);
  166324. cinfo->min_DCT_scaled_size = 4;
  166325. } else {
  166326. /* Provide 1/1 scaling */
  166327. cinfo->output_width = cinfo->image_width;
  166328. cinfo->output_height = cinfo->image_height;
  166329. cinfo->min_DCT_scaled_size = DCTSIZE;
  166330. }
  166331. /* In selecting the actual DCT scaling for each component, we try to
  166332. * scale up the chroma components via IDCT scaling rather than upsampling.
  166333. * This saves time if the upsampler gets to use 1:1 scaling.
  166334. * Note this code assumes that the supported DCT scalings are powers of 2.
  166335. */
  166336. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166337. ci++, compptr++) {
  166338. int ssize = cinfo->min_DCT_scaled_size;
  166339. while (ssize < DCTSIZE &&
  166340. (compptr->h_samp_factor * ssize * 2 <=
  166341. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  166342. (compptr->v_samp_factor * ssize * 2 <=
  166343. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  166344. ssize = ssize * 2;
  166345. }
  166346. compptr->DCT_scaled_size = ssize;
  166347. }
  166348. /* Recompute downsampled dimensions of components;
  166349. * application needs to know these if using raw downsampled data.
  166350. */
  166351. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166352. ci++, compptr++) {
  166353. /* Size in samples, after IDCT scaling */
  166354. compptr->downsampled_width = (JDIMENSION)
  166355. jdiv_round_up((long) cinfo->image_width *
  166356. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  166357. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  166358. compptr->downsampled_height = (JDIMENSION)
  166359. jdiv_round_up((long) cinfo->image_height *
  166360. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  166361. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  166362. }
  166363. #else /* !IDCT_SCALING_SUPPORTED */
  166364. /* Hardwire it to "no scaling" */
  166365. cinfo->output_width = cinfo->image_width;
  166366. cinfo->output_height = cinfo->image_height;
  166367. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  166368. * and has computed unscaled downsampled_width and downsampled_height.
  166369. */
  166370. #endif /* IDCT_SCALING_SUPPORTED */
  166371. /* Report number of components in selected colorspace. */
  166372. /* Probably this should be in the color conversion module... */
  166373. switch (cinfo->out_color_space) {
  166374. case JCS_GRAYSCALE:
  166375. cinfo->out_color_components = 1;
  166376. break;
  166377. case JCS_RGB:
  166378. #if RGB_PIXELSIZE != 3
  166379. cinfo->out_color_components = RGB_PIXELSIZE;
  166380. break;
  166381. #endif /* else share code with YCbCr */
  166382. case JCS_YCbCr:
  166383. cinfo->out_color_components = 3;
  166384. break;
  166385. case JCS_CMYK:
  166386. case JCS_YCCK:
  166387. cinfo->out_color_components = 4;
  166388. break;
  166389. default: /* else must be same colorspace as in file */
  166390. cinfo->out_color_components = cinfo->num_components;
  166391. break;
  166392. }
  166393. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  166394. cinfo->out_color_components);
  166395. /* See if upsampler will want to emit more than one row at a time */
  166396. if (use_merged_upsample(cinfo))
  166397. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  166398. else
  166399. cinfo->rec_outbuf_height = 1;
  166400. }
  166401. /*
  166402. * Several decompression processes need to range-limit values to the range
  166403. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  166404. * due to noise introduced by quantization, roundoff error, etc. These
  166405. * processes are inner loops and need to be as fast as possible. On most
  166406. * machines, particularly CPUs with pipelines or instruction prefetch,
  166407. * a (subscript-check-less) C table lookup
  166408. * x = sample_range_limit[x];
  166409. * is faster than explicit tests
  166410. * if (x < 0) x = 0;
  166411. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  166412. * These processes all use a common table prepared by the routine below.
  166413. *
  166414. * For most steps we can mathematically guarantee that the initial value
  166415. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  166416. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  166417. * limiting step (just after the IDCT), a wildly out-of-range value is
  166418. * possible if the input data is corrupt. To avoid any chance of indexing
  166419. * off the end of memory and getting a bad-pointer trap, we perform the
  166420. * post-IDCT limiting thus:
  166421. * x = range_limit[x & MASK];
  166422. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  166423. * samples. Under normal circumstances this is more than enough range and
  166424. * a correct output will be generated; with bogus input data the mask will
  166425. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  166426. * For the post-IDCT step, we want to convert the data from signed to unsigned
  166427. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  166428. * So the post-IDCT limiting table ends up looking like this:
  166429. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  166430. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  166431. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  166432. * 0,1,...,CENTERJSAMPLE-1
  166433. * Negative inputs select values from the upper half of the table after
  166434. * masking.
  166435. *
  166436. * We can save some space by overlapping the start of the post-IDCT table
  166437. * with the simpler range limiting table. The post-IDCT table begins at
  166438. * sample_range_limit + CENTERJSAMPLE.
  166439. *
  166440. * Note that the table is allocated in near data space on PCs; it's small
  166441. * enough and used often enough to justify this.
  166442. */
  166443. LOCAL(void)
  166444. prepare_range_limit_table (j_decompress_ptr cinfo)
  166445. /* Allocate and fill in the sample_range_limit table */
  166446. {
  166447. JSAMPLE * table;
  166448. int i;
  166449. table = (JSAMPLE *)
  166450. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166451. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  166452. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  166453. cinfo->sample_range_limit = table;
  166454. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  166455. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  166456. /* Main part of "simple" table: limit[x] = x */
  166457. for (i = 0; i <= MAXJSAMPLE; i++)
  166458. table[i] = (JSAMPLE) i;
  166459. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  166460. /* End of simple table, rest of first half of post-IDCT table */
  166461. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  166462. table[i] = MAXJSAMPLE;
  166463. /* Second half of post-IDCT table */
  166464. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  166465. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  166466. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  166467. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  166468. }
  166469. /*
  166470. * Master selection of decompression modules.
  166471. * This is done once at jpeg_start_decompress time. We determine
  166472. * which modules will be used and give them appropriate initialization calls.
  166473. * We also initialize the decompressor input side to begin consuming data.
  166474. *
  166475. * Since jpeg_read_header has finished, we know what is in the SOF
  166476. * and (first) SOS markers. We also have all the application parameter
  166477. * settings.
  166478. */
  166479. LOCAL(void)
  166480. master_selection (j_decompress_ptr cinfo)
  166481. {
  166482. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  166483. boolean use_c_buffer;
  166484. long samplesperrow;
  166485. JDIMENSION jd_samplesperrow;
  166486. /* Initialize dimensions and other stuff */
  166487. jpeg_calc_output_dimensions(cinfo);
  166488. prepare_range_limit_table(cinfo);
  166489. /* Width of an output scanline must be representable as JDIMENSION. */
  166490. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  166491. jd_samplesperrow = (JDIMENSION) samplesperrow;
  166492. if ((long) jd_samplesperrow != samplesperrow)
  166493. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  166494. /* Initialize my private state */
  166495. master->pass_number = 0;
  166496. master->using_merged_upsample = use_merged_upsample(cinfo);
  166497. /* Color quantizer selection */
  166498. master->quantizer_1pass = NULL;
  166499. master->quantizer_2pass = NULL;
  166500. /* No mode changes if not using buffered-image mode. */
  166501. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  166502. cinfo->enable_1pass_quant = FALSE;
  166503. cinfo->enable_external_quant = FALSE;
  166504. cinfo->enable_2pass_quant = FALSE;
  166505. }
  166506. if (cinfo->quantize_colors) {
  166507. if (cinfo->raw_data_out)
  166508. ERREXIT(cinfo, JERR_NOTIMPL);
  166509. /* 2-pass quantizer only works in 3-component color space. */
  166510. if (cinfo->out_color_components != 3) {
  166511. cinfo->enable_1pass_quant = TRUE;
  166512. cinfo->enable_external_quant = FALSE;
  166513. cinfo->enable_2pass_quant = FALSE;
  166514. cinfo->colormap = NULL;
  166515. } else if (cinfo->colormap != NULL) {
  166516. cinfo->enable_external_quant = TRUE;
  166517. } else if (cinfo->two_pass_quantize) {
  166518. cinfo->enable_2pass_quant = TRUE;
  166519. } else {
  166520. cinfo->enable_1pass_quant = TRUE;
  166521. }
  166522. if (cinfo->enable_1pass_quant) {
  166523. #ifdef QUANT_1PASS_SUPPORTED
  166524. jinit_1pass_quantizer(cinfo);
  166525. master->quantizer_1pass = cinfo->cquantize;
  166526. #else
  166527. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166528. #endif
  166529. }
  166530. /* We use the 2-pass code to map to external colormaps. */
  166531. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  166532. #ifdef QUANT_2PASS_SUPPORTED
  166533. jinit_2pass_quantizer(cinfo);
  166534. master->quantizer_2pass = cinfo->cquantize;
  166535. #else
  166536. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166537. #endif
  166538. }
  166539. /* If both quantizers are initialized, the 2-pass one is left active;
  166540. * this is necessary for starting with quantization to an external map.
  166541. */
  166542. }
  166543. /* Post-processing: in particular, color conversion first */
  166544. if (! cinfo->raw_data_out) {
  166545. if (master->using_merged_upsample) {
  166546. #ifdef UPSAMPLE_MERGING_SUPPORTED
  166547. jinit_merged_upsampler(cinfo); /* does color conversion too */
  166548. #else
  166549. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166550. #endif
  166551. } else {
  166552. jinit_color_deconverter(cinfo);
  166553. jinit_upsampler(cinfo);
  166554. }
  166555. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  166556. }
  166557. /* Inverse DCT */
  166558. jinit_inverse_dct(cinfo);
  166559. /* Entropy decoding: either Huffman or arithmetic coding. */
  166560. if (cinfo->arith_code) {
  166561. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  166562. } else {
  166563. if (cinfo->progressive_mode) {
  166564. #ifdef D_PROGRESSIVE_SUPPORTED
  166565. jinit_phuff_decoder(cinfo);
  166566. #else
  166567. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166568. #endif
  166569. } else
  166570. jinit_huff_decoder(cinfo);
  166571. }
  166572. /* Initialize principal buffer controllers. */
  166573. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  166574. jinit_d_coef_controller(cinfo, use_c_buffer);
  166575. if (! cinfo->raw_data_out)
  166576. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  166577. /* We can now tell the memory manager to allocate virtual arrays. */
  166578. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  166579. /* Initialize input side of decompressor to consume first scan. */
  166580. (*cinfo->inputctl->start_input_pass) (cinfo);
  166581. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166582. /* If jpeg_start_decompress will read the whole file, initialize
  166583. * progress monitoring appropriately. The input step is counted
  166584. * as one pass.
  166585. */
  166586. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  166587. cinfo->inputctl->has_multiple_scans) {
  166588. int nscans;
  166589. /* Estimate number of scans to set pass_limit. */
  166590. if (cinfo->progressive_mode) {
  166591. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  166592. nscans = 2 + 3 * cinfo->num_components;
  166593. } else {
  166594. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  166595. nscans = cinfo->num_components;
  166596. }
  166597. cinfo->progress->pass_counter = 0L;
  166598. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  166599. cinfo->progress->completed_passes = 0;
  166600. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  166601. /* Count the input pass as done */
  166602. master->pass_number++;
  166603. }
  166604. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  166605. }
  166606. /*
  166607. * Per-pass setup.
  166608. * This is called at the beginning of each output pass. We determine which
  166609. * modules will be active during this pass and give them appropriate
  166610. * start_pass calls. We also set is_dummy_pass to indicate whether this
  166611. * is a "real" output pass or a dummy pass for color quantization.
  166612. * (In the latter case, jdapistd.c will crank the pass to completion.)
  166613. */
  166614. METHODDEF(void)
  166615. prepare_for_output_pass (j_decompress_ptr cinfo)
  166616. {
  166617. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  166618. if (master->pub.is_dummy_pass) {
  166619. #ifdef QUANT_2PASS_SUPPORTED
  166620. /* Final pass of 2-pass quantization */
  166621. master->pub.is_dummy_pass = FALSE;
  166622. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  166623. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  166624. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  166625. #else
  166626. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166627. #endif /* QUANT_2PASS_SUPPORTED */
  166628. } else {
  166629. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  166630. /* Select new quantization method */
  166631. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  166632. cinfo->cquantize = master->quantizer_2pass;
  166633. master->pub.is_dummy_pass = TRUE;
  166634. } else if (cinfo->enable_1pass_quant) {
  166635. cinfo->cquantize = master->quantizer_1pass;
  166636. } else {
  166637. ERREXIT(cinfo, JERR_MODE_CHANGE);
  166638. }
  166639. }
  166640. (*cinfo->idct->start_pass) (cinfo);
  166641. (*cinfo->coef->start_output_pass) (cinfo);
  166642. if (! cinfo->raw_data_out) {
  166643. if (! master->using_merged_upsample)
  166644. (*cinfo->cconvert->start_pass) (cinfo);
  166645. (*cinfo->upsample->start_pass) (cinfo);
  166646. if (cinfo->quantize_colors)
  166647. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  166648. (*cinfo->post->start_pass) (cinfo,
  166649. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  166650. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  166651. }
  166652. }
  166653. /* Set up progress monitor's pass info if present */
  166654. if (cinfo->progress != NULL) {
  166655. cinfo->progress->completed_passes = master->pass_number;
  166656. cinfo->progress->total_passes = master->pass_number +
  166657. (master->pub.is_dummy_pass ? 2 : 1);
  166658. /* In buffered-image mode, we assume one more output pass if EOI not
  166659. * yet reached, but no more passes if EOI has been reached.
  166660. */
  166661. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  166662. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  166663. }
  166664. }
  166665. }
  166666. /*
  166667. * Finish up at end of an output pass.
  166668. */
  166669. METHODDEF(void)
  166670. finish_output_pass (j_decompress_ptr cinfo)
  166671. {
  166672. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  166673. if (cinfo->quantize_colors)
  166674. (*cinfo->cquantize->finish_pass) (cinfo);
  166675. master->pass_number++;
  166676. }
  166677. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166678. /*
  166679. * Switch to a new external colormap between output passes.
  166680. */
  166681. GLOBAL(void)
  166682. jpeg_new_colormap (j_decompress_ptr cinfo)
  166683. {
  166684. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  166685. /* Prevent application from calling me at wrong times */
  166686. if (cinfo->global_state != DSTATE_BUFIMAGE)
  166687. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166688. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  166689. cinfo->colormap != NULL) {
  166690. /* Select 2-pass quantizer for external colormap use */
  166691. cinfo->cquantize = master->quantizer_2pass;
  166692. /* Notify quantizer of colormap change */
  166693. (*cinfo->cquantize->new_color_map) (cinfo);
  166694. master->pub.is_dummy_pass = FALSE; /* just in case */
  166695. } else
  166696. ERREXIT(cinfo, JERR_MODE_CHANGE);
  166697. }
  166698. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  166699. /*
  166700. * Initialize master decompression control and select active modules.
  166701. * This is performed at the start of jpeg_start_decompress.
  166702. */
  166703. GLOBAL(void)
  166704. jinit_master_decompress (j_decompress_ptr cinfo)
  166705. {
  166706. my_master_ptr6 master;
  166707. master = (my_master_ptr6)
  166708. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166709. SIZEOF(my_decomp_master));
  166710. cinfo->master = (struct jpeg_decomp_master *) master;
  166711. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  166712. master->pub.finish_output_pass = finish_output_pass;
  166713. master->pub.is_dummy_pass = FALSE;
  166714. master_selection(cinfo);
  166715. }
  166716. /********* End of inlined file: jdmaster.c *********/
  166717. #undef FIX
  166718. /********* Start of inlined file: jdmerge.c *********/
  166719. #define JPEG_INTERNALS
  166720. #ifdef UPSAMPLE_MERGING_SUPPORTED
  166721. /* Private subobject */
  166722. typedef struct {
  166723. struct jpeg_upsampler pub; /* public fields */
  166724. /* Pointer to routine to do actual upsampling/conversion of one row group */
  166725. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  166726. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  166727. JSAMPARRAY output_buf));
  166728. /* Private state for YCC->RGB conversion */
  166729. int * Cr_r_tab; /* => table for Cr to R conversion */
  166730. int * Cb_b_tab; /* => table for Cb to B conversion */
  166731. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  166732. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  166733. /* For 2:1 vertical sampling, we produce two output rows at a time.
  166734. * We need a "spare" row buffer to hold the second output row if the
  166735. * application provides just a one-row buffer; we also use the spare
  166736. * to discard the dummy last row if the image height is odd.
  166737. */
  166738. JSAMPROW spare_row;
  166739. boolean spare_full; /* T if spare buffer is occupied */
  166740. JDIMENSION out_row_width; /* samples per output row */
  166741. JDIMENSION rows_to_go; /* counts rows remaining in image */
  166742. } my_upsampler;
  166743. typedef my_upsampler * my_upsample_ptr;
  166744. #define SCALEBITS 16 /* speediest right-shift on some machines */
  166745. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  166746. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  166747. /*
  166748. * Initialize tables for YCC->RGB colorspace conversion.
  166749. * This is taken directly from jdcolor.c; see that file for more info.
  166750. */
  166751. LOCAL(void)
  166752. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  166753. {
  166754. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166755. int i;
  166756. INT32 x;
  166757. SHIFT_TEMPS
  166758. upsample->Cr_r_tab = (int *)
  166759. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166760. (MAXJSAMPLE+1) * SIZEOF(int));
  166761. upsample->Cb_b_tab = (int *)
  166762. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166763. (MAXJSAMPLE+1) * SIZEOF(int));
  166764. upsample->Cr_g_tab = (INT32 *)
  166765. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166766. (MAXJSAMPLE+1) * SIZEOF(INT32));
  166767. upsample->Cb_g_tab = (INT32 *)
  166768. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166769. (MAXJSAMPLE+1) * SIZEOF(INT32));
  166770. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  166771. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  166772. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  166773. /* Cr=>R value is nearest int to 1.40200 * x */
  166774. upsample->Cr_r_tab[i] = (int)
  166775. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  166776. /* Cb=>B value is nearest int to 1.77200 * x */
  166777. upsample->Cb_b_tab[i] = (int)
  166778. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  166779. /* Cr=>G value is scaled-up -0.71414 * x */
  166780. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  166781. /* Cb=>G value is scaled-up -0.34414 * x */
  166782. /* We also add in ONE_HALF so that need not do it in inner loop */
  166783. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  166784. }
  166785. }
  166786. /*
  166787. * Initialize for an upsampling pass.
  166788. */
  166789. METHODDEF(void)
  166790. start_pass_merged_upsample (j_decompress_ptr cinfo)
  166791. {
  166792. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166793. /* Mark the spare buffer empty */
  166794. upsample->spare_full = FALSE;
  166795. /* Initialize total-height counter for detecting bottom of image */
  166796. upsample->rows_to_go = cinfo->output_height;
  166797. }
  166798. /*
  166799. * Control routine to do upsampling (and color conversion).
  166800. *
  166801. * The control routine just handles the row buffering considerations.
  166802. */
  166803. METHODDEF(void)
  166804. merged_2v_upsample (j_decompress_ptr cinfo,
  166805. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166806. JDIMENSION in_row_groups_avail,
  166807. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166808. JDIMENSION out_rows_avail)
  166809. /* 2:1 vertical sampling case: may need a spare row. */
  166810. {
  166811. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166812. JSAMPROW work_ptrs[2];
  166813. JDIMENSION num_rows; /* number of rows returned to caller */
  166814. if (upsample->spare_full) {
  166815. /* If we have a spare row saved from a previous cycle, just return it. */
  166816. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  166817. 1, upsample->out_row_width);
  166818. num_rows = 1;
  166819. upsample->spare_full = FALSE;
  166820. } else {
  166821. /* Figure number of rows to return to caller. */
  166822. num_rows = 2;
  166823. /* Not more than the distance to the end of the image. */
  166824. if (num_rows > upsample->rows_to_go)
  166825. num_rows = upsample->rows_to_go;
  166826. /* And not more than what the client can accept: */
  166827. out_rows_avail -= *out_row_ctr;
  166828. if (num_rows > out_rows_avail)
  166829. num_rows = out_rows_avail;
  166830. /* Create output pointer array for upsampler. */
  166831. work_ptrs[0] = output_buf[*out_row_ctr];
  166832. if (num_rows > 1) {
  166833. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  166834. } else {
  166835. work_ptrs[1] = upsample->spare_row;
  166836. upsample->spare_full = TRUE;
  166837. }
  166838. /* Now do the upsampling. */
  166839. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  166840. }
  166841. /* Adjust counts */
  166842. *out_row_ctr += num_rows;
  166843. upsample->rows_to_go -= num_rows;
  166844. /* When the buffer is emptied, declare this input row group consumed */
  166845. if (! upsample->spare_full)
  166846. (*in_row_group_ctr)++;
  166847. }
  166848. METHODDEF(void)
  166849. merged_1v_upsample (j_decompress_ptr cinfo,
  166850. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166851. JDIMENSION in_row_groups_avail,
  166852. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166853. JDIMENSION out_rows_avail)
  166854. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  166855. {
  166856. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166857. /* Just do the upsampling. */
  166858. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  166859. output_buf + *out_row_ctr);
  166860. /* Adjust counts */
  166861. (*out_row_ctr)++;
  166862. (*in_row_group_ctr)++;
  166863. }
  166864. /*
  166865. * These are the routines invoked by the control routines to do
  166866. * the actual upsampling/conversion. One row group is processed per call.
  166867. *
  166868. * Note: since we may be writing directly into application-supplied buffers,
  166869. * we have to be honest about the output width; we can't assume the buffer
  166870. * has been rounded up to an even width.
  166871. */
  166872. /*
  166873. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  166874. */
  166875. METHODDEF(void)
  166876. h2v1_merged_upsample (j_decompress_ptr cinfo,
  166877. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  166878. JSAMPARRAY output_buf)
  166879. {
  166880. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166881. register int y, cred, cgreen, cblue;
  166882. int cb, cr;
  166883. register JSAMPROW outptr;
  166884. JSAMPROW inptr0, inptr1, inptr2;
  166885. JDIMENSION col;
  166886. /* copy these pointers into registers if possible */
  166887. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  166888. int * Crrtab = upsample->Cr_r_tab;
  166889. int * Cbbtab = upsample->Cb_b_tab;
  166890. INT32 * Crgtab = upsample->Cr_g_tab;
  166891. INT32 * Cbgtab = upsample->Cb_g_tab;
  166892. SHIFT_TEMPS
  166893. inptr0 = input_buf[0][in_row_group_ctr];
  166894. inptr1 = input_buf[1][in_row_group_ctr];
  166895. inptr2 = input_buf[2][in_row_group_ctr];
  166896. outptr = output_buf[0];
  166897. /* Loop for each pair of output pixels */
  166898. for (col = cinfo->output_width >> 1; col > 0; col--) {
  166899. /* Do the chroma part of the calculation */
  166900. cb = GETJSAMPLE(*inptr1++);
  166901. cr = GETJSAMPLE(*inptr2++);
  166902. cred = Crrtab[cr];
  166903. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  166904. cblue = Cbbtab[cb];
  166905. /* Fetch 2 Y values and emit 2 pixels */
  166906. y = GETJSAMPLE(*inptr0++);
  166907. outptr[RGB_RED] = range_limit[y + cred];
  166908. outptr[RGB_GREEN] = range_limit[y + cgreen];
  166909. outptr[RGB_BLUE] = range_limit[y + cblue];
  166910. outptr += RGB_PIXELSIZE;
  166911. y = GETJSAMPLE(*inptr0++);
  166912. outptr[RGB_RED] = range_limit[y + cred];
  166913. outptr[RGB_GREEN] = range_limit[y + cgreen];
  166914. outptr[RGB_BLUE] = range_limit[y + cblue];
  166915. outptr += RGB_PIXELSIZE;
  166916. }
  166917. /* If image width is odd, do the last output column separately */
  166918. if (cinfo->output_width & 1) {
  166919. cb = GETJSAMPLE(*inptr1);
  166920. cr = GETJSAMPLE(*inptr2);
  166921. cred = Crrtab[cr];
  166922. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  166923. cblue = Cbbtab[cb];
  166924. y = GETJSAMPLE(*inptr0);
  166925. outptr[RGB_RED] = range_limit[y + cred];
  166926. outptr[RGB_GREEN] = range_limit[y + cgreen];
  166927. outptr[RGB_BLUE] = range_limit[y + cblue];
  166928. }
  166929. }
  166930. /*
  166931. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  166932. */
  166933. METHODDEF(void)
  166934. h2v2_merged_upsample (j_decompress_ptr cinfo,
  166935. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  166936. JSAMPARRAY output_buf)
  166937. {
  166938. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166939. register int y, cred, cgreen, cblue;
  166940. int cb, cr;
  166941. register JSAMPROW outptr0, outptr1;
  166942. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  166943. JDIMENSION col;
  166944. /* copy these pointers into registers if possible */
  166945. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  166946. int * Crrtab = upsample->Cr_r_tab;
  166947. int * Cbbtab = upsample->Cb_b_tab;
  166948. INT32 * Crgtab = upsample->Cr_g_tab;
  166949. INT32 * Cbgtab = upsample->Cb_g_tab;
  166950. SHIFT_TEMPS
  166951. inptr00 = input_buf[0][in_row_group_ctr*2];
  166952. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  166953. inptr1 = input_buf[1][in_row_group_ctr];
  166954. inptr2 = input_buf[2][in_row_group_ctr];
  166955. outptr0 = output_buf[0];
  166956. outptr1 = output_buf[1];
  166957. /* Loop for each group of output pixels */
  166958. for (col = cinfo->output_width >> 1; col > 0; col--) {
  166959. /* Do the chroma part of the calculation */
  166960. cb = GETJSAMPLE(*inptr1++);
  166961. cr = GETJSAMPLE(*inptr2++);
  166962. cred = Crrtab[cr];
  166963. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  166964. cblue = Cbbtab[cb];
  166965. /* Fetch 4 Y values and emit 4 pixels */
  166966. y = GETJSAMPLE(*inptr00++);
  166967. outptr0[RGB_RED] = range_limit[y + cred];
  166968. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  166969. outptr0[RGB_BLUE] = range_limit[y + cblue];
  166970. outptr0 += RGB_PIXELSIZE;
  166971. y = GETJSAMPLE(*inptr00++);
  166972. outptr0[RGB_RED] = range_limit[y + cred];
  166973. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  166974. outptr0[RGB_BLUE] = range_limit[y + cblue];
  166975. outptr0 += RGB_PIXELSIZE;
  166976. y = GETJSAMPLE(*inptr01++);
  166977. outptr1[RGB_RED] = range_limit[y + cred];
  166978. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  166979. outptr1[RGB_BLUE] = range_limit[y + cblue];
  166980. outptr1 += RGB_PIXELSIZE;
  166981. y = GETJSAMPLE(*inptr01++);
  166982. outptr1[RGB_RED] = range_limit[y + cred];
  166983. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  166984. outptr1[RGB_BLUE] = range_limit[y + cblue];
  166985. outptr1 += RGB_PIXELSIZE;
  166986. }
  166987. /* If image width is odd, do the last output column separately */
  166988. if (cinfo->output_width & 1) {
  166989. cb = GETJSAMPLE(*inptr1);
  166990. cr = GETJSAMPLE(*inptr2);
  166991. cred = Crrtab[cr];
  166992. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  166993. cblue = Cbbtab[cb];
  166994. y = GETJSAMPLE(*inptr00);
  166995. outptr0[RGB_RED] = range_limit[y + cred];
  166996. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  166997. outptr0[RGB_BLUE] = range_limit[y + cblue];
  166998. y = GETJSAMPLE(*inptr01);
  166999. outptr1[RGB_RED] = range_limit[y + cred];
  167000. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  167001. outptr1[RGB_BLUE] = range_limit[y + cblue];
  167002. }
  167003. }
  167004. /*
  167005. * Module initialization routine for merged upsampling/color conversion.
  167006. *
  167007. * NB: this is called under the conditions determined by use_merged_upsample()
  167008. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  167009. * of this module; no safety checks are made here.
  167010. */
  167011. GLOBAL(void)
  167012. jinit_merged_upsampler (j_decompress_ptr cinfo)
  167013. {
  167014. my_upsample_ptr upsample;
  167015. upsample = (my_upsample_ptr)
  167016. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167017. SIZEOF(my_upsampler));
  167018. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  167019. upsample->pub.start_pass = start_pass_merged_upsample;
  167020. upsample->pub.need_context_rows = FALSE;
  167021. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  167022. if (cinfo->max_v_samp_factor == 2) {
  167023. upsample->pub.upsample = merged_2v_upsample;
  167024. upsample->upmethod = h2v2_merged_upsample;
  167025. /* Allocate a spare row buffer */
  167026. upsample->spare_row = (JSAMPROW)
  167027. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167028. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  167029. } else {
  167030. upsample->pub.upsample = merged_1v_upsample;
  167031. upsample->upmethod = h2v1_merged_upsample;
  167032. /* No spare row needed */
  167033. upsample->spare_row = NULL;
  167034. }
  167035. build_ycc_rgb_table2(cinfo);
  167036. }
  167037. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  167038. /********* End of inlined file: jdmerge.c *********/
  167039. #undef ASSIGN_STATE
  167040. /********* Start of inlined file: jdphuff.c *********/
  167041. #define JPEG_INTERNALS
  167042. #ifdef D_PROGRESSIVE_SUPPORTED
  167043. /*
  167044. * Expanded entropy decoder object for progressive Huffman decoding.
  167045. *
  167046. * The savable_state subrecord contains fields that change within an MCU,
  167047. * but must not be updated permanently until we complete the MCU.
  167048. */
  167049. typedef struct {
  167050. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  167051. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  167052. } savable_state3;
  167053. /* This macro is to work around compilers with missing or broken
  167054. * structure assignment. You'll need to fix this code if you have
  167055. * such a compiler and you change MAX_COMPS_IN_SCAN.
  167056. */
  167057. #ifndef NO_STRUCT_ASSIGN
  167058. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  167059. #else
  167060. #if MAX_COMPS_IN_SCAN == 4
  167061. #define ASSIGN_STATE(dest,src) \
  167062. ((dest).EOBRUN = (src).EOBRUN, \
  167063. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  167064. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  167065. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  167066. (dest).last_dc_val[3] = (src).last_dc_val[3])
  167067. #endif
  167068. #endif
  167069. typedef struct {
  167070. struct jpeg_entropy_decoder pub; /* public fields */
  167071. /* These fields are loaded into local variables at start of each MCU.
  167072. * In case of suspension, we exit WITHOUT updating them.
  167073. */
  167074. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  167075. savable_state3 saved; /* Other state at start of MCU */
  167076. /* These fields are NOT loaded into local working state. */
  167077. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  167078. /* Pointers to derived tables (these workspaces have image lifespan) */
  167079. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  167080. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  167081. } phuff_entropy_decoder;
  167082. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  167083. /* Forward declarations */
  167084. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  167085. JBLOCKROW *MCU_data));
  167086. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  167087. JBLOCKROW *MCU_data));
  167088. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  167089. JBLOCKROW *MCU_data));
  167090. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  167091. JBLOCKROW *MCU_data));
  167092. /*
  167093. * Initialize for a Huffman-compressed scan.
  167094. */
  167095. METHODDEF(void)
  167096. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  167097. {
  167098. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  167099. boolean is_DC_band, bad;
  167100. int ci, coefi, tbl;
  167101. int *coef_bit_ptr;
  167102. jpeg_component_info * compptr;
  167103. is_DC_band = (cinfo->Ss == 0);
  167104. /* Validate scan parameters */
  167105. bad = FALSE;
  167106. if (is_DC_band) {
  167107. if (cinfo->Se != 0)
  167108. bad = TRUE;
  167109. } else {
  167110. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  167111. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  167112. bad = TRUE;
  167113. /* AC scans may have only one component */
  167114. if (cinfo->comps_in_scan != 1)
  167115. bad = TRUE;
  167116. }
  167117. if (cinfo->Ah != 0) {
  167118. /* Successive approximation refinement scan: must have Al = Ah-1. */
  167119. if (cinfo->Al != cinfo->Ah-1)
  167120. bad = TRUE;
  167121. }
  167122. if (cinfo->Al > 13) /* need not check for < 0 */
  167123. bad = TRUE;
  167124. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  167125. * but the spec doesn't say so, and we try to be liberal about what we
  167126. * accept. Note: large Al values could result in out-of-range DC
  167127. * coefficients during early scans, leading to bizarre displays due to
  167128. * overflows in the IDCT math. But we won't crash.
  167129. */
  167130. if (bad)
  167131. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  167132. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  167133. /* Update progression status, and verify that scan order is legal.
  167134. * Note that inter-scan inconsistencies are treated as warnings
  167135. * not fatal errors ... not clear if this is right way to behave.
  167136. */
  167137. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167138. int cindex = cinfo->cur_comp_info[ci]->component_index;
  167139. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  167140. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  167141. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  167142. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  167143. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  167144. if (cinfo->Ah != expected)
  167145. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  167146. coef_bit_ptr[coefi] = cinfo->Al;
  167147. }
  167148. }
  167149. /* Select MCU decoding routine */
  167150. if (cinfo->Ah == 0) {
  167151. if (is_DC_band)
  167152. entropy->pub.decode_mcu = decode_mcu_DC_first;
  167153. else
  167154. entropy->pub.decode_mcu = decode_mcu_AC_first;
  167155. } else {
  167156. if (is_DC_band)
  167157. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  167158. else
  167159. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  167160. }
  167161. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167162. compptr = cinfo->cur_comp_info[ci];
  167163. /* Make sure requested tables are present, and compute derived tables.
  167164. * We may build same derived table more than once, but it's not expensive.
  167165. */
  167166. if (is_DC_band) {
  167167. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  167168. tbl = compptr->dc_tbl_no;
  167169. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  167170. & entropy->derived_tbls[tbl]);
  167171. }
  167172. } else {
  167173. tbl = compptr->ac_tbl_no;
  167174. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  167175. & entropy->derived_tbls[tbl]);
  167176. /* remember the single active table */
  167177. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  167178. }
  167179. /* Initialize DC predictions to 0 */
  167180. entropy->saved.last_dc_val[ci] = 0;
  167181. }
  167182. /* Initialize bitread state variables */
  167183. entropy->bitstate.bits_left = 0;
  167184. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  167185. entropy->pub.insufficient_data = FALSE;
  167186. /* Initialize private state variables */
  167187. entropy->saved.EOBRUN = 0;
  167188. /* Initialize restart counter */
  167189. entropy->restarts_to_go = cinfo->restart_interval;
  167190. }
  167191. /*
  167192. * Check for a restart marker & resynchronize decoder.
  167193. * Returns FALSE if must suspend.
  167194. */
  167195. LOCAL(boolean)
  167196. process_restartp (j_decompress_ptr cinfo)
  167197. {
  167198. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  167199. int ci;
  167200. /* Throw away any unused bits remaining in bit buffer; */
  167201. /* include any full bytes in next_marker's count of discarded bytes */
  167202. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  167203. entropy->bitstate.bits_left = 0;
  167204. /* Advance past the RSTn marker */
  167205. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  167206. return FALSE;
  167207. /* Re-initialize DC predictions to 0 */
  167208. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  167209. entropy->saved.last_dc_val[ci] = 0;
  167210. /* Re-init EOB run count, too */
  167211. entropy->saved.EOBRUN = 0;
  167212. /* Reset restart counter */
  167213. entropy->restarts_to_go = cinfo->restart_interval;
  167214. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  167215. * against a marker. In that case we will end up treating the next data
  167216. * segment as empty, and we can avoid producing bogus output pixels by
  167217. * leaving the flag set.
  167218. */
  167219. if (cinfo->unread_marker == 0)
  167220. entropy->pub.insufficient_data = FALSE;
  167221. return TRUE;
  167222. }
  167223. /*
  167224. * Huffman MCU decoding.
  167225. * Each of these routines decodes and returns one MCU's worth of
  167226. * Huffman-compressed coefficients.
  167227. * The coefficients are reordered from zigzag order into natural array order,
  167228. * but are not dequantized.
  167229. *
  167230. * The i'th block of the MCU is stored into the block pointed to by
  167231. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  167232. *
  167233. * We return FALSE if data source requested suspension. In that case no
  167234. * changes have been made to permanent state. (Exception: some output
  167235. * coefficients may already have been assigned. This is harmless for
  167236. * spectral selection, since we'll just re-assign them on the next call.
  167237. * Successive approximation AC refinement has to be more careful, however.)
  167238. */
  167239. /*
  167240. * MCU decoding for DC initial scan (either spectral selection,
  167241. * or first pass of successive approximation).
  167242. */
  167243. METHODDEF(boolean)
  167244. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  167245. {
  167246. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  167247. int Al = cinfo->Al;
  167248. register int s, r;
  167249. int blkn, ci;
  167250. JBLOCKROW block;
  167251. BITREAD_STATE_VARS;
  167252. savable_state3 state;
  167253. d_derived_tbl * tbl;
  167254. jpeg_component_info * compptr;
  167255. /* Process restart marker if needed; may have to suspend */
  167256. if (cinfo->restart_interval) {
  167257. if (entropy->restarts_to_go == 0)
  167258. if (! process_restartp(cinfo))
  167259. return FALSE;
  167260. }
  167261. /* If we've run out of data, just leave the MCU set to zeroes.
  167262. * This way, we return uniform gray for the remainder of the segment.
  167263. */
  167264. if (! entropy->pub.insufficient_data) {
  167265. /* Load up working state */
  167266. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  167267. ASSIGN_STATE(state, entropy->saved);
  167268. /* Outer loop handles each block in the MCU */
  167269. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  167270. block = MCU_data[blkn];
  167271. ci = cinfo->MCU_membership[blkn];
  167272. compptr = cinfo->cur_comp_info[ci];
  167273. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  167274. /* Decode a single block's worth of coefficients */
  167275. /* Section F.2.2.1: decode the DC coefficient difference */
  167276. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  167277. if (s) {
  167278. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  167279. r = GET_BITS(s);
  167280. s = HUFF_EXTEND(r, s);
  167281. }
  167282. /* Convert DC difference to actual value, update last_dc_val */
  167283. s += state.last_dc_val[ci];
  167284. state.last_dc_val[ci] = s;
  167285. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  167286. (*block)[0] = (JCOEF) (s << Al);
  167287. }
  167288. /* Completed MCU, so update state */
  167289. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  167290. ASSIGN_STATE(entropy->saved, state);
  167291. }
  167292. /* Account for restart interval (no-op if not using restarts) */
  167293. entropy->restarts_to_go--;
  167294. return TRUE;
  167295. }
  167296. /*
  167297. * MCU decoding for AC initial scan (either spectral selection,
  167298. * or first pass of successive approximation).
  167299. */
  167300. METHODDEF(boolean)
  167301. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  167302. {
  167303. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  167304. int Se = cinfo->Se;
  167305. int Al = cinfo->Al;
  167306. register int s, k, r;
  167307. unsigned int EOBRUN;
  167308. JBLOCKROW block;
  167309. BITREAD_STATE_VARS;
  167310. d_derived_tbl * tbl;
  167311. /* Process restart marker if needed; may have to suspend */
  167312. if (cinfo->restart_interval) {
  167313. if (entropy->restarts_to_go == 0)
  167314. if (! process_restartp(cinfo))
  167315. return FALSE;
  167316. }
  167317. /* If we've run out of data, just leave the MCU set to zeroes.
  167318. * This way, we return uniform gray for the remainder of the segment.
  167319. */
  167320. if (! entropy->pub.insufficient_data) {
  167321. /* Load up working state.
  167322. * We can avoid loading/saving bitread state if in an EOB run.
  167323. */
  167324. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  167325. /* There is always only one block per MCU */
  167326. if (EOBRUN > 0) /* if it's a band of zeroes... */
  167327. EOBRUN--; /* ...process it now (we do nothing) */
  167328. else {
  167329. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  167330. block = MCU_data[0];
  167331. tbl = entropy->ac_derived_tbl;
  167332. for (k = cinfo->Ss; k <= Se; k++) {
  167333. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  167334. r = s >> 4;
  167335. s &= 15;
  167336. if (s) {
  167337. k += r;
  167338. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  167339. r = GET_BITS(s);
  167340. s = HUFF_EXTEND(r, s);
  167341. /* Scale and output coefficient in natural (dezigzagged) order */
  167342. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  167343. } else {
  167344. if (r == 15) { /* ZRL */
  167345. k += 15; /* skip 15 zeroes in band */
  167346. } else { /* EOBr, run length is 2^r + appended bits */
  167347. EOBRUN = 1 << r;
  167348. if (r) { /* EOBr, r > 0 */
  167349. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  167350. r = GET_BITS(r);
  167351. EOBRUN += r;
  167352. }
  167353. EOBRUN--; /* this band is processed at this moment */
  167354. break; /* force end-of-band */
  167355. }
  167356. }
  167357. }
  167358. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  167359. }
  167360. /* Completed MCU, so update state */
  167361. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  167362. }
  167363. /* Account for restart interval (no-op if not using restarts) */
  167364. entropy->restarts_to_go--;
  167365. return TRUE;
  167366. }
  167367. /*
  167368. * MCU decoding for DC successive approximation refinement scan.
  167369. * Note: we assume such scans can be multi-component, although the spec
  167370. * is not very clear on the point.
  167371. */
  167372. METHODDEF(boolean)
  167373. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  167374. {
  167375. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  167376. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  167377. int blkn;
  167378. JBLOCKROW block;
  167379. BITREAD_STATE_VARS;
  167380. /* Process restart marker if needed; may have to suspend */
  167381. if (cinfo->restart_interval) {
  167382. if (entropy->restarts_to_go == 0)
  167383. if (! process_restartp(cinfo))
  167384. return FALSE;
  167385. }
  167386. /* Not worth the cycles to check insufficient_data here,
  167387. * since we will not change the data anyway if we read zeroes.
  167388. */
  167389. /* Load up working state */
  167390. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  167391. /* Outer loop handles each block in the MCU */
  167392. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  167393. block = MCU_data[blkn];
  167394. /* Encoded data is simply the next bit of the two's-complement DC value */
  167395. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  167396. if (GET_BITS(1))
  167397. (*block)[0] |= p1;
  167398. /* Note: since we use |=, repeating the assignment later is safe */
  167399. }
  167400. /* Completed MCU, so update state */
  167401. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  167402. /* Account for restart interval (no-op if not using restarts) */
  167403. entropy->restarts_to_go--;
  167404. return TRUE;
  167405. }
  167406. /*
  167407. * MCU decoding for AC successive approximation refinement scan.
  167408. */
  167409. METHODDEF(boolean)
  167410. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  167411. {
  167412. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  167413. int Se = cinfo->Se;
  167414. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  167415. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  167416. register int s, k, r;
  167417. unsigned int EOBRUN;
  167418. JBLOCKROW block;
  167419. JCOEFPTR thiscoef;
  167420. BITREAD_STATE_VARS;
  167421. d_derived_tbl * tbl;
  167422. int num_newnz;
  167423. int newnz_pos[DCTSIZE2];
  167424. /* Process restart marker if needed; may have to suspend */
  167425. if (cinfo->restart_interval) {
  167426. if (entropy->restarts_to_go == 0)
  167427. if (! process_restartp(cinfo))
  167428. return FALSE;
  167429. }
  167430. /* If we've run out of data, don't modify the MCU.
  167431. */
  167432. if (! entropy->pub.insufficient_data) {
  167433. /* Load up working state */
  167434. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  167435. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  167436. /* There is always only one block per MCU */
  167437. block = MCU_data[0];
  167438. tbl = entropy->ac_derived_tbl;
  167439. /* If we are forced to suspend, we must undo the assignments to any newly
  167440. * nonzero coefficients in the block, because otherwise we'd get confused
  167441. * next time about which coefficients were already nonzero.
  167442. * But we need not undo addition of bits to already-nonzero coefficients;
  167443. * instead, we can test the current bit to see if we already did it.
  167444. */
  167445. num_newnz = 0;
  167446. /* initialize coefficient loop counter to start of band */
  167447. k = cinfo->Ss;
  167448. if (EOBRUN == 0) {
  167449. for (; k <= Se; k++) {
  167450. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  167451. r = s >> 4;
  167452. s &= 15;
  167453. if (s) {
  167454. if (s != 1) /* size of new coef should always be 1 */
  167455. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  167456. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  167457. if (GET_BITS(1))
  167458. s = p1; /* newly nonzero coef is positive */
  167459. else
  167460. s = m1; /* newly nonzero coef is negative */
  167461. } else {
  167462. if (r != 15) {
  167463. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  167464. if (r) {
  167465. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  167466. r = GET_BITS(r);
  167467. EOBRUN += r;
  167468. }
  167469. break; /* rest of block is handled by EOB logic */
  167470. }
  167471. /* note s = 0 for processing ZRL */
  167472. }
  167473. /* Advance over already-nonzero coefs and r still-zero coefs,
  167474. * appending correction bits to the nonzeroes. A correction bit is 1
  167475. * if the absolute value of the coefficient must be increased.
  167476. */
  167477. do {
  167478. thiscoef = *block + jpeg_natural_order[k];
  167479. if (*thiscoef != 0) {
  167480. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  167481. if (GET_BITS(1)) {
  167482. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  167483. if (*thiscoef >= 0)
  167484. *thiscoef += p1;
  167485. else
  167486. *thiscoef += m1;
  167487. }
  167488. }
  167489. } else {
  167490. if (--r < 0)
  167491. break; /* reached target zero coefficient */
  167492. }
  167493. k++;
  167494. } while (k <= Se);
  167495. if (s) {
  167496. int pos = jpeg_natural_order[k];
  167497. /* Output newly nonzero coefficient */
  167498. (*block)[pos] = (JCOEF) s;
  167499. /* Remember its position in case we have to suspend */
  167500. newnz_pos[num_newnz++] = pos;
  167501. }
  167502. }
  167503. }
  167504. if (EOBRUN > 0) {
  167505. /* Scan any remaining coefficient positions after the end-of-band
  167506. * (the last newly nonzero coefficient, if any). Append a correction
  167507. * bit to each already-nonzero coefficient. A correction bit is 1
  167508. * if the absolute value of the coefficient must be increased.
  167509. */
  167510. for (; k <= Se; k++) {
  167511. thiscoef = *block + jpeg_natural_order[k];
  167512. if (*thiscoef != 0) {
  167513. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  167514. if (GET_BITS(1)) {
  167515. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  167516. if (*thiscoef >= 0)
  167517. *thiscoef += p1;
  167518. else
  167519. *thiscoef += m1;
  167520. }
  167521. }
  167522. }
  167523. }
  167524. /* Count one block completed in EOB run */
  167525. EOBRUN--;
  167526. }
  167527. /* Completed MCU, so update state */
  167528. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  167529. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  167530. }
  167531. /* Account for restart interval (no-op if not using restarts) */
  167532. entropy->restarts_to_go--;
  167533. return TRUE;
  167534. undoit:
  167535. /* Re-zero any output coefficients that we made newly nonzero */
  167536. while (num_newnz > 0)
  167537. (*block)[newnz_pos[--num_newnz]] = 0;
  167538. return FALSE;
  167539. }
  167540. /*
  167541. * Module initialization routine for progressive Huffman entropy decoding.
  167542. */
  167543. GLOBAL(void)
  167544. jinit_phuff_decoder (j_decompress_ptr cinfo)
  167545. {
  167546. phuff_entropy_ptr2 entropy;
  167547. int *coef_bit_ptr;
  167548. int ci, i;
  167549. entropy = (phuff_entropy_ptr2)
  167550. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167551. SIZEOF(phuff_entropy_decoder));
  167552. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  167553. entropy->pub.start_pass = start_pass_phuff_decoder;
  167554. /* Mark derived tables unallocated */
  167555. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167556. entropy->derived_tbls[i] = NULL;
  167557. }
  167558. /* Create progression status table */
  167559. cinfo->coef_bits = (int (*)[DCTSIZE2])
  167560. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167561. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  167562. coef_bit_ptr = & cinfo->coef_bits[0][0];
  167563. for (ci = 0; ci < cinfo->num_components; ci++)
  167564. for (i = 0; i < DCTSIZE2; i++)
  167565. *coef_bit_ptr++ = -1;
  167566. }
  167567. #endif /* D_PROGRESSIVE_SUPPORTED */
  167568. /********* End of inlined file: jdphuff.c *********/
  167569. /********* Start of inlined file: jdpostct.c *********/
  167570. #define JPEG_INTERNALS
  167571. /* Private buffer controller object */
  167572. typedef struct {
  167573. struct jpeg_d_post_controller pub; /* public fields */
  167574. /* Color quantization source buffer: this holds output data from
  167575. * the upsample/color conversion step to be passed to the quantizer.
  167576. * For two-pass color quantization, we need a full-image buffer;
  167577. * for one-pass operation, a strip buffer is sufficient.
  167578. */
  167579. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  167580. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  167581. JDIMENSION strip_height; /* buffer size in rows */
  167582. /* for two-pass mode only: */
  167583. JDIMENSION starting_row; /* row # of first row in current strip */
  167584. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  167585. } my_post_controller;
  167586. typedef my_post_controller * my_post_ptr;
  167587. /* Forward declarations */
  167588. METHODDEF(void) post_process_1pass
  167589. JPP((j_decompress_ptr cinfo,
  167590. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167591. JDIMENSION in_row_groups_avail,
  167592. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167593. JDIMENSION out_rows_avail));
  167594. #ifdef QUANT_2PASS_SUPPORTED
  167595. METHODDEF(void) post_process_prepass
  167596. JPP((j_decompress_ptr cinfo,
  167597. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167598. JDIMENSION in_row_groups_avail,
  167599. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167600. JDIMENSION out_rows_avail));
  167601. METHODDEF(void) post_process_2pass
  167602. JPP((j_decompress_ptr cinfo,
  167603. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167604. JDIMENSION in_row_groups_avail,
  167605. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167606. JDIMENSION out_rows_avail));
  167607. #endif
  167608. /*
  167609. * Initialize for a processing pass.
  167610. */
  167611. METHODDEF(void)
  167612. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  167613. {
  167614. my_post_ptr post = (my_post_ptr) cinfo->post;
  167615. switch (pass_mode) {
  167616. case JBUF_PASS_THRU:
  167617. if (cinfo->quantize_colors) {
  167618. /* Single-pass processing with color quantization. */
  167619. post->pub.post_process_data = post_process_1pass;
  167620. /* We could be doing buffered-image output before starting a 2-pass
  167621. * color quantization; in that case, jinit_d_post_controller did not
  167622. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  167623. */
  167624. if (post->buffer == NULL) {
  167625. post->buffer = (*cinfo->mem->access_virt_sarray)
  167626. ((j_common_ptr) cinfo, post->whole_image,
  167627. (JDIMENSION) 0, post->strip_height, TRUE);
  167628. }
  167629. } else {
  167630. /* For single-pass processing without color quantization,
  167631. * I have no work to do; just call the upsampler directly.
  167632. */
  167633. post->pub.post_process_data = cinfo->upsample->upsample;
  167634. }
  167635. break;
  167636. #ifdef QUANT_2PASS_SUPPORTED
  167637. case JBUF_SAVE_AND_PASS:
  167638. /* First pass of 2-pass quantization */
  167639. if (post->whole_image == NULL)
  167640. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167641. post->pub.post_process_data = post_process_prepass;
  167642. break;
  167643. case JBUF_CRANK_DEST:
  167644. /* Second pass of 2-pass quantization */
  167645. if (post->whole_image == NULL)
  167646. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167647. post->pub.post_process_data = post_process_2pass;
  167648. break;
  167649. #endif /* QUANT_2PASS_SUPPORTED */
  167650. default:
  167651. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167652. break;
  167653. }
  167654. post->starting_row = post->next_row = 0;
  167655. }
  167656. /*
  167657. * Process some data in the one-pass (strip buffer) case.
  167658. * This is used for color precision reduction as well as one-pass quantization.
  167659. */
  167660. METHODDEF(void)
  167661. post_process_1pass (j_decompress_ptr cinfo,
  167662. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167663. JDIMENSION in_row_groups_avail,
  167664. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167665. JDIMENSION out_rows_avail)
  167666. {
  167667. my_post_ptr post = (my_post_ptr) cinfo->post;
  167668. JDIMENSION num_rows, max_rows;
  167669. /* Fill the buffer, but not more than what we can dump out in one go. */
  167670. /* Note we rely on the upsampler to detect bottom of image. */
  167671. max_rows = out_rows_avail - *out_row_ctr;
  167672. if (max_rows > post->strip_height)
  167673. max_rows = post->strip_height;
  167674. num_rows = 0;
  167675. (*cinfo->upsample->upsample) (cinfo,
  167676. input_buf, in_row_group_ctr, in_row_groups_avail,
  167677. post->buffer, &num_rows, max_rows);
  167678. /* Quantize and emit data. */
  167679. (*cinfo->cquantize->color_quantize) (cinfo,
  167680. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  167681. *out_row_ctr += num_rows;
  167682. }
  167683. #ifdef QUANT_2PASS_SUPPORTED
  167684. /*
  167685. * Process some data in the first pass of 2-pass quantization.
  167686. */
  167687. METHODDEF(void)
  167688. post_process_prepass (j_decompress_ptr cinfo,
  167689. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167690. JDIMENSION in_row_groups_avail,
  167691. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167692. JDIMENSION out_rows_avail)
  167693. {
  167694. my_post_ptr post = (my_post_ptr) cinfo->post;
  167695. JDIMENSION old_next_row, num_rows;
  167696. /* Reposition virtual buffer if at start of strip. */
  167697. if (post->next_row == 0) {
  167698. post->buffer = (*cinfo->mem->access_virt_sarray)
  167699. ((j_common_ptr) cinfo, post->whole_image,
  167700. post->starting_row, post->strip_height, TRUE);
  167701. }
  167702. /* Upsample some data (up to a strip height's worth). */
  167703. old_next_row = post->next_row;
  167704. (*cinfo->upsample->upsample) (cinfo,
  167705. input_buf, in_row_group_ctr, in_row_groups_avail,
  167706. post->buffer, &post->next_row, post->strip_height);
  167707. /* Allow quantizer to scan new data. No data is emitted, */
  167708. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  167709. if (post->next_row > old_next_row) {
  167710. num_rows = post->next_row - old_next_row;
  167711. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  167712. (JSAMPARRAY) NULL, (int) num_rows);
  167713. *out_row_ctr += num_rows;
  167714. }
  167715. /* Advance if we filled the strip. */
  167716. if (post->next_row >= post->strip_height) {
  167717. post->starting_row += post->strip_height;
  167718. post->next_row = 0;
  167719. }
  167720. }
  167721. /*
  167722. * Process some data in the second pass of 2-pass quantization.
  167723. */
  167724. METHODDEF(void)
  167725. post_process_2pass (j_decompress_ptr cinfo,
  167726. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167727. JDIMENSION in_row_groups_avail,
  167728. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167729. JDIMENSION out_rows_avail)
  167730. {
  167731. my_post_ptr post = (my_post_ptr) cinfo->post;
  167732. JDIMENSION num_rows, max_rows;
  167733. /* Reposition virtual buffer if at start of strip. */
  167734. if (post->next_row == 0) {
  167735. post->buffer = (*cinfo->mem->access_virt_sarray)
  167736. ((j_common_ptr) cinfo, post->whole_image,
  167737. post->starting_row, post->strip_height, FALSE);
  167738. }
  167739. /* Determine number of rows to emit. */
  167740. num_rows = post->strip_height - post->next_row; /* available in strip */
  167741. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  167742. if (num_rows > max_rows)
  167743. num_rows = max_rows;
  167744. /* We have to check bottom of image here, can't depend on upsampler. */
  167745. max_rows = cinfo->output_height - post->starting_row;
  167746. if (num_rows > max_rows)
  167747. num_rows = max_rows;
  167748. /* Quantize and emit data. */
  167749. (*cinfo->cquantize->color_quantize) (cinfo,
  167750. post->buffer + post->next_row, output_buf + *out_row_ctr,
  167751. (int) num_rows);
  167752. *out_row_ctr += num_rows;
  167753. /* Advance if we filled the strip. */
  167754. post->next_row += num_rows;
  167755. if (post->next_row >= post->strip_height) {
  167756. post->starting_row += post->strip_height;
  167757. post->next_row = 0;
  167758. }
  167759. }
  167760. #endif /* QUANT_2PASS_SUPPORTED */
  167761. /*
  167762. * Initialize postprocessing controller.
  167763. */
  167764. GLOBAL(void)
  167765. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  167766. {
  167767. my_post_ptr post;
  167768. post = (my_post_ptr)
  167769. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167770. SIZEOF(my_post_controller));
  167771. cinfo->post = (struct jpeg_d_post_controller *) post;
  167772. post->pub.start_pass = start_pass_dpost;
  167773. post->whole_image = NULL; /* flag for no virtual arrays */
  167774. post->buffer = NULL; /* flag for no strip buffer */
  167775. /* Create the quantization buffer, if needed */
  167776. if (cinfo->quantize_colors) {
  167777. /* The buffer strip height is max_v_samp_factor, which is typically
  167778. * an efficient number of rows for upsampling to return.
  167779. * (In the presence of output rescaling, we might want to be smarter?)
  167780. */
  167781. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  167782. if (need_full_buffer) {
  167783. /* Two-pass color quantization: need full-image storage. */
  167784. /* We round up the number of rows to a multiple of the strip height. */
  167785. #ifdef QUANT_2PASS_SUPPORTED
  167786. post->whole_image = (*cinfo->mem->request_virt_sarray)
  167787. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  167788. cinfo->output_width * cinfo->out_color_components,
  167789. (JDIMENSION) jround_up((long) cinfo->output_height,
  167790. (long) post->strip_height),
  167791. post->strip_height);
  167792. #else
  167793. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167794. #endif /* QUANT_2PASS_SUPPORTED */
  167795. } else {
  167796. /* One-pass color quantization: just make a strip buffer. */
  167797. post->buffer = (*cinfo->mem->alloc_sarray)
  167798. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167799. cinfo->output_width * cinfo->out_color_components,
  167800. post->strip_height);
  167801. }
  167802. }
  167803. }
  167804. /********* End of inlined file: jdpostct.c *********/
  167805. #undef FIX
  167806. /********* Start of inlined file: jdsample.c *********/
  167807. #define JPEG_INTERNALS
  167808. /* Pointer to routine to upsample a single component */
  167809. typedef JMETHOD(void, upsample1_ptr,
  167810. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167811. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  167812. /* Private subobject */
  167813. typedef struct {
  167814. struct jpeg_upsampler pub; /* public fields */
  167815. /* Color conversion buffer. When using separate upsampling and color
  167816. * conversion steps, this buffer holds one upsampled row group until it
  167817. * has been color converted and output.
  167818. * Note: we do not allocate any storage for component(s) which are full-size,
  167819. * ie do not need rescaling. The corresponding entry of color_buf[] is
  167820. * simply set to point to the input data array, thereby avoiding copying.
  167821. */
  167822. JSAMPARRAY color_buf[MAX_COMPONENTS];
  167823. /* Per-component upsampling method pointers */
  167824. upsample1_ptr methods[MAX_COMPONENTS];
  167825. int next_row_out; /* counts rows emitted from color_buf */
  167826. JDIMENSION rows_to_go; /* counts rows remaining in image */
  167827. /* Height of an input row group for each component. */
  167828. int rowgroup_height[MAX_COMPONENTS];
  167829. /* These arrays save pixel expansion factors so that int_expand need not
  167830. * recompute them each time. They are unused for other upsampling methods.
  167831. */
  167832. UINT8 h_expand[MAX_COMPONENTS];
  167833. UINT8 v_expand[MAX_COMPONENTS];
  167834. } my_upsampler2;
  167835. typedef my_upsampler2 * my_upsample_ptr2;
  167836. /*
  167837. * Initialize for an upsampling pass.
  167838. */
  167839. METHODDEF(void)
  167840. start_pass_upsample (j_decompress_ptr cinfo)
  167841. {
  167842. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  167843. /* Mark the conversion buffer empty */
  167844. upsample->next_row_out = cinfo->max_v_samp_factor;
  167845. /* Initialize total-height counter for detecting bottom of image */
  167846. upsample->rows_to_go = cinfo->output_height;
  167847. }
  167848. /*
  167849. * Control routine to do upsampling (and color conversion).
  167850. *
  167851. * In this version we upsample each component independently.
  167852. * We upsample one row group into the conversion buffer, then apply
  167853. * color conversion a row at a time.
  167854. */
  167855. METHODDEF(void)
  167856. sep_upsample (j_decompress_ptr cinfo,
  167857. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167858. JDIMENSION in_row_groups_avail,
  167859. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167860. JDIMENSION out_rows_avail)
  167861. {
  167862. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  167863. int ci;
  167864. jpeg_component_info * compptr;
  167865. JDIMENSION num_rows;
  167866. /* Fill the conversion buffer, if it's empty */
  167867. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  167868. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167869. ci++, compptr++) {
  167870. /* Invoke per-component upsample method. Notice we pass a POINTER
  167871. * to color_buf[ci], so that fullsize_upsample can change it.
  167872. */
  167873. (*upsample->methods[ci]) (cinfo, compptr,
  167874. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  167875. upsample->color_buf + ci);
  167876. }
  167877. upsample->next_row_out = 0;
  167878. }
  167879. /* Color-convert and emit rows */
  167880. /* How many we have in the buffer: */
  167881. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  167882. /* Not more than the distance to the end of the image. Need this test
  167883. * in case the image height is not a multiple of max_v_samp_factor:
  167884. */
  167885. if (num_rows > upsample->rows_to_go)
  167886. num_rows = upsample->rows_to_go;
  167887. /* And not more than what the client can accept: */
  167888. out_rows_avail -= *out_row_ctr;
  167889. if (num_rows > out_rows_avail)
  167890. num_rows = out_rows_avail;
  167891. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  167892. (JDIMENSION) upsample->next_row_out,
  167893. output_buf + *out_row_ctr,
  167894. (int) num_rows);
  167895. /* Adjust counts */
  167896. *out_row_ctr += num_rows;
  167897. upsample->rows_to_go -= num_rows;
  167898. upsample->next_row_out += num_rows;
  167899. /* When the buffer is emptied, declare this input row group consumed */
  167900. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  167901. (*in_row_group_ctr)++;
  167902. }
  167903. /*
  167904. * These are the routines invoked by sep_upsample to upsample pixel values
  167905. * of a single component. One row group is processed per call.
  167906. */
  167907. /*
  167908. * For full-size components, we just make color_buf[ci] point at the
  167909. * input buffer, and thus avoid copying any data. Note that this is
  167910. * safe only because sep_upsample doesn't declare the input row group
  167911. * "consumed" until we are done color converting and emitting it.
  167912. */
  167913. METHODDEF(void)
  167914. fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167915. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167916. {
  167917. *output_data_ptr = input_data;
  167918. }
  167919. /*
  167920. * This is a no-op version used for "uninteresting" components.
  167921. * These components will not be referenced by color conversion.
  167922. */
  167923. METHODDEF(void)
  167924. noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167925. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167926. {
  167927. *output_data_ptr = NULL; /* safety check */
  167928. }
  167929. /*
  167930. * This version handles any integral sampling ratios.
  167931. * This is not used for typical JPEG files, so it need not be fast.
  167932. * Nor, for that matter, is it particularly accurate: the algorithm is
  167933. * simple replication of the input pixel onto the corresponding output
  167934. * pixels. The hi-falutin sampling literature refers to this as a
  167935. * "box filter". A box filter tends to introduce visible artifacts,
  167936. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  167937. * you would be well advised to improve this code.
  167938. */
  167939. METHODDEF(void)
  167940. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167941. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167942. {
  167943. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  167944. JSAMPARRAY output_data = *output_data_ptr;
  167945. register JSAMPROW inptr, outptr;
  167946. register JSAMPLE invalue;
  167947. register int h;
  167948. JSAMPROW outend;
  167949. int h_expand, v_expand;
  167950. int inrow, outrow;
  167951. h_expand = upsample->h_expand[compptr->component_index];
  167952. v_expand = upsample->v_expand[compptr->component_index];
  167953. inrow = outrow = 0;
  167954. while (outrow < cinfo->max_v_samp_factor) {
  167955. /* Generate one output row with proper horizontal expansion */
  167956. inptr = input_data[inrow];
  167957. outptr = output_data[outrow];
  167958. outend = outptr + cinfo->output_width;
  167959. while (outptr < outend) {
  167960. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  167961. for (h = h_expand; h > 0; h--) {
  167962. *outptr++ = invalue;
  167963. }
  167964. }
  167965. /* Generate any additional output rows by duplicating the first one */
  167966. if (v_expand > 1) {
  167967. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  167968. v_expand-1, cinfo->output_width);
  167969. }
  167970. inrow++;
  167971. outrow += v_expand;
  167972. }
  167973. }
  167974. /*
  167975. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  167976. * It's still a box filter.
  167977. */
  167978. METHODDEF(void)
  167979. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167980. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167981. {
  167982. JSAMPARRAY output_data = *output_data_ptr;
  167983. register JSAMPROW inptr, outptr;
  167984. register JSAMPLE invalue;
  167985. JSAMPROW outend;
  167986. int inrow;
  167987. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  167988. inptr = input_data[inrow];
  167989. outptr = output_data[inrow];
  167990. outend = outptr + cinfo->output_width;
  167991. while (outptr < outend) {
  167992. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  167993. *outptr++ = invalue;
  167994. *outptr++ = invalue;
  167995. }
  167996. }
  167997. }
  167998. /*
  167999. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  168000. * It's still a box filter.
  168001. */
  168002. METHODDEF(void)
  168003. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168004. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168005. {
  168006. JSAMPARRAY output_data = *output_data_ptr;
  168007. register JSAMPROW inptr, outptr;
  168008. register JSAMPLE invalue;
  168009. JSAMPROW outend;
  168010. int inrow, outrow;
  168011. inrow = outrow = 0;
  168012. while (outrow < cinfo->max_v_samp_factor) {
  168013. inptr = input_data[inrow];
  168014. outptr = output_data[outrow];
  168015. outend = outptr + cinfo->output_width;
  168016. while (outptr < outend) {
  168017. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  168018. *outptr++ = invalue;
  168019. *outptr++ = invalue;
  168020. }
  168021. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  168022. 1, cinfo->output_width);
  168023. inrow++;
  168024. outrow += 2;
  168025. }
  168026. }
  168027. /*
  168028. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  168029. *
  168030. * The upsampling algorithm is linear interpolation between pixel centers,
  168031. * also known as a "triangle filter". This is a good compromise between
  168032. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  168033. * of the way between input pixel centers.
  168034. *
  168035. * A note about the "bias" calculations: when rounding fractional values to
  168036. * integer, we do not want to always round 0.5 up to the next integer.
  168037. * If we did that, we'd introduce a noticeable bias towards larger values.
  168038. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  168039. * alternate pixel locations (a simple ordered dither pattern).
  168040. */
  168041. METHODDEF(void)
  168042. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168043. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168044. {
  168045. JSAMPARRAY output_data = *output_data_ptr;
  168046. register JSAMPROW inptr, outptr;
  168047. register int invalue;
  168048. register JDIMENSION colctr;
  168049. int inrow;
  168050. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  168051. inptr = input_data[inrow];
  168052. outptr = output_data[inrow];
  168053. /* Special case for first column */
  168054. invalue = GETJSAMPLE(*inptr++);
  168055. *outptr++ = (JSAMPLE) invalue;
  168056. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  168057. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  168058. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  168059. invalue = GETJSAMPLE(*inptr++) * 3;
  168060. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  168061. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  168062. }
  168063. /* Special case for last column */
  168064. invalue = GETJSAMPLE(*inptr);
  168065. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  168066. *outptr++ = (JSAMPLE) invalue;
  168067. }
  168068. }
  168069. /*
  168070. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  168071. * Again a triangle filter; see comments for h2v1 case, above.
  168072. *
  168073. * It is OK for us to reference the adjacent input rows because we demanded
  168074. * context from the main buffer controller (see initialization code).
  168075. */
  168076. METHODDEF(void)
  168077. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168078. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168079. {
  168080. JSAMPARRAY output_data = *output_data_ptr;
  168081. register JSAMPROW inptr0, inptr1, outptr;
  168082. #if BITS_IN_JSAMPLE == 8
  168083. register int thiscolsum, lastcolsum, nextcolsum;
  168084. #else
  168085. register INT32 thiscolsum, lastcolsum, nextcolsum;
  168086. #endif
  168087. register JDIMENSION colctr;
  168088. int inrow, outrow, v;
  168089. inrow = outrow = 0;
  168090. while (outrow < cinfo->max_v_samp_factor) {
  168091. for (v = 0; v < 2; v++) {
  168092. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  168093. inptr0 = input_data[inrow];
  168094. if (v == 0) /* next nearest is row above */
  168095. inptr1 = input_data[inrow-1];
  168096. else /* next nearest is row below */
  168097. inptr1 = input_data[inrow+1];
  168098. outptr = output_data[outrow++];
  168099. /* Special case for first column */
  168100. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  168101. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  168102. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  168103. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  168104. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  168105. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  168106. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  168107. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  168108. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  168109. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  168110. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  168111. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  168112. }
  168113. /* Special case for last column */
  168114. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  168115. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  168116. }
  168117. inrow++;
  168118. }
  168119. }
  168120. /*
  168121. * Module initialization routine for upsampling.
  168122. */
  168123. GLOBAL(void)
  168124. jinit_upsampler (j_decompress_ptr cinfo)
  168125. {
  168126. my_upsample_ptr2 upsample;
  168127. int ci;
  168128. jpeg_component_info * compptr;
  168129. boolean need_buffer, do_fancy;
  168130. int h_in_group, v_in_group, h_out_group, v_out_group;
  168131. upsample = (my_upsample_ptr2)
  168132. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168133. SIZEOF(my_upsampler2));
  168134. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  168135. upsample->pub.start_pass = start_pass_upsample;
  168136. upsample->pub.upsample = sep_upsample;
  168137. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  168138. if (cinfo->CCIR601_sampling) /* this isn't supported */
  168139. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  168140. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  168141. * so don't ask for it.
  168142. */
  168143. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  168144. /* Verify we can handle the sampling factors, select per-component methods,
  168145. * and create storage as needed.
  168146. */
  168147. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168148. ci++, compptr++) {
  168149. /* Compute size of an "input group" after IDCT scaling. This many samples
  168150. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  168151. */
  168152. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  168153. cinfo->min_DCT_scaled_size;
  168154. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  168155. cinfo->min_DCT_scaled_size;
  168156. h_out_group = cinfo->max_h_samp_factor;
  168157. v_out_group = cinfo->max_v_samp_factor;
  168158. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  168159. need_buffer = TRUE;
  168160. if (! compptr->component_needed) {
  168161. /* Don't bother to upsample an uninteresting component. */
  168162. upsample->methods[ci] = noop_upsample;
  168163. need_buffer = FALSE;
  168164. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  168165. /* Fullsize components can be processed without any work. */
  168166. upsample->methods[ci] = fullsize_upsample;
  168167. need_buffer = FALSE;
  168168. } else if (h_in_group * 2 == h_out_group &&
  168169. v_in_group == v_out_group) {
  168170. /* Special cases for 2h1v upsampling */
  168171. if (do_fancy && compptr->downsampled_width > 2)
  168172. upsample->methods[ci] = h2v1_fancy_upsample;
  168173. else
  168174. upsample->methods[ci] = h2v1_upsample;
  168175. } else if (h_in_group * 2 == h_out_group &&
  168176. v_in_group * 2 == v_out_group) {
  168177. /* Special cases for 2h2v upsampling */
  168178. if (do_fancy && compptr->downsampled_width > 2) {
  168179. upsample->methods[ci] = h2v2_fancy_upsample;
  168180. upsample->pub.need_context_rows = TRUE;
  168181. } else
  168182. upsample->methods[ci] = h2v2_upsample;
  168183. } else if ((h_out_group % h_in_group) == 0 &&
  168184. (v_out_group % v_in_group) == 0) {
  168185. /* Generic integral-factors upsampling method */
  168186. upsample->methods[ci] = int_upsample;
  168187. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  168188. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  168189. } else
  168190. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  168191. if (need_buffer) {
  168192. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  168193. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168194. (JDIMENSION) jround_up((long) cinfo->output_width,
  168195. (long) cinfo->max_h_samp_factor),
  168196. (JDIMENSION) cinfo->max_v_samp_factor);
  168197. }
  168198. }
  168199. }
  168200. /********* End of inlined file: jdsample.c *********/
  168201. /********* Start of inlined file: jdtrans.c *********/
  168202. #define JPEG_INTERNALS
  168203. /* Forward declarations */
  168204. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  168205. /*
  168206. * Read the coefficient arrays from a JPEG file.
  168207. * jpeg_read_header must be completed before calling this.
  168208. *
  168209. * The entire image is read into a set of virtual coefficient-block arrays,
  168210. * one per component. The return value is a pointer to the array of
  168211. * virtual-array descriptors. These can be manipulated directly via the
  168212. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  168213. * To release the memory occupied by the virtual arrays, call
  168214. * jpeg_finish_decompress() when done with the data.
  168215. *
  168216. * An alternative usage is to simply obtain access to the coefficient arrays
  168217. * during a buffered-image-mode decompression operation. This is allowed
  168218. * after any jpeg_finish_output() call. The arrays can be accessed until
  168219. * jpeg_finish_decompress() is called. (Note that any call to the library
  168220. * may reposition the arrays, so don't rely on access_virt_barray() results
  168221. * to stay valid across library calls.)
  168222. *
  168223. * Returns NULL if suspended. This case need be checked only if
  168224. * a suspending data source is used.
  168225. */
  168226. GLOBAL(jvirt_barray_ptr *)
  168227. jpeg_read_coefficients (j_decompress_ptr cinfo)
  168228. {
  168229. if (cinfo->global_state == DSTATE_READY) {
  168230. /* First call: initialize active modules */
  168231. transdecode_master_selection(cinfo);
  168232. cinfo->global_state = DSTATE_RDCOEFS;
  168233. }
  168234. if (cinfo->global_state == DSTATE_RDCOEFS) {
  168235. /* Absorb whole file into the coef buffer */
  168236. for (;;) {
  168237. int retcode;
  168238. /* Call progress monitor hook if present */
  168239. if (cinfo->progress != NULL)
  168240. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  168241. /* Absorb some more input */
  168242. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168243. if (retcode == JPEG_SUSPENDED)
  168244. return NULL;
  168245. if (retcode == JPEG_REACHED_EOI)
  168246. break;
  168247. /* Advance progress counter if appropriate */
  168248. if (cinfo->progress != NULL &&
  168249. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  168250. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  168251. /* startup underestimated number of scans; ratchet up one scan */
  168252. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  168253. }
  168254. }
  168255. }
  168256. /* Set state so that jpeg_finish_decompress does the right thing */
  168257. cinfo->global_state = DSTATE_STOPPING;
  168258. }
  168259. /* At this point we should be in state DSTATE_STOPPING if being used
  168260. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  168261. * to the coefficients during a full buffered-image-mode decompression.
  168262. */
  168263. if ((cinfo->global_state == DSTATE_STOPPING ||
  168264. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  168265. return cinfo->coef->coef_arrays;
  168266. }
  168267. /* Oops, improper usage */
  168268. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168269. return NULL; /* keep compiler happy */
  168270. }
  168271. /*
  168272. * Master selection of decompression modules for transcoding.
  168273. * This substitutes for jdmaster.c's initialization of the full decompressor.
  168274. */
  168275. LOCAL(void)
  168276. transdecode_master_selection (j_decompress_ptr cinfo)
  168277. {
  168278. /* This is effectively a buffered-image operation. */
  168279. cinfo->buffered_image = TRUE;
  168280. /* Entropy decoding: either Huffman or arithmetic coding. */
  168281. if (cinfo->arith_code) {
  168282. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  168283. } else {
  168284. if (cinfo->progressive_mode) {
  168285. #ifdef D_PROGRESSIVE_SUPPORTED
  168286. jinit_phuff_decoder(cinfo);
  168287. #else
  168288. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168289. #endif
  168290. } else
  168291. jinit_huff_decoder(cinfo);
  168292. }
  168293. /* Always get a full-image coefficient buffer. */
  168294. jinit_d_coef_controller(cinfo, TRUE);
  168295. /* We can now tell the memory manager to allocate virtual arrays. */
  168296. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  168297. /* Initialize input side of decompressor to consume first scan. */
  168298. (*cinfo->inputctl->start_input_pass) (cinfo);
  168299. /* Initialize progress monitoring. */
  168300. if (cinfo->progress != NULL) {
  168301. int nscans;
  168302. /* Estimate number of scans to set pass_limit. */
  168303. if (cinfo->progressive_mode) {
  168304. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  168305. nscans = 2 + 3 * cinfo->num_components;
  168306. } else if (cinfo->inputctl->has_multiple_scans) {
  168307. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  168308. nscans = cinfo->num_components;
  168309. } else {
  168310. nscans = 1;
  168311. }
  168312. cinfo->progress->pass_counter = 0L;
  168313. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  168314. cinfo->progress->completed_passes = 0;
  168315. cinfo->progress->total_passes = 1;
  168316. }
  168317. }
  168318. /********* End of inlined file: jdtrans.c *********/
  168319. /********* Start of inlined file: jfdctflt.c *********/
  168320. #define JPEG_INTERNALS
  168321. #ifdef DCT_FLOAT_SUPPORTED
  168322. /*
  168323. * This module is specialized to the case DCTSIZE = 8.
  168324. */
  168325. #if DCTSIZE != 8
  168326. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168327. #endif
  168328. /*
  168329. * Perform the forward DCT on one block of samples.
  168330. */
  168331. GLOBAL(void)
  168332. jpeg_fdct_float (FAST_FLOAT * data)
  168333. {
  168334. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  168335. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  168336. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  168337. FAST_FLOAT *dataptr;
  168338. int ctr;
  168339. /* Pass 1: process rows. */
  168340. dataptr = data;
  168341. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168342. tmp0 = dataptr[0] + dataptr[7];
  168343. tmp7 = dataptr[0] - dataptr[7];
  168344. tmp1 = dataptr[1] + dataptr[6];
  168345. tmp6 = dataptr[1] - dataptr[6];
  168346. tmp2 = dataptr[2] + dataptr[5];
  168347. tmp5 = dataptr[2] - dataptr[5];
  168348. tmp3 = dataptr[3] + dataptr[4];
  168349. tmp4 = dataptr[3] - dataptr[4];
  168350. /* Even part */
  168351. tmp10 = tmp0 + tmp3; /* phase 2 */
  168352. tmp13 = tmp0 - tmp3;
  168353. tmp11 = tmp1 + tmp2;
  168354. tmp12 = tmp1 - tmp2;
  168355. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  168356. dataptr[4] = tmp10 - tmp11;
  168357. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  168358. dataptr[2] = tmp13 + z1; /* phase 5 */
  168359. dataptr[6] = tmp13 - z1;
  168360. /* Odd part */
  168361. tmp10 = tmp4 + tmp5; /* phase 2 */
  168362. tmp11 = tmp5 + tmp6;
  168363. tmp12 = tmp6 + tmp7;
  168364. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  168365. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  168366. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  168367. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  168368. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  168369. z11 = tmp7 + z3; /* phase 5 */
  168370. z13 = tmp7 - z3;
  168371. dataptr[5] = z13 + z2; /* phase 6 */
  168372. dataptr[3] = z13 - z2;
  168373. dataptr[1] = z11 + z4;
  168374. dataptr[7] = z11 - z4;
  168375. dataptr += DCTSIZE; /* advance pointer to next row */
  168376. }
  168377. /* Pass 2: process columns. */
  168378. dataptr = data;
  168379. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168380. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  168381. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  168382. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  168383. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  168384. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  168385. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  168386. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  168387. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  168388. /* Even part */
  168389. tmp10 = tmp0 + tmp3; /* phase 2 */
  168390. tmp13 = tmp0 - tmp3;
  168391. tmp11 = tmp1 + tmp2;
  168392. tmp12 = tmp1 - tmp2;
  168393. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  168394. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  168395. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  168396. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  168397. dataptr[DCTSIZE*6] = tmp13 - z1;
  168398. /* Odd part */
  168399. tmp10 = tmp4 + tmp5; /* phase 2 */
  168400. tmp11 = tmp5 + tmp6;
  168401. tmp12 = tmp6 + tmp7;
  168402. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  168403. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  168404. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  168405. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  168406. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  168407. z11 = tmp7 + z3; /* phase 5 */
  168408. z13 = tmp7 - z3;
  168409. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  168410. dataptr[DCTSIZE*3] = z13 - z2;
  168411. dataptr[DCTSIZE*1] = z11 + z4;
  168412. dataptr[DCTSIZE*7] = z11 - z4;
  168413. dataptr++; /* advance pointer to next column */
  168414. }
  168415. }
  168416. #endif /* DCT_FLOAT_SUPPORTED */
  168417. /********* End of inlined file: jfdctflt.c *********/
  168418. /********* Start of inlined file: jfdctint.c *********/
  168419. #define JPEG_INTERNALS
  168420. #ifdef DCT_ISLOW_SUPPORTED
  168421. /*
  168422. * This module is specialized to the case DCTSIZE = 8.
  168423. */
  168424. #if DCTSIZE != 8
  168425. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168426. #endif
  168427. /*
  168428. * The poop on this scaling stuff is as follows:
  168429. *
  168430. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  168431. * larger than the true DCT outputs. The final outputs are therefore
  168432. * a factor of N larger than desired; since N=8 this can be cured by
  168433. * a simple right shift at the end of the algorithm. The advantage of
  168434. * this arrangement is that we save two multiplications per 1-D DCT,
  168435. * because the y0 and y4 outputs need not be divided by sqrt(N).
  168436. * In the IJG code, this factor of 8 is removed by the quantization step
  168437. * (in jcdctmgr.c), NOT in this module.
  168438. *
  168439. * We have to do addition and subtraction of the integer inputs, which
  168440. * is no problem, and multiplication by fractional constants, which is
  168441. * a problem to do in integer arithmetic. We multiply all the constants
  168442. * by CONST_SCALE and convert them to integer constants (thus retaining
  168443. * CONST_BITS bits of precision in the constants). After doing a
  168444. * multiplication we have to divide the product by CONST_SCALE, with proper
  168445. * rounding, to produce the correct output. This division can be done
  168446. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  168447. * as long as possible so that partial sums can be added together with
  168448. * full fractional precision.
  168449. *
  168450. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  168451. * they are represented to better-than-integral precision. These outputs
  168452. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  168453. * with the recommended scaling. (For 12-bit sample data, the intermediate
  168454. * array is INT32 anyway.)
  168455. *
  168456. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  168457. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  168458. * shows that the values given below are the most effective.
  168459. */
  168460. #if BITS_IN_JSAMPLE == 8
  168461. #define CONST_BITS 13
  168462. #define PASS1_BITS 2
  168463. #else
  168464. #define CONST_BITS 13
  168465. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  168466. #endif
  168467. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  168468. * causing a lot of useless floating-point operations at run time.
  168469. * To get around this we use the following pre-calculated constants.
  168470. * If you change CONST_BITS you may want to add appropriate values.
  168471. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  168472. */
  168473. #if CONST_BITS == 13
  168474. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  168475. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  168476. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  168477. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  168478. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  168479. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  168480. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  168481. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  168482. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  168483. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  168484. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  168485. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  168486. #else
  168487. #define FIX_0_298631336 FIX(0.298631336)
  168488. #define FIX_0_390180644 FIX(0.390180644)
  168489. #define FIX_0_541196100 FIX(0.541196100)
  168490. #define FIX_0_765366865 FIX(0.765366865)
  168491. #define FIX_0_899976223 FIX(0.899976223)
  168492. #define FIX_1_175875602 FIX(1.175875602)
  168493. #define FIX_1_501321110 FIX(1.501321110)
  168494. #define FIX_1_847759065 FIX(1.847759065)
  168495. #define FIX_1_961570560 FIX(1.961570560)
  168496. #define FIX_2_053119869 FIX(2.053119869)
  168497. #define FIX_2_562915447 FIX(2.562915447)
  168498. #define FIX_3_072711026 FIX(3.072711026)
  168499. #endif
  168500. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  168501. * For 8-bit samples with the recommended scaling, all the variable
  168502. * and constant values involved are no more than 16 bits wide, so a
  168503. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  168504. * For 12-bit samples, a full 32-bit multiplication will be needed.
  168505. */
  168506. #if BITS_IN_JSAMPLE == 8
  168507. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  168508. #else
  168509. #define MULTIPLY(var,const) ((var) * (const))
  168510. #endif
  168511. /*
  168512. * Perform the forward DCT on one block of samples.
  168513. */
  168514. GLOBAL(void)
  168515. jpeg_fdct_islow (DCTELEM * data)
  168516. {
  168517. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  168518. INT32 tmp10, tmp11, tmp12, tmp13;
  168519. INT32 z1, z2, z3, z4, z5;
  168520. DCTELEM *dataptr;
  168521. int ctr;
  168522. SHIFT_TEMPS
  168523. /* Pass 1: process rows. */
  168524. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  168525. /* furthermore, we scale the results by 2**PASS1_BITS. */
  168526. dataptr = data;
  168527. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168528. tmp0 = dataptr[0] + dataptr[7];
  168529. tmp7 = dataptr[0] - dataptr[7];
  168530. tmp1 = dataptr[1] + dataptr[6];
  168531. tmp6 = dataptr[1] - dataptr[6];
  168532. tmp2 = dataptr[2] + dataptr[5];
  168533. tmp5 = dataptr[2] - dataptr[5];
  168534. tmp3 = dataptr[3] + dataptr[4];
  168535. tmp4 = dataptr[3] - dataptr[4];
  168536. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  168537. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  168538. */
  168539. tmp10 = tmp0 + tmp3;
  168540. tmp13 = tmp0 - tmp3;
  168541. tmp11 = tmp1 + tmp2;
  168542. tmp12 = tmp1 - tmp2;
  168543. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  168544. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  168545. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  168546. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  168547. CONST_BITS-PASS1_BITS);
  168548. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  168549. CONST_BITS-PASS1_BITS);
  168550. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  168551. * cK represents cos(K*pi/16).
  168552. * i0..i3 in the paper are tmp4..tmp7 here.
  168553. */
  168554. z1 = tmp4 + tmp7;
  168555. z2 = tmp5 + tmp6;
  168556. z3 = tmp4 + tmp6;
  168557. z4 = tmp5 + tmp7;
  168558. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  168559. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  168560. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  168561. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  168562. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  168563. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  168564. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  168565. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  168566. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  168567. z3 += z5;
  168568. z4 += z5;
  168569. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  168570. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  168571. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  168572. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  168573. dataptr += DCTSIZE; /* advance pointer to next row */
  168574. }
  168575. /* Pass 2: process columns.
  168576. * We remove the PASS1_BITS scaling, but leave the results scaled up
  168577. * by an overall factor of 8.
  168578. */
  168579. dataptr = data;
  168580. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168581. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  168582. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  168583. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  168584. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  168585. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  168586. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  168587. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  168588. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  168589. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  168590. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  168591. */
  168592. tmp10 = tmp0 + tmp3;
  168593. tmp13 = tmp0 - tmp3;
  168594. tmp11 = tmp1 + tmp2;
  168595. tmp12 = tmp1 - tmp2;
  168596. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  168597. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  168598. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  168599. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  168600. CONST_BITS+PASS1_BITS);
  168601. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  168602. CONST_BITS+PASS1_BITS);
  168603. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  168604. * cK represents cos(K*pi/16).
  168605. * i0..i3 in the paper are tmp4..tmp7 here.
  168606. */
  168607. z1 = tmp4 + tmp7;
  168608. z2 = tmp5 + tmp6;
  168609. z3 = tmp4 + tmp6;
  168610. z4 = tmp5 + tmp7;
  168611. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  168612. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  168613. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  168614. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  168615. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  168616. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  168617. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  168618. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  168619. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  168620. z3 += z5;
  168621. z4 += z5;
  168622. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  168623. CONST_BITS+PASS1_BITS);
  168624. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  168625. CONST_BITS+PASS1_BITS);
  168626. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  168627. CONST_BITS+PASS1_BITS);
  168628. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  168629. CONST_BITS+PASS1_BITS);
  168630. dataptr++; /* advance pointer to next column */
  168631. }
  168632. }
  168633. #endif /* DCT_ISLOW_SUPPORTED */
  168634. /********* End of inlined file: jfdctint.c *********/
  168635. #undef CONST_BITS
  168636. #undef MULTIPLY
  168637. #undef FIX_0_541196100
  168638. /********* Start of inlined file: jfdctfst.c *********/
  168639. #define JPEG_INTERNALS
  168640. #ifdef DCT_IFAST_SUPPORTED
  168641. /*
  168642. * This module is specialized to the case DCTSIZE = 8.
  168643. */
  168644. #if DCTSIZE != 8
  168645. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168646. #endif
  168647. /* Scaling decisions are generally the same as in the LL&M algorithm;
  168648. * see jfdctint.c for more details. However, we choose to descale
  168649. * (right shift) multiplication products as soon as they are formed,
  168650. * rather than carrying additional fractional bits into subsequent additions.
  168651. * This compromises accuracy slightly, but it lets us save a few shifts.
  168652. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  168653. * everywhere except in the multiplications proper; this saves a good deal
  168654. * of work on 16-bit-int machines.
  168655. *
  168656. * Again to save a few shifts, the intermediate results between pass 1 and
  168657. * pass 2 are not upscaled, but are represented only to integral precision.
  168658. *
  168659. * A final compromise is to represent the multiplicative constants to only
  168660. * 8 fractional bits, rather than 13. This saves some shifting work on some
  168661. * machines, and may also reduce the cost of multiplication (since there
  168662. * are fewer one-bits in the constants).
  168663. */
  168664. #define CONST_BITS 8
  168665. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  168666. * causing a lot of useless floating-point operations at run time.
  168667. * To get around this we use the following pre-calculated constants.
  168668. * If you change CONST_BITS you may want to add appropriate values.
  168669. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  168670. */
  168671. #if CONST_BITS == 8
  168672. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  168673. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  168674. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  168675. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  168676. #else
  168677. #define FIX_0_382683433 FIX(0.382683433)
  168678. #define FIX_0_541196100 FIX(0.541196100)
  168679. #define FIX_0_707106781 FIX(0.707106781)
  168680. #define FIX_1_306562965 FIX(1.306562965)
  168681. #endif
  168682. /* We can gain a little more speed, with a further compromise in accuracy,
  168683. * by omitting the addition in a descaling shift. This yields an incorrectly
  168684. * rounded result half the time...
  168685. */
  168686. #ifndef USE_ACCURATE_ROUNDING
  168687. #undef DESCALE
  168688. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  168689. #endif
  168690. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  168691. * descale to yield a DCTELEM result.
  168692. */
  168693. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  168694. /*
  168695. * Perform the forward DCT on one block of samples.
  168696. */
  168697. GLOBAL(void)
  168698. jpeg_fdct_ifast (DCTELEM * data)
  168699. {
  168700. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  168701. DCTELEM tmp10, tmp11, tmp12, tmp13;
  168702. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  168703. DCTELEM *dataptr;
  168704. int ctr;
  168705. SHIFT_TEMPS
  168706. /* Pass 1: process rows. */
  168707. dataptr = data;
  168708. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168709. tmp0 = dataptr[0] + dataptr[7];
  168710. tmp7 = dataptr[0] - dataptr[7];
  168711. tmp1 = dataptr[1] + dataptr[6];
  168712. tmp6 = dataptr[1] - dataptr[6];
  168713. tmp2 = dataptr[2] + dataptr[5];
  168714. tmp5 = dataptr[2] - dataptr[5];
  168715. tmp3 = dataptr[3] + dataptr[4];
  168716. tmp4 = dataptr[3] - dataptr[4];
  168717. /* Even part */
  168718. tmp10 = tmp0 + tmp3; /* phase 2 */
  168719. tmp13 = tmp0 - tmp3;
  168720. tmp11 = tmp1 + tmp2;
  168721. tmp12 = tmp1 - tmp2;
  168722. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  168723. dataptr[4] = tmp10 - tmp11;
  168724. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  168725. dataptr[2] = tmp13 + z1; /* phase 5 */
  168726. dataptr[6] = tmp13 - z1;
  168727. /* Odd part */
  168728. tmp10 = tmp4 + tmp5; /* phase 2 */
  168729. tmp11 = tmp5 + tmp6;
  168730. tmp12 = tmp6 + tmp7;
  168731. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  168732. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  168733. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  168734. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  168735. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  168736. z11 = tmp7 + z3; /* phase 5 */
  168737. z13 = tmp7 - z3;
  168738. dataptr[5] = z13 + z2; /* phase 6 */
  168739. dataptr[3] = z13 - z2;
  168740. dataptr[1] = z11 + z4;
  168741. dataptr[7] = z11 - z4;
  168742. dataptr += DCTSIZE; /* advance pointer to next row */
  168743. }
  168744. /* Pass 2: process columns. */
  168745. dataptr = data;
  168746. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168747. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  168748. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  168749. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  168750. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  168751. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  168752. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  168753. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  168754. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  168755. /* Even part */
  168756. tmp10 = tmp0 + tmp3; /* phase 2 */
  168757. tmp13 = tmp0 - tmp3;
  168758. tmp11 = tmp1 + tmp2;
  168759. tmp12 = tmp1 - tmp2;
  168760. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  168761. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  168762. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  168763. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  168764. dataptr[DCTSIZE*6] = tmp13 - z1;
  168765. /* Odd part */
  168766. tmp10 = tmp4 + tmp5; /* phase 2 */
  168767. tmp11 = tmp5 + tmp6;
  168768. tmp12 = tmp6 + tmp7;
  168769. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  168770. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  168771. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  168772. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  168773. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  168774. z11 = tmp7 + z3; /* phase 5 */
  168775. z13 = tmp7 - z3;
  168776. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  168777. dataptr[DCTSIZE*3] = z13 - z2;
  168778. dataptr[DCTSIZE*1] = z11 + z4;
  168779. dataptr[DCTSIZE*7] = z11 - z4;
  168780. dataptr++; /* advance pointer to next column */
  168781. }
  168782. }
  168783. #endif /* DCT_IFAST_SUPPORTED */
  168784. /********* End of inlined file: jfdctfst.c *********/
  168785. #undef FIX_0_541196100
  168786. /********* Start of inlined file: jidctflt.c *********/
  168787. #define JPEG_INTERNALS
  168788. #ifdef DCT_FLOAT_SUPPORTED
  168789. /*
  168790. * This module is specialized to the case DCTSIZE = 8.
  168791. */
  168792. #if DCTSIZE != 8
  168793. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168794. #endif
  168795. /* Dequantize a coefficient by multiplying it by the multiplier-table
  168796. * entry; produce a float result.
  168797. */
  168798. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  168799. /*
  168800. * Perform dequantization and inverse DCT on one block of coefficients.
  168801. */
  168802. GLOBAL(void)
  168803. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168804. JCOEFPTR coef_block,
  168805. JSAMPARRAY output_buf, JDIMENSION output_col)
  168806. {
  168807. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  168808. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  168809. FAST_FLOAT z5, z10, z11, z12, z13;
  168810. JCOEFPTR inptr;
  168811. FLOAT_MULT_TYPE * quantptr;
  168812. FAST_FLOAT * wsptr;
  168813. JSAMPROW outptr;
  168814. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  168815. int ctr;
  168816. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  168817. SHIFT_TEMPS
  168818. /* Pass 1: process columns from input, store into work array. */
  168819. inptr = coef_block;
  168820. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  168821. wsptr = workspace;
  168822. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  168823. /* Due to quantization, we will usually find that many of the input
  168824. * coefficients are zero, especially the AC terms. We can exploit this
  168825. * by short-circuiting the IDCT calculation for any column in which all
  168826. * the AC terms are zero. In that case each output is equal to the
  168827. * DC coefficient (with scale factor as needed).
  168828. * With typical images and quantization tables, half or more of the
  168829. * column DCT calculations can be simplified this way.
  168830. */
  168831. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  168832. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  168833. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  168834. inptr[DCTSIZE*7] == 0) {
  168835. /* AC terms all zero */
  168836. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  168837. wsptr[DCTSIZE*0] = dcval;
  168838. wsptr[DCTSIZE*1] = dcval;
  168839. wsptr[DCTSIZE*2] = dcval;
  168840. wsptr[DCTSIZE*3] = dcval;
  168841. wsptr[DCTSIZE*4] = dcval;
  168842. wsptr[DCTSIZE*5] = dcval;
  168843. wsptr[DCTSIZE*6] = dcval;
  168844. wsptr[DCTSIZE*7] = dcval;
  168845. inptr++; /* advance pointers to next column */
  168846. quantptr++;
  168847. wsptr++;
  168848. continue;
  168849. }
  168850. /* Even part */
  168851. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  168852. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  168853. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  168854. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  168855. tmp10 = tmp0 + tmp2; /* phase 3 */
  168856. tmp11 = tmp0 - tmp2;
  168857. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  168858. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  168859. tmp0 = tmp10 + tmp13; /* phase 2 */
  168860. tmp3 = tmp10 - tmp13;
  168861. tmp1 = tmp11 + tmp12;
  168862. tmp2 = tmp11 - tmp12;
  168863. /* Odd part */
  168864. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  168865. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  168866. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  168867. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  168868. z13 = tmp6 + tmp5; /* phase 6 */
  168869. z10 = tmp6 - tmp5;
  168870. z11 = tmp4 + tmp7;
  168871. z12 = tmp4 - tmp7;
  168872. tmp7 = z11 + z13; /* phase 5 */
  168873. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  168874. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  168875. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  168876. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  168877. tmp6 = tmp12 - tmp7; /* phase 2 */
  168878. tmp5 = tmp11 - tmp6;
  168879. tmp4 = tmp10 + tmp5;
  168880. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  168881. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  168882. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  168883. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  168884. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  168885. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  168886. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  168887. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  168888. inptr++; /* advance pointers to next column */
  168889. quantptr++;
  168890. wsptr++;
  168891. }
  168892. /* Pass 2: process rows from work array, store into output array. */
  168893. /* Note that we must descale the results by a factor of 8 == 2**3. */
  168894. wsptr = workspace;
  168895. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  168896. outptr = output_buf[ctr] + output_col;
  168897. /* Rows of zeroes can be exploited in the same way as we did with columns.
  168898. * However, the column calculation has created many nonzero AC terms, so
  168899. * the simplification applies less often (typically 5% to 10% of the time).
  168900. * And testing floats for zero is relatively expensive, so we don't bother.
  168901. */
  168902. /* Even part */
  168903. tmp10 = wsptr[0] + wsptr[4];
  168904. tmp11 = wsptr[0] - wsptr[4];
  168905. tmp13 = wsptr[2] + wsptr[6];
  168906. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  168907. tmp0 = tmp10 + tmp13;
  168908. tmp3 = tmp10 - tmp13;
  168909. tmp1 = tmp11 + tmp12;
  168910. tmp2 = tmp11 - tmp12;
  168911. /* Odd part */
  168912. z13 = wsptr[5] + wsptr[3];
  168913. z10 = wsptr[5] - wsptr[3];
  168914. z11 = wsptr[1] + wsptr[7];
  168915. z12 = wsptr[1] - wsptr[7];
  168916. tmp7 = z11 + z13;
  168917. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  168918. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  168919. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  168920. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  168921. tmp6 = tmp12 - tmp7;
  168922. tmp5 = tmp11 - tmp6;
  168923. tmp4 = tmp10 + tmp5;
  168924. /* Final output stage: scale down by a factor of 8 and range-limit */
  168925. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  168926. & RANGE_MASK];
  168927. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  168928. & RANGE_MASK];
  168929. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  168930. & RANGE_MASK];
  168931. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  168932. & RANGE_MASK];
  168933. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  168934. & RANGE_MASK];
  168935. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  168936. & RANGE_MASK];
  168937. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  168938. & RANGE_MASK];
  168939. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  168940. & RANGE_MASK];
  168941. wsptr += DCTSIZE; /* advance pointer to next row */
  168942. }
  168943. }
  168944. #endif /* DCT_FLOAT_SUPPORTED */
  168945. /********* End of inlined file: jidctflt.c *********/
  168946. #undef CONST_BITS
  168947. #undef FIX_1_847759065
  168948. #undef MULTIPLY
  168949. #undef DEQUANTIZE
  168950. #undef DESCALE
  168951. /********* Start of inlined file: jidctfst.c *********/
  168952. #define JPEG_INTERNALS
  168953. #ifdef DCT_IFAST_SUPPORTED
  168954. /*
  168955. * This module is specialized to the case DCTSIZE = 8.
  168956. */
  168957. #if DCTSIZE != 8
  168958. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168959. #endif
  168960. /* Scaling decisions are generally the same as in the LL&M algorithm;
  168961. * see jidctint.c for more details. However, we choose to descale
  168962. * (right shift) multiplication products as soon as they are formed,
  168963. * rather than carrying additional fractional bits into subsequent additions.
  168964. * This compromises accuracy slightly, but it lets us save a few shifts.
  168965. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  168966. * everywhere except in the multiplications proper; this saves a good deal
  168967. * of work on 16-bit-int machines.
  168968. *
  168969. * The dequantized coefficients are not integers because the AA&N scaling
  168970. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  168971. * so that the first and second IDCT rounds have the same input scaling.
  168972. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  168973. * avoid a descaling shift; this compromises accuracy rather drastically
  168974. * for small quantization table entries, but it saves a lot of shifts.
  168975. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  168976. * so we use a much larger scaling factor to preserve accuracy.
  168977. *
  168978. * A final compromise is to represent the multiplicative constants to only
  168979. * 8 fractional bits, rather than 13. This saves some shifting work on some
  168980. * machines, and may also reduce the cost of multiplication (since there
  168981. * are fewer one-bits in the constants).
  168982. */
  168983. #if BITS_IN_JSAMPLE == 8
  168984. #define CONST_BITS 8
  168985. #define PASS1_BITS 2
  168986. #else
  168987. #define CONST_BITS 8
  168988. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  168989. #endif
  168990. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  168991. * causing a lot of useless floating-point operations at run time.
  168992. * To get around this we use the following pre-calculated constants.
  168993. * If you change CONST_BITS you may want to add appropriate values.
  168994. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  168995. */
  168996. #if CONST_BITS == 8
  168997. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  168998. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  168999. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  169000. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  169001. #else
  169002. #define FIX_1_082392200 FIX(1.082392200)
  169003. #define FIX_1_414213562 FIX(1.414213562)
  169004. #define FIX_1_847759065 FIX(1.847759065)
  169005. #define FIX_2_613125930 FIX(2.613125930)
  169006. #endif
  169007. /* We can gain a little more speed, with a further compromise in accuracy,
  169008. * by omitting the addition in a descaling shift. This yields an incorrectly
  169009. * rounded result half the time...
  169010. */
  169011. #ifndef USE_ACCURATE_ROUNDING
  169012. #undef DESCALE
  169013. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  169014. #endif
  169015. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  169016. * descale to yield a DCTELEM result.
  169017. */
  169018. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  169019. /* Dequantize a coefficient by multiplying it by the multiplier-table
  169020. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  169021. * multiplication will do. For 12-bit data, the multiplier table is
  169022. * declared INT32, so a 32-bit multiply will be used.
  169023. */
  169024. #if BITS_IN_JSAMPLE == 8
  169025. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  169026. #else
  169027. #define DEQUANTIZE(coef,quantval) \
  169028. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  169029. #endif
  169030. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  169031. * We assume that int right shift is unsigned if INT32 right shift is.
  169032. */
  169033. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  169034. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  169035. #if BITS_IN_JSAMPLE == 8
  169036. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  169037. #else
  169038. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  169039. #endif
  169040. #define IRIGHT_SHIFT(x,shft) \
  169041. ((ishift_temp = (x)) < 0 ? \
  169042. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  169043. (ishift_temp >> (shft)))
  169044. #else
  169045. #define ISHIFT_TEMPS
  169046. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  169047. #endif
  169048. #ifdef USE_ACCURATE_ROUNDING
  169049. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  169050. #else
  169051. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  169052. #endif
  169053. /*
  169054. * Perform dequantization and inverse DCT on one block of coefficients.
  169055. */
  169056. GLOBAL(void)
  169057. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169058. JCOEFPTR coef_block,
  169059. JSAMPARRAY output_buf, JDIMENSION output_col)
  169060. {
  169061. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  169062. DCTELEM tmp10, tmp11, tmp12, tmp13;
  169063. DCTELEM z5, z10, z11, z12, z13;
  169064. JCOEFPTR inptr;
  169065. IFAST_MULT_TYPE * quantptr;
  169066. int * wsptr;
  169067. JSAMPROW outptr;
  169068. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169069. int ctr;
  169070. int workspace[DCTSIZE2]; /* buffers data between passes */
  169071. SHIFT_TEMPS /* for DESCALE */
  169072. ISHIFT_TEMPS /* for IDESCALE */
  169073. /* Pass 1: process columns from input, store into work array. */
  169074. inptr = coef_block;
  169075. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  169076. wsptr = workspace;
  169077. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  169078. /* Due to quantization, we will usually find that many of the input
  169079. * coefficients are zero, especially the AC terms. We can exploit this
  169080. * by short-circuiting the IDCT calculation for any column in which all
  169081. * the AC terms are zero. In that case each output is equal to the
  169082. * DC coefficient (with scale factor as needed).
  169083. * With typical images and quantization tables, half or more of the
  169084. * column DCT calculations can be simplified this way.
  169085. */
  169086. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  169087. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  169088. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  169089. inptr[DCTSIZE*7] == 0) {
  169090. /* AC terms all zero */
  169091. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169092. wsptr[DCTSIZE*0] = dcval;
  169093. wsptr[DCTSIZE*1] = dcval;
  169094. wsptr[DCTSIZE*2] = dcval;
  169095. wsptr[DCTSIZE*3] = dcval;
  169096. wsptr[DCTSIZE*4] = dcval;
  169097. wsptr[DCTSIZE*5] = dcval;
  169098. wsptr[DCTSIZE*6] = dcval;
  169099. wsptr[DCTSIZE*7] = dcval;
  169100. inptr++; /* advance pointers to next column */
  169101. quantptr++;
  169102. wsptr++;
  169103. continue;
  169104. }
  169105. /* Even part */
  169106. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169107. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  169108. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  169109. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  169110. tmp10 = tmp0 + tmp2; /* phase 3 */
  169111. tmp11 = tmp0 - tmp2;
  169112. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  169113. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  169114. tmp0 = tmp10 + tmp13; /* phase 2 */
  169115. tmp3 = tmp10 - tmp13;
  169116. tmp1 = tmp11 + tmp12;
  169117. tmp2 = tmp11 - tmp12;
  169118. /* Odd part */
  169119. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  169120. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  169121. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  169122. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  169123. z13 = tmp6 + tmp5; /* phase 6 */
  169124. z10 = tmp6 - tmp5;
  169125. z11 = tmp4 + tmp7;
  169126. z12 = tmp4 - tmp7;
  169127. tmp7 = z11 + z13; /* phase 5 */
  169128. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  169129. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  169130. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  169131. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  169132. tmp6 = tmp12 - tmp7; /* phase 2 */
  169133. tmp5 = tmp11 - tmp6;
  169134. tmp4 = tmp10 + tmp5;
  169135. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  169136. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  169137. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  169138. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  169139. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  169140. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  169141. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  169142. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  169143. inptr++; /* advance pointers to next column */
  169144. quantptr++;
  169145. wsptr++;
  169146. }
  169147. /* Pass 2: process rows from work array, store into output array. */
  169148. /* Note that we must descale the results by a factor of 8 == 2**3, */
  169149. /* and also undo the PASS1_BITS scaling. */
  169150. wsptr = workspace;
  169151. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  169152. outptr = output_buf[ctr] + output_col;
  169153. /* Rows of zeroes can be exploited in the same way as we did with columns.
  169154. * However, the column calculation has created many nonzero AC terms, so
  169155. * the simplification applies less often (typically 5% to 10% of the time).
  169156. * On machines with very fast multiplication, it's possible that the
  169157. * test takes more time than it's worth. In that case this section
  169158. * may be commented out.
  169159. */
  169160. #ifndef NO_ZERO_ROW_TEST
  169161. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  169162. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  169163. /* AC terms all zero */
  169164. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  169165. & RANGE_MASK];
  169166. outptr[0] = dcval;
  169167. outptr[1] = dcval;
  169168. outptr[2] = dcval;
  169169. outptr[3] = dcval;
  169170. outptr[4] = dcval;
  169171. outptr[5] = dcval;
  169172. outptr[6] = dcval;
  169173. outptr[7] = dcval;
  169174. wsptr += DCTSIZE; /* advance pointer to next row */
  169175. continue;
  169176. }
  169177. #endif
  169178. /* Even part */
  169179. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  169180. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  169181. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  169182. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  169183. - tmp13;
  169184. tmp0 = tmp10 + tmp13;
  169185. tmp3 = tmp10 - tmp13;
  169186. tmp1 = tmp11 + tmp12;
  169187. tmp2 = tmp11 - tmp12;
  169188. /* Odd part */
  169189. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  169190. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  169191. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  169192. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  169193. tmp7 = z11 + z13; /* phase 5 */
  169194. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  169195. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  169196. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  169197. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  169198. tmp6 = tmp12 - tmp7; /* phase 2 */
  169199. tmp5 = tmp11 - tmp6;
  169200. tmp4 = tmp10 + tmp5;
  169201. /* Final output stage: scale down by a factor of 8 and range-limit */
  169202. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  169203. & RANGE_MASK];
  169204. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  169205. & RANGE_MASK];
  169206. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  169207. & RANGE_MASK];
  169208. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  169209. & RANGE_MASK];
  169210. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  169211. & RANGE_MASK];
  169212. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  169213. & RANGE_MASK];
  169214. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  169215. & RANGE_MASK];
  169216. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  169217. & RANGE_MASK];
  169218. wsptr += DCTSIZE; /* advance pointer to next row */
  169219. }
  169220. }
  169221. #endif /* DCT_IFAST_SUPPORTED */
  169222. /********* End of inlined file: jidctfst.c *********/
  169223. #undef CONST_BITS
  169224. #undef FIX_1_847759065
  169225. #undef MULTIPLY
  169226. #undef DEQUANTIZE
  169227. /********* Start of inlined file: jidctint.c *********/
  169228. #define JPEG_INTERNALS
  169229. #ifdef DCT_ISLOW_SUPPORTED
  169230. /*
  169231. * This module is specialized to the case DCTSIZE = 8.
  169232. */
  169233. #if DCTSIZE != 8
  169234. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169235. #endif
  169236. /*
  169237. * The poop on this scaling stuff is as follows:
  169238. *
  169239. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  169240. * larger than the true IDCT outputs. The final outputs are therefore
  169241. * a factor of N larger than desired; since N=8 this can be cured by
  169242. * a simple right shift at the end of the algorithm. The advantage of
  169243. * this arrangement is that we save two multiplications per 1-D IDCT,
  169244. * because the y0 and y4 inputs need not be divided by sqrt(N).
  169245. *
  169246. * We have to do addition and subtraction of the integer inputs, which
  169247. * is no problem, and multiplication by fractional constants, which is
  169248. * a problem to do in integer arithmetic. We multiply all the constants
  169249. * by CONST_SCALE and convert them to integer constants (thus retaining
  169250. * CONST_BITS bits of precision in the constants). After doing a
  169251. * multiplication we have to divide the product by CONST_SCALE, with proper
  169252. * rounding, to produce the correct output. This division can be done
  169253. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  169254. * as long as possible so that partial sums can be added together with
  169255. * full fractional precision.
  169256. *
  169257. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  169258. * they are represented to better-than-integral precision. These outputs
  169259. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  169260. * with the recommended scaling. (To scale up 12-bit sample data further, an
  169261. * intermediate INT32 array would be needed.)
  169262. *
  169263. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  169264. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  169265. * shows that the values given below are the most effective.
  169266. */
  169267. #if BITS_IN_JSAMPLE == 8
  169268. #define CONST_BITS 13
  169269. #define PASS1_BITS 2
  169270. #else
  169271. #define CONST_BITS 13
  169272. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  169273. #endif
  169274. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  169275. * causing a lot of useless floating-point operations at run time.
  169276. * To get around this we use the following pre-calculated constants.
  169277. * If you change CONST_BITS you may want to add appropriate values.
  169278. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  169279. */
  169280. #if CONST_BITS == 13
  169281. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  169282. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  169283. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  169284. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  169285. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  169286. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  169287. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  169288. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  169289. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  169290. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  169291. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  169292. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  169293. #else
  169294. #define FIX_0_298631336 FIX(0.298631336)
  169295. #define FIX_0_390180644 FIX(0.390180644)
  169296. #define FIX_0_541196100 FIX(0.541196100)
  169297. #define FIX_0_765366865 FIX(0.765366865)
  169298. #define FIX_0_899976223 FIX(0.899976223)
  169299. #define FIX_1_175875602 FIX(1.175875602)
  169300. #define FIX_1_501321110 FIX(1.501321110)
  169301. #define FIX_1_847759065 FIX(1.847759065)
  169302. #define FIX_1_961570560 FIX(1.961570560)
  169303. #define FIX_2_053119869 FIX(2.053119869)
  169304. #define FIX_2_562915447 FIX(2.562915447)
  169305. #define FIX_3_072711026 FIX(3.072711026)
  169306. #endif
  169307. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  169308. * For 8-bit samples with the recommended scaling, all the variable
  169309. * and constant values involved are no more than 16 bits wide, so a
  169310. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  169311. * For 12-bit samples, a full 32-bit multiplication will be needed.
  169312. */
  169313. #if BITS_IN_JSAMPLE == 8
  169314. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  169315. #else
  169316. #define MULTIPLY(var,const) ((var) * (const))
  169317. #endif
  169318. /* Dequantize a coefficient by multiplying it by the multiplier-table
  169319. * entry; produce an int result. In this module, both inputs and result
  169320. * are 16 bits or less, so either int or short multiply will work.
  169321. */
  169322. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  169323. /*
  169324. * Perform dequantization and inverse DCT on one block of coefficients.
  169325. */
  169326. GLOBAL(void)
  169327. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169328. JCOEFPTR coef_block,
  169329. JSAMPARRAY output_buf, JDIMENSION output_col)
  169330. {
  169331. INT32 tmp0, tmp1, tmp2, tmp3;
  169332. INT32 tmp10, tmp11, tmp12, tmp13;
  169333. INT32 z1, z2, z3, z4, z5;
  169334. JCOEFPTR inptr;
  169335. ISLOW_MULT_TYPE * quantptr;
  169336. int * wsptr;
  169337. JSAMPROW outptr;
  169338. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169339. int ctr;
  169340. int workspace[DCTSIZE2]; /* buffers data between passes */
  169341. SHIFT_TEMPS
  169342. /* Pass 1: process columns from input, store into work array. */
  169343. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  169344. /* furthermore, we scale the results by 2**PASS1_BITS. */
  169345. inptr = coef_block;
  169346. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169347. wsptr = workspace;
  169348. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  169349. /* Due to quantization, we will usually find that many of the input
  169350. * coefficients are zero, especially the AC terms. We can exploit this
  169351. * by short-circuiting the IDCT calculation for any column in which all
  169352. * the AC terms are zero. In that case each output is equal to the
  169353. * DC coefficient (with scale factor as needed).
  169354. * With typical images and quantization tables, half or more of the
  169355. * column DCT calculations can be simplified this way.
  169356. */
  169357. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  169358. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  169359. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  169360. inptr[DCTSIZE*7] == 0) {
  169361. /* AC terms all zero */
  169362. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  169363. wsptr[DCTSIZE*0] = dcval;
  169364. wsptr[DCTSIZE*1] = dcval;
  169365. wsptr[DCTSIZE*2] = dcval;
  169366. wsptr[DCTSIZE*3] = dcval;
  169367. wsptr[DCTSIZE*4] = dcval;
  169368. wsptr[DCTSIZE*5] = dcval;
  169369. wsptr[DCTSIZE*6] = dcval;
  169370. wsptr[DCTSIZE*7] = dcval;
  169371. inptr++; /* advance pointers to next column */
  169372. quantptr++;
  169373. wsptr++;
  169374. continue;
  169375. }
  169376. /* Even part: reverse the even part of the forward DCT. */
  169377. /* The rotator is sqrt(2)*c(-6). */
  169378. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  169379. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  169380. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  169381. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  169382. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  169383. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169384. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  169385. tmp0 = (z2 + z3) << CONST_BITS;
  169386. tmp1 = (z2 - z3) << CONST_BITS;
  169387. tmp10 = tmp0 + tmp3;
  169388. tmp13 = tmp0 - tmp3;
  169389. tmp11 = tmp1 + tmp2;
  169390. tmp12 = tmp1 - tmp2;
  169391. /* Odd part per figure 8; the matrix is unitary and hence its
  169392. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  169393. */
  169394. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  169395. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  169396. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  169397. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  169398. z1 = tmp0 + tmp3;
  169399. z2 = tmp1 + tmp2;
  169400. z3 = tmp0 + tmp2;
  169401. z4 = tmp1 + tmp3;
  169402. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  169403. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  169404. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  169405. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  169406. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  169407. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  169408. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  169409. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  169410. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  169411. z3 += z5;
  169412. z4 += z5;
  169413. tmp0 += z1 + z3;
  169414. tmp1 += z2 + z4;
  169415. tmp2 += z2 + z3;
  169416. tmp3 += z1 + z4;
  169417. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  169418. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  169419. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  169420. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  169421. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  169422. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  169423. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  169424. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  169425. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  169426. inptr++; /* advance pointers to next column */
  169427. quantptr++;
  169428. wsptr++;
  169429. }
  169430. /* Pass 2: process rows from work array, store into output array. */
  169431. /* Note that we must descale the results by a factor of 8 == 2**3, */
  169432. /* and also undo the PASS1_BITS scaling. */
  169433. wsptr = workspace;
  169434. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  169435. outptr = output_buf[ctr] + output_col;
  169436. /* Rows of zeroes can be exploited in the same way as we did with columns.
  169437. * However, the column calculation has created many nonzero AC terms, so
  169438. * the simplification applies less often (typically 5% to 10% of the time).
  169439. * On machines with very fast multiplication, it's possible that the
  169440. * test takes more time than it's worth. In that case this section
  169441. * may be commented out.
  169442. */
  169443. #ifndef NO_ZERO_ROW_TEST
  169444. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  169445. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  169446. /* AC terms all zero */
  169447. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  169448. & RANGE_MASK];
  169449. outptr[0] = dcval;
  169450. outptr[1] = dcval;
  169451. outptr[2] = dcval;
  169452. outptr[3] = dcval;
  169453. outptr[4] = dcval;
  169454. outptr[5] = dcval;
  169455. outptr[6] = dcval;
  169456. outptr[7] = dcval;
  169457. wsptr += DCTSIZE; /* advance pointer to next row */
  169458. continue;
  169459. }
  169460. #endif
  169461. /* Even part: reverse the even part of the forward DCT. */
  169462. /* The rotator is sqrt(2)*c(-6). */
  169463. z2 = (INT32) wsptr[2];
  169464. z3 = (INT32) wsptr[6];
  169465. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  169466. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  169467. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  169468. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  169469. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  169470. tmp10 = tmp0 + tmp3;
  169471. tmp13 = tmp0 - tmp3;
  169472. tmp11 = tmp1 + tmp2;
  169473. tmp12 = tmp1 - tmp2;
  169474. /* Odd part per figure 8; the matrix is unitary and hence its
  169475. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  169476. */
  169477. tmp0 = (INT32) wsptr[7];
  169478. tmp1 = (INT32) wsptr[5];
  169479. tmp2 = (INT32) wsptr[3];
  169480. tmp3 = (INT32) wsptr[1];
  169481. z1 = tmp0 + tmp3;
  169482. z2 = tmp1 + tmp2;
  169483. z3 = tmp0 + tmp2;
  169484. z4 = tmp1 + tmp3;
  169485. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  169486. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  169487. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  169488. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  169489. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  169490. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  169491. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  169492. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  169493. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  169494. z3 += z5;
  169495. z4 += z5;
  169496. tmp0 += z1 + z3;
  169497. tmp1 += z2 + z4;
  169498. tmp2 += z2 + z3;
  169499. tmp3 += z1 + z4;
  169500. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  169501. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  169502. CONST_BITS+PASS1_BITS+3)
  169503. & RANGE_MASK];
  169504. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  169505. CONST_BITS+PASS1_BITS+3)
  169506. & RANGE_MASK];
  169507. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  169508. CONST_BITS+PASS1_BITS+3)
  169509. & RANGE_MASK];
  169510. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  169511. CONST_BITS+PASS1_BITS+3)
  169512. & RANGE_MASK];
  169513. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  169514. CONST_BITS+PASS1_BITS+3)
  169515. & RANGE_MASK];
  169516. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  169517. CONST_BITS+PASS1_BITS+3)
  169518. & RANGE_MASK];
  169519. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  169520. CONST_BITS+PASS1_BITS+3)
  169521. & RANGE_MASK];
  169522. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  169523. CONST_BITS+PASS1_BITS+3)
  169524. & RANGE_MASK];
  169525. wsptr += DCTSIZE; /* advance pointer to next row */
  169526. }
  169527. }
  169528. #endif /* DCT_ISLOW_SUPPORTED */
  169529. /********* End of inlined file: jidctint.c *********/
  169530. /********* Start of inlined file: jidctred.c *********/
  169531. #define JPEG_INTERNALS
  169532. #ifdef IDCT_SCALING_SUPPORTED
  169533. /*
  169534. * This module is specialized to the case DCTSIZE = 8.
  169535. */
  169536. #if DCTSIZE != 8
  169537. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169538. #endif
  169539. /* Scaling is the same as in jidctint.c. */
  169540. #if BITS_IN_JSAMPLE == 8
  169541. #define CONST_BITS 13
  169542. #define PASS1_BITS 2
  169543. #else
  169544. #define CONST_BITS 13
  169545. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  169546. #endif
  169547. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  169548. * causing a lot of useless floating-point operations at run time.
  169549. * To get around this we use the following pre-calculated constants.
  169550. * If you change CONST_BITS you may want to add appropriate values.
  169551. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  169552. */
  169553. #if CONST_BITS == 13
  169554. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  169555. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  169556. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  169557. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  169558. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  169559. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  169560. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  169561. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  169562. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  169563. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  169564. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  169565. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  169566. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  169567. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  169568. #else
  169569. #define FIX_0_211164243 FIX(0.211164243)
  169570. #define FIX_0_509795579 FIX(0.509795579)
  169571. #define FIX_0_601344887 FIX(0.601344887)
  169572. #define FIX_0_720959822 FIX(0.720959822)
  169573. #define FIX_0_765366865 FIX(0.765366865)
  169574. #define FIX_0_850430095 FIX(0.850430095)
  169575. #define FIX_0_899976223 FIX(0.899976223)
  169576. #define FIX_1_061594337 FIX(1.061594337)
  169577. #define FIX_1_272758580 FIX(1.272758580)
  169578. #define FIX_1_451774981 FIX(1.451774981)
  169579. #define FIX_1_847759065 FIX(1.847759065)
  169580. #define FIX_2_172734803 FIX(2.172734803)
  169581. #define FIX_2_562915447 FIX(2.562915447)
  169582. #define FIX_3_624509785 FIX(3.624509785)
  169583. #endif
  169584. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  169585. * For 8-bit samples with the recommended scaling, all the variable
  169586. * and constant values involved are no more than 16 bits wide, so a
  169587. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  169588. * For 12-bit samples, a full 32-bit multiplication will be needed.
  169589. */
  169590. #if BITS_IN_JSAMPLE == 8
  169591. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  169592. #else
  169593. #define MULTIPLY(var,const) ((var) * (const))
  169594. #endif
  169595. /* Dequantize a coefficient by multiplying it by the multiplier-table
  169596. * entry; produce an int result. In this module, both inputs and result
  169597. * are 16 bits or less, so either int or short multiply will work.
  169598. */
  169599. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  169600. /*
  169601. * Perform dequantization and inverse DCT on one block of coefficients,
  169602. * producing a reduced-size 4x4 output block.
  169603. */
  169604. GLOBAL(void)
  169605. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169606. JCOEFPTR coef_block,
  169607. JSAMPARRAY output_buf, JDIMENSION output_col)
  169608. {
  169609. INT32 tmp0, tmp2, tmp10, tmp12;
  169610. INT32 z1, z2, z3, z4;
  169611. JCOEFPTR inptr;
  169612. ISLOW_MULT_TYPE * quantptr;
  169613. int * wsptr;
  169614. JSAMPROW outptr;
  169615. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169616. int ctr;
  169617. int workspace[DCTSIZE*4]; /* buffers data between passes */
  169618. SHIFT_TEMPS
  169619. /* Pass 1: process columns from input, store into work array. */
  169620. inptr = coef_block;
  169621. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169622. wsptr = workspace;
  169623. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  169624. /* Don't bother to process column 4, because second pass won't use it */
  169625. if (ctr == DCTSIZE-4)
  169626. continue;
  169627. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  169628. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  169629. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  169630. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  169631. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  169632. wsptr[DCTSIZE*0] = dcval;
  169633. wsptr[DCTSIZE*1] = dcval;
  169634. wsptr[DCTSIZE*2] = dcval;
  169635. wsptr[DCTSIZE*3] = dcval;
  169636. continue;
  169637. }
  169638. /* Even part */
  169639. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169640. tmp0 <<= (CONST_BITS+1);
  169641. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  169642. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  169643. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  169644. tmp10 = tmp0 + tmp2;
  169645. tmp12 = tmp0 - tmp2;
  169646. /* Odd part */
  169647. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  169648. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  169649. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  169650. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  169651. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  169652. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  169653. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  169654. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  169655. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  169656. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  169657. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  169658. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  169659. /* Final output stage */
  169660. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  169661. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  169662. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  169663. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  169664. }
  169665. /* Pass 2: process 4 rows from work array, store into output array. */
  169666. wsptr = workspace;
  169667. for (ctr = 0; ctr < 4; ctr++) {
  169668. outptr = output_buf[ctr] + output_col;
  169669. /* It's not clear whether a zero row test is worthwhile here ... */
  169670. #ifndef NO_ZERO_ROW_TEST
  169671. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  169672. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  169673. /* AC terms all zero */
  169674. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  169675. & RANGE_MASK];
  169676. outptr[0] = dcval;
  169677. outptr[1] = dcval;
  169678. outptr[2] = dcval;
  169679. outptr[3] = dcval;
  169680. wsptr += DCTSIZE; /* advance pointer to next row */
  169681. continue;
  169682. }
  169683. #endif
  169684. /* Even part */
  169685. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  169686. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  169687. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  169688. tmp10 = tmp0 + tmp2;
  169689. tmp12 = tmp0 - tmp2;
  169690. /* Odd part */
  169691. z1 = (INT32) wsptr[7];
  169692. z2 = (INT32) wsptr[5];
  169693. z3 = (INT32) wsptr[3];
  169694. z4 = (INT32) wsptr[1];
  169695. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  169696. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  169697. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  169698. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  169699. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  169700. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  169701. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  169702. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  169703. /* Final output stage */
  169704. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  169705. CONST_BITS+PASS1_BITS+3+1)
  169706. & RANGE_MASK];
  169707. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  169708. CONST_BITS+PASS1_BITS+3+1)
  169709. & RANGE_MASK];
  169710. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  169711. CONST_BITS+PASS1_BITS+3+1)
  169712. & RANGE_MASK];
  169713. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  169714. CONST_BITS+PASS1_BITS+3+1)
  169715. & RANGE_MASK];
  169716. wsptr += DCTSIZE; /* advance pointer to next row */
  169717. }
  169718. }
  169719. /*
  169720. * Perform dequantization and inverse DCT on one block of coefficients,
  169721. * producing a reduced-size 2x2 output block.
  169722. */
  169723. GLOBAL(void)
  169724. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169725. JCOEFPTR coef_block,
  169726. JSAMPARRAY output_buf, JDIMENSION output_col)
  169727. {
  169728. INT32 tmp0, tmp10, z1;
  169729. JCOEFPTR inptr;
  169730. ISLOW_MULT_TYPE * quantptr;
  169731. int * wsptr;
  169732. JSAMPROW outptr;
  169733. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169734. int ctr;
  169735. int workspace[DCTSIZE*2]; /* buffers data between passes */
  169736. SHIFT_TEMPS
  169737. /* Pass 1: process columns from input, store into work array. */
  169738. inptr = coef_block;
  169739. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169740. wsptr = workspace;
  169741. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  169742. /* Don't bother to process columns 2,4,6 */
  169743. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  169744. continue;
  169745. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  169746. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  169747. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  169748. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  169749. wsptr[DCTSIZE*0] = dcval;
  169750. wsptr[DCTSIZE*1] = dcval;
  169751. continue;
  169752. }
  169753. /* Even part */
  169754. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169755. tmp10 = z1 << (CONST_BITS+2);
  169756. /* Odd part */
  169757. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  169758. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  169759. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  169760. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  169761. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  169762. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  169763. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  169764. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  169765. /* Final output stage */
  169766. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  169767. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  169768. }
  169769. /* Pass 2: process 2 rows from work array, store into output array. */
  169770. wsptr = workspace;
  169771. for (ctr = 0; ctr < 2; ctr++) {
  169772. outptr = output_buf[ctr] + output_col;
  169773. /* It's not clear whether a zero row test is worthwhile here ... */
  169774. #ifndef NO_ZERO_ROW_TEST
  169775. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  169776. /* AC terms all zero */
  169777. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  169778. & RANGE_MASK];
  169779. outptr[0] = dcval;
  169780. outptr[1] = dcval;
  169781. wsptr += DCTSIZE; /* advance pointer to next row */
  169782. continue;
  169783. }
  169784. #endif
  169785. /* Even part */
  169786. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  169787. /* Odd part */
  169788. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  169789. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  169790. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  169791. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  169792. /* Final output stage */
  169793. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  169794. CONST_BITS+PASS1_BITS+3+2)
  169795. & RANGE_MASK];
  169796. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  169797. CONST_BITS+PASS1_BITS+3+2)
  169798. & RANGE_MASK];
  169799. wsptr += DCTSIZE; /* advance pointer to next row */
  169800. }
  169801. }
  169802. /*
  169803. * Perform dequantization and inverse DCT on one block of coefficients,
  169804. * producing a reduced-size 1x1 output block.
  169805. */
  169806. GLOBAL(void)
  169807. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169808. JCOEFPTR coef_block,
  169809. JSAMPARRAY output_buf, JDIMENSION output_col)
  169810. {
  169811. int dcval;
  169812. ISLOW_MULT_TYPE * quantptr;
  169813. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169814. SHIFT_TEMPS
  169815. /* We hardly need an inverse DCT routine for this: just take the
  169816. * average pixel value, which is one-eighth of the DC coefficient.
  169817. */
  169818. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169819. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  169820. dcval = (int) DESCALE((INT32) dcval, 3);
  169821. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  169822. }
  169823. #endif /* IDCT_SCALING_SUPPORTED */
  169824. /********* End of inlined file: jidctred.c *********/
  169825. /********* Start of inlined file: jmemmgr.c *********/
  169826. #define JPEG_INTERNALS
  169827. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  169828. /********* Start of inlined file: jmemsys.h *********/
  169829. #ifndef __jmemsys_h__
  169830. #define __jmemsys_h__
  169831. /* Short forms of external names for systems with brain-damaged linkers. */
  169832. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169833. #define jpeg_get_small jGetSmall
  169834. #define jpeg_free_small jFreeSmall
  169835. #define jpeg_get_large jGetLarge
  169836. #define jpeg_free_large jFreeLarge
  169837. #define jpeg_mem_available jMemAvail
  169838. #define jpeg_open_backing_store jOpenBackStore
  169839. #define jpeg_mem_init jMemInit
  169840. #define jpeg_mem_term jMemTerm
  169841. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169842. /*
  169843. * These two functions are used to allocate and release small chunks of
  169844. * memory. (Typically the total amount requested through jpeg_get_small is
  169845. * no more than 20K or so; this will be requested in chunks of a few K each.)
  169846. * Behavior should be the same as for the standard library functions malloc
  169847. * and free; in particular, jpeg_get_small must return NULL on failure.
  169848. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  169849. * size of the object being freed, just in case it's needed.
  169850. * On an 80x86 machine using small-data memory model, these manage near heap.
  169851. */
  169852. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  169853. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  169854. size_t sizeofobject));
  169855. /*
  169856. * These two functions are used to allocate and release large chunks of
  169857. * memory (up to the total free space designated by jpeg_mem_available).
  169858. * The interface is the same as above, except that on an 80x86 machine,
  169859. * far pointers are used. On most other machines these are identical to
  169860. * the jpeg_get/free_small routines; but we keep them separate anyway,
  169861. * in case a different allocation strategy is desirable for large chunks.
  169862. */
  169863. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  169864. size_t sizeofobject));
  169865. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  169866. size_t sizeofobject));
  169867. /*
  169868. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  169869. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  169870. * matter, but that case should never come into play). This macro is needed
  169871. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  169872. * On those machines, we expect that jconfig.h will provide a proper value.
  169873. * On machines with 32-bit flat address spaces, any large constant may be used.
  169874. *
  169875. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  169876. * size_t and will be a multiple of sizeof(align_type).
  169877. */
  169878. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  169879. #define MAX_ALLOC_CHUNK 1000000000L
  169880. #endif
  169881. /*
  169882. * This routine computes the total space still available for allocation by
  169883. * jpeg_get_large. If more space than this is needed, backing store will be
  169884. * used. NOTE: any memory already allocated must not be counted.
  169885. *
  169886. * There is a minimum space requirement, corresponding to the minimum
  169887. * feasible buffer sizes; jmemmgr.c will request that much space even if
  169888. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  169889. * all working storage in memory, is also passed in case it is useful.
  169890. * Finally, the total space already allocated is passed. If no better
  169891. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  169892. * is often a suitable calculation.
  169893. *
  169894. * It is OK for jpeg_mem_available to underestimate the space available
  169895. * (that'll just lead to more backing-store access than is really necessary).
  169896. * However, an overestimate will lead to failure. Hence it's wise to subtract
  169897. * a slop factor from the true available space. 5% should be enough.
  169898. *
  169899. * On machines with lots of virtual memory, any large constant may be returned.
  169900. * Conversely, zero may be returned to always use the minimum amount of memory.
  169901. */
  169902. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  169903. long min_bytes_needed,
  169904. long max_bytes_needed,
  169905. long already_allocated));
  169906. /*
  169907. * This structure holds whatever state is needed to access a single
  169908. * backing-store object. The read/write/close method pointers are called
  169909. * by jmemmgr.c to manipulate the backing-store object; all other fields
  169910. * are private to the system-dependent backing store routines.
  169911. */
  169912. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  169913. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  169914. typedef unsigned short XMSH; /* type of extended-memory handles */
  169915. typedef unsigned short EMSH; /* type of expanded-memory handles */
  169916. typedef union {
  169917. short file_handle; /* DOS file handle if it's a temp file */
  169918. XMSH xms_handle; /* handle if it's a chunk of XMS */
  169919. EMSH ems_handle; /* handle if it's a chunk of EMS */
  169920. } handle_union;
  169921. #endif /* USE_MSDOS_MEMMGR */
  169922. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  169923. #include <Files.h>
  169924. #endif /* USE_MAC_MEMMGR */
  169925. //typedef struct backing_store_struct * backing_store_ptr;
  169926. typedef struct backing_store_struct {
  169927. /* Methods for reading/writing/closing this backing-store object */
  169928. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  169929. struct backing_store_struct *info,
  169930. void FAR * buffer_address,
  169931. long file_offset, long byte_count));
  169932. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  169933. struct backing_store_struct *info,
  169934. void FAR * buffer_address,
  169935. long file_offset, long byte_count));
  169936. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  169937. struct backing_store_struct *info));
  169938. /* Private fields for system-dependent backing-store management */
  169939. #ifdef USE_MSDOS_MEMMGR
  169940. /* For the MS-DOS manager (jmemdos.c), we need: */
  169941. handle_union handle; /* reference to backing-store storage object */
  169942. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  169943. #else
  169944. #ifdef USE_MAC_MEMMGR
  169945. /* For the Mac manager (jmemmac.c), we need: */
  169946. short temp_file; /* file reference number to temp file */
  169947. FSSpec tempSpec; /* the FSSpec for the temp file */
  169948. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  169949. #else
  169950. /* For a typical implementation with temp files, we need: */
  169951. FILE * temp_file; /* stdio reference to temp file */
  169952. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  169953. #endif
  169954. #endif
  169955. } backing_store_info;
  169956. /*
  169957. * Initial opening of a backing-store object. This must fill in the
  169958. * read/write/close pointers in the object. The read/write routines
  169959. * may take an error exit if the specified maximum file size is exceeded.
  169960. * (If jpeg_mem_available always returns a large value, this routine can
  169961. * just take an error exit.)
  169962. */
  169963. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  169964. struct backing_store_struct *info,
  169965. long total_bytes_needed));
  169966. /*
  169967. * These routines take care of any system-dependent initialization and
  169968. * cleanup required. jpeg_mem_init will be called before anything is
  169969. * allocated (and, therefore, nothing in cinfo is of use except the error
  169970. * manager pointer). It should return a suitable default value for
  169971. * max_memory_to_use; this may subsequently be overridden by the surrounding
  169972. * application. (Note that max_memory_to_use is only important if
  169973. * jpeg_mem_available chooses to consult it ... no one else will.)
  169974. * jpeg_mem_term may assume that all requested memory has been freed and that
  169975. * all opened backing-store objects have been closed.
  169976. */
  169977. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  169978. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  169979. #endif
  169980. /********* End of inlined file: jmemsys.h *********/
  169981. /* import the system-dependent declarations */
  169982. #ifndef NO_GETENV
  169983. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  169984. extern char * getenv JPP((const char * name));
  169985. #endif
  169986. #endif
  169987. /*
  169988. * Some important notes:
  169989. * The allocation routines provided here must never return NULL.
  169990. * They should exit to error_exit if unsuccessful.
  169991. *
  169992. * It's not a good idea to try to merge the sarray and barray routines,
  169993. * even though they are textually almost the same, because samples are
  169994. * usually stored as bytes while coefficients are shorts or ints. Thus,
  169995. * in machines where byte pointers have a different representation from
  169996. * word pointers, the resulting machine code could not be the same.
  169997. */
  169998. /*
  169999. * Many machines require storage alignment: longs must start on 4-byte
  170000. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  170001. * always returns pointers that are multiples of the worst-case alignment
  170002. * requirement, and we had better do so too.
  170003. * There isn't any really portable way to determine the worst-case alignment
  170004. * requirement. This module assumes that the alignment requirement is
  170005. * multiples of sizeof(ALIGN_TYPE).
  170006. * By default, we define ALIGN_TYPE as double. This is necessary on some
  170007. * workstations (where doubles really do need 8-byte alignment) and will work
  170008. * fine on nearly everything. If your machine has lesser alignment needs,
  170009. * you can save a few bytes by making ALIGN_TYPE smaller.
  170010. * The only place I know of where this will NOT work is certain Macintosh
  170011. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  170012. * Doing 10-byte alignment is counterproductive because longwords won't be
  170013. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  170014. * such a compiler.
  170015. */
  170016. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  170017. #define ALIGN_TYPE double
  170018. #endif
  170019. /*
  170020. * We allocate objects from "pools", where each pool is gotten with a single
  170021. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  170022. * overhead within a pool, except for alignment padding. Each pool has a
  170023. * header with a link to the next pool of the same class.
  170024. * Small and large pool headers are identical except that the latter's
  170025. * link pointer must be FAR on 80x86 machines.
  170026. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  170027. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  170028. * of the alignment requirement of ALIGN_TYPE.
  170029. */
  170030. typedef union small_pool_struct * small_pool_ptr;
  170031. typedef union small_pool_struct {
  170032. struct {
  170033. small_pool_ptr next; /* next in list of pools */
  170034. size_t bytes_used; /* how many bytes already used within pool */
  170035. size_t bytes_left; /* bytes still available in this pool */
  170036. } hdr;
  170037. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  170038. } small_pool_hdr;
  170039. typedef union large_pool_struct FAR * large_pool_ptr;
  170040. typedef union large_pool_struct {
  170041. struct {
  170042. large_pool_ptr next; /* next in list of pools */
  170043. size_t bytes_used; /* how many bytes already used within pool */
  170044. size_t bytes_left; /* bytes still available in this pool */
  170045. } hdr;
  170046. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  170047. } large_pool_hdr;
  170048. /*
  170049. * Here is the full definition of a memory manager object.
  170050. */
  170051. typedef struct {
  170052. struct jpeg_memory_mgr pub; /* public fields */
  170053. /* Each pool identifier (lifetime class) names a linked list of pools. */
  170054. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  170055. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  170056. /* Since we only have one lifetime class of virtual arrays, only one
  170057. * linked list is necessary (for each datatype). Note that the virtual
  170058. * array control blocks being linked together are actually stored somewhere
  170059. * in the small-pool list.
  170060. */
  170061. jvirt_sarray_ptr virt_sarray_list;
  170062. jvirt_barray_ptr virt_barray_list;
  170063. /* This counts total space obtained from jpeg_get_small/large */
  170064. long total_space_allocated;
  170065. /* alloc_sarray and alloc_barray set this value for use by virtual
  170066. * array routines.
  170067. */
  170068. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  170069. } my_memory_mgr;
  170070. typedef my_memory_mgr * my_mem_ptr;
  170071. /*
  170072. * The control blocks for virtual arrays.
  170073. * Note that these blocks are allocated in the "small" pool area.
  170074. * System-dependent info for the associated backing store (if any) is hidden
  170075. * inside the backing_store_info struct.
  170076. */
  170077. struct jvirt_sarray_control {
  170078. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  170079. JDIMENSION rows_in_array; /* total virtual array height */
  170080. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  170081. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  170082. JDIMENSION rows_in_mem; /* height of memory buffer */
  170083. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  170084. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  170085. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  170086. boolean pre_zero; /* pre-zero mode requested? */
  170087. boolean dirty; /* do current buffer contents need written? */
  170088. boolean b_s_open; /* is backing-store data valid? */
  170089. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  170090. backing_store_info b_s_info; /* System-dependent control info */
  170091. };
  170092. struct jvirt_barray_control {
  170093. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  170094. JDIMENSION rows_in_array; /* total virtual array height */
  170095. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  170096. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  170097. JDIMENSION rows_in_mem; /* height of memory buffer */
  170098. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  170099. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  170100. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  170101. boolean pre_zero; /* pre-zero mode requested? */
  170102. boolean dirty; /* do current buffer contents need written? */
  170103. boolean b_s_open; /* is backing-store data valid? */
  170104. jvirt_barray_ptr next; /* link to next virtual barray control block */
  170105. backing_store_info b_s_info; /* System-dependent control info */
  170106. };
  170107. #ifdef MEM_STATS /* optional extra stuff for statistics */
  170108. LOCAL(void)
  170109. print_mem_stats (j_common_ptr cinfo, int pool_id)
  170110. {
  170111. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170112. small_pool_ptr shdr_ptr;
  170113. large_pool_ptr lhdr_ptr;
  170114. /* Since this is only a debugging stub, we can cheat a little by using
  170115. * fprintf directly rather than going through the trace message code.
  170116. * This is helpful because message parm array can't handle longs.
  170117. */
  170118. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  170119. pool_id, mem->total_space_allocated);
  170120. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  170121. lhdr_ptr = lhdr_ptr->hdr.next) {
  170122. fprintf(stderr, " Large chunk used %ld\n",
  170123. (long) lhdr_ptr->hdr.bytes_used);
  170124. }
  170125. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  170126. shdr_ptr = shdr_ptr->hdr.next) {
  170127. fprintf(stderr, " Small chunk used %ld free %ld\n",
  170128. (long) shdr_ptr->hdr.bytes_used,
  170129. (long) shdr_ptr->hdr.bytes_left);
  170130. }
  170131. }
  170132. #endif /* MEM_STATS */
  170133. LOCAL(void)
  170134. out_of_memory (j_common_ptr cinfo, int which)
  170135. /* Report an out-of-memory error and stop execution */
  170136. /* If we compiled MEM_STATS support, report alloc requests before dying */
  170137. {
  170138. #ifdef MEM_STATS
  170139. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  170140. #endif
  170141. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  170142. }
  170143. /*
  170144. * Allocation of "small" objects.
  170145. *
  170146. * For these, we use pooled storage. When a new pool must be created,
  170147. * we try to get enough space for the current request plus a "slop" factor,
  170148. * where the slop will be the amount of leftover space in the new pool.
  170149. * The speed vs. space tradeoff is largely determined by the slop values.
  170150. * A different slop value is provided for each pool class (lifetime),
  170151. * and we also distinguish the first pool of a class from later ones.
  170152. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  170153. * machines, but may be too small if longs are 64 bits or more.
  170154. */
  170155. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  170156. {
  170157. 1600, /* first PERMANENT pool */
  170158. 16000 /* first IMAGE pool */
  170159. };
  170160. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  170161. {
  170162. 0, /* additional PERMANENT pools */
  170163. 5000 /* additional IMAGE pools */
  170164. };
  170165. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  170166. METHODDEF(void *)
  170167. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  170168. /* Allocate a "small" object */
  170169. {
  170170. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170171. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  170172. char * data_ptr;
  170173. size_t odd_bytes, min_request, slop;
  170174. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  170175. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  170176. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  170177. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  170178. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  170179. if (odd_bytes > 0)
  170180. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  170181. /* See if space is available in any existing pool */
  170182. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  170183. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  170184. prev_hdr_ptr = NULL;
  170185. hdr_ptr = mem->small_list[pool_id];
  170186. while (hdr_ptr != NULL) {
  170187. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  170188. break; /* found pool with enough space */
  170189. prev_hdr_ptr = hdr_ptr;
  170190. hdr_ptr = hdr_ptr->hdr.next;
  170191. }
  170192. /* Time to make a new pool? */
  170193. if (hdr_ptr == NULL) {
  170194. /* min_request is what we need now, slop is what will be leftover */
  170195. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  170196. if (prev_hdr_ptr == NULL) /* first pool in class? */
  170197. slop = first_pool_slop[pool_id];
  170198. else
  170199. slop = extra_pool_slop[pool_id];
  170200. /* Don't ask for more than MAX_ALLOC_CHUNK */
  170201. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  170202. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  170203. /* Try to get space, if fail reduce slop and try again */
  170204. for (;;) {
  170205. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  170206. if (hdr_ptr != NULL)
  170207. break;
  170208. slop /= 2;
  170209. if (slop < MIN_SLOP) /* give up when it gets real small */
  170210. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  170211. }
  170212. mem->total_space_allocated += min_request + slop;
  170213. /* Success, initialize the new pool header and add to end of list */
  170214. hdr_ptr->hdr.next = NULL;
  170215. hdr_ptr->hdr.bytes_used = 0;
  170216. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  170217. if (prev_hdr_ptr == NULL) /* first pool in class? */
  170218. mem->small_list[pool_id] = hdr_ptr;
  170219. else
  170220. prev_hdr_ptr->hdr.next = hdr_ptr;
  170221. }
  170222. /* OK, allocate the object from the current pool */
  170223. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  170224. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  170225. hdr_ptr->hdr.bytes_used += sizeofobject;
  170226. hdr_ptr->hdr.bytes_left -= sizeofobject;
  170227. return (void *) data_ptr;
  170228. }
  170229. /*
  170230. * Allocation of "large" objects.
  170231. *
  170232. * The external semantics of these are the same as "small" objects,
  170233. * except that FAR pointers are used on 80x86. However the pool
  170234. * management heuristics are quite different. We assume that each
  170235. * request is large enough that it may as well be passed directly to
  170236. * jpeg_get_large; the pool management just links everything together
  170237. * so that we can free it all on demand.
  170238. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  170239. * structures. The routines that create these structures (see below)
  170240. * deliberately bunch rows together to ensure a large request size.
  170241. */
  170242. METHODDEF(void FAR *)
  170243. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  170244. /* Allocate a "large" object */
  170245. {
  170246. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170247. large_pool_ptr hdr_ptr;
  170248. size_t odd_bytes;
  170249. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  170250. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  170251. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  170252. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  170253. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  170254. if (odd_bytes > 0)
  170255. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  170256. /* Always make a new pool */
  170257. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  170258. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  170259. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  170260. SIZEOF(large_pool_hdr));
  170261. if (hdr_ptr == NULL)
  170262. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  170263. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  170264. /* Success, initialize the new pool header and add to list */
  170265. hdr_ptr->hdr.next = mem->large_list[pool_id];
  170266. /* We maintain space counts in each pool header for statistical purposes,
  170267. * even though they are not needed for allocation.
  170268. */
  170269. hdr_ptr->hdr.bytes_used = sizeofobject;
  170270. hdr_ptr->hdr.bytes_left = 0;
  170271. mem->large_list[pool_id] = hdr_ptr;
  170272. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  170273. }
  170274. /*
  170275. * Creation of 2-D sample arrays.
  170276. * The pointers are in near heap, the samples themselves in FAR heap.
  170277. *
  170278. * To minimize allocation overhead and to allow I/O of large contiguous
  170279. * blocks, we allocate the sample rows in groups of as many rows as possible
  170280. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  170281. * NB: the virtual array control routines, later in this file, know about
  170282. * this chunking of rows. The rowsperchunk value is left in the mem manager
  170283. * object so that it can be saved away if this sarray is the workspace for
  170284. * a virtual array.
  170285. */
  170286. METHODDEF(JSAMPARRAY)
  170287. alloc_sarray (j_common_ptr cinfo, int pool_id,
  170288. JDIMENSION samplesperrow, JDIMENSION numrows)
  170289. /* Allocate a 2-D sample array */
  170290. {
  170291. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170292. JSAMPARRAY result;
  170293. JSAMPROW workspace;
  170294. JDIMENSION rowsperchunk, currow, i;
  170295. long ltemp;
  170296. /* Calculate max # of rows allowed in one allocation chunk */
  170297. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  170298. ((long) samplesperrow * SIZEOF(JSAMPLE));
  170299. if (ltemp <= 0)
  170300. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  170301. if (ltemp < (long) numrows)
  170302. rowsperchunk = (JDIMENSION) ltemp;
  170303. else
  170304. rowsperchunk = numrows;
  170305. mem->last_rowsperchunk = rowsperchunk;
  170306. /* Get space for row pointers (small object) */
  170307. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  170308. (size_t) (numrows * SIZEOF(JSAMPROW)));
  170309. /* Get the rows themselves (large objects) */
  170310. currow = 0;
  170311. while (currow < numrows) {
  170312. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  170313. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  170314. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  170315. * SIZEOF(JSAMPLE)));
  170316. for (i = rowsperchunk; i > 0; i--) {
  170317. result[currow++] = workspace;
  170318. workspace += samplesperrow;
  170319. }
  170320. }
  170321. return result;
  170322. }
  170323. /*
  170324. * Creation of 2-D coefficient-block arrays.
  170325. * This is essentially the same as the code for sample arrays, above.
  170326. */
  170327. METHODDEF(JBLOCKARRAY)
  170328. alloc_barray (j_common_ptr cinfo, int pool_id,
  170329. JDIMENSION blocksperrow, JDIMENSION numrows)
  170330. /* Allocate a 2-D coefficient-block array */
  170331. {
  170332. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170333. JBLOCKARRAY result;
  170334. JBLOCKROW workspace;
  170335. JDIMENSION rowsperchunk, currow, i;
  170336. long ltemp;
  170337. /* Calculate max # of rows allowed in one allocation chunk */
  170338. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  170339. ((long) blocksperrow * SIZEOF(JBLOCK));
  170340. if (ltemp <= 0)
  170341. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  170342. if (ltemp < (long) numrows)
  170343. rowsperchunk = (JDIMENSION) ltemp;
  170344. else
  170345. rowsperchunk = numrows;
  170346. mem->last_rowsperchunk = rowsperchunk;
  170347. /* Get space for row pointers (small object) */
  170348. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  170349. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  170350. /* Get the rows themselves (large objects) */
  170351. currow = 0;
  170352. while (currow < numrows) {
  170353. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  170354. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  170355. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  170356. * SIZEOF(JBLOCK)));
  170357. for (i = rowsperchunk; i > 0; i--) {
  170358. result[currow++] = workspace;
  170359. workspace += blocksperrow;
  170360. }
  170361. }
  170362. return result;
  170363. }
  170364. /*
  170365. * About virtual array management:
  170366. *
  170367. * The above "normal" array routines are only used to allocate strip buffers
  170368. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  170369. * are handled as "virtual" arrays. The array is still accessed a strip at a
  170370. * time, but the memory manager must save the whole array for repeated
  170371. * accesses. The intended implementation is that there is a strip buffer in
  170372. * memory (as high as is possible given the desired memory limit), plus a
  170373. * backing file that holds the rest of the array.
  170374. *
  170375. * The request_virt_array routines are told the total size of the image and
  170376. * the maximum number of rows that will be accessed at once. The in-memory
  170377. * buffer must be at least as large as the maxaccess value.
  170378. *
  170379. * The request routines create control blocks but not the in-memory buffers.
  170380. * That is postponed until realize_virt_arrays is called. At that time the
  170381. * total amount of space needed is known (approximately, anyway), so free
  170382. * memory can be divided up fairly.
  170383. *
  170384. * The access_virt_array routines are responsible for making a specific strip
  170385. * area accessible (after reading or writing the backing file, if necessary).
  170386. * Note that the access routines are told whether the caller intends to modify
  170387. * the accessed strip; during a read-only pass this saves having to rewrite
  170388. * data to disk. The access routines are also responsible for pre-zeroing
  170389. * any newly accessed rows, if pre-zeroing was requested.
  170390. *
  170391. * In current usage, the access requests are usually for nonoverlapping
  170392. * strips; that is, successive access start_row numbers differ by exactly
  170393. * num_rows = maxaccess. This means we can get good performance with simple
  170394. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  170395. * of the access height; then there will never be accesses across bufferload
  170396. * boundaries. The code will still work with overlapping access requests,
  170397. * but it doesn't handle bufferload overlaps very efficiently.
  170398. */
  170399. METHODDEF(jvirt_sarray_ptr)
  170400. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  170401. JDIMENSION samplesperrow, JDIMENSION numrows,
  170402. JDIMENSION maxaccess)
  170403. /* Request a virtual 2-D sample array */
  170404. {
  170405. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170406. jvirt_sarray_ptr result;
  170407. /* Only IMAGE-lifetime virtual arrays are currently supported */
  170408. if (pool_id != JPOOL_IMAGE)
  170409. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  170410. /* get control block */
  170411. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  170412. SIZEOF(struct jvirt_sarray_control));
  170413. result->mem_buffer = NULL; /* marks array not yet realized */
  170414. result->rows_in_array = numrows;
  170415. result->samplesperrow = samplesperrow;
  170416. result->maxaccess = maxaccess;
  170417. result->pre_zero = pre_zero;
  170418. result->b_s_open = FALSE; /* no associated backing-store object */
  170419. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  170420. mem->virt_sarray_list = result;
  170421. return result;
  170422. }
  170423. METHODDEF(jvirt_barray_ptr)
  170424. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  170425. JDIMENSION blocksperrow, JDIMENSION numrows,
  170426. JDIMENSION maxaccess)
  170427. /* Request a virtual 2-D coefficient-block array */
  170428. {
  170429. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170430. jvirt_barray_ptr result;
  170431. /* Only IMAGE-lifetime virtual arrays are currently supported */
  170432. if (pool_id != JPOOL_IMAGE)
  170433. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  170434. /* get control block */
  170435. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  170436. SIZEOF(struct jvirt_barray_control));
  170437. result->mem_buffer = NULL; /* marks array not yet realized */
  170438. result->rows_in_array = numrows;
  170439. result->blocksperrow = blocksperrow;
  170440. result->maxaccess = maxaccess;
  170441. result->pre_zero = pre_zero;
  170442. result->b_s_open = FALSE; /* no associated backing-store object */
  170443. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  170444. mem->virt_barray_list = result;
  170445. return result;
  170446. }
  170447. METHODDEF(void)
  170448. realize_virt_arrays (j_common_ptr cinfo)
  170449. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  170450. {
  170451. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170452. long space_per_minheight, maximum_space, avail_mem;
  170453. long minheights, max_minheights;
  170454. jvirt_sarray_ptr sptr;
  170455. jvirt_barray_ptr bptr;
  170456. /* Compute the minimum space needed (maxaccess rows in each buffer)
  170457. * and the maximum space needed (full image height in each buffer).
  170458. * These may be of use to the system-dependent jpeg_mem_available routine.
  170459. */
  170460. space_per_minheight = 0;
  170461. maximum_space = 0;
  170462. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  170463. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  170464. space_per_minheight += (long) sptr->maxaccess *
  170465. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  170466. maximum_space += (long) sptr->rows_in_array *
  170467. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  170468. }
  170469. }
  170470. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  170471. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  170472. space_per_minheight += (long) bptr->maxaccess *
  170473. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  170474. maximum_space += (long) bptr->rows_in_array *
  170475. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  170476. }
  170477. }
  170478. if (space_per_minheight <= 0)
  170479. return; /* no unrealized arrays, no work */
  170480. /* Determine amount of memory to actually use; this is system-dependent. */
  170481. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  170482. mem->total_space_allocated);
  170483. /* If the maximum space needed is available, make all the buffers full
  170484. * height; otherwise parcel it out with the same number of minheights
  170485. * in each buffer.
  170486. */
  170487. if (avail_mem >= maximum_space)
  170488. max_minheights = 1000000000L;
  170489. else {
  170490. max_minheights = avail_mem / space_per_minheight;
  170491. /* If there doesn't seem to be enough space, try to get the minimum
  170492. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  170493. */
  170494. if (max_minheights <= 0)
  170495. max_minheights = 1;
  170496. }
  170497. /* Allocate the in-memory buffers and initialize backing store as needed. */
  170498. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  170499. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  170500. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  170501. if (minheights <= max_minheights) {
  170502. /* This buffer fits in memory */
  170503. sptr->rows_in_mem = sptr->rows_in_array;
  170504. } else {
  170505. /* It doesn't fit in memory, create backing store. */
  170506. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  170507. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  170508. (long) sptr->rows_in_array *
  170509. (long) sptr->samplesperrow *
  170510. (long) SIZEOF(JSAMPLE));
  170511. sptr->b_s_open = TRUE;
  170512. }
  170513. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  170514. sptr->samplesperrow, sptr->rows_in_mem);
  170515. sptr->rowsperchunk = mem->last_rowsperchunk;
  170516. sptr->cur_start_row = 0;
  170517. sptr->first_undef_row = 0;
  170518. sptr->dirty = FALSE;
  170519. }
  170520. }
  170521. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  170522. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  170523. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  170524. if (minheights <= max_minheights) {
  170525. /* This buffer fits in memory */
  170526. bptr->rows_in_mem = bptr->rows_in_array;
  170527. } else {
  170528. /* It doesn't fit in memory, create backing store. */
  170529. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  170530. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  170531. (long) bptr->rows_in_array *
  170532. (long) bptr->blocksperrow *
  170533. (long) SIZEOF(JBLOCK));
  170534. bptr->b_s_open = TRUE;
  170535. }
  170536. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  170537. bptr->blocksperrow, bptr->rows_in_mem);
  170538. bptr->rowsperchunk = mem->last_rowsperchunk;
  170539. bptr->cur_start_row = 0;
  170540. bptr->first_undef_row = 0;
  170541. bptr->dirty = FALSE;
  170542. }
  170543. }
  170544. }
  170545. LOCAL(void)
  170546. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  170547. /* Do backing store read or write of a virtual sample array */
  170548. {
  170549. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  170550. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  170551. file_offset = ptr->cur_start_row * bytesperrow;
  170552. /* Loop to read or write each allocation chunk in mem_buffer */
  170553. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  170554. /* One chunk, but check for short chunk at end of buffer */
  170555. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  170556. /* Transfer no more than is currently defined */
  170557. thisrow = (long) ptr->cur_start_row + i;
  170558. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  170559. /* Transfer no more than fits in file */
  170560. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  170561. if (rows <= 0) /* this chunk might be past end of file! */
  170562. break;
  170563. byte_count = rows * bytesperrow;
  170564. if (writing)
  170565. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  170566. (void FAR *) ptr->mem_buffer[i],
  170567. file_offset, byte_count);
  170568. else
  170569. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  170570. (void FAR *) ptr->mem_buffer[i],
  170571. file_offset, byte_count);
  170572. file_offset += byte_count;
  170573. }
  170574. }
  170575. LOCAL(void)
  170576. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  170577. /* Do backing store read or write of a virtual coefficient-block array */
  170578. {
  170579. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  170580. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  170581. file_offset = ptr->cur_start_row * bytesperrow;
  170582. /* Loop to read or write each allocation chunk in mem_buffer */
  170583. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  170584. /* One chunk, but check for short chunk at end of buffer */
  170585. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  170586. /* Transfer no more than is currently defined */
  170587. thisrow = (long) ptr->cur_start_row + i;
  170588. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  170589. /* Transfer no more than fits in file */
  170590. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  170591. if (rows <= 0) /* this chunk might be past end of file! */
  170592. break;
  170593. byte_count = rows * bytesperrow;
  170594. if (writing)
  170595. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  170596. (void FAR *) ptr->mem_buffer[i],
  170597. file_offset, byte_count);
  170598. else
  170599. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  170600. (void FAR *) ptr->mem_buffer[i],
  170601. file_offset, byte_count);
  170602. file_offset += byte_count;
  170603. }
  170604. }
  170605. METHODDEF(JSAMPARRAY)
  170606. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  170607. JDIMENSION start_row, JDIMENSION num_rows,
  170608. boolean writable)
  170609. /* Access the part of a virtual sample array starting at start_row */
  170610. /* and extending for num_rows rows. writable is true if */
  170611. /* caller intends to modify the accessed area. */
  170612. {
  170613. JDIMENSION end_row = start_row + num_rows;
  170614. JDIMENSION undef_row;
  170615. /* debugging check */
  170616. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  170617. ptr->mem_buffer == NULL)
  170618. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170619. /* Make the desired part of the virtual array accessible */
  170620. if (start_row < ptr->cur_start_row ||
  170621. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  170622. if (! ptr->b_s_open)
  170623. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  170624. /* Flush old buffer contents if necessary */
  170625. if (ptr->dirty) {
  170626. do_sarray_io(cinfo, ptr, TRUE);
  170627. ptr->dirty = FALSE;
  170628. }
  170629. /* Decide what part of virtual array to access.
  170630. * Algorithm: if target address > current window, assume forward scan,
  170631. * load starting at target address. If target address < current window,
  170632. * assume backward scan, load so that target area is top of window.
  170633. * Note that when switching from forward write to forward read, will have
  170634. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  170635. */
  170636. if (start_row > ptr->cur_start_row) {
  170637. ptr->cur_start_row = start_row;
  170638. } else {
  170639. /* use long arithmetic here to avoid overflow & unsigned problems */
  170640. long ltemp;
  170641. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  170642. if (ltemp < 0)
  170643. ltemp = 0; /* don't fall off front end of file */
  170644. ptr->cur_start_row = (JDIMENSION) ltemp;
  170645. }
  170646. /* Read in the selected part of the array.
  170647. * During the initial write pass, we will do no actual read
  170648. * because the selected part is all undefined.
  170649. */
  170650. do_sarray_io(cinfo, ptr, FALSE);
  170651. }
  170652. /* Ensure the accessed part of the array is defined; prezero if needed.
  170653. * To improve locality of access, we only prezero the part of the array
  170654. * that the caller is about to access, not the entire in-memory array.
  170655. */
  170656. if (ptr->first_undef_row < end_row) {
  170657. if (ptr->first_undef_row < start_row) {
  170658. if (writable) /* writer skipped over a section of array */
  170659. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170660. undef_row = start_row; /* but reader is allowed to read ahead */
  170661. } else {
  170662. undef_row = ptr->first_undef_row;
  170663. }
  170664. if (writable)
  170665. ptr->first_undef_row = end_row;
  170666. if (ptr->pre_zero) {
  170667. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  170668. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  170669. end_row -= ptr->cur_start_row;
  170670. while (undef_row < end_row) {
  170671. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  170672. undef_row++;
  170673. }
  170674. } else {
  170675. if (! writable) /* reader looking at undefined data */
  170676. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170677. }
  170678. }
  170679. /* Flag the buffer dirty if caller will write in it */
  170680. if (writable)
  170681. ptr->dirty = TRUE;
  170682. /* Return address of proper part of the buffer */
  170683. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  170684. }
  170685. METHODDEF(JBLOCKARRAY)
  170686. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  170687. JDIMENSION start_row, JDIMENSION num_rows,
  170688. boolean writable)
  170689. /* Access the part of a virtual block array starting at start_row */
  170690. /* and extending for num_rows rows. writable is true if */
  170691. /* caller intends to modify the accessed area. */
  170692. {
  170693. JDIMENSION end_row = start_row + num_rows;
  170694. JDIMENSION undef_row;
  170695. /* debugging check */
  170696. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  170697. ptr->mem_buffer == NULL)
  170698. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170699. /* Make the desired part of the virtual array accessible */
  170700. if (start_row < ptr->cur_start_row ||
  170701. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  170702. if (! ptr->b_s_open)
  170703. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  170704. /* Flush old buffer contents if necessary */
  170705. if (ptr->dirty) {
  170706. do_barray_io(cinfo, ptr, TRUE);
  170707. ptr->dirty = FALSE;
  170708. }
  170709. /* Decide what part of virtual array to access.
  170710. * Algorithm: if target address > current window, assume forward scan,
  170711. * load starting at target address. If target address < current window,
  170712. * assume backward scan, load so that target area is top of window.
  170713. * Note that when switching from forward write to forward read, will have
  170714. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  170715. */
  170716. if (start_row > ptr->cur_start_row) {
  170717. ptr->cur_start_row = start_row;
  170718. } else {
  170719. /* use long arithmetic here to avoid overflow & unsigned problems */
  170720. long ltemp;
  170721. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  170722. if (ltemp < 0)
  170723. ltemp = 0; /* don't fall off front end of file */
  170724. ptr->cur_start_row = (JDIMENSION) ltemp;
  170725. }
  170726. /* Read in the selected part of the array.
  170727. * During the initial write pass, we will do no actual read
  170728. * because the selected part is all undefined.
  170729. */
  170730. do_barray_io(cinfo, ptr, FALSE);
  170731. }
  170732. /* Ensure the accessed part of the array is defined; prezero if needed.
  170733. * To improve locality of access, we only prezero the part of the array
  170734. * that the caller is about to access, not the entire in-memory array.
  170735. */
  170736. if (ptr->first_undef_row < end_row) {
  170737. if (ptr->first_undef_row < start_row) {
  170738. if (writable) /* writer skipped over a section of array */
  170739. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170740. undef_row = start_row; /* but reader is allowed to read ahead */
  170741. } else {
  170742. undef_row = ptr->first_undef_row;
  170743. }
  170744. if (writable)
  170745. ptr->first_undef_row = end_row;
  170746. if (ptr->pre_zero) {
  170747. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  170748. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  170749. end_row -= ptr->cur_start_row;
  170750. while (undef_row < end_row) {
  170751. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  170752. undef_row++;
  170753. }
  170754. } else {
  170755. if (! writable) /* reader looking at undefined data */
  170756. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170757. }
  170758. }
  170759. /* Flag the buffer dirty if caller will write in it */
  170760. if (writable)
  170761. ptr->dirty = TRUE;
  170762. /* Return address of proper part of the buffer */
  170763. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  170764. }
  170765. /*
  170766. * Release all objects belonging to a specified pool.
  170767. */
  170768. METHODDEF(void)
  170769. free_pool (j_common_ptr cinfo, int pool_id)
  170770. {
  170771. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170772. small_pool_ptr shdr_ptr;
  170773. large_pool_ptr lhdr_ptr;
  170774. size_t space_freed;
  170775. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  170776. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  170777. #ifdef MEM_STATS
  170778. if (cinfo->err->trace_level > 1)
  170779. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  170780. #endif
  170781. /* If freeing IMAGE pool, close any virtual arrays first */
  170782. if (pool_id == JPOOL_IMAGE) {
  170783. jvirt_sarray_ptr sptr;
  170784. jvirt_barray_ptr bptr;
  170785. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  170786. if (sptr->b_s_open) { /* there may be no backing store */
  170787. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  170788. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  170789. }
  170790. }
  170791. mem->virt_sarray_list = NULL;
  170792. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  170793. if (bptr->b_s_open) { /* there may be no backing store */
  170794. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  170795. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  170796. }
  170797. }
  170798. mem->virt_barray_list = NULL;
  170799. }
  170800. /* Release large objects */
  170801. lhdr_ptr = mem->large_list[pool_id];
  170802. mem->large_list[pool_id] = NULL;
  170803. while (lhdr_ptr != NULL) {
  170804. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  170805. space_freed = lhdr_ptr->hdr.bytes_used +
  170806. lhdr_ptr->hdr.bytes_left +
  170807. SIZEOF(large_pool_hdr);
  170808. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  170809. mem->total_space_allocated -= space_freed;
  170810. lhdr_ptr = next_lhdr_ptr;
  170811. }
  170812. /* Release small objects */
  170813. shdr_ptr = mem->small_list[pool_id];
  170814. mem->small_list[pool_id] = NULL;
  170815. while (shdr_ptr != NULL) {
  170816. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  170817. space_freed = shdr_ptr->hdr.bytes_used +
  170818. shdr_ptr->hdr.bytes_left +
  170819. SIZEOF(small_pool_hdr);
  170820. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  170821. mem->total_space_allocated -= space_freed;
  170822. shdr_ptr = next_shdr_ptr;
  170823. }
  170824. }
  170825. /*
  170826. * Close up shop entirely.
  170827. * Note that this cannot be called unless cinfo->mem is non-NULL.
  170828. */
  170829. METHODDEF(void)
  170830. self_destruct (j_common_ptr cinfo)
  170831. {
  170832. int pool;
  170833. /* Close all backing store, release all memory.
  170834. * Releasing pools in reverse order might help avoid fragmentation
  170835. * with some (brain-damaged) malloc libraries.
  170836. */
  170837. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  170838. free_pool(cinfo, pool);
  170839. }
  170840. /* Release the memory manager control block too. */
  170841. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  170842. cinfo->mem = NULL; /* ensures I will be called only once */
  170843. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  170844. }
  170845. /*
  170846. * Memory manager initialization.
  170847. * When this is called, only the error manager pointer is valid in cinfo!
  170848. */
  170849. GLOBAL(void)
  170850. jinit_memory_mgr (j_common_ptr cinfo)
  170851. {
  170852. my_mem_ptr mem;
  170853. long max_to_use;
  170854. int pool;
  170855. size_t test_mac;
  170856. cinfo->mem = NULL; /* for safety if init fails */
  170857. /* Check for configuration errors.
  170858. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  170859. * doesn't reflect any real hardware alignment requirement.
  170860. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  170861. * in common if and only if X is a power of 2, ie has only one one-bit.
  170862. * Some compilers may give an "unreachable code" warning here; ignore it.
  170863. */
  170864. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  170865. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  170866. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  170867. * a multiple of SIZEOF(ALIGN_TYPE).
  170868. * Again, an "unreachable code" warning may be ignored here.
  170869. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  170870. */
  170871. test_mac = (size_t) MAX_ALLOC_CHUNK;
  170872. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  170873. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  170874. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  170875. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  170876. /* Attempt to allocate memory manager's control block */
  170877. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  170878. if (mem == NULL) {
  170879. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  170880. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  170881. }
  170882. /* OK, fill in the method pointers */
  170883. mem->pub.alloc_small = alloc_small;
  170884. mem->pub.alloc_large = alloc_large;
  170885. mem->pub.alloc_sarray = alloc_sarray;
  170886. mem->pub.alloc_barray = alloc_barray;
  170887. mem->pub.request_virt_sarray = request_virt_sarray;
  170888. mem->pub.request_virt_barray = request_virt_barray;
  170889. mem->pub.realize_virt_arrays = realize_virt_arrays;
  170890. mem->pub.access_virt_sarray = access_virt_sarray;
  170891. mem->pub.access_virt_barray = access_virt_barray;
  170892. mem->pub.free_pool = free_pool;
  170893. mem->pub.self_destruct = self_destruct;
  170894. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  170895. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  170896. /* Initialize working state */
  170897. mem->pub.max_memory_to_use = max_to_use;
  170898. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  170899. mem->small_list[pool] = NULL;
  170900. mem->large_list[pool] = NULL;
  170901. }
  170902. mem->virt_sarray_list = NULL;
  170903. mem->virt_barray_list = NULL;
  170904. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  170905. /* Declare ourselves open for business */
  170906. cinfo->mem = & mem->pub;
  170907. /* Check for an environment variable JPEGMEM; if found, override the
  170908. * default max_memory setting from jpeg_mem_init. Note that the
  170909. * surrounding application may again override this value.
  170910. * If your system doesn't support getenv(), define NO_GETENV to disable
  170911. * this feature.
  170912. */
  170913. #ifndef NO_GETENV
  170914. { char * memenv;
  170915. if ((memenv = getenv("JPEGMEM")) != NULL) {
  170916. char ch = 'x';
  170917. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  170918. if (ch == 'm' || ch == 'M')
  170919. max_to_use *= 1000L;
  170920. mem->pub.max_memory_to_use = max_to_use * 1000L;
  170921. }
  170922. }
  170923. }
  170924. #endif
  170925. }
  170926. /********* End of inlined file: jmemmgr.c *********/
  170927. /********* Start of inlined file: jmemnobs.c *********/
  170928. #define JPEG_INTERNALS
  170929. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  170930. extern void * malloc JPP((size_t size));
  170931. extern void free JPP((void *ptr));
  170932. #endif
  170933. /*
  170934. * Memory allocation and freeing are controlled by the regular library
  170935. * routines malloc() and free().
  170936. */
  170937. GLOBAL(void *)
  170938. jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
  170939. {
  170940. return (void *) malloc(sizeofobject);
  170941. }
  170942. GLOBAL(void)
  170943. jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
  170944. {
  170945. free(object);
  170946. }
  170947. /*
  170948. * "Large" objects are treated the same as "small" ones.
  170949. * NB: although we include FAR keywords in the routine declarations,
  170950. * this file won't actually work in 80x86 small/medium model; at least,
  170951. * you probably won't be able to process useful-size images in only 64KB.
  170952. */
  170953. GLOBAL(void FAR *)
  170954. jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
  170955. {
  170956. return (void FAR *) malloc(sizeofobject);
  170957. }
  170958. GLOBAL(void)
  170959. jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
  170960. {
  170961. free(object);
  170962. }
  170963. /*
  170964. * This routine computes the total memory space available for allocation.
  170965. * Here we always say, "we got all you want bud!"
  170966. */
  170967. GLOBAL(long)
  170968. jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
  170969. long max_bytes_needed, long already_allocated)
  170970. {
  170971. return max_bytes_needed;
  170972. }
  170973. /*
  170974. * Backing store (temporary file) management.
  170975. * Since jpeg_mem_available always promised the moon,
  170976. * this should never be called and we can just error out.
  170977. */
  170978. GLOBAL(void)
  170979. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *info,
  170980. long total_bytes_needed)
  170981. {
  170982. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  170983. }
  170984. /*
  170985. * These routines take care of any system-dependent initialization and
  170986. * cleanup required. Here, there isn't any.
  170987. */
  170988. GLOBAL(long)
  170989. jpeg_mem_init (j_common_ptr cinfo)
  170990. {
  170991. return 0; /* just set max_memory_to_use to 0 */
  170992. }
  170993. GLOBAL(void)
  170994. jpeg_mem_term (j_common_ptr cinfo)
  170995. {
  170996. /* no work */
  170997. }
  170998. /********* End of inlined file: jmemnobs.c *********/
  170999. /********* Start of inlined file: jquant1.c *********/
  171000. #define JPEG_INTERNALS
  171001. #ifdef QUANT_1PASS_SUPPORTED
  171002. /*
  171003. * The main purpose of 1-pass quantization is to provide a fast, if not very
  171004. * high quality, colormapped output capability. A 2-pass quantizer usually
  171005. * gives better visual quality; however, for quantized grayscale output this
  171006. * quantizer is perfectly adequate. Dithering is highly recommended with this
  171007. * quantizer, though you can turn it off if you really want to.
  171008. *
  171009. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  171010. * image. We use a map consisting of all combinations of Ncolors[i] color
  171011. * values for the i'th component. The Ncolors[] values are chosen so that
  171012. * their product, the total number of colors, is no more than that requested.
  171013. * (In most cases, the product will be somewhat less.)
  171014. *
  171015. * Since the colormap is orthogonal, the representative value for each color
  171016. * component can be determined without considering the other components;
  171017. * then these indexes can be combined into a colormap index by a standard
  171018. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  171019. * can be precalculated and stored in the lookup table colorindex[].
  171020. * colorindex[i][j] maps pixel value j in component i to the nearest
  171021. * representative value (grid plane) for that component; this index is
  171022. * multiplied by the array stride for component i, so that the
  171023. * index of the colormap entry closest to a given pixel value is just
  171024. * sum( colorindex[component-number][pixel-component-value] )
  171025. * Aside from being fast, this scheme allows for variable spacing between
  171026. * representative values with no additional lookup cost.
  171027. *
  171028. * If gamma correction has been applied in color conversion, it might be wise
  171029. * to adjust the color grid spacing so that the representative colors are
  171030. * equidistant in linear space. At this writing, gamma correction is not
  171031. * implemented by jdcolor, so nothing is done here.
  171032. */
  171033. /* Declarations for ordered dithering.
  171034. *
  171035. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  171036. * dithering is described in many references, for instance Dale Schumacher's
  171037. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  171038. * In place of Schumacher's comparisons against a "threshold" value, we add a
  171039. * "dither" value to the input pixel and then round the result to the nearest
  171040. * output value. The dither value is equivalent to (0.5 - threshold) times
  171041. * the distance between output values. For ordered dithering, we assume that
  171042. * the output colors are equally spaced; if not, results will probably be
  171043. * worse, since the dither may be too much or too little at a given point.
  171044. *
  171045. * The normal calculation would be to form pixel value + dither, range-limit
  171046. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  171047. * We can skip the separate range-limiting step by extending the colorindex
  171048. * table in both directions.
  171049. */
  171050. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  171051. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  171052. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  171053. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  171054. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  171055. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  171056. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  171057. /* Bayer's order-4 dither array. Generated by the code given in
  171058. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  171059. * The values in this array must range from 0 to ODITHER_CELLS-1.
  171060. */
  171061. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  171062. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  171063. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  171064. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  171065. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  171066. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  171067. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  171068. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  171069. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  171070. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  171071. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  171072. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  171073. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  171074. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  171075. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  171076. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  171077. };
  171078. /* Declarations for Floyd-Steinberg dithering.
  171079. *
  171080. * Errors are accumulated into the array fserrors[], at a resolution of
  171081. * 1/16th of a pixel count. The error at a given pixel is propagated
  171082. * to its not-yet-processed neighbors using the standard F-S fractions,
  171083. * ... (here) 7/16
  171084. * 3/16 5/16 1/16
  171085. * We work left-to-right on even rows, right-to-left on odd rows.
  171086. *
  171087. * We can get away with a single array (holding one row's worth of errors)
  171088. * by using it to store the current row's errors at pixel columns not yet
  171089. * processed, but the next row's errors at columns already processed. We
  171090. * need only a few extra variables to hold the errors immediately around the
  171091. * current column. (If we are lucky, those variables are in registers, but
  171092. * even if not, they're probably cheaper to access than array elements are.)
  171093. *
  171094. * The fserrors[] array is indexed [component#][position].
  171095. * We provide (#columns + 2) entries per component; the extra entry at each
  171096. * end saves us from special-casing the first and last pixels.
  171097. *
  171098. * Note: on a wide image, we might not have enough room in a PC's near data
  171099. * segment to hold the error array; so it is allocated with alloc_large.
  171100. */
  171101. #if BITS_IN_JSAMPLE == 8
  171102. typedef INT16 FSERROR; /* 16 bits should be enough */
  171103. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  171104. #else
  171105. typedef INT32 FSERROR; /* may need more than 16 bits */
  171106. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  171107. #endif
  171108. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  171109. /* Private subobject */
  171110. #define MAX_Q_COMPS 4 /* max components I can handle */
  171111. typedef struct {
  171112. struct jpeg_color_quantizer pub; /* public fields */
  171113. /* Initially allocated colormap is saved here */
  171114. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  171115. int sv_actual; /* number of entries in use */
  171116. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  171117. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  171118. * premultiplied as described above. Since colormap indexes must fit into
  171119. * JSAMPLEs, the entries of this array will too.
  171120. */
  171121. boolean is_padded; /* is the colorindex padded for odither? */
  171122. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  171123. /* Variables for ordered dithering */
  171124. int row_index; /* cur row's vertical index in dither matrix */
  171125. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  171126. /* Variables for Floyd-Steinberg dithering */
  171127. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  171128. boolean on_odd_row; /* flag to remember which row we are on */
  171129. } my_cquantizer;
  171130. typedef my_cquantizer * my_cquantize_ptr;
  171131. /*
  171132. * Policy-making subroutines for create_colormap and create_colorindex.
  171133. * These routines determine the colormap to be used. The rest of the module
  171134. * only assumes that the colormap is orthogonal.
  171135. *
  171136. * * select_ncolors decides how to divvy up the available colors
  171137. * among the components.
  171138. * * output_value defines the set of representative values for a component.
  171139. * * largest_input_value defines the mapping from input values to
  171140. * representative values for a component.
  171141. * Note that the latter two routines may impose different policies for
  171142. * different components, though this is not currently done.
  171143. */
  171144. LOCAL(int)
  171145. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  171146. /* Determine allocation of desired colors to components, */
  171147. /* and fill in Ncolors[] array to indicate choice. */
  171148. /* Return value is total number of colors (product of Ncolors[] values). */
  171149. {
  171150. int nc = cinfo->out_color_components; /* number of color components */
  171151. int max_colors = cinfo->desired_number_of_colors;
  171152. int total_colors, iroot, i, j;
  171153. boolean changed;
  171154. long temp;
  171155. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  171156. /* We can allocate at least the nc'th root of max_colors per component. */
  171157. /* Compute floor(nc'th root of max_colors). */
  171158. iroot = 1;
  171159. do {
  171160. iroot++;
  171161. temp = iroot; /* set temp = iroot ** nc */
  171162. for (i = 1; i < nc; i++)
  171163. temp *= iroot;
  171164. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  171165. iroot--; /* now iroot = floor(root) */
  171166. /* Must have at least 2 color values per component */
  171167. if (iroot < 2)
  171168. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  171169. /* Initialize to iroot color values for each component */
  171170. total_colors = 1;
  171171. for (i = 0; i < nc; i++) {
  171172. Ncolors[i] = iroot;
  171173. total_colors *= iroot;
  171174. }
  171175. /* We may be able to increment the count for one or more components without
  171176. * exceeding max_colors, though we know not all can be incremented.
  171177. * Sometimes, the first component can be incremented more than once!
  171178. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  171179. * In RGB colorspace, try to increment G first, then R, then B.
  171180. */
  171181. do {
  171182. changed = FALSE;
  171183. for (i = 0; i < nc; i++) {
  171184. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  171185. /* calculate new total_colors if Ncolors[j] is incremented */
  171186. temp = total_colors / Ncolors[j];
  171187. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  171188. if (temp > (long) max_colors)
  171189. break; /* won't fit, done with this pass */
  171190. Ncolors[j]++; /* OK, apply the increment */
  171191. total_colors = (int) temp;
  171192. changed = TRUE;
  171193. }
  171194. } while (changed);
  171195. return total_colors;
  171196. }
  171197. LOCAL(int)
  171198. output_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  171199. /* Return j'th output value, where j will range from 0 to maxj */
  171200. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  171201. {
  171202. /* We always provide values 0 and MAXJSAMPLE for each component;
  171203. * any additional values are equally spaced between these limits.
  171204. * (Forcing the upper and lower values to the limits ensures that
  171205. * dithering can't produce a color outside the selected gamut.)
  171206. */
  171207. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  171208. }
  171209. LOCAL(int)
  171210. largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  171211. /* Return largest input value that should map to j'th output value */
  171212. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  171213. {
  171214. /* Breakpoints are halfway between values returned by output_value */
  171215. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  171216. }
  171217. /*
  171218. * Create the colormap.
  171219. */
  171220. LOCAL(void)
  171221. create_colormap (j_decompress_ptr cinfo)
  171222. {
  171223. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171224. JSAMPARRAY colormap; /* Created colormap */
  171225. int total_colors; /* Number of distinct output colors */
  171226. int i,j,k, nci, blksize, blkdist, ptr, val;
  171227. /* Select number of colors for each component */
  171228. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  171229. /* Report selected color counts */
  171230. if (cinfo->out_color_components == 3)
  171231. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  171232. total_colors, cquantize->Ncolors[0],
  171233. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  171234. else
  171235. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  171236. /* Allocate and fill in the colormap. */
  171237. /* The colors are ordered in the map in standard row-major order, */
  171238. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  171239. colormap = (*cinfo->mem->alloc_sarray)
  171240. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171241. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  171242. /* blksize is number of adjacent repeated entries for a component */
  171243. /* blkdist is distance between groups of identical entries for a component */
  171244. blkdist = total_colors;
  171245. for (i = 0; i < cinfo->out_color_components; i++) {
  171246. /* fill in colormap entries for i'th color component */
  171247. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  171248. blksize = blkdist / nci;
  171249. for (j = 0; j < nci; j++) {
  171250. /* Compute j'th output value (out of nci) for component */
  171251. val = output_value(cinfo, i, j, nci-1);
  171252. /* Fill in all colormap entries that have this value of this component */
  171253. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  171254. /* fill in blksize entries beginning at ptr */
  171255. for (k = 0; k < blksize; k++)
  171256. colormap[i][ptr+k] = (JSAMPLE) val;
  171257. }
  171258. }
  171259. blkdist = blksize; /* blksize of this color is blkdist of next */
  171260. }
  171261. /* Save the colormap in private storage,
  171262. * where it will survive color quantization mode changes.
  171263. */
  171264. cquantize->sv_colormap = colormap;
  171265. cquantize->sv_actual = total_colors;
  171266. }
  171267. /*
  171268. * Create the color index table.
  171269. */
  171270. LOCAL(void)
  171271. create_colorindex (j_decompress_ptr cinfo)
  171272. {
  171273. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171274. JSAMPROW indexptr;
  171275. int i,j,k, nci, blksize, val, pad;
  171276. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  171277. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  171278. * This is not necessary in the other dithering modes. However, we
  171279. * flag whether it was done in case user changes dithering mode.
  171280. */
  171281. if (cinfo->dither_mode == JDITHER_ORDERED) {
  171282. pad = MAXJSAMPLE*2;
  171283. cquantize->is_padded = TRUE;
  171284. } else {
  171285. pad = 0;
  171286. cquantize->is_padded = FALSE;
  171287. }
  171288. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  171289. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171290. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  171291. (JDIMENSION) cinfo->out_color_components);
  171292. /* blksize is number of adjacent repeated entries for a component */
  171293. blksize = cquantize->sv_actual;
  171294. for (i = 0; i < cinfo->out_color_components; i++) {
  171295. /* fill in colorindex entries for i'th color component */
  171296. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  171297. blksize = blksize / nci;
  171298. /* adjust colorindex pointers to provide padding at negative indexes. */
  171299. if (pad)
  171300. cquantize->colorindex[i] += MAXJSAMPLE;
  171301. /* in loop, val = index of current output value, */
  171302. /* and k = largest j that maps to current val */
  171303. indexptr = cquantize->colorindex[i];
  171304. val = 0;
  171305. k = largest_input_value(cinfo, i, 0, nci-1);
  171306. for (j = 0; j <= MAXJSAMPLE; j++) {
  171307. while (j > k) /* advance val if past boundary */
  171308. k = largest_input_value(cinfo, i, ++val, nci-1);
  171309. /* premultiply so that no multiplication needed in main processing */
  171310. indexptr[j] = (JSAMPLE) (val * blksize);
  171311. }
  171312. /* Pad at both ends if necessary */
  171313. if (pad)
  171314. for (j = 1; j <= MAXJSAMPLE; j++) {
  171315. indexptr[-j] = indexptr[0];
  171316. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  171317. }
  171318. }
  171319. }
  171320. /*
  171321. * Create an ordered-dither array for a component having ncolors
  171322. * distinct output values.
  171323. */
  171324. LOCAL(ODITHER_MATRIX_PTR)
  171325. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  171326. {
  171327. ODITHER_MATRIX_PTR odither;
  171328. int j,k;
  171329. INT32 num,den;
  171330. odither = (ODITHER_MATRIX_PTR)
  171331. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171332. SIZEOF(ODITHER_MATRIX));
  171333. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  171334. * Hence the dither value for the matrix cell with fill order f
  171335. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  171336. * On 16-bit-int machine, be careful to avoid overflow.
  171337. */
  171338. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  171339. for (j = 0; j < ODITHER_SIZE; j++) {
  171340. for (k = 0; k < ODITHER_SIZE; k++) {
  171341. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  171342. * MAXJSAMPLE;
  171343. /* Ensure round towards zero despite C's lack of consistency
  171344. * about rounding negative values in integer division...
  171345. */
  171346. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  171347. }
  171348. }
  171349. return odither;
  171350. }
  171351. /*
  171352. * Create the ordered-dither tables.
  171353. * Components having the same number of representative colors may
  171354. * share a dither table.
  171355. */
  171356. LOCAL(void)
  171357. create_odither_tables (j_decompress_ptr cinfo)
  171358. {
  171359. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171360. ODITHER_MATRIX_PTR odither;
  171361. int i, j, nci;
  171362. for (i = 0; i < cinfo->out_color_components; i++) {
  171363. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  171364. odither = NULL; /* search for matching prior component */
  171365. for (j = 0; j < i; j++) {
  171366. if (nci == cquantize->Ncolors[j]) {
  171367. odither = cquantize->odither[j];
  171368. break;
  171369. }
  171370. }
  171371. if (odither == NULL) /* need a new table? */
  171372. odither = make_odither_array(cinfo, nci);
  171373. cquantize->odither[i] = odither;
  171374. }
  171375. }
  171376. /*
  171377. * Map some rows of pixels to the output colormapped representation.
  171378. */
  171379. METHODDEF(void)
  171380. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171381. JSAMPARRAY output_buf, int num_rows)
  171382. /* General case, no dithering */
  171383. {
  171384. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171385. JSAMPARRAY colorindex = cquantize->colorindex;
  171386. register int pixcode, ci;
  171387. register JSAMPROW ptrin, ptrout;
  171388. int row;
  171389. JDIMENSION col;
  171390. JDIMENSION width = cinfo->output_width;
  171391. register int nc = cinfo->out_color_components;
  171392. for (row = 0; row < num_rows; row++) {
  171393. ptrin = input_buf[row];
  171394. ptrout = output_buf[row];
  171395. for (col = width; col > 0; col--) {
  171396. pixcode = 0;
  171397. for (ci = 0; ci < nc; ci++) {
  171398. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  171399. }
  171400. *ptrout++ = (JSAMPLE) pixcode;
  171401. }
  171402. }
  171403. }
  171404. METHODDEF(void)
  171405. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171406. JSAMPARRAY output_buf, int num_rows)
  171407. /* Fast path for out_color_components==3, no dithering */
  171408. {
  171409. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171410. register int pixcode;
  171411. register JSAMPROW ptrin, ptrout;
  171412. JSAMPROW colorindex0 = cquantize->colorindex[0];
  171413. JSAMPROW colorindex1 = cquantize->colorindex[1];
  171414. JSAMPROW colorindex2 = cquantize->colorindex[2];
  171415. int row;
  171416. JDIMENSION col;
  171417. JDIMENSION width = cinfo->output_width;
  171418. for (row = 0; row < num_rows; row++) {
  171419. ptrin = input_buf[row];
  171420. ptrout = output_buf[row];
  171421. for (col = width; col > 0; col--) {
  171422. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  171423. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  171424. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  171425. *ptrout++ = (JSAMPLE) pixcode;
  171426. }
  171427. }
  171428. }
  171429. METHODDEF(void)
  171430. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171431. JSAMPARRAY output_buf, int num_rows)
  171432. /* General case, with ordered dithering */
  171433. {
  171434. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171435. register JSAMPROW input_ptr;
  171436. register JSAMPROW output_ptr;
  171437. JSAMPROW colorindex_ci;
  171438. int * dither; /* points to active row of dither matrix */
  171439. int row_index, col_index; /* current indexes into dither matrix */
  171440. int nc = cinfo->out_color_components;
  171441. int ci;
  171442. int row;
  171443. JDIMENSION col;
  171444. JDIMENSION width = cinfo->output_width;
  171445. for (row = 0; row < num_rows; row++) {
  171446. /* Initialize output values to 0 so can process components separately */
  171447. jzero_far((void FAR *) output_buf[row],
  171448. (size_t) (width * SIZEOF(JSAMPLE)));
  171449. row_index = cquantize->row_index;
  171450. for (ci = 0; ci < nc; ci++) {
  171451. input_ptr = input_buf[row] + ci;
  171452. output_ptr = output_buf[row];
  171453. colorindex_ci = cquantize->colorindex[ci];
  171454. dither = cquantize->odither[ci][row_index];
  171455. col_index = 0;
  171456. for (col = width; col > 0; col--) {
  171457. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  171458. * select output value, accumulate into output code for this pixel.
  171459. * Range-limiting need not be done explicitly, as we have extended
  171460. * the colorindex table to produce the right answers for out-of-range
  171461. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  171462. * required amount of padding.
  171463. */
  171464. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  171465. input_ptr += nc;
  171466. output_ptr++;
  171467. col_index = (col_index + 1) & ODITHER_MASK;
  171468. }
  171469. }
  171470. /* Advance row index for next row */
  171471. row_index = (row_index + 1) & ODITHER_MASK;
  171472. cquantize->row_index = row_index;
  171473. }
  171474. }
  171475. METHODDEF(void)
  171476. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171477. JSAMPARRAY output_buf, int num_rows)
  171478. /* Fast path for out_color_components==3, with ordered dithering */
  171479. {
  171480. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171481. register int pixcode;
  171482. register JSAMPROW input_ptr;
  171483. register JSAMPROW output_ptr;
  171484. JSAMPROW colorindex0 = cquantize->colorindex[0];
  171485. JSAMPROW colorindex1 = cquantize->colorindex[1];
  171486. JSAMPROW colorindex2 = cquantize->colorindex[2];
  171487. int * dither0; /* points to active row of dither matrix */
  171488. int * dither1;
  171489. int * dither2;
  171490. int row_index, col_index; /* current indexes into dither matrix */
  171491. int row;
  171492. JDIMENSION col;
  171493. JDIMENSION width = cinfo->output_width;
  171494. for (row = 0; row < num_rows; row++) {
  171495. row_index = cquantize->row_index;
  171496. input_ptr = input_buf[row];
  171497. output_ptr = output_buf[row];
  171498. dither0 = cquantize->odither[0][row_index];
  171499. dither1 = cquantize->odither[1][row_index];
  171500. dither2 = cquantize->odither[2][row_index];
  171501. col_index = 0;
  171502. for (col = width; col > 0; col--) {
  171503. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  171504. dither0[col_index]]);
  171505. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  171506. dither1[col_index]]);
  171507. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  171508. dither2[col_index]]);
  171509. *output_ptr++ = (JSAMPLE) pixcode;
  171510. col_index = (col_index + 1) & ODITHER_MASK;
  171511. }
  171512. row_index = (row_index + 1) & ODITHER_MASK;
  171513. cquantize->row_index = row_index;
  171514. }
  171515. }
  171516. METHODDEF(void)
  171517. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171518. JSAMPARRAY output_buf, int num_rows)
  171519. /* General case, with Floyd-Steinberg dithering */
  171520. {
  171521. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171522. register LOCFSERROR cur; /* current error or pixel value */
  171523. LOCFSERROR belowerr; /* error for pixel below cur */
  171524. LOCFSERROR bpreverr; /* error for below/prev col */
  171525. LOCFSERROR bnexterr; /* error for below/next col */
  171526. LOCFSERROR delta;
  171527. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  171528. register JSAMPROW input_ptr;
  171529. register JSAMPROW output_ptr;
  171530. JSAMPROW colorindex_ci;
  171531. JSAMPROW colormap_ci;
  171532. int pixcode;
  171533. int nc = cinfo->out_color_components;
  171534. int dir; /* 1 for left-to-right, -1 for right-to-left */
  171535. int dirnc; /* dir * nc */
  171536. int ci;
  171537. int row;
  171538. JDIMENSION col;
  171539. JDIMENSION width = cinfo->output_width;
  171540. JSAMPLE *range_limit = cinfo->sample_range_limit;
  171541. SHIFT_TEMPS
  171542. for (row = 0; row < num_rows; row++) {
  171543. /* Initialize output values to 0 so can process components separately */
  171544. jzero_far((void FAR *) output_buf[row],
  171545. (size_t) (width * SIZEOF(JSAMPLE)));
  171546. for (ci = 0; ci < nc; ci++) {
  171547. input_ptr = input_buf[row] + ci;
  171548. output_ptr = output_buf[row];
  171549. if (cquantize->on_odd_row) {
  171550. /* work right to left in this row */
  171551. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  171552. output_ptr += width-1;
  171553. dir = -1;
  171554. dirnc = -nc;
  171555. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  171556. } else {
  171557. /* work left to right in this row */
  171558. dir = 1;
  171559. dirnc = nc;
  171560. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  171561. }
  171562. colorindex_ci = cquantize->colorindex[ci];
  171563. colormap_ci = cquantize->sv_colormap[ci];
  171564. /* Preset error values: no error propagated to first pixel from left */
  171565. cur = 0;
  171566. /* and no error propagated to row below yet */
  171567. belowerr = bpreverr = 0;
  171568. for (col = width; col > 0; col--) {
  171569. /* cur holds the error propagated from the previous pixel on the
  171570. * current line. Add the error propagated from the previous line
  171571. * to form the complete error correction term for this pixel, and
  171572. * round the error term (which is expressed * 16) to an integer.
  171573. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  171574. * for either sign of the error value.
  171575. * Note: errorptr points to *previous* column's array entry.
  171576. */
  171577. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  171578. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  171579. * The maximum error is +- MAXJSAMPLE; this sets the required size
  171580. * of the range_limit array.
  171581. */
  171582. cur += GETJSAMPLE(*input_ptr);
  171583. cur = GETJSAMPLE(range_limit[cur]);
  171584. /* Select output value, accumulate into output code for this pixel */
  171585. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  171586. *output_ptr += (JSAMPLE) pixcode;
  171587. /* Compute actual representation error at this pixel */
  171588. /* Note: we can do this even though we don't have the final */
  171589. /* pixel code, because the colormap is orthogonal. */
  171590. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  171591. /* Compute error fractions to be propagated to adjacent pixels.
  171592. * Add these into the running sums, and simultaneously shift the
  171593. * next-line error sums left by 1 column.
  171594. */
  171595. bnexterr = cur;
  171596. delta = cur * 2;
  171597. cur += delta; /* form error * 3 */
  171598. errorptr[0] = (FSERROR) (bpreverr + cur);
  171599. cur += delta; /* form error * 5 */
  171600. bpreverr = belowerr + cur;
  171601. belowerr = bnexterr;
  171602. cur += delta; /* form error * 7 */
  171603. /* At this point cur contains the 7/16 error value to be propagated
  171604. * to the next pixel on the current line, and all the errors for the
  171605. * next line have been shifted over. We are therefore ready to move on.
  171606. */
  171607. input_ptr += dirnc; /* advance input ptr to next column */
  171608. output_ptr += dir; /* advance output ptr to next column */
  171609. errorptr += dir; /* advance errorptr to current column */
  171610. }
  171611. /* Post-loop cleanup: we must unload the final error value into the
  171612. * final fserrors[] entry. Note we need not unload belowerr because
  171613. * it is for the dummy column before or after the actual array.
  171614. */
  171615. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  171616. }
  171617. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  171618. }
  171619. }
  171620. /*
  171621. * Allocate workspace for Floyd-Steinberg errors.
  171622. */
  171623. LOCAL(void)
  171624. alloc_fs_workspace (j_decompress_ptr cinfo)
  171625. {
  171626. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171627. size_t arraysize;
  171628. int i;
  171629. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  171630. for (i = 0; i < cinfo->out_color_components; i++) {
  171631. cquantize->fserrors[i] = (FSERRPTR)
  171632. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  171633. }
  171634. }
  171635. /*
  171636. * Initialize for one-pass color quantization.
  171637. */
  171638. METHODDEF(void)
  171639. start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  171640. {
  171641. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171642. size_t arraysize;
  171643. int i;
  171644. /* Install my colormap. */
  171645. cinfo->colormap = cquantize->sv_colormap;
  171646. cinfo->actual_number_of_colors = cquantize->sv_actual;
  171647. /* Initialize for desired dithering mode. */
  171648. switch (cinfo->dither_mode) {
  171649. case JDITHER_NONE:
  171650. if (cinfo->out_color_components == 3)
  171651. cquantize->pub.color_quantize = color_quantize3;
  171652. else
  171653. cquantize->pub.color_quantize = color_quantize;
  171654. break;
  171655. case JDITHER_ORDERED:
  171656. if (cinfo->out_color_components == 3)
  171657. cquantize->pub.color_quantize = quantize3_ord_dither;
  171658. else
  171659. cquantize->pub.color_quantize = quantize_ord_dither;
  171660. cquantize->row_index = 0; /* initialize state for ordered dither */
  171661. /* If user changed to ordered dither from another mode,
  171662. * we must recreate the color index table with padding.
  171663. * This will cost extra space, but probably isn't very likely.
  171664. */
  171665. if (! cquantize->is_padded)
  171666. create_colorindex(cinfo);
  171667. /* Create ordered-dither tables if we didn't already. */
  171668. if (cquantize->odither[0] == NULL)
  171669. create_odither_tables(cinfo);
  171670. break;
  171671. case JDITHER_FS:
  171672. cquantize->pub.color_quantize = quantize_fs_dither;
  171673. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  171674. /* Allocate Floyd-Steinberg workspace if didn't already. */
  171675. if (cquantize->fserrors[0] == NULL)
  171676. alloc_fs_workspace(cinfo);
  171677. /* Initialize the propagated errors to zero. */
  171678. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  171679. for (i = 0; i < cinfo->out_color_components; i++)
  171680. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  171681. break;
  171682. default:
  171683. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171684. break;
  171685. }
  171686. }
  171687. /*
  171688. * Finish up at the end of the pass.
  171689. */
  171690. METHODDEF(void)
  171691. finish_pass_1_quant (j_decompress_ptr cinfo)
  171692. {
  171693. /* no work in 1-pass case */
  171694. }
  171695. /*
  171696. * Switch to a new external colormap between output passes.
  171697. * Shouldn't get to this module!
  171698. */
  171699. METHODDEF(void)
  171700. new_color_map_1_quant (j_decompress_ptr cinfo)
  171701. {
  171702. ERREXIT(cinfo, JERR_MODE_CHANGE);
  171703. }
  171704. /*
  171705. * Module initialization routine for 1-pass color quantization.
  171706. */
  171707. GLOBAL(void)
  171708. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  171709. {
  171710. my_cquantize_ptr cquantize;
  171711. cquantize = (my_cquantize_ptr)
  171712. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171713. SIZEOF(my_cquantizer));
  171714. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  171715. cquantize->pub.start_pass = start_pass_1_quant;
  171716. cquantize->pub.finish_pass = finish_pass_1_quant;
  171717. cquantize->pub.new_color_map = new_color_map_1_quant;
  171718. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  171719. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  171720. /* Make sure my internal arrays won't overflow */
  171721. if (cinfo->out_color_components > MAX_Q_COMPS)
  171722. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  171723. /* Make sure colormap indexes can be represented by JSAMPLEs */
  171724. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  171725. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  171726. /* Create the colormap and color index table. */
  171727. create_colormap(cinfo);
  171728. create_colorindex(cinfo);
  171729. /* Allocate Floyd-Steinberg workspace now if requested.
  171730. * We do this now since it is FAR storage and may affect the memory
  171731. * manager's space calculations. If the user changes to FS dither
  171732. * mode in a later pass, we will allocate the space then, and will
  171733. * possibly overrun the max_memory_to_use setting.
  171734. */
  171735. if (cinfo->dither_mode == JDITHER_FS)
  171736. alloc_fs_workspace(cinfo);
  171737. }
  171738. #endif /* QUANT_1PASS_SUPPORTED */
  171739. /********* End of inlined file: jquant1.c *********/
  171740. /********* Start of inlined file: jquant2.c *********/
  171741. #define JPEG_INTERNALS
  171742. #ifdef QUANT_2PASS_SUPPORTED
  171743. /*
  171744. * This module implements the well-known Heckbert paradigm for color
  171745. * quantization. Most of the ideas used here can be traced back to
  171746. * Heckbert's seminal paper
  171747. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  171748. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  171749. *
  171750. * In the first pass over the image, we accumulate a histogram showing the
  171751. * usage count of each possible color. To keep the histogram to a reasonable
  171752. * size, we reduce the precision of the input; typical practice is to retain
  171753. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  171754. * in the same histogram cell.
  171755. *
  171756. * Next, the color-selection step begins with a box representing the whole
  171757. * color space, and repeatedly splits the "largest" remaining box until we
  171758. * have as many boxes as desired colors. Then the mean color in each
  171759. * remaining box becomes one of the possible output colors.
  171760. *
  171761. * The second pass over the image maps each input pixel to the closest output
  171762. * color (optionally after applying a Floyd-Steinberg dithering correction).
  171763. * This mapping is logically trivial, but making it go fast enough requires
  171764. * considerable care.
  171765. *
  171766. * Heckbert-style quantizers vary a good deal in their policies for choosing
  171767. * the "largest" box and deciding where to cut it. The particular policies
  171768. * used here have proved out well in experimental comparisons, but better ones
  171769. * may yet be found.
  171770. *
  171771. * In earlier versions of the IJG code, this module quantized in YCbCr color
  171772. * space, processing the raw upsampled data without a color conversion step.
  171773. * This allowed the color conversion math to be done only once per colormap
  171774. * entry, not once per pixel. However, that optimization precluded other
  171775. * useful optimizations (such as merging color conversion with upsampling)
  171776. * and it also interfered with desired capabilities such as quantizing to an
  171777. * externally-supplied colormap. We have therefore abandoned that approach.
  171778. * The present code works in the post-conversion color space, typically RGB.
  171779. *
  171780. * To improve the visual quality of the results, we actually work in scaled
  171781. * RGB space, giving G distances more weight than R, and R in turn more than
  171782. * B. To do everything in integer math, we must use integer scale factors.
  171783. * The 2/3/1 scale factors used here correspond loosely to the relative
  171784. * weights of the colors in the NTSC grayscale equation.
  171785. * If you want to use this code to quantize a non-RGB color space, you'll
  171786. * probably need to change these scale factors.
  171787. */
  171788. #define R_SCALE 2 /* scale R distances by this much */
  171789. #define G_SCALE 3 /* scale G distances by this much */
  171790. #define B_SCALE 1 /* and B by this much */
  171791. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  171792. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  171793. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  171794. * you'll get compile errors until you extend this logic. In that case
  171795. * you'll probably want to tweak the histogram sizes too.
  171796. */
  171797. #if RGB_RED == 0
  171798. #define C0_SCALE R_SCALE
  171799. #endif
  171800. #if RGB_BLUE == 0
  171801. #define C0_SCALE B_SCALE
  171802. #endif
  171803. #if RGB_GREEN == 1
  171804. #define C1_SCALE G_SCALE
  171805. #endif
  171806. #if RGB_RED == 2
  171807. #define C2_SCALE R_SCALE
  171808. #endif
  171809. #if RGB_BLUE == 2
  171810. #define C2_SCALE B_SCALE
  171811. #endif
  171812. /*
  171813. * First we have the histogram data structure and routines for creating it.
  171814. *
  171815. * The number of bits of precision can be adjusted by changing these symbols.
  171816. * We recommend keeping 6 bits for G and 5 each for R and B.
  171817. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  171818. * better results; if you are short of memory, 5 bits all around will save
  171819. * some space but degrade the results.
  171820. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  171821. * (preferably unsigned long) for each cell. In practice this is overkill;
  171822. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  171823. * and clamping those that do overflow to the maximum value will give close-
  171824. * enough results. This reduces the recommended histogram size from 256Kb
  171825. * to 128Kb, which is a useful savings on PC-class machines.
  171826. * (In the second pass the histogram space is re-used for pixel mapping data;
  171827. * in that capacity, each cell must be able to store zero to the number of
  171828. * desired colors. 16 bits/cell is plenty for that too.)
  171829. * Since the JPEG code is intended to run in small memory model on 80x86
  171830. * machines, we can't just allocate the histogram in one chunk. Instead
  171831. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  171832. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  171833. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  171834. * on 80x86 machines, the pointer row is in near memory but the actual
  171835. * arrays are in far memory (same arrangement as we use for image arrays).
  171836. */
  171837. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  171838. /* These will do the right thing for either R,G,B or B,G,R color order,
  171839. * but you may not like the results for other color orders.
  171840. */
  171841. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  171842. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  171843. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  171844. /* Number of elements along histogram axes. */
  171845. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  171846. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  171847. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  171848. /* These are the amounts to shift an input value to get a histogram index. */
  171849. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  171850. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  171851. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  171852. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  171853. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  171854. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  171855. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  171856. typedef hist2d * hist3d; /* type for top-level pointer */
  171857. /* Declarations for Floyd-Steinberg dithering.
  171858. *
  171859. * Errors are accumulated into the array fserrors[], at a resolution of
  171860. * 1/16th of a pixel count. The error at a given pixel is propagated
  171861. * to its not-yet-processed neighbors using the standard F-S fractions,
  171862. * ... (here) 7/16
  171863. * 3/16 5/16 1/16
  171864. * We work left-to-right on even rows, right-to-left on odd rows.
  171865. *
  171866. * We can get away with a single array (holding one row's worth of errors)
  171867. * by using it to store the current row's errors at pixel columns not yet
  171868. * processed, but the next row's errors at columns already processed. We
  171869. * need only a few extra variables to hold the errors immediately around the
  171870. * current column. (If we are lucky, those variables are in registers, but
  171871. * even if not, they're probably cheaper to access than array elements are.)
  171872. *
  171873. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  171874. * each end saves us from special-casing the first and last pixels.
  171875. * Each entry is three values long, one value for each color component.
  171876. *
  171877. * Note: on a wide image, we might not have enough room in a PC's near data
  171878. * segment to hold the error array; so it is allocated with alloc_large.
  171879. */
  171880. #if BITS_IN_JSAMPLE == 8
  171881. typedef INT16 FSERROR; /* 16 bits should be enough */
  171882. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  171883. #else
  171884. typedef INT32 FSERROR; /* may need more than 16 bits */
  171885. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  171886. #endif
  171887. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  171888. /* Private subobject */
  171889. typedef struct {
  171890. struct jpeg_color_quantizer pub; /* public fields */
  171891. /* Space for the eventually created colormap is stashed here */
  171892. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  171893. int desired; /* desired # of colors = size of colormap */
  171894. /* Variables for accumulating image statistics */
  171895. hist3d histogram; /* pointer to the histogram */
  171896. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  171897. /* Variables for Floyd-Steinberg dithering */
  171898. FSERRPTR fserrors; /* accumulated errors */
  171899. boolean on_odd_row; /* flag to remember which row we are on */
  171900. int * error_limiter; /* table for clamping the applied error */
  171901. } my_cquantizer2;
  171902. typedef my_cquantizer2 * my_cquantize_ptr2;
  171903. /*
  171904. * Prescan some rows of pixels.
  171905. * In this module the prescan simply updates the histogram, which has been
  171906. * initialized to zeroes by start_pass.
  171907. * An output_buf parameter is required by the method signature, but no data
  171908. * is actually output (in fact the buffer controller is probably passing a
  171909. * NULL pointer).
  171910. */
  171911. METHODDEF(void)
  171912. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171913. JSAMPARRAY output_buf, int num_rows)
  171914. {
  171915. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  171916. register JSAMPROW ptr;
  171917. register histptr histp;
  171918. register hist3d histogram = cquantize->histogram;
  171919. int row;
  171920. JDIMENSION col;
  171921. JDIMENSION width = cinfo->output_width;
  171922. for (row = 0; row < num_rows; row++) {
  171923. ptr = input_buf[row];
  171924. for (col = width; col > 0; col--) {
  171925. /* get pixel value and index into the histogram */
  171926. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  171927. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  171928. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  171929. /* increment, check for overflow and undo increment if so. */
  171930. if (++(*histp) <= 0)
  171931. (*histp)--;
  171932. ptr += 3;
  171933. }
  171934. }
  171935. }
  171936. /*
  171937. * Next we have the really interesting routines: selection of a colormap
  171938. * given the completed histogram.
  171939. * These routines work with a list of "boxes", each representing a rectangular
  171940. * subset of the input color space (to histogram precision).
  171941. */
  171942. typedef struct {
  171943. /* The bounds of the box (inclusive); expressed as histogram indexes */
  171944. int c0min, c0max;
  171945. int c1min, c1max;
  171946. int c2min, c2max;
  171947. /* The volume (actually 2-norm) of the box */
  171948. INT32 volume;
  171949. /* The number of nonzero histogram cells within this box */
  171950. long colorcount;
  171951. } box;
  171952. typedef box * boxptr;
  171953. LOCAL(boxptr)
  171954. find_biggest_color_pop (boxptr boxlist, int numboxes)
  171955. /* Find the splittable box with the largest color population */
  171956. /* Returns NULL if no splittable boxes remain */
  171957. {
  171958. register boxptr boxp;
  171959. register int i;
  171960. register long maxc = 0;
  171961. boxptr which = NULL;
  171962. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  171963. if (boxp->colorcount > maxc && boxp->volume > 0) {
  171964. which = boxp;
  171965. maxc = boxp->colorcount;
  171966. }
  171967. }
  171968. return which;
  171969. }
  171970. LOCAL(boxptr)
  171971. find_biggest_volume (boxptr boxlist, int numboxes)
  171972. /* Find the splittable box with the largest (scaled) volume */
  171973. /* Returns NULL if no splittable boxes remain */
  171974. {
  171975. register boxptr boxp;
  171976. register int i;
  171977. register INT32 maxv = 0;
  171978. boxptr which = NULL;
  171979. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  171980. if (boxp->volume > maxv) {
  171981. which = boxp;
  171982. maxv = boxp->volume;
  171983. }
  171984. }
  171985. return which;
  171986. }
  171987. LOCAL(void)
  171988. update_box (j_decompress_ptr cinfo, boxptr boxp)
  171989. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  171990. /* and recompute its volume and population */
  171991. {
  171992. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  171993. hist3d histogram = cquantize->histogram;
  171994. histptr histp;
  171995. int c0,c1,c2;
  171996. int c0min,c0max,c1min,c1max,c2min,c2max;
  171997. INT32 dist0,dist1,dist2;
  171998. long ccount;
  171999. c0min = boxp->c0min; c0max = boxp->c0max;
  172000. c1min = boxp->c1min; c1max = boxp->c1max;
  172001. c2min = boxp->c2min; c2max = boxp->c2max;
  172002. if (c0max > c0min)
  172003. for (c0 = c0min; c0 <= c0max; c0++)
  172004. for (c1 = c1min; c1 <= c1max; c1++) {
  172005. histp = & histogram[c0][c1][c2min];
  172006. for (c2 = c2min; c2 <= c2max; c2++)
  172007. if (*histp++ != 0) {
  172008. boxp->c0min = c0min = c0;
  172009. goto have_c0min;
  172010. }
  172011. }
  172012. have_c0min:
  172013. if (c0max > c0min)
  172014. for (c0 = c0max; c0 >= c0min; c0--)
  172015. for (c1 = c1min; c1 <= c1max; c1++) {
  172016. histp = & histogram[c0][c1][c2min];
  172017. for (c2 = c2min; c2 <= c2max; c2++)
  172018. if (*histp++ != 0) {
  172019. boxp->c0max = c0max = c0;
  172020. goto have_c0max;
  172021. }
  172022. }
  172023. have_c0max:
  172024. if (c1max > c1min)
  172025. for (c1 = c1min; c1 <= c1max; c1++)
  172026. for (c0 = c0min; c0 <= c0max; c0++) {
  172027. histp = & histogram[c0][c1][c2min];
  172028. for (c2 = c2min; c2 <= c2max; c2++)
  172029. if (*histp++ != 0) {
  172030. boxp->c1min = c1min = c1;
  172031. goto have_c1min;
  172032. }
  172033. }
  172034. have_c1min:
  172035. if (c1max > c1min)
  172036. for (c1 = c1max; c1 >= c1min; c1--)
  172037. for (c0 = c0min; c0 <= c0max; c0++) {
  172038. histp = & histogram[c0][c1][c2min];
  172039. for (c2 = c2min; c2 <= c2max; c2++)
  172040. if (*histp++ != 0) {
  172041. boxp->c1max = c1max = c1;
  172042. goto have_c1max;
  172043. }
  172044. }
  172045. have_c1max:
  172046. if (c2max > c2min)
  172047. for (c2 = c2min; c2 <= c2max; c2++)
  172048. for (c0 = c0min; c0 <= c0max; c0++) {
  172049. histp = & histogram[c0][c1min][c2];
  172050. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  172051. if (*histp != 0) {
  172052. boxp->c2min = c2min = c2;
  172053. goto have_c2min;
  172054. }
  172055. }
  172056. have_c2min:
  172057. if (c2max > c2min)
  172058. for (c2 = c2max; c2 >= c2min; c2--)
  172059. for (c0 = c0min; c0 <= c0max; c0++) {
  172060. histp = & histogram[c0][c1min][c2];
  172061. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  172062. if (*histp != 0) {
  172063. boxp->c2max = c2max = c2;
  172064. goto have_c2max;
  172065. }
  172066. }
  172067. have_c2max:
  172068. /* Update box volume.
  172069. * We use 2-norm rather than real volume here; this biases the method
  172070. * against making long narrow boxes, and it has the side benefit that
  172071. * a box is splittable iff norm > 0.
  172072. * Since the differences are expressed in histogram-cell units,
  172073. * we have to shift back to JSAMPLE units to get consistent distances;
  172074. * after which, we scale according to the selected distance scale factors.
  172075. */
  172076. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  172077. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  172078. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  172079. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  172080. /* Now scan remaining volume of box and compute population */
  172081. ccount = 0;
  172082. for (c0 = c0min; c0 <= c0max; c0++)
  172083. for (c1 = c1min; c1 <= c1max; c1++) {
  172084. histp = & histogram[c0][c1][c2min];
  172085. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  172086. if (*histp != 0) {
  172087. ccount++;
  172088. }
  172089. }
  172090. boxp->colorcount = ccount;
  172091. }
  172092. LOCAL(int)
  172093. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  172094. int desired_colors)
  172095. /* Repeatedly select and split the largest box until we have enough boxes */
  172096. {
  172097. int n,lb;
  172098. int c0,c1,c2,cmax;
  172099. register boxptr b1,b2;
  172100. while (numboxes < desired_colors) {
  172101. /* Select box to split.
  172102. * Current algorithm: by population for first half, then by volume.
  172103. */
  172104. if (numboxes*2 <= desired_colors) {
  172105. b1 = find_biggest_color_pop(boxlist, numboxes);
  172106. } else {
  172107. b1 = find_biggest_volume(boxlist, numboxes);
  172108. }
  172109. if (b1 == NULL) /* no splittable boxes left! */
  172110. break;
  172111. b2 = &boxlist[numboxes]; /* where new box will go */
  172112. /* Copy the color bounds to the new box. */
  172113. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  172114. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  172115. /* Choose which axis to split the box on.
  172116. * Current algorithm: longest scaled axis.
  172117. * See notes in update_box about scaling distances.
  172118. */
  172119. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  172120. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  172121. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  172122. /* We want to break any ties in favor of green, then red, blue last.
  172123. * This code does the right thing for R,G,B or B,G,R color orders only.
  172124. */
  172125. #if RGB_RED == 0
  172126. cmax = c1; n = 1;
  172127. if (c0 > cmax) { cmax = c0; n = 0; }
  172128. if (c2 > cmax) { n = 2; }
  172129. #else
  172130. cmax = c1; n = 1;
  172131. if (c2 > cmax) { cmax = c2; n = 2; }
  172132. if (c0 > cmax) { n = 0; }
  172133. #endif
  172134. /* Choose split point along selected axis, and update box bounds.
  172135. * Current algorithm: split at halfway point.
  172136. * (Since the box has been shrunk to minimum volume,
  172137. * any split will produce two nonempty subboxes.)
  172138. * Note that lb value is max for lower box, so must be < old max.
  172139. */
  172140. switch (n) {
  172141. case 0:
  172142. lb = (b1->c0max + b1->c0min) / 2;
  172143. b1->c0max = lb;
  172144. b2->c0min = lb+1;
  172145. break;
  172146. case 1:
  172147. lb = (b1->c1max + b1->c1min) / 2;
  172148. b1->c1max = lb;
  172149. b2->c1min = lb+1;
  172150. break;
  172151. case 2:
  172152. lb = (b1->c2max + b1->c2min) / 2;
  172153. b1->c2max = lb;
  172154. b2->c2min = lb+1;
  172155. break;
  172156. }
  172157. /* Update stats for boxes */
  172158. update_box(cinfo, b1);
  172159. update_box(cinfo, b2);
  172160. numboxes++;
  172161. }
  172162. return numboxes;
  172163. }
  172164. LOCAL(void)
  172165. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  172166. /* Compute representative color for a box, put it in colormap[icolor] */
  172167. {
  172168. /* Current algorithm: mean weighted by pixels (not colors) */
  172169. /* Note it is important to get the rounding correct! */
  172170. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172171. hist3d histogram = cquantize->histogram;
  172172. histptr histp;
  172173. int c0,c1,c2;
  172174. int c0min,c0max,c1min,c1max,c2min,c2max;
  172175. long count;
  172176. long total = 0;
  172177. long c0total = 0;
  172178. long c1total = 0;
  172179. long c2total = 0;
  172180. c0min = boxp->c0min; c0max = boxp->c0max;
  172181. c1min = boxp->c1min; c1max = boxp->c1max;
  172182. c2min = boxp->c2min; c2max = boxp->c2max;
  172183. for (c0 = c0min; c0 <= c0max; c0++)
  172184. for (c1 = c1min; c1 <= c1max; c1++) {
  172185. histp = & histogram[c0][c1][c2min];
  172186. for (c2 = c2min; c2 <= c2max; c2++) {
  172187. if ((count = *histp++) != 0) {
  172188. total += count;
  172189. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  172190. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  172191. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  172192. }
  172193. }
  172194. }
  172195. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  172196. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  172197. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  172198. }
  172199. LOCAL(void)
  172200. select_colors (j_decompress_ptr cinfo, int desired_colors)
  172201. /* Master routine for color selection */
  172202. {
  172203. boxptr boxlist;
  172204. int numboxes;
  172205. int i;
  172206. /* Allocate workspace for box list */
  172207. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  172208. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  172209. /* Initialize one box containing whole space */
  172210. numboxes = 1;
  172211. boxlist[0].c0min = 0;
  172212. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  172213. boxlist[0].c1min = 0;
  172214. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  172215. boxlist[0].c2min = 0;
  172216. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  172217. /* Shrink it to actually-used volume and set its statistics */
  172218. update_box(cinfo, & boxlist[0]);
  172219. /* Perform median-cut to produce final box list */
  172220. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  172221. /* Compute the representative color for each box, fill colormap */
  172222. for (i = 0; i < numboxes; i++)
  172223. compute_color(cinfo, & boxlist[i], i);
  172224. cinfo->actual_number_of_colors = numboxes;
  172225. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  172226. }
  172227. /*
  172228. * These routines are concerned with the time-critical task of mapping input
  172229. * colors to the nearest color in the selected colormap.
  172230. *
  172231. * We re-use the histogram space as an "inverse color map", essentially a
  172232. * cache for the results of nearest-color searches. All colors within a
  172233. * histogram cell will be mapped to the same colormap entry, namely the one
  172234. * closest to the cell's center. This may not be quite the closest entry to
  172235. * the actual input color, but it's almost as good. A zero in the cache
  172236. * indicates we haven't found the nearest color for that cell yet; the array
  172237. * is cleared to zeroes before starting the mapping pass. When we find the
  172238. * nearest color for a cell, its colormap index plus one is recorded in the
  172239. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  172240. * when they need to use an unfilled entry in the cache.
  172241. *
  172242. * Our method of efficiently finding nearest colors is based on the "locally
  172243. * sorted search" idea described by Heckbert and on the incremental distance
  172244. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  172245. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  172246. * the distances from a given colormap entry to each cell of the histogram can
  172247. * be computed quickly using an incremental method: the differences between
  172248. * distances to adjacent cells themselves differ by a constant. This allows a
  172249. * fairly fast implementation of the "brute force" approach of computing the
  172250. * distance from every colormap entry to every histogram cell. Unfortunately,
  172251. * it needs a work array to hold the best-distance-so-far for each histogram
  172252. * cell (because the inner loop has to be over cells, not colormap entries).
  172253. * The work array elements have to be INT32s, so the work array would need
  172254. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  172255. *
  172256. * To get around these problems, we apply Thomas' method to compute the
  172257. * nearest colors for only the cells within a small subbox of the histogram.
  172258. * The work array need be only as big as the subbox, so the memory usage
  172259. * problem is solved. Furthermore, we need not fill subboxes that are never
  172260. * referenced in pass2; many images use only part of the color gamut, so a
  172261. * fair amount of work is saved. An additional advantage of this
  172262. * approach is that we can apply Heckbert's locality criterion to quickly
  172263. * eliminate colormap entries that are far away from the subbox; typically
  172264. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  172265. * and we need not compute their distances to individual cells in the subbox.
  172266. * The speed of this approach is heavily influenced by the subbox size: too
  172267. * small means too much overhead, too big loses because Heckbert's criterion
  172268. * can't eliminate as many colormap entries. Empirically the best subbox
  172269. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  172270. *
  172271. * Thomas' article also describes a refined method which is asymptotically
  172272. * faster than the brute-force method, but it is also far more complex and
  172273. * cannot efficiently be applied to small subboxes. It is therefore not
  172274. * useful for programs intended to be portable to DOS machines. On machines
  172275. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  172276. * refined method might be faster than the present code --- but then again,
  172277. * it might not be any faster, and it's certainly more complicated.
  172278. */
  172279. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  172280. #define BOX_C0_LOG (HIST_C0_BITS-3)
  172281. #define BOX_C1_LOG (HIST_C1_BITS-3)
  172282. #define BOX_C2_LOG (HIST_C2_BITS-3)
  172283. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  172284. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  172285. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  172286. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  172287. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  172288. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  172289. /*
  172290. * The next three routines implement inverse colormap filling. They could
  172291. * all be folded into one big routine, but splitting them up this way saves
  172292. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  172293. * and may allow some compilers to produce better code by registerizing more
  172294. * inner-loop variables.
  172295. */
  172296. LOCAL(int)
  172297. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  172298. JSAMPLE colorlist[])
  172299. /* Locate the colormap entries close enough to an update box to be candidates
  172300. * for the nearest entry to some cell(s) in the update box. The update box
  172301. * is specified by the center coordinates of its first cell. The number of
  172302. * candidate colormap entries is returned, and their colormap indexes are
  172303. * placed in colorlist[].
  172304. * This routine uses Heckbert's "locally sorted search" criterion to select
  172305. * the colors that need further consideration.
  172306. */
  172307. {
  172308. int numcolors = cinfo->actual_number_of_colors;
  172309. int maxc0, maxc1, maxc2;
  172310. int centerc0, centerc1, centerc2;
  172311. int i, x, ncolors;
  172312. INT32 minmaxdist, min_dist, max_dist, tdist;
  172313. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  172314. /* Compute true coordinates of update box's upper corner and center.
  172315. * Actually we compute the coordinates of the center of the upper-corner
  172316. * histogram cell, which are the upper bounds of the volume we care about.
  172317. * Note that since ">>" rounds down, the "center" values may be closer to
  172318. * min than to max; hence comparisons to them must be "<=", not "<".
  172319. */
  172320. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  172321. centerc0 = (minc0 + maxc0) >> 1;
  172322. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  172323. centerc1 = (minc1 + maxc1) >> 1;
  172324. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  172325. centerc2 = (minc2 + maxc2) >> 1;
  172326. /* For each color in colormap, find:
  172327. * 1. its minimum squared-distance to any point in the update box
  172328. * (zero if color is within update box);
  172329. * 2. its maximum squared-distance to any point in the update box.
  172330. * Both of these can be found by considering only the corners of the box.
  172331. * We save the minimum distance for each color in mindist[];
  172332. * only the smallest maximum distance is of interest.
  172333. */
  172334. minmaxdist = 0x7FFFFFFFL;
  172335. for (i = 0; i < numcolors; i++) {
  172336. /* We compute the squared-c0-distance term, then add in the other two. */
  172337. x = GETJSAMPLE(cinfo->colormap[0][i]);
  172338. if (x < minc0) {
  172339. tdist = (x - minc0) * C0_SCALE;
  172340. min_dist = tdist*tdist;
  172341. tdist = (x - maxc0) * C0_SCALE;
  172342. max_dist = tdist*tdist;
  172343. } else if (x > maxc0) {
  172344. tdist = (x - maxc0) * C0_SCALE;
  172345. min_dist = tdist*tdist;
  172346. tdist = (x - minc0) * C0_SCALE;
  172347. max_dist = tdist*tdist;
  172348. } else {
  172349. /* within cell range so no contribution to min_dist */
  172350. min_dist = 0;
  172351. if (x <= centerc0) {
  172352. tdist = (x - maxc0) * C0_SCALE;
  172353. max_dist = tdist*tdist;
  172354. } else {
  172355. tdist = (x - minc0) * C0_SCALE;
  172356. max_dist = tdist*tdist;
  172357. }
  172358. }
  172359. x = GETJSAMPLE(cinfo->colormap[1][i]);
  172360. if (x < minc1) {
  172361. tdist = (x - minc1) * C1_SCALE;
  172362. min_dist += tdist*tdist;
  172363. tdist = (x - maxc1) * C1_SCALE;
  172364. max_dist += tdist*tdist;
  172365. } else if (x > maxc1) {
  172366. tdist = (x - maxc1) * C1_SCALE;
  172367. min_dist += tdist*tdist;
  172368. tdist = (x - minc1) * C1_SCALE;
  172369. max_dist += tdist*tdist;
  172370. } else {
  172371. /* within cell range so no contribution to min_dist */
  172372. if (x <= centerc1) {
  172373. tdist = (x - maxc1) * C1_SCALE;
  172374. max_dist += tdist*tdist;
  172375. } else {
  172376. tdist = (x - minc1) * C1_SCALE;
  172377. max_dist += tdist*tdist;
  172378. }
  172379. }
  172380. x = GETJSAMPLE(cinfo->colormap[2][i]);
  172381. if (x < minc2) {
  172382. tdist = (x - minc2) * C2_SCALE;
  172383. min_dist += tdist*tdist;
  172384. tdist = (x - maxc2) * C2_SCALE;
  172385. max_dist += tdist*tdist;
  172386. } else if (x > maxc2) {
  172387. tdist = (x - maxc2) * C2_SCALE;
  172388. min_dist += tdist*tdist;
  172389. tdist = (x - minc2) * C2_SCALE;
  172390. max_dist += tdist*tdist;
  172391. } else {
  172392. /* within cell range so no contribution to min_dist */
  172393. if (x <= centerc2) {
  172394. tdist = (x - maxc2) * C2_SCALE;
  172395. max_dist += tdist*tdist;
  172396. } else {
  172397. tdist = (x - minc2) * C2_SCALE;
  172398. max_dist += tdist*tdist;
  172399. }
  172400. }
  172401. mindist[i] = min_dist; /* save away the results */
  172402. if (max_dist < minmaxdist)
  172403. minmaxdist = max_dist;
  172404. }
  172405. /* Now we know that no cell in the update box is more than minmaxdist
  172406. * away from some colormap entry. Therefore, only colors that are
  172407. * within minmaxdist of some part of the box need be considered.
  172408. */
  172409. ncolors = 0;
  172410. for (i = 0; i < numcolors; i++) {
  172411. if (mindist[i] <= minmaxdist)
  172412. colorlist[ncolors++] = (JSAMPLE) i;
  172413. }
  172414. return ncolors;
  172415. }
  172416. LOCAL(void)
  172417. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  172418. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  172419. /* Find the closest colormap entry for each cell in the update box,
  172420. * given the list of candidate colors prepared by find_nearby_colors.
  172421. * Return the indexes of the closest entries in the bestcolor[] array.
  172422. * This routine uses Thomas' incremental distance calculation method to
  172423. * find the distance from a colormap entry to successive cells in the box.
  172424. */
  172425. {
  172426. int ic0, ic1, ic2;
  172427. int i, icolor;
  172428. register INT32 * bptr; /* pointer into bestdist[] array */
  172429. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  172430. INT32 dist0, dist1; /* initial distance values */
  172431. register INT32 dist2; /* current distance in inner loop */
  172432. INT32 xx0, xx1; /* distance increments */
  172433. register INT32 xx2;
  172434. INT32 inc0, inc1, inc2; /* initial values for increments */
  172435. /* This array holds the distance to the nearest-so-far color for each cell */
  172436. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  172437. /* Initialize best-distance for each cell of the update box */
  172438. bptr = bestdist;
  172439. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  172440. *bptr++ = 0x7FFFFFFFL;
  172441. /* For each color selected by find_nearby_colors,
  172442. * compute its distance to the center of each cell in the box.
  172443. * If that's less than best-so-far, update best distance and color number.
  172444. */
  172445. /* Nominal steps between cell centers ("x" in Thomas article) */
  172446. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  172447. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  172448. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  172449. for (i = 0; i < numcolors; i++) {
  172450. icolor = GETJSAMPLE(colorlist[i]);
  172451. /* Compute (square of) distance from minc0/c1/c2 to this color */
  172452. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  172453. dist0 = inc0*inc0;
  172454. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  172455. dist0 += inc1*inc1;
  172456. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  172457. dist0 += inc2*inc2;
  172458. /* Form the initial difference increments */
  172459. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  172460. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  172461. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  172462. /* Now loop over all cells in box, updating distance per Thomas method */
  172463. bptr = bestdist;
  172464. cptr = bestcolor;
  172465. xx0 = inc0;
  172466. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  172467. dist1 = dist0;
  172468. xx1 = inc1;
  172469. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  172470. dist2 = dist1;
  172471. xx2 = inc2;
  172472. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  172473. if (dist2 < *bptr) {
  172474. *bptr = dist2;
  172475. *cptr = (JSAMPLE) icolor;
  172476. }
  172477. dist2 += xx2;
  172478. xx2 += 2 * STEP_C2 * STEP_C2;
  172479. bptr++;
  172480. cptr++;
  172481. }
  172482. dist1 += xx1;
  172483. xx1 += 2 * STEP_C1 * STEP_C1;
  172484. }
  172485. dist0 += xx0;
  172486. xx0 += 2 * STEP_C0 * STEP_C0;
  172487. }
  172488. }
  172489. }
  172490. LOCAL(void)
  172491. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  172492. /* Fill the inverse-colormap entries in the update box that contains */
  172493. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  172494. /* we can fill as many others as we wish.) */
  172495. {
  172496. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172497. hist3d histogram = cquantize->histogram;
  172498. int minc0, minc1, minc2; /* lower left corner of update box */
  172499. int ic0, ic1, ic2;
  172500. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  172501. register histptr cachep; /* pointer into main cache array */
  172502. /* This array lists the candidate colormap indexes. */
  172503. JSAMPLE colorlist[MAXNUMCOLORS];
  172504. int numcolors; /* number of candidate colors */
  172505. /* This array holds the actually closest colormap index for each cell. */
  172506. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  172507. /* Convert cell coordinates to update box ID */
  172508. c0 >>= BOX_C0_LOG;
  172509. c1 >>= BOX_C1_LOG;
  172510. c2 >>= BOX_C2_LOG;
  172511. /* Compute true coordinates of update box's origin corner.
  172512. * Actually we compute the coordinates of the center of the corner
  172513. * histogram cell, which are the lower bounds of the volume we care about.
  172514. */
  172515. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  172516. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  172517. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  172518. /* Determine which colormap entries are close enough to be candidates
  172519. * for the nearest entry to some cell in the update box.
  172520. */
  172521. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  172522. /* Determine the actually nearest colors. */
  172523. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  172524. bestcolor);
  172525. /* Save the best color numbers (plus 1) in the main cache array */
  172526. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  172527. c1 <<= BOX_C1_LOG;
  172528. c2 <<= BOX_C2_LOG;
  172529. cptr = bestcolor;
  172530. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  172531. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  172532. cachep = & histogram[c0+ic0][c1+ic1][c2];
  172533. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  172534. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  172535. }
  172536. }
  172537. }
  172538. }
  172539. /*
  172540. * Map some rows of pixels to the output colormapped representation.
  172541. */
  172542. METHODDEF(void)
  172543. pass2_no_dither (j_decompress_ptr cinfo,
  172544. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  172545. /* This version performs no dithering */
  172546. {
  172547. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172548. hist3d histogram = cquantize->histogram;
  172549. register JSAMPROW inptr, outptr;
  172550. register histptr cachep;
  172551. register int c0, c1, c2;
  172552. int row;
  172553. JDIMENSION col;
  172554. JDIMENSION width = cinfo->output_width;
  172555. for (row = 0; row < num_rows; row++) {
  172556. inptr = input_buf[row];
  172557. outptr = output_buf[row];
  172558. for (col = width; col > 0; col--) {
  172559. /* get pixel value and index into the cache */
  172560. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  172561. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  172562. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  172563. cachep = & histogram[c0][c1][c2];
  172564. /* If we have not seen this color before, find nearest colormap entry */
  172565. /* and update the cache */
  172566. if (*cachep == 0)
  172567. fill_inverse_cmap(cinfo, c0,c1,c2);
  172568. /* Now emit the colormap index for this cell */
  172569. *outptr++ = (JSAMPLE) (*cachep - 1);
  172570. }
  172571. }
  172572. }
  172573. METHODDEF(void)
  172574. pass2_fs_dither (j_decompress_ptr cinfo,
  172575. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  172576. /* This version performs Floyd-Steinberg dithering */
  172577. {
  172578. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172579. hist3d histogram = cquantize->histogram;
  172580. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  172581. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  172582. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  172583. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  172584. JSAMPROW inptr; /* => current input pixel */
  172585. JSAMPROW outptr; /* => current output pixel */
  172586. histptr cachep;
  172587. int dir; /* +1 or -1 depending on direction */
  172588. int dir3; /* 3*dir, for advancing inptr & errorptr */
  172589. int row;
  172590. JDIMENSION col;
  172591. JDIMENSION width = cinfo->output_width;
  172592. JSAMPLE *range_limit = cinfo->sample_range_limit;
  172593. int *error_limit = cquantize->error_limiter;
  172594. JSAMPROW colormap0 = cinfo->colormap[0];
  172595. JSAMPROW colormap1 = cinfo->colormap[1];
  172596. JSAMPROW colormap2 = cinfo->colormap[2];
  172597. SHIFT_TEMPS
  172598. for (row = 0; row < num_rows; row++) {
  172599. inptr = input_buf[row];
  172600. outptr = output_buf[row];
  172601. if (cquantize->on_odd_row) {
  172602. /* work right to left in this row */
  172603. inptr += (width-1) * 3; /* so point to rightmost pixel */
  172604. outptr += width-1;
  172605. dir = -1;
  172606. dir3 = -3;
  172607. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  172608. cquantize->on_odd_row = FALSE; /* flip for next time */
  172609. } else {
  172610. /* work left to right in this row */
  172611. dir = 1;
  172612. dir3 = 3;
  172613. errorptr = cquantize->fserrors; /* => entry before first real column */
  172614. cquantize->on_odd_row = TRUE; /* flip for next time */
  172615. }
  172616. /* Preset error values: no error propagated to first pixel from left */
  172617. cur0 = cur1 = cur2 = 0;
  172618. /* and no error propagated to row below yet */
  172619. belowerr0 = belowerr1 = belowerr2 = 0;
  172620. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  172621. for (col = width; col > 0; col--) {
  172622. /* curN holds the error propagated from the previous pixel on the
  172623. * current line. Add the error propagated from the previous line
  172624. * to form the complete error correction term for this pixel, and
  172625. * round the error term (which is expressed * 16) to an integer.
  172626. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  172627. * for either sign of the error value.
  172628. * Note: errorptr points to *previous* column's array entry.
  172629. */
  172630. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  172631. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  172632. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  172633. /* Limit the error using transfer function set by init_error_limit.
  172634. * See comments with init_error_limit for rationale.
  172635. */
  172636. cur0 = error_limit[cur0];
  172637. cur1 = error_limit[cur1];
  172638. cur2 = error_limit[cur2];
  172639. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  172640. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  172641. * this sets the required size of the range_limit array.
  172642. */
  172643. cur0 += GETJSAMPLE(inptr[0]);
  172644. cur1 += GETJSAMPLE(inptr[1]);
  172645. cur2 += GETJSAMPLE(inptr[2]);
  172646. cur0 = GETJSAMPLE(range_limit[cur0]);
  172647. cur1 = GETJSAMPLE(range_limit[cur1]);
  172648. cur2 = GETJSAMPLE(range_limit[cur2]);
  172649. /* Index into the cache with adjusted pixel value */
  172650. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  172651. /* If we have not seen this color before, find nearest colormap */
  172652. /* entry and update the cache */
  172653. if (*cachep == 0)
  172654. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  172655. /* Now emit the colormap index for this cell */
  172656. { register int pixcode = *cachep - 1;
  172657. *outptr = (JSAMPLE) pixcode;
  172658. /* Compute representation error for this pixel */
  172659. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  172660. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  172661. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  172662. }
  172663. /* Compute error fractions to be propagated to adjacent pixels.
  172664. * Add these into the running sums, and simultaneously shift the
  172665. * next-line error sums left by 1 column.
  172666. */
  172667. { register LOCFSERROR bnexterr, delta;
  172668. bnexterr = cur0; /* Process component 0 */
  172669. delta = cur0 * 2;
  172670. cur0 += delta; /* form error * 3 */
  172671. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  172672. cur0 += delta; /* form error * 5 */
  172673. bpreverr0 = belowerr0 + cur0;
  172674. belowerr0 = bnexterr;
  172675. cur0 += delta; /* form error * 7 */
  172676. bnexterr = cur1; /* Process component 1 */
  172677. delta = cur1 * 2;
  172678. cur1 += delta; /* form error * 3 */
  172679. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  172680. cur1 += delta; /* form error * 5 */
  172681. bpreverr1 = belowerr1 + cur1;
  172682. belowerr1 = bnexterr;
  172683. cur1 += delta; /* form error * 7 */
  172684. bnexterr = cur2; /* Process component 2 */
  172685. delta = cur2 * 2;
  172686. cur2 += delta; /* form error * 3 */
  172687. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  172688. cur2 += delta; /* form error * 5 */
  172689. bpreverr2 = belowerr2 + cur2;
  172690. belowerr2 = bnexterr;
  172691. cur2 += delta; /* form error * 7 */
  172692. }
  172693. /* At this point curN contains the 7/16 error value to be propagated
  172694. * to the next pixel on the current line, and all the errors for the
  172695. * next line have been shifted over. We are therefore ready to move on.
  172696. */
  172697. inptr += dir3; /* Advance pixel pointers to next column */
  172698. outptr += dir;
  172699. errorptr += dir3; /* advance errorptr to current column */
  172700. }
  172701. /* Post-loop cleanup: we must unload the final error values into the
  172702. * final fserrors[] entry. Note we need not unload belowerrN because
  172703. * it is for the dummy column before or after the actual array.
  172704. */
  172705. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  172706. errorptr[1] = (FSERROR) bpreverr1;
  172707. errorptr[2] = (FSERROR) bpreverr2;
  172708. }
  172709. }
  172710. /*
  172711. * Initialize the error-limiting transfer function (lookup table).
  172712. * The raw F-S error computation can potentially compute error values of up to
  172713. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  172714. * much less, otherwise obviously wrong pixels will be created. (Typical
  172715. * effects include weird fringes at color-area boundaries, isolated bright
  172716. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  172717. * is to ensure that the "corners" of the color cube are allocated as output
  172718. * colors; then repeated errors in the same direction cannot cause cascading
  172719. * error buildup. However, that only prevents the error from getting
  172720. * completely out of hand; Aaron Giles reports that error limiting improves
  172721. * the results even with corner colors allocated.
  172722. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  172723. * well, but the smoother transfer function used below is even better. Thanks
  172724. * to Aaron Giles for this idea.
  172725. */
  172726. LOCAL(void)
  172727. init_error_limit (j_decompress_ptr cinfo)
  172728. /* Allocate and fill in the error_limiter table */
  172729. {
  172730. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172731. int * table;
  172732. int in, out;
  172733. table = (int *) (*cinfo->mem->alloc_small)
  172734. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  172735. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  172736. cquantize->error_limiter = table;
  172737. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  172738. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  172739. out = 0;
  172740. for (in = 0; in < STEPSIZE; in++, out++) {
  172741. table[in] = out; table[-in] = -out;
  172742. }
  172743. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  172744. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  172745. table[in] = out; table[-in] = -out;
  172746. }
  172747. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  172748. for (; in <= MAXJSAMPLE; in++) {
  172749. table[in] = out; table[-in] = -out;
  172750. }
  172751. #undef STEPSIZE
  172752. }
  172753. /*
  172754. * Finish up at the end of each pass.
  172755. */
  172756. METHODDEF(void)
  172757. finish_pass1 (j_decompress_ptr cinfo)
  172758. {
  172759. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172760. /* Select the representative colors and fill in cinfo->colormap */
  172761. cinfo->colormap = cquantize->sv_colormap;
  172762. select_colors(cinfo, cquantize->desired);
  172763. /* Force next pass to zero the color index table */
  172764. cquantize->needs_zeroed = TRUE;
  172765. }
  172766. METHODDEF(void)
  172767. finish_pass2 (j_decompress_ptr cinfo)
  172768. {
  172769. /* no work */
  172770. }
  172771. /*
  172772. * Initialize for each processing pass.
  172773. */
  172774. METHODDEF(void)
  172775. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  172776. {
  172777. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172778. hist3d histogram = cquantize->histogram;
  172779. int i;
  172780. /* Only F-S dithering or no dithering is supported. */
  172781. /* If user asks for ordered dither, give him F-S. */
  172782. if (cinfo->dither_mode != JDITHER_NONE)
  172783. cinfo->dither_mode = JDITHER_FS;
  172784. if (is_pre_scan) {
  172785. /* Set up method pointers */
  172786. cquantize->pub.color_quantize = prescan_quantize;
  172787. cquantize->pub.finish_pass = finish_pass1;
  172788. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  172789. } else {
  172790. /* Set up method pointers */
  172791. if (cinfo->dither_mode == JDITHER_FS)
  172792. cquantize->pub.color_quantize = pass2_fs_dither;
  172793. else
  172794. cquantize->pub.color_quantize = pass2_no_dither;
  172795. cquantize->pub.finish_pass = finish_pass2;
  172796. /* Make sure color count is acceptable */
  172797. i = cinfo->actual_number_of_colors;
  172798. if (i < 1)
  172799. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  172800. if (i > MAXNUMCOLORS)
  172801. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  172802. if (cinfo->dither_mode == JDITHER_FS) {
  172803. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  172804. (3 * SIZEOF(FSERROR)));
  172805. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  172806. if (cquantize->fserrors == NULL)
  172807. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  172808. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  172809. /* Initialize the propagated errors to zero. */
  172810. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  172811. /* Make the error-limit table if we didn't already. */
  172812. if (cquantize->error_limiter == NULL)
  172813. init_error_limit(cinfo);
  172814. cquantize->on_odd_row = FALSE;
  172815. }
  172816. }
  172817. /* Zero the histogram or inverse color map, if necessary */
  172818. if (cquantize->needs_zeroed) {
  172819. for (i = 0; i < HIST_C0_ELEMS; i++) {
  172820. jzero_far((void FAR *) histogram[i],
  172821. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  172822. }
  172823. cquantize->needs_zeroed = FALSE;
  172824. }
  172825. }
  172826. /*
  172827. * Switch to a new external colormap between output passes.
  172828. */
  172829. METHODDEF(void)
  172830. new_color_map_2_quant (j_decompress_ptr cinfo)
  172831. {
  172832. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172833. /* Reset the inverse color map */
  172834. cquantize->needs_zeroed = TRUE;
  172835. }
  172836. /*
  172837. * Module initialization routine for 2-pass color quantization.
  172838. */
  172839. GLOBAL(void)
  172840. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  172841. {
  172842. my_cquantize_ptr2 cquantize;
  172843. int i;
  172844. cquantize = (my_cquantize_ptr2)
  172845. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172846. SIZEOF(my_cquantizer2));
  172847. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  172848. cquantize->pub.start_pass = start_pass_2_quant;
  172849. cquantize->pub.new_color_map = new_color_map_2_quant;
  172850. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  172851. cquantize->error_limiter = NULL;
  172852. /* Make sure jdmaster didn't give me a case I can't handle */
  172853. if (cinfo->out_color_components != 3)
  172854. ERREXIT(cinfo, JERR_NOTIMPL);
  172855. /* Allocate the histogram/inverse colormap storage */
  172856. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  172857. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  172858. for (i = 0; i < HIST_C0_ELEMS; i++) {
  172859. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  172860. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172861. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  172862. }
  172863. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  172864. /* Allocate storage for the completed colormap, if required.
  172865. * We do this now since it is FAR storage and may affect
  172866. * the memory manager's space calculations.
  172867. */
  172868. if (cinfo->enable_2pass_quant) {
  172869. /* Make sure color count is acceptable */
  172870. int desired = cinfo->desired_number_of_colors;
  172871. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  172872. if (desired < 8)
  172873. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  172874. /* Make sure colormap indexes can be represented by JSAMPLEs */
  172875. if (desired > MAXNUMCOLORS)
  172876. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  172877. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  172878. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  172879. cquantize->desired = desired;
  172880. } else
  172881. cquantize->sv_colormap = NULL;
  172882. /* Only F-S dithering or no dithering is supported. */
  172883. /* If user asks for ordered dither, give him F-S. */
  172884. if (cinfo->dither_mode != JDITHER_NONE)
  172885. cinfo->dither_mode = JDITHER_FS;
  172886. /* Allocate Floyd-Steinberg workspace if necessary.
  172887. * This isn't really needed until pass 2, but again it is FAR storage.
  172888. * Although we will cope with a later change in dither_mode,
  172889. * we do not promise to honor max_memory_to_use if dither_mode changes.
  172890. */
  172891. if (cinfo->dither_mode == JDITHER_FS) {
  172892. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  172893. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172894. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  172895. /* Might as well create the error-limiting table too. */
  172896. init_error_limit(cinfo);
  172897. }
  172898. }
  172899. #endif /* QUANT_2PASS_SUPPORTED */
  172900. /********* End of inlined file: jquant2.c *********/
  172901. /********* Start of inlined file: jutils.c *********/
  172902. #define JPEG_INTERNALS
  172903. /*
  172904. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  172905. * of a DCT block read in natural order (left to right, top to bottom).
  172906. */
  172907. #if 0 /* This table is not actually needed in v6a */
  172908. const int jpeg_zigzag_order[DCTSIZE2] = {
  172909. 0, 1, 5, 6, 14, 15, 27, 28,
  172910. 2, 4, 7, 13, 16, 26, 29, 42,
  172911. 3, 8, 12, 17, 25, 30, 41, 43,
  172912. 9, 11, 18, 24, 31, 40, 44, 53,
  172913. 10, 19, 23, 32, 39, 45, 52, 54,
  172914. 20, 22, 33, 38, 46, 51, 55, 60,
  172915. 21, 34, 37, 47, 50, 56, 59, 61,
  172916. 35, 36, 48, 49, 57, 58, 62, 63
  172917. };
  172918. #endif
  172919. /*
  172920. * jpeg_natural_order[i] is the natural-order position of the i'th element
  172921. * of zigzag order.
  172922. *
  172923. * When reading corrupted data, the Huffman decoders could attempt
  172924. * to reference an entry beyond the end of this array (if the decoded
  172925. * zero run length reaches past the end of the block). To prevent
  172926. * wild stores without adding an inner-loop test, we put some extra
  172927. * "63"s after the real entries. This will cause the extra coefficient
  172928. * to be stored in location 63 of the block, not somewhere random.
  172929. * The worst case would be a run-length of 15, which means we need 16
  172930. * fake entries.
  172931. */
  172932. const int jpeg_natural_order[DCTSIZE2+16] = {
  172933. 0, 1, 8, 16, 9, 2, 3, 10,
  172934. 17, 24, 32, 25, 18, 11, 4, 5,
  172935. 12, 19, 26, 33, 40, 48, 41, 34,
  172936. 27, 20, 13, 6, 7, 14, 21, 28,
  172937. 35, 42, 49, 56, 57, 50, 43, 36,
  172938. 29, 22, 15, 23, 30, 37, 44, 51,
  172939. 58, 59, 52, 45, 38, 31, 39, 46,
  172940. 53, 60, 61, 54, 47, 55, 62, 63,
  172941. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  172942. 63, 63, 63, 63, 63, 63, 63, 63
  172943. };
  172944. /*
  172945. * Arithmetic utilities
  172946. */
  172947. GLOBAL(long)
  172948. jdiv_round_up (long a, long b)
  172949. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  172950. /* Assumes a >= 0, b > 0 */
  172951. {
  172952. return (a + b - 1L) / b;
  172953. }
  172954. GLOBAL(long)
  172955. jround_up (long a, long b)
  172956. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  172957. /* Assumes a >= 0, b > 0 */
  172958. {
  172959. a += b - 1L;
  172960. return a - (a % b);
  172961. }
  172962. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  172963. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  172964. * are FAR and we're assuming a small-pointer memory model. However, some
  172965. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  172966. * in the small-model libraries. These will be used if USE_FMEM is defined.
  172967. * Otherwise, the routines below do it the hard way. (The performance cost
  172968. * is not all that great, because these routines aren't very heavily used.)
  172969. */
  172970. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  172971. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  172972. #define FMEMZERO(target,size) MEMZERO(target,size)
  172973. #else /* 80x86 case, define if we can */
  172974. #ifdef USE_FMEM
  172975. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  172976. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  172977. #endif
  172978. #endif
  172979. GLOBAL(void)
  172980. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  172981. JSAMPARRAY output_array, int dest_row,
  172982. int num_rows, JDIMENSION num_cols)
  172983. /* Copy some rows of samples from one place to another.
  172984. * num_rows rows are copied from input_array[source_row++]
  172985. * to output_array[dest_row++]; these areas may overlap for duplication.
  172986. * The source and destination arrays must be at least as wide as num_cols.
  172987. */
  172988. {
  172989. register JSAMPROW inptr, outptr;
  172990. #ifdef FMEMCOPY
  172991. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  172992. #else
  172993. register JDIMENSION count;
  172994. #endif
  172995. register int row;
  172996. input_array += source_row;
  172997. output_array += dest_row;
  172998. for (row = num_rows; row > 0; row--) {
  172999. inptr = *input_array++;
  173000. outptr = *output_array++;
  173001. #ifdef FMEMCOPY
  173002. FMEMCOPY(outptr, inptr, count);
  173003. #else
  173004. for (count = num_cols; count > 0; count--)
  173005. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  173006. #endif
  173007. }
  173008. }
  173009. GLOBAL(void)
  173010. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  173011. JDIMENSION num_blocks)
  173012. /* Copy a row of coefficient blocks from one place to another. */
  173013. {
  173014. #ifdef FMEMCOPY
  173015. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  173016. #else
  173017. register JCOEFPTR inptr, outptr;
  173018. register long count;
  173019. inptr = (JCOEFPTR) input_row;
  173020. outptr = (JCOEFPTR) output_row;
  173021. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  173022. *outptr++ = *inptr++;
  173023. }
  173024. #endif
  173025. }
  173026. GLOBAL(void)
  173027. jzero_far (void FAR * target, size_t bytestozero)
  173028. /* Zero out a chunk of FAR memory. */
  173029. /* This might be sample-array data, block-array data, or alloc_large data. */
  173030. {
  173031. #ifdef FMEMZERO
  173032. FMEMZERO(target, bytestozero);
  173033. #else
  173034. register char FAR * ptr = (char FAR *) target;
  173035. register size_t count;
  173036. for (count = bytestozero; count > 0; count--) {
  173037. *ptr++ = 0;
  173038. }
  173039. #endif
  173040. }
  173041. /********* End of inlined file: jutils.c *********/
  173042. /********* Start of inlined file: transupp.c *********/
  173043. /* Although this file really shouldn't have access to the library internals,
  173044. * it's helpful to let it call jround_up() and jcopy_block_row().
  173045. */
  173046. #define JPEG_INTERNALS
  173047. /********* Start of inlined file: transupp.h *********/
  173048. /* If you happen not to want the image transform support, disable it here */
  173049. #ifndef TRANSFORMS_SUPPORTED
  173050. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  173051. #endif
  173052. /* Short forms of external names for systems with brain-damaged linkers. */
  173053. #ifdef NEED_SHORT_EXTERNAL_NAMES
  173054. #define jtransform_request_workspace jTrRequest
  173055. #define jtransform_adjust_parameters jTrAdjust
  173056. #define jtransform_execute_transformation jTrExec
  173057. #define jcopy_markers_setup jCMrkSetup
  173058. #define jcopy_markers_execute jCMrkExec
  173059. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  173060. /*
  173061. * Codes for supported types of image transformations.
  173062. */
  173063. typedef enum {
  173064. JXFORM_NONE, /* no transformation */
  173065. JXFORM_FLIP_H, /* horizontal flip */
  173066. JXFORM_FLIP_V, /* vertical flip */
  173067. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  173068. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  173069. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  173070. JXFORM_ROT_180, /* 180-degree rotation */
  173071. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  173072. } JXFORM_CODE;
  173073. /*
  173074. * Although rotating and flipping data expressed as DCT coefficients is not
  173075. * hard, there is an asymmetry in the JPEG format specification for images
  173076. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  173077. * image edges are padded out to the next iMCU boundary with junk data; but
  173078. * no padding is possible at the top and left edges. If we were to flip
  173079. * the whole image including the pad data, then pad garbage would become
  173080. * visible at the top and/or left, and real pixels would disappear into the
  173081. * pad margins --- perhaps permanently, since encoders & decoders may not
  173082. * bother to preserve DCT blocks that appear to be completely outside the
  173083. * nominal image area. So, we have to exclude any partial iMCUs from the
  173084. * basic transformation.
  173085. *
  173086. * Transpose is the only transformation that can handle partial iMCUs at the
  173087. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  173088. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  173089. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  173090. * The other transforms are defined as combinations of these basic transforms
  173091. * and process edge blocks in a way that preserves the equivalence.
  173092. *
  173093. * The "trim" option causes untransformable partial iMCUs to be dropped;
  173094. * this is not strictly lossless, but it usually gives the best-looking
  173095. * result for odd-size images. Note that when this option is active,
  173096. * the expected mathematical equivalences between the transforms may not hold.
  173097. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  173098. * followed by -rot 180 -trim trims both edges.)
  173099. *
  173100. * We also offer a "force to grayscale" option, which simply discards the
  173101. * chrominance channels of a YCbCr image. This is lossless in the sense that
  173102. * the luminance channel is preserved exactly. It's not the same kind of
  173103. * thing as the rotate/flip transformations, but it's convenient to handle it
  173104. * as part of this package, mainly because the transformation routines have to
  173105. * be aware of the option to know how many components to work on.
  173106. */
  173107. typedef struct {
  173108. /* Options: set by caller */
  173109. JXFORM_CODE transform; /* image transform operator */
  173110. boolean trim; /* if TRUE, trim partial MCUs as needed */
  173111. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  173112. /* Internal workspace: caller should not touch these */
  173113. int num_components; /* # of components in workspace */
  173114. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  173115. } jpeg_transform_info;
  173116. #if TRANSFORMS_SUPPORTED
  173117. /* Request any required workspace */
  173118. EXTERN(void) jtransform_request_workspace
  173119. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  173120. /* Adjust output image parameters */
  173121. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  173122. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173123. jvirt_barray_ptr *src_coef_arrays,
  173124. jpeg_transform_info *info));
  173125. /* Execute the actual transformation, if any */
  173126. EXTERN(void) jtransform_execute_transformation
  173127. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173128. jvirt_barray_ptr *src_coef_arrays,
  173129. jpeg_transform_info *info));
  173130. #endif /* TRANSFORMS_SUPPORTED */
  173131. /*
  173132. * Support for copying optional markers from source to destination file.
  173133. */
  173134. typedef enum {
  173135. JCOPYOPT_NONE, /* copy no optional markers */
  173136. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  173137. JCOPYOPT_ALL /* copy all optional markers */
  173138. } JCOPY_OPTION;
  173139. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  173140. /* Setup decompression object to save desired markers in memory */
  173141. EXTERN(void) jcopy_markers_setup
  173142. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  173143. /* Copy markers saved in the given source object to the destination object */
  173144. EXTERN(void) jcopy_markers_execute
  173145. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173146. JCOPY_OPTION option));
  173147. /********* End of inlined file: transupp.h *********/
  173148. /* My own external interface */
  173149. #if TRANSFORMS_SUPPORTED
  173150. /*
  173151. * Lossless image transformation routines. These routines work on DCT
  173152. * coefficient arrays and thus do not require any lossy decompression
  173153. * or recompression of the image.
  173154. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  173155. *
  173156. * Horizontal flipping is done in-place, using a single top-to-bottom
  173157. * pass through the virtual source array. It will thus be much the
  173158. * fastest option for images larger than main memory.
  173159. *
  173160. * The other routines require a set of destination virtual arrays, so they
  173161. * need twice as much memory as jpegtran normally does. The destination
  173162. * arrays are always written in normal scan order (top to bottom) because
  173163. * the virtual array manager expects this. The source arrays will be scanned
  173164. * in the corresponding order, which means multiple passes through the source
  173165. * arrays for most of the transforms. That could result in much thrashing
  173166. * if the image is larger than main memory.
  173167. *
  173168. * Some notes about the operating environment of the individual transform
  173169. * routines:
  173170. * 1. Both the source and destination virtual arrays are allocated from the
  173171. * source JPEG object, and therefore should be manipulated by calling the
  173172. * source's memory manager.
  173173. * 2. The destination's component count should be used. It may be smaller
  173174. * than the source's when forcing to grayscale.
  173175. * 3. Likewise the destination's sampling factors should be used. When
  173176. * forcing to grayscale the destination's sampling factors will be all 1,
  173177. * and we may as well take that as the effective iMCU size.
  173178. * 4. When "trim" is in effect, the destination's dimensions will be the
  173179. * trimmed values but the source's will be untrimmed.
  173180. * 5. All the routines assume that the source and destination buffers are
  173181. * padded out to a full iMCU boundary. This is true, although for the
  173182. * source buffer it is an undocumented property of jdcoefct.c.
  173183. * Notes 2,3,4 boil down to this: generally we should use the destination's
  173184. * dimensions and ignore the source's.
  173185. */
  173186. LOCAL(void)
  173187. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173188. jvirt_barray_ptr *src_coef_arrays)
  173189. /* Horizontal flip; done in-place, so no separate dest array is required */
  173190. {
  173191. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  173192. int ci, k, offset_y;
  173193. JBLOCKARRAY buffer;
  173194. JCOEFPTR ptr1, ptr2;
  173195. JCOEF temp1, temp2;
  173196. jpeg_component_info *compptr;
  173197. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  173198. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  173199. * mirroring by changing the signs of odd-numbered columns.
  173200. * Partial iMCUs at the right edge are left untouched.
  173201. */
  173202. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  173203. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173204. compptr = dstinfo->comp_info + ci;
  173205. comp_width = MCU_cols * compptr->h_samp_factor;
  173206. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  173207. blk_y += compptr->v_samp_factor) {
  173208. buffer = (*srcinfo->mem->access_virt_barray)
  173209. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  173210. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173211. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173212. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  173213. ptr1 = buffer[offset_y][blk_x];
  173214. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  173215. /* this unrolled loop doesn't need to know which row it's on... */
  173216. for (k = 0; k < DCTSIZE2; k += 2) {
  173217. temp1 = *ptr1; /* swap even column */
  173218. temp2 = *ptr2;
  173219. *ptr1++ = temp2;
  173220. *ptr2++ = temp1;
  173221. temp1 = *ptr1; /* swap odd column with sign change */
  173222. temp2 = *ptr2;
  173223. *ptr1++ = -temp2;
  173224. *ptr2++ = -temp1;
  173225. }
  173226. }
  173227. }
  173228. }
  173229. }
  173230. }
  173231. LOCAL(void)
  173232. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173233. jvirt_barray_ptr *src_coef_arrays,
  173234. jvirt_barray_ptr *dst_coef_arrays)
  173235. /* Vertical flip */
  173236. {
  173237. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  173238. int ci, i, j, offset_y;
  173239. JBLOCKARRAY src_buffer, dst_buffer;
  173240. JBLOCKROW src_row_ptr, dst_row_ptr;
  173241. JCOEFPTR src_ptr, dst_ptr;
  173242. jpeg_component_info *compptr;
  173243. /* We output into a separate array because we can't touch different
  173244. * rows of the source virtual array simultaneously. Otherwise, this
  173245. * is a pretty straightforward analog of horizontal flip.
  173246. * Within a DCT block, vertical mirroring is done by changing the signs
  173247. * of odd-numbered rows.
  173248. * Partial iMCUs at the bottom edge are copied verbatim.
  173249. */
  173250. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  173251. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173252. compptr = dstinfo->comp_info + ci;
  173253. comp_height = MCU_rows * compptr->v_samp_factor;
  173254. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  173255. dst_blk_y += compptr->v_samp_factor) {
  173256. dst_buffer = (*srcinfo->mem->access_virt_barray)
  173257. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  173258. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173259. if (dst_blk_y < comp_height) {
  173260. /* Row is within the mirrorable area. */
  173261. src_buffer = (*srcinfo->mem->access_virt_barray)
  173262. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  173263. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  173264. (JDIMENSION) compptr->v_samp_factor, FALSE);
  173265. } else {
  173266. /* Bottom-edge blocks will be copied verbatim. */
  173267. src_buffer = (*srcinfo->mem->access_virt_barray)
  173268. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  173269. (JDIMENSION) compptr->v_samp_factor, FALSE);
  173270. }
  173271. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173272. if (dst_blk_y < comp_height) {
  173273. /* Row is within the mirrorable area. */
  173274. dst_row_ptr = dst_buffer[offset_y];
  173275. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  173276. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  173277. dst_blk_x++) {
  173278. dst_ptr = dst_row_ptr[dst_blk_x];
  173279. src_ptr = src_row_ptr[dst_blk_x];
  173280. for (i = 0; i < DCTSIZE; i += 2) {
  173281. /* copy even row */
  173282. for (j = 0; j < DCTSIZE; j++)
  173283. *dst_ptr++ = *src_ptr++;
  173284. /* copy odd row with sign change */
  173285. for (j = 0; j < DCTSIZE; j++)
  173286. *dst_ptr++ = - *src_ptr++;
  173287. }
  173288. }
  173289. } else {
  173290. /* Just copy row verbatim. */
  173291. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  173292. compptr->width_in_blocks);
  173293. }
  173294. }
  173295. }
  173296. }
  173297. }
  173298. LOCAL(void)
  173299. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173300. jvirt_barray_ptr *src_coef_arrays,
  173301. jvirt_barray_ptr *dst_coef_arrays)
  173302. /* Transpose source into destination */
  173303. {
  173304. JDIMENSION dst_blk_x, dst_blk_y;
  173305. int ci, i, j, offset_x, offset_y;
  173306. JBLOCKARRAY src_buffer, dst_buffer;
  173307. JCOEFPTR src_ptr, dst_ptr;
  173308. jpeg_component_info *compptr;
  173309. /* Transposing pixels within a block just requires transposing the
  173310. * DCT coefficients.
  173311. * Partial iMCUs at the edges require no special treatment; we simply
  173312. * process all the available DCT blocks for every component.
  173313. */
  173314. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173315. compptr = dstinfo->comp_info + ci;
  173316. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  173317. dst_blk_y += compptr->v_samp_factor) {
  173318. dst_buffer = (*srcinfo->mem->access_virt_barray)
  173319. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  173320. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173321. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173322. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  173323. dst_blk_x += compptr->h_samp_factor) {
  173324. src_buffer = (*srcinfo->mem->access_virt_barray)
  173325. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  173326. (JDIMENSION) compptr->h_samp_factor, FALSE);
  173327. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  173328. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  173329. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  173330. for (i = 0; i < DCTSIZE; i++)
  173331. for (j = 0; j < DCTSIZE; j++)
  173332. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173333. }
  173334. }
  173335. }
  173336. }
  173337. }
  173338. }
  173339. LOCAL(void)
  173340. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173341. jvirt_barray_ptr *src_coef_arrays,
  173342. jvirt_barray_ptr *dst_coef_arrays)
  173343. /* 90 degree rotation is equivalent to
  173344. * 1. Transposing the image;
  173345. * 2. Horizontal mirroring.
  173346. * These two steps are merged into a single processing routine.
  173347. */
  173348. {
  173349. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  173350. int ci, i, j, offset_x, offset_y;
  173351. JBLOCKARRAY src_buffer, dst_buffer;
  173352. JCOEFPTR src_ptr, dst_ptr;
  173353. jpeg_component_info *compptr;
  173354. /* Because of the horizontal mirror step, we can't process partial iMCUs
  173355. * at the (output) right edge properly. They just get transposed and
  173356. * not mirrored.
  173357. */
  173358. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  173359. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173360. compptr = dstinfo->comp_info + ci;
  173361. comp_width = MCU_cols * compptr->h_samp_factor;
  173362. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  173363. dst_blk_y += compptr->v_samp_factor) {
  173364. dst_buffer = (*srcinfo->mem->access_virt_barray)
  173365. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  173366. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173367. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173368. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  173369. dst_blk_x += compptr->h_samp_factor) {
  173370. src_buffer = (*srcinfo->mem->access_virt_barray)
  173371. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  173372. (JDIMENSION) compptr->h_samp_factor, FALSE);
  173373. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  173374. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  173375. if (dst_blk_x < comp_width) {
  173376. /* Block is within the mirrorable area. */
  173377. dst_ptr = dst_buffer[offset_y]
  173378. [comp_width - dst_blk_x - offset_x - 1];
  173379. for (i = 0; i < DCTSIZE; i++) {
  173380. for (j = 0; j < DCTSIZE; j++)
  173381. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173382. i++;
  173383. for (j = 0; j < DCTSIZE; j++)
  173384. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  173385. }
  173386. } else {
  173387. /* Edge blocks are transposed but not mirrored. */
  173388. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  173389. for (i = 0; i < DCTSIZE; i++)
  173390. for (j = 0; j < DCTSIZE; j++)
  173391. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173392. }
  173393. }
  173394. }
  173395. }
  173396. }
  173397. }
  173398. }
  173399. LOCAL(void)
  173400. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173401. jvirt_barray_ptr *src_coef_arrays,
  173402. jvirt_barray_ptr *dst_coef_arrays)
  173403. /* 270 degree rotation is equivalent to
  173404. * 1. Horizontal mirroring;
  173405. * 2. Transposing the image.
  173406. * These two steps are merged into a single processing routine.
  173407. */
  173408. {
  173409. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  173410. int ci, i, j, offset_x, offset_y;
  173411. JBLOCKARRAY src_buffer, dst_buffer;
  173412. JCOEFPTR src_ptr, dst_ptr;
  173413. jpeg_component_info *compptr;
  173414. /* Because of the horizontal mirror step, we can't process partial iMCUs
  173415. * at the (output) bottom edge properly. They just get transposed and
  173416. * not mirrored.
  173417. */
  173418. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  173419. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173420. compptr = dstinfo->comp_info + ci;
  173421. comp_height = MCU_rows * compptr->v_samp_factor;
  173422. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  173423. dst_blk_y += compptr->v_samp_factor) {
  173424. dst_buffer = (*srcinfo->mem->access_virt_barray)
  173425. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  173426. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173427. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173428. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  173429. dst_blk_x += compptr->h_samp_factor) {
  173430. src_buffer = (*srcinfo->mem->access_virt_barray)
  173431. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  173432. (JDIMENSION) compptr->h_samp_factor, FALSE);
  173433. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  173434. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  173435. if (dst_blk_y < comp_height) {
  173436. /* Block is within the mirrorable area. */
  173437. src_ptr = src_buffer[offset_x]
  173438. [comp_height - dst_blk_y - offset_y - 1];
  173439. for (i = 0; i < DCTSIZE; i++) {
  173440. for (j = 0; j < DCTSIZE; j++) {
  173441. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173442. j++;
  173443. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  173444. }
  173445. }
  173446. } else {
  173447. /* Edge blocks are transposed but not mirrored. */
  173448. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  173449. for (i = 0; i < DCTSIZE; i++)
  173450. for (j = 0; j < DCTSIZE; j++)
  173451. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173452. }
  173453. }
  173454. }
  173455. }
  173456. }
  173457. }
  173458. }
  173459. LOCAL(void)
  173460. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173461. jvirt_barray_ptr *src_coef_arrays,
  173462. jvirt_barray_ptr *dst_coef_arrays)
  173463. /* 180 degree rotation is equivalent to
  173464. * 1. Vertical mirroring;
  173465. * 2. Horizontal mirroring.
  173466. * These two steps are merged into a single processing routine.
  173467. */
  173468. {
  173469. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  173470. int ci, i, j, offset_y;
  173471. JBLOCKARRAY src_buffer, dst_buffer;
  173472. JBLOCKROW src_row_ptr, dst_row_ptr;
  173473. JCOEFPTR src_ptr, dst_ptr;
  173474. jpeg_component_info *compptr;
  173475. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  173476. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  173477. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173478. compptr = dstinfo->comp_info + ci;
  173479. comp_width = MCU_cols * compptr->h_samp_factor;
  173480. comp_height = MCU_rows * compptr->v_samp_factor;
  173481. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  173482. dst_blk_y += compptr->v_samp_factor) {
  173483. dst_buffer = (*srcinfo->mem->access_virt_barray)
  173484. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  173485. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173486. if (dst_blk_y < comp_height) {
  173487. /* Row is within the vertically mirrorable area. */
  173488. src_buffer = (*srcinfo->mem->access_virt_barray)
  173489. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  173490. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  173491. (JDIMENSION) compptr->v_samp_factor, FALSE);
  173492. } else {
  173493. /* Bottom-edge rows are only mirrored horizontally. */
  173494. src_buffer = (*srcinfo->mem->access_virt_barray)
  173495. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  173496. (JDIMENSION) compptr->v_samp_factor, FALSE);
  173497. }
  173498. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173499. if (dst_blk_y < comp_height) {
  173500. /* Row is within the mirrorable area. */
  173501. dst_row_ptr = dst_buffer[offset_y];
  173502. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  173503. /* Process the blocks that can be mirrored both ways. */
  173504. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  173505. dst_ptr = dst_row_ptr[dst_blk_x];
  173506. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  173507. for (i = 0; i < DCTSIZE; i += 2) {
  173508. /* For even row, negate every odd column. */
  173509. for (j = 0; j < DCTSIZE; j += 2) {
  173510. *dst_ptr++ = *src_ptr++;
  173511. *dst_ptr++ = - *src_ptr++;
  173512. }
  173513. /* For odd row, negate every even column. */
  173514. for (j = 0; j < DCTSIZE; j += 2) {
  173515. *dst_ptr++ = - *src_ptr++;
  173516. *dst_ptr++ = *src_ptr++;
  173517. }
  173518. }
  173519. }
  173520. /* Any remaining right-edge blocks are only mirrored vertically. */
  173521. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  173522. dst_ptr = dst_row_ptr[dst_blk_x];
  173523. src_ptr = src_row_ptr[dst_blk_x];
  173524. for (i = 0; i < DCTSIZE; i += 2) {
  173525. for (j = 0; j < DCTSIZE; j++)
  173526. *dst_ptr++ = *src_ptr++;
  173527. for (j = 0; j < DCTSIZE; j++)
  173528. *dst_ptr++ = - *src_ptr++;
  173529. }
  173530. }
  173531. } else {
  173532. /* Remaining rows are just mirrored horizontally. */
  173533. dst_row_ptr = dst_buffer[offset_y];
  173534. src_row_ptr = src_buffer[offset_y];
  173535. /* Process the blocks that can be mirrored. */
  173536. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  173537. dst_ptr = dst_row_ptr[dst_blk_x];
  173538. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  173539. for (i = 0; i < DCTSIZE2; i += 2) {
  173540. *dst_ptr++ = *src_ptr++;
  173541. *dst_ptr++ = - *src_ptr++;
  173542. }
  173543. }
  173544. /* Any remaining right-edge blocks are only copied. */
  173545. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  173546. dst_ptr = dst_row_ptr[dst_blk_x];
  173547. src_ptr = src_row_ptr[dst_blk_x];
  173548. for (i = 0; i < DCTSIZE2; i++)
  173549. *dst_ptr++ = *src_ptr++;
  173550. }
  173551. }
  173552. }
  173553. }
  173554. }
  173555. }
  173556. LOCAL(void)
  173557. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173558. jvirt_barray_ptr *src_coef_arrays,
  173559. jvirt_barray_ptr *dst_coef_arrays)
  173560. /* Transverse transpose is equivalent to
  173561. * 1. 180 degree rotation;
  173562. * 2. Transposition;
  173563. * or
  173564. * 1. Horizontal mirroring;
  173565. * 2. Transposition;
  173566. * 3. Horizontal mirroring.
  173567. * These steps are merged into a single processing routine.
  173568. */
  173569. {
  173570. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  173571. int ci, i, j, offset_x, offset_y;
  173572. JBLOCKARRAY src_buffer, dst_buffer;
  173573. JCOEFPTR src_ptr, dst_ptr;
  173574. jpeg_component_info *compptr;
  173575. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  173576. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  173577. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173578. compptr = dstinfo->comp_info + ci;
  173579. comp_width = MCU_cols * compptr->h_samp_factor;
  173580. comp_height = MCU_rows * compptr->v_samp_factor;
  173581. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  173582. dst_blk_y += compptr->v_samp_factor) {
  173583. dst_buffer = (*srcinfo->mem->access_virt_barray)
  173584. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  173585. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173586. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173587. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  173588. dst_blk_x += compptr->h_samp_factor) {
  173589. src_buffer = (*srcinfo->mem->access_virt_barray)
  173590. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  173591. (JDIMENSION) compptr->h_samp_factor, FALSE);
  173592. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  173593. if (dst_blk_y < comp_height) {
  173594. src_ptr = src_buffer[offset_x]
  173595. [comp_height - dst_blk_y - offset_y - 1];
  173596. if (dst_blk_x < comp_width) {
  173597. /* Block is within the mirrorable area. */
  173598. dst_ptr = dst_buffer[offset_y]
  173599. [comp_width - dst_blk_x - offset_x - 1];
  173600. for (i = 0; i < DCTSIZE; i++) {
  173601. for (j = 0; j < DCTSIZE; j++) {
  173602. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173603. j++;
  173604. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  173605. }
  173606. i++;
  173607. for (j = 0; j < DCTSIZE; j++) {
  173608. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  173609. j++;
  173610. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173611. }
  173612. }
  173613. } else {
  173614. /* Right-edge blocks are mirrored in y only */
  173615. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  173616. for (i = 0; i < DCTSIZE; i++) {
  173617. for (j = 0; j < DCTSIZE; j++) {
  173618. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173619. j++;
  173620. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  173621. }
  173622. }
  173623. }
  173624. } else {
  173625. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  173626. if (dst_blk_x < comp_width) {
  173627. /* Bottom-edge blocks are mirrored in x only */
  173628. dst_ptr = dst_buffer[offset_y]
  173629. [comp_width - dst_blk_x - offset_x - 1];
  173630. for (i = 0; i < DCTSIZE; i++) {
  173631. for (j = 0; j < DCTSIZE; j++)
  173632. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173633. i++;
  173634. for (j = 0; j < DCTSIZE; j++)
  173635. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  173636. }
  173637. } else {
  173638. /* At lower right corner, just transpose, no mirroring */
  173639. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  173640. for (i = 0; i < DCTSIZE; i++)
  173641. for (j = 0; j < DCTSIZE; j++)
  173642. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173643. }
  173644. }
  173645. }
  173646. }
  173647. }
  173648. }
  173649. }
  173650. }
  173651. /* Request any required workspace.
  173652. *
  173653. * We allocate the workspace virtual arrays from the source decompression
  173654. * object, so that all the arrays (both the original data and the workspace)
  173655. * will be taken into account while making memory management decisions.
  173656. * Hence, this routine must be called after jpeg_read_header (which reads
  173657. * the image dimensions) and before jpeg_read_coefficients (which realizes
  173658. * the source's virtual arrays).
  173659. */
  173660. GLOBAL(void)
  173661. jtransform_request_workspace (j_decompress_ptr srcinfo,
  173662. jpeg_transform_info *info)
  173663. {
  173664. jvirt_barray_ptr *coef_arrays = NULL;
  173665. jpeg_component_info *compptr;
  173666. int ci;
  173667. if (info->force_grayscale &&
  173668. srcinfo->jpeg_color_space == JCS_YCbCr &&
  173669. srcinfo->num_components == 3) {
  173670. /* We'll only process the first component */
  173671. info->num_components = 1;
  173672. } else {
  173673. /* Process all the components */
  173674. info->num_components = srcinfo->num_components;
  173675. }
  173676. switch (info->transform) {
  173677. case JXFORM_NONE:
  173678. case JXFORM_FLIP_H:
  173679. /* Don't need a workspace array */
  173680. break;
  173681. case JXFORM_FLIP_V:
  173682. case JXFORM_ROT_180:
  173683. /* Need workspace arrays having same dimensions as source image.
  173684. * Note that we allocate arrays padded out to the next iMCU boundary,
  173685. * so that transform routines need not worry about missing edge blocks.
  173686. */
  173687. coef_arrays = (jvirt_barray_ptr *)
  173688. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  173689. SIZEOF(jvirt_barray_ptr) * info->num_components);
  173690. for (ci = 0; ci < info->num_components; ci++) {
  173691. compptr = srcinfo->comp_info + ci;
  173692. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  173693. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  173694. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  173695. (long) compptr->h_samp_factor),
  173696. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  173697. (long) compptr->v_samp_factor),
  173698. (JDIMENSION) compptr->v_samp_factor);
  173699. }
  173700. break;
  173701. case JXFORM_TRANSPOSE:
  173702. case JXFORM_TRANSVERSE:
  173703. case JXFORM_ROT_90:
  173704. case JXFORM_ROT_270:
  173705. /* Need workspace arrays having transposed dimensions.
  173706. * Note that we allocate arrays padded out to the next iMCU boundary,
  173707. * so that transform routines need not worry about missing edge blocks.
  173708. */
  173709. coef_arrays = (jvirt_barray_ptr *)
  173710. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  173711. SIZEOF(jvirt_barray_ptr) * info->num_components);
  173712. for (ci = 0; ci < info->num_components; ci++) {
  173713. compptr = srcinfo->comp_info + ci;
  173714. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  173715. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  173716. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  173717. (long) compptr->v_samp_factor),
  173718. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  173719. (long) compptr->h_samp_factor),
  173720. (JDIMENSION) compptr->h_samp_factor);
  173721. }
  173722. break;
  173723. }
  173724. info->workspace_coef_arrays = coef_arrays;
  173725. }
  173726. /* Transpose destination image parameters */
  173727. LOCAL(void)
  173728. transpose_critical_parameters (j_compress_ptr dstinfo)
  173729. {
  173730. int tblno, i, j, ci, itemp;
  173731. jpeg_component_info *compptr;
  173732. JQUANT_TBL *qtblptr;
  173733. JDIMENSION dtemp;
  173734. UINT16 qtemp;
  173735. /* Transpose basic image dimensions */
  173736. dtemp = dstinfo->image_width;
  173737. dstinfo->image_width = dstinfo->image_height;
  173738. dstinfo->image_height = dtemp;
  173739. /* Transpose sampling factors */
  173740. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173741. compptr = dstinfo->comp_info + ci;
  173742. itemp = compptr->h_samp_factor;
  173743. compptr->h_samp_factor = compptr->v_samp_factor;
  173744. compptr->v_samp_factor = itemp;
  173745. }
  173746. /* Transpose quantization tables */
  173747. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  173748. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  173749. if (qtblptr != NULL) {
  173750. for (i = 0; i < DCTSIZE; i++) {
  173751. for (j = 0; j < i; j++) {
  173752. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  173753. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  173754. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  173755. }
  173756. }
  173757. }
  173758. }
  173759. }
  173760. /* Trim off any partial iMCUs on the indicated destination edge */
  173761. LOCAL(void)
  173762. trim_right_edge (j_compress_ptr dstinfo)
  173763. {
  173764. int ci, max_h_samp_factor;
  173765. JDIMENSION MCU_cols;
  173766. /* We have to compute max_h_samp_factor ourselves,
  173767. * because it hasn't been set yet in the destination
  173768. * (and we don't want to use the source's value).
  173769. */
  173770. max_h_samp_factor = 1;
  173771. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173772. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  173773. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  173774. }
  173775. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  173776. if (MCU_cols > 0) /* can't trim to 0 pixels */
  173777. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  173778. }
  173779. LOCAL(void)
  173780. trim_bottom_edge (j_compress_ptr dstinfo)
  173781. {
  173782. int ci, max_v_samp_factor;
  173783. JDIMENSION MCU_rows;
  173784. /* We have to compute max_v_samp_factor ourselves,
  173785. * because it hasn't been set yet in the destination
  173786. * (and we don't want to use the source's value).
  173787. */
  173788. max_v_samp_factor = 1;
  173789. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173790. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  173791. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  173792. }
  173793. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  173794. if (MCU_rows > 0) /* can't trim to 0 pixels */
  173795. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  173796. }
  173797. /* Adjust output image parameters as needed.
  173798. *
  173799. * This must be called after jpeg_copy_critical_parameters()
  173800. * and before jpeg_write_coefficients().
  173801. *
  173802. * The return value is the set of virtual coefficient arrays to be written
  173803. * (either the ones allocated by jtransform_request_workspace, or the
  173804. * original source data arrays). The caller will need to pass this value
  173805. * to jpeg_write_coefficients().
  173806. */
  173807. GLOBAL(jvirt_barray_ptr *)
  173808. jtransform_adjust_parameters (j_decompress_ptr srcinfo,
  173809. j_compress_ptr dstinfo,
  173810. jvirt_barray_ptr *src_coef_arrays,
  173811. jpeg_transform_info *info)
  173812. {
  173813. /* If force-to-grayscale is requested, adjust destination parameters */
  173814. if (info->force_grayscale) {
  173815. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  173816. * properly. Among other things, the target h_samp_factor & v_samp_factor
  173817. * will get set to 1, which typically won't match the source.
  173818. * In fact we do this even if the source is already grayscale; that
  173819. * provides an easy way of coercing a grayscale JPEG with funny sampling
  173820. * factors to the customary 1,1. (Some decoders fail on other factors.)
  173821. */
  173822. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  173823. dstinfo->num_components == 3) ||
  173824. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  173825. dstinfo->num_components == 1)) {
  173826. /* We have to preserve the source's quantization table number. */
  173827. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  173828. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  173829. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  173830. } else {
  173831. /* Sorry, can't do it */
  173832. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  173833. }
  173834. }
  173835. /* Correct the destination's image dimensions etc if necessary */
  173836. switch (info->transform) {
  173837. case JXFORM_NONE:
  173838. /* Nothing to do */
  173839. break;
  173840. case JXFORM_FLIP_H:
  173841. if (info->trim)
  173842. trim_right_edge(dstinfo);
  173843. break;
  173844. case JXFORM_FLIP_V:
  173845. if (info->trim)
  173846. trim_bottom_edge(dstinfo);
  173847. break;
  173848. case JXFORM_TRANSPOSE:
  173849. transpose_critical_parameters(dstinfo);
  173850. /* transpose does NOT have to trim anything */
  173851. break;
  173852. case JXFORM_TRANSVERSE:
  173853. transpose_critical_parameters(dstinfo);
  173854. if (info->trim) {
  173855. trim_right_edge(dstinfo);
  173856. trim_bottom_edge(dstinfo);
  173857. }
  173858. break;
  173859. case JXFORM_ROT_90:
  173860. transpose_critical_parameters(dstinfo);
  173861. if (info->trim)
  173862. trim_right_edge(dstinfo);
  173863. break;
  173864. case JXFORM_ROT_180:
  173865. if (info->trim) {
  173866. trim_right_edge(dstinfo);
  173867. trim_bottom_edge(dstinfo);
  173868. }
  173869. break;
  173870. case JXFORM_ROT_270:
  173871. transpose_critical_parameters(dstinfo);
  173872. if (info->trim)
  173873. trim_bottom_edge(dstinfo);
  173874. break;
  173875. }
  173876. /* Return the appropriate output data set */
  173877. if (info->workspace_coef_arrays != NULL)
  173878. return info->workspace_coef_arrays;
  173879. return src_coef_arrays;
  173880. }
  173881. /* Execute the actual transformation, if any.
  173882. *
  173883. * This must be called *after* jpeg_write_coefficients, because it depends
  173884. * on jpeg_write_coefficients to have computed subsidiary values such as
  173885. * the per-component width and height fields in the destination object.
  173886. *
  173887. * Note that some transformations will modify the source data arrays!
  173888. */
  173889. GLOBAL(void)
  173890. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  173891. j_compress_ptr dstinfo,
  173892. jvirt_barray_ptr *src_coef_arrays,
  173893. jpeg_transform_info *info)
  173894. {
  173895. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  173896. switch (info->transform) {
  173897. case JXFORM_NONE:
  173898. break;
  173899. case JXFORM_FLIP_H:
  173900. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  173901. break;
  173902. case JXFORM_FLIP_V:
  173903. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173904. break;
  173905. case JXFORM_TRANSPOSE:
  173906. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173907. break;
  173908. case JXFORM_TRANSVERSE:
  173909. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173910. break;
  173911. case JXFORM_ROT_90:
  173912. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173913. break;
  173914. case JXFORM_ROT_180:
  173915. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173916. break;
  173917. case JXFORM_ROT_270:
  173918. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173919. break;
  173920. }
  173921. }
  173922. #endif /* TRANSFORMS_SUPPORTED */
  173923. /* Setup decompression object to save desired markers in memory.
  173924. * This must be called before jpeg_read_header() to have the desired effect.
  173925. */
  173926. GLOBAL(void)
  173927. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  173928. {
  173929. #ifdef SAVE_MARKERS_SUPPORTED
  173930. int m;
  173931. /* Save comments except under NONE option */
  173932. if (option != JCOPYOPT_NONE) {
  173933. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  173934. }
  173935. /* Save all types of APPn markers iff ALL option */
  173936. if (option == JCOPYOPT_ALL) {
  173937. for (m = 0; m < 16; m++)
  173938. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  173939. }
  173940. #endif /* SAVE_MARKERS_SUPPORTED */
  173941. }
  173942. /* Copy markers saved in the given source object to the destination object.
  173943. * This should be called just after jpeg_start_compress() or
  173944. * jpeg_write_coefficients().
  173945. * Note that those routines will have written the SOI, and also the
  173946. * JFIF APP0 or Adobe APP14 markers if selected.
  173947. */
  173948. GLOBAL(void)
  173949. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173950. JCOPY_OPTION option)
  173951. {
  173952. jpeg_saved_marker_ptr marker;
  173953. /* In the current implementation, we don't actually need to examine the
  173954. * option flag here; we just copy everything that got saved.
  173955. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  173956. * if the encoder library already wrote one.
  173957. */
  173958. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  173959. if (dstinfo->write_JFIF_header &&
  173960. marker->marker == JPEG_APP0 &&
  173961. marker->data_length >= 5 &&
  173962. GETJOCTET(marker->data[0]) == 0x4A &&
  173963. GETJOCTET(marker->data[1]) == 0x46 &&
  173964. GETJOCTET(marker->data[2]) == 0x49 &&
  173965. GETJOCTET(marker->data[3]) == 0x46 &&
  173966. GETJOCTET(marker->data[4]) == 0)
  173967. continue; /* reject duplicate JFIF */
  173968. if (dstinfo->write_Adobe_marker &&
  173969. marker->marker == JPEG_APP0+14 &&
  173970. marker->data_length >= 5 &&
  173971. GETJOCTET(marker->data[0]) == 0x41 &&
  173972. GETJOCTET(marker->data[1]) == 0x64 &&
  173973. GETJOCTET(marker->data[2]) == 0x6F &&
  173974. GETJOCTET(marker->data[3]) == 0x62 &&
  173975. GETJOCTET(marker->data[4]) == 0x65)
  173976. continue; /* reject duplicate Adobe */
  173977. #ifdef NEED_FAR_POINTERS
  173978. /* We could use jpeg_write_marker if the data weren't FAR... */
  173979. {
  173980. unsigned int i;
  173981. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  173982. for (i = 0; i < marker->data_length; i++)
  173983. jpeg_write_m_byte(dstinfo, marker->data[i]);
  173984. }
  173985. #else
  173986. jpeg_write_marker(dstinfo, marker->marker,
  173987. marker->data, marker->data_length);
  173988. #endif
  173989. }
  173990. }
  173991. /********* End of inlined file: transupp.c *********/
  173992. }
  173993. }
  173994. #if JUCE_MSVC
  173995. #pragma warning (pop)
  173996. #endif
  173997. BEGIN_JUCE_NAMESPACE
  173998. using namespace jpeglibNamespace;
  173999. struct JPEGDecodingFailure {};
  174000. static void fatalErrorHandler (j_common_ptr)
  174001. {
  174002. throw JPEGDecodingFailure();
  174003. }
  174004. static void silentErrorCallback1 (j_common_ptr) {}
  174005. static void silentErrorCallback2 (j_common_ptr, int) {}
  174006. static void silentErrorCallback3 (j_common_ptr, char*) {}
  174007. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  174008. {
  174009. zerostruct (err);
  174010. err.error_exit = fatalErrorHandler;
  174011. err.emit_message = silentErrorCallback2;
  174012. err.output_message = silentErrorCallback1;
  174013. err.format_message = silentErrorCallback3;
  174014. err.reset_error_mgr = silentErrorCallback1;
  174015. }
  174016. static void dummyCallback1 (j_decompress_ptr) throw()
  174017. {
  174018. }
  174019. static void jpegSkip (j_decompress_ptr decompStruct, long num) throw()
  174020. {
  174021. decompStruct->src->next_input_byte += num;
  174022. num = jmin (num, (int) decompStruct->src->bytes_in_buffer);
  174023. decompStruct->src->bytes_in_buffer -= num;
  174024. }
  174025. static boolean jpegFill (j_decompress_ptr) throw()
  174026. {
  174027. return 0;
  174028. }
  174029. Image* juce_loadJPEGImageFromStream (InputStream& in) throw()
  174030. {
  174031. MemoryBlock mb;
  174032. in.readIntoMemoryBlock (mb);
  174033. Image* image = 0;
  174034. if (mb.getSize() > 16)
  174035. {
  174036. struct jpeg_decompress_struct jpegDecompStruct;
  174037. struct jpeg_error_mgr jerr;
  174038. setupSilentErrorHandler (jerr);
  174039. jpegDecompStruct.err = &jerr;
  174040. jpeg_create_decompress (&jpegDecompStruct);
  174041. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  174042. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  174043. jpegDecompStruct.src->init_source = dummyCallback1;
  174044. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  174045. jpegDecompStruct.src->skip_input_data = jpegSkip;
  174046. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  174047. jpegDecompStruct.src->term_source = dummyCallback1;
  174048. jpegDecompStruct.src->next_input_byte = (const unsigned char*) mb.getData();
  174049. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  174050. try
  174051. {
  174052. jpeg_read_header (&jpegDecompStruct, TRUE);
  174053. jpeg_calc_output_dimensions (&jpegDecompStruct);
  174054. const int width = jpegDecompStruct.output_width;
  174055. const int height = jpegDecompStruct.output_height;
  174056. jpegDecompStruct.out_color_space = JCS_RGB;
  174057. JSAMPARRAY buffer
  174058. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  174059. JPOOL_IMAGE,
  174060. width * 3, 1);
  174061. if (jpeg_start_decompress (&jpegDecompStruct))
  174062. {
  174063. image = new Image (Image::RGB, width, height, false);
  174064. for (int y = 0; y < height; ++y)
  174065. {
  174066. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  174067. int stride, pixelStride;
  174068. uint8* pixels = image->lockPixelDataReadWrite (0, y, width, 1, stride, pixelStride);
  174069. const uint8* src = *buffer;
  174070. uint8* dest = pixels;
  174071. for (int i = width; --i >= 0;)
  174072. {
  174073. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  174074. dest += pixelStride;
  174075. src += 3;
  174076. }
  174077. image->releasePixelDataReadWrite (pixels);
  174078. }
  174079. jpeg_finish_decompress (&jpegDecompStruct);
  174080. }
  174081. jpeg_destroy_decompress (&jpegDecompStruct);
  174082. }
  174083. catch (...)
  174084. {}
  174085. }
  174086. return image;
  174087. }
  174088. static const int bufferSize = 512;
  174089. struct JuceJpegDest : public jpeg_destination_mgr
  174090. {
  174091. OutputStream* output;
  174092. char* buffer;
  174093. };
  174094. static void jpegWriteInit (j_compress_ptr) throw()
  174095. {
  174096. }
  174097. static void jpegWriteTerminate (j_compress_ptr cinfo) throw()
  174098. {
  174099. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  174100. const int numToWrite = bufferSize - dest->free_in_buffer;
  174101. dest->output->write (dest->buffer, numToWrite);
  174102. }
  174103. static boolean jpegWriteFlush (j_compress_ptr cinfo) throw()
  174104. {
  174105. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  174106. const int numToWrite = bufferSize;
  174107. dest->next_output_byte = (JOCTET*) dest->buffer;
  174108. dest->free_in_buffer = bufferSize;
  174109. return dest->output->write (dest->buffer, numToWrite);
  174110. }
  174111. bool juce_writeJPEGImageToStream (const Image& image,
  174112. OutputStream& out,
  174113. float quality) throw()
  174114. {
  174115. if (image.hasAlphaChannel())
  174116. {
  174117. // this method could fill the background in white and still save the image..
  174118. jassertfalse
  174119. return true;
  174120. }
  174121. struct jpeg_compress_struct jpegCompStruct;
  174122. struct jpeg_error_mgr jerr;
  174123. setupSilentErrorHandler (jerr);
  174124. jpegCompStruct.err = &jerr;
  174125. jpeg_create_compress (&jpegCompStruct);
  174126. JuceJpegDest dest;
  174127. jpegCompStruct.dest = &dest;
  174128. dest.output = &out;
  174129. dest.buffer = (char*) juce_malloc (bufferSize);
  174130. dest.next_output_byte = (JOCTET*) dest.buffer;
  174131. dest.free_in_buffer = bufferSize;
  174132. dest.init_destination = jpegWriteInit;
  174133. dest.empty_output_buffer = jpegWriteFlush;
  174134. dest.term_destination = jpegWriteTerminate;
  174135. jpegCompStruct.image_width = image.getWidth();
  174136. jpegCompStruct.image_height = image.getHeight();
  174137. jpegCompStruct.input_components = 3;
  174138. jpegCompStruct.in_color_space = JCS_RGB;
  174139. jpegCompStruct.write_JFIF_header = 1;
  174140. jpegCompStruct.X_density = 72;
  174141. jpegCompStruct.Y_density = 72;
  174142. jpeg_set_defaults (&jpegCompStruct);
  174143. jpegCompStruct.dct_method = JDCT_FLOAT;
  174144. jpegCompStruct.optimize_coding = 1;
  174145. // jpegCompStruct.smoothing_factor = 10;
  174146. if (quality < 0.0f)
  174147. quality = 6.0f;
  174148. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundFloatToInt (quality * 100.0f)), TRUE);
  174149. jpeg_start_compress (&jpegCompStruct, TRUE);
  174150. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  174151. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  174152. JPOOL_IMAGE,
  174153. strideBytes, 1);
  174154. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  174155. {
  174156. int stride, pixelStride;
  174157. const uint8* pixels = image.lockPixelDataReadOnly (0, jpegCompStruct.next_scanline, jpegCompStruct.image_width, 1, stride, pixelStride);
  174158. const uint8* src = pixels;
  174159. uint8* dst = *buffer;
  174160. for (int i = jpegCompStruct.image_width; --i >= 0;)
  174161. {
  174162. *dst++ = ((const PixelRGB*) src)->getRed();
  174163. *dst++ = ((const PixelRGB*) src)->getGreen();
  174164. *dst++ = ((const PixelRGB*) src)->getBlue();
  174165. src += pixelStride;
  174166. }
  174167. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  174168. image.releasePixelDataReadOnly (pixels);
  174169. }
  174170. jpeg_finish_compress (&jpegCompStruct);
  174171. jpeg_destroy_compress (&jpegCompStruct);
  174172. juce_free (dest.buffer);
  174173. out.flush();
  174174. return true;
  174175. }
  174176. END_JUCE_NAMESPACE
  174177. /********* End of inlined file: juce_JPEGLoader.cpp *********/
  174178. /********* Start of inlined file: juce_PNGLoader.cpp *********/
  174179. #ifdef _MSC_VER
  174180. #pragma warning (push)
  174181. #pragma warning (disable: 4390 4611)
  174182. #endif
  174183. namespace zlibNamespace
  174184. {
  174185. #undef OS_CODE
  174186. #undef fdopen
  174187. #undef OS_CODE
  174188. }
  174189. namespace pnglibNamespace
  174190. {
  174191. using namespace zlibNamespace;
  174192. using ::malloc;
  174193. using ::free;
  174194. extern "C"
  174195. {
  174196. using ::abs;
  174197. #define PNG_INTERNAL
  174198. #define NO_DUMMY_DECL
  174199. #define PNG_SETJMP_NOT_SUPPORTED
  174200. /********* Start of inlined file: png.h *********/
  174201. /* png.h - header file for PNG reference library
  174202. *
  174203. * libpng version 1.2.21 - October 4, 2007
  174204. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  174205. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  174206. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  174207. *
  174208. * Authors and maintainers:
  174209. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  174210. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  174211. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  174212. * See also "Contributing Authors", below.
  174213. *
  174214. * Note about libpng version numbers:
  174215. *
  174216. * Due to various miscommunications, unforeseen code incompatibilities
  174217. * and occasional factors outside the authors' control, version numbering
  174218. * on the library has not always been consistent and straightforward.
  174219. * The following table summarizes matters since version 0.89c, which was
  174220. * the first widely used release:
  174221. *
  174222. * source png.h png.h shared-lib
  174223. * version string int version
  174224. * ------- ------ ----- ----------
  174225. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  174226. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  174227. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  174228. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  174229. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  174230. * 0.97c 0.97 97 2.0.97
  174231. * 0.98 0.98 98 2.0.98
  174232. * 0.99 0.99 98 2.0.99
  174233. * 0.99a-m 0.99 99 2.0.99
  174234. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  174235. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  174236. * 1.0.1 png.h string is 10001 2.1.0
  174237. * 1.0.1a-e identical to the 10002 from here on, the shared library
  174238. * 1.0.2 source version) 10002 is 2.V where V is the source code
  174239. * 1.0.2a-b 10003 version, except as noted.
  174240. * 1.0.3 10003
  174241. * 1.0.3a-d 10004
  174242. * 1.0.4 10004
  174243. * 1.0.4a-f 10005
  174244. * 1.0.5 (+ 2 patches) 10005
  174245. * 1.0.5a-d 10006
  174246. * 1.0.5e-r 10100 (not source compatible)
  174247. * 1.0.5s-v 10006 (not binary compatible)
  174248. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  174249. * 1.0.6d-f 10007 (still binary incompatible)
  174250. * 1.0.6g 10007
  174251. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  174252. * 1.0.6i 10007 10.6i
  174253. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  174254. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  174255. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  174256. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  174257. * 1.0.7 1 10007 (still compatible)
  174258. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  174259. * 1.0.8rc1 1 10008 2.1.0.8rc1
  174260. * 1.0.8 1 10008 2.1.0.8
  174261. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  174262. * 1.0.9rc1 1 10009 2.1.0.9rc1
  174263. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  174264. * 1.0.9rc2 1 10009 2.1.0.9rc2
  174265. * 1.0.9 1 10009 2.1.0.9
  174266. * 1.0.10beta1 1 10010 2.1.0.10beta1
  174267. * 1.0.10rc1 1 10010 2.1.0.10rc1
  174268. * 1.0.10 1 10010 2.1.0.10
  174269. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  174270. * 1.0.11rc1 1 10011 2.1.0.11rc1
  174271. * 1.0.11 1 10011 2.1.0.11
  174272. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  174273. * 1.0.12rc1 2 10012 2.1.0.12rc1
  174274. * 1.0.12 2 10012 2.1.0.12
  174275. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  174276. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  174277. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  174278. * 1.2.0rc1 3 10200 3.1.2.0rc1
  174279. * 1.2.0 3 10200 3.1.2.0
  174280. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  174281. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  174282. * 1.2.1 3 10201 3.1.2.1
  174283. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  174284. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  174285. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  174286. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  174287. * 1.0.13 10 10013 10.so.0.1.0.13
  174288. * 1.2.2 12 10202 12.so.0.1.2.2
  174289. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  174290. * 1.2.3 12 10203 12.so.0.1.2.3
  174291. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  174292. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  174293. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  174294. * 1.0.14 10 10014 10.so.0.1.0.14
  174295. * 1.2.4 13 10204 12.so.0.1.2.4
  174296. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  174297. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  174298. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  174299. * 1.0.15 10 10015 10.so.0.1.0.15
  174300. * 1.2.5 13 10205 12.so.0.1.2.5
  174301. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  174302. * 1.0.16 10 10016 10.so.0.1.0.16
  174303. * 1.2.6 13 10206 12.so.0.1.2.6
  174304. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  174305. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  174306. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  174307. * 1.0.17 10 10017 10.so.0.1.0.17
  174308. * 1.2.7 13 10207 12.so.0.1.2.7
  174309. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  174310. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  174311. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  174312. * 1.0.18 10 10018 10.so.0.1.0.18
  174313. * 1.2.8 13 10208 12.so.0.1.2.8
  174314. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  174315. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  174316. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  174317. * 1.2.9 13 10209 12.so.0.9[.0]
  174318. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  174319. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  174320. * 1.2.10 13 10210 12.so.0.10[.0]
  174321. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  174322. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  174323. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  174324. * 1.0.19 10 10019 10.so.0.19[.0]
  174325. * 1.2.11 13 10211 12.so.0.11[.0]
  174326. * 1.0.20 10 10020 10.so.0.20[.0]
  174327. * 1.2.12 13 10212 12.so.0.12[.0]
  174328. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  174329. * 1.0.21 10 10021 10.so.0.21[.0]
  174330. * 1.2.13 13 10213 12.so.0.13[.0]
  174331. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  174332. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  174333. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  174334. * 1.0.22 10 10022 10.so.0.22[.0]
  174335. * 1.2.14 13 10214 12.so.0.14[.0]
  174336. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  174337. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  174338. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  174339. * 1.0.23 10 10023 10.so.0.23[.0]
  174340. * 1.2.15 13 10215 12.so.0.15[.0]
  174341. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  174342. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  174343. * 1.0.24 10 10024 10.so.0.24[.0]
  174344. * 1.2.16 13 10216 12.so.0.16[.0]
  174345. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  174346. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  174347. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  174348. * 1.0.25 10 10025 10.so.0.25[.0]
  174349. * 1.2.17 13 10217 12.so.0.17[.0]
  174350. * 1.0.26 10 10026 10.so.0.26[.0]
  174351. * 1.2.18 13 10218 12.so.0.18[.0]
  174352. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  174353. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  174354. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  174355. * 1.0.27 10 10027 10.so.0.27[.0]
  174356. * 1.2.19 13 10219 12.so.0.19[.0]
  174357. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  174358. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  174359. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  174360. * 1.0.28 10 10028 10.so.0.28[.0]
  174361. * 1.2.20 13 10220 12.so.0.20[.0]
  174362. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  174363. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  174364. * 1.0.29 10 10029 10.so.0.29[.0]
  174365. * 1.2.21 13 10221 12.so.0.21[.0]
  174366. *
  174367. * Henceforth the source version will match the shared-library major
  174368. * and minor numbers; the shared-library major version number will be
  174369. * used for changes in backward compatibility, as it is intended. The
  174370. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  174371. * for applications, is an unsigned integer of the form xyyzz corresponding
  174372. * to the source version x.y.z (leading zeros in y and z). Beta versions
  174373. * were given the previous public release number plus a letter, until
  174374. * version 1.0.6j; from then on they were given the upcoming public
  174375. * release number plus "betaNN" or "rcN".
  174376. *
  174377. * Binary incompatibility exists only when applications make direct access
  174378. * to the info_ptr or png_ptr members through png.h, and the compiled
  174379. * application is loaded with a different version of the library.
  174380. *
  174381. * DLLNUM will change each time there are forward or backward changes
  174382. * in binary compatibility (e.g., when a new feature is added).
  174383. *
  174384. * See libpng.txt or libpng.3 for more information. The PNG specification
  174385. * is available as a W3C Recommendation and as an ISO Specification,
  174386. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  174387. */
  174388. /*
  174389. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  174390. *
  174391. * If you modify libpng you may insert additional notices immediately following
  174392. * this sentence.
  174393. *
  174394. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  174395. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  174396. * distributed according to the same disclaimer and license as libpng-1.2.5
  174397. * with the following individual added to the list of Contributing Authors:
  174398. *
  174399. * Cosmin Truta
  174400. *
  174401. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  174402. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  174403. * distributed according to the same disclaimer and license as libpng-1.0.6
  174404. * with the following individuals added to the list of Contributing Authors:
  174405. *
  174406. * Simon-Pierre Cadieux
  174407. * Eric S. Raymond
  174408. * Gilles Vollant
  174409. *
  174410. * and with the following additions to the disclaimer:
  174411. *
  174412. * There is no warranty against interference with your enjoyment of the
  174413. * library or against infringement. There is no warranty that our
  174414. * efforts or the library will fulfill any of your particular purposes
  174415. * or needs. This library is provided with all faults, and the entire
  174416. * risk of satisfactory quality, performance, accuracy, and effort is with
  174417. * the user.
  174418. *
  174419. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  174420. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  174421. * distributed according to the same disclaimer and license as libpng-0.96,
  174422. * with the following individuals added to the list of Contributing Authors:
  174423. *
  174424. * Tom Lane
  174425. * Glenn Randers-Pehrson
  174426. * Willem van Schaik
  174427. *
  174428. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  174429. * Copyright (c) 1996, 1997 Andreas Dilger
  174430. * Distributed according to the same disclaimer and license as libpng-0.88,
  174431. * with the following individuals added to the list of Contributing Authors:
  174432. *
  174433. * John Bowler
  174434. * Kevin Bracey
  174435. * Sam Bushell
  174436. * Magnus Holmgren
  174437. * Greg Roelofs
  174438. * Tom Tanner
  174439. *
  174440. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  174441. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  174442. *
  174443. * For the purposes of this copyright and license, "Contributing Authors"
  174444. * is defined as the following set of individuals:
  174445. *
  174446. * Andreas Dilger
  174447. * Dave Martindale
  174448. * Guy Eric Schalnat
  174449. * Paul Schmidt
  174450. * Tim Wegner
  174451. *
  174452. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  174453. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  174454. * including, without limitation, the warranties of merchantability and of
  174455. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  174456. * assume no liability for direct, indirect, incidental, special, exemplary,
  174457. * or consequential damages, which may result from the use of the PNG
  174458. * Reference Library, even if advised of the possibility of such damage.
  174459. *
  174460. * Permission is hereby granted to use, copy, modify, and distribute this
  174461. * source code, or portions hereof, for any purpose, without fee, subject
  174462. * to the following restrictions:
  174463. *
  174464. * 1. The origin of this source code must not be misrepresented.
  174465. *
  174466. * 2. Altered versions must be plainly marked as such and
  174467. * must not be misrepresented as being the original source.
  174468. *
  174469. * 3. This Copyright notice may not be removed or altered from
  174470. * any source or altered source distribution.
  174471. *
  174472. * The Contributing Authors and Group 42, Inc. specifically permit, without
  174473. * fee, and encourage the use of this source code as a component to
  174474. * supporting the PNG file format in commercial products. If you use this
  174475. * source code in a product, acknowledgment is not required but would be
  174476. * appreciated.
  174477. */
  174478. /*
  174479. * A "png_get_copyright" function is available, for convenient use in "about"
  174480. * boxes and the like:
  174481. *
  174482. * printf("%s",png_get_copyright(NULL));
  174483. *
  174484. * Also, the PNG logo (in PNG format, of course) is supplied in the
  174485. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  174486. */
  174487. /*
  174488. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  174489. * certification mark of the Open Source Initiative.
  174490. */
  174491. /*
  174492. * The contributing authors would like to thank all those who helped
  174493. * with testing, bug fixes, and patience. This wouldn't have been
  174494. * possible without all of you.
  174495. *
  174496. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  174497. */
  174498. /*
  174499. * Y2K compliance in libpng:
  174500. * =========================
  174501. *
  174502. * October 4, 2007
  174503. *
  174504. * Since the PNG Development group is an ad-hoc body, we can't make
  174505. * an official declaration.
  174506. *
  174507. * This is your unofficial assurance that libpng from version 0.71 and
  174508. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  174509. * versions were also Y2K compliant.
  174510. *
  174511. * Libpng only has three year fields. One is a 2-byte unsigned integer
  174512. * that will hold years up to 65535. The other two hold the date in text
  174513. * format, and will hold years up to 9999.
  174514. *
  174515. * The integer is
  174516. * "png_uint_16 year" in png_time_struct.
  174517. *
  174518. * The strings are
  174519. * "png_charp time_buffer" in png_struct and
  174520. * "near_time_buffer", which is a local character string in png.c.
  174521. *
  174522. * There are seven time-related functions:
  174523. * png.c: png_convert_to_rfc_1123() in png.c
  174524. * (formerly png_convert_to_rfc_1152() in error)
  174525. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  174526. * png_convert_from_time_t() in pngwrite.c
  174527. * png_get_tIME() in pngget.c
  174528. * png_handle_tIME() in pngrutil.c, called in pngread.c
  174529. * png_set_tIME() in pngset.c
  174530. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  174531. *
  174532. * All handle dates properly in a Y2K environment. The
  174533. * png_convert_from_time_t() function calls gmtime() to convert from system
  174534. * clock time, which returns (year - 1900), which we properly convert to
  174535. * the full 4-digit year. There is a possibility that applications using
  174536. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  174537. * function, or that they are incorrectly passing only a 2-digit year
  174538. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  174539. * but this is not under our control. The libpng documentation has always
  174540. * stated that it works with 4-digit years, and the APIs have been
  174541. * documented as such.
  174542. *
  174543. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  174544. * integer to hold the year, and can hold years as large as 65535.
  174545. *
  174546. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  174547. * no date-related code.
  174548. *
  174549. * Glenn Randers-Pehrson
  174550. * libpng maintainer
  174551. * PNG Development Group
  174552. */
  174553. #ifndef PNG_H
  174554. #define PNG_H
  174555. /* This is not the place to learn how to use libpng. The file libpng.txt
  174556. * describes how to use libpng, and the file example.c summarizes it
  174557. * with some code on which to build. This file is useful for looking
  174558. * at the actual function definitions and structure components.
  174559. */
  174560. /* Version information for png.h - this should match the version in png.c */
  174561. #define PNG_LIBPNG_VER_STRING "1.2.21"
  174562. #define PNG_HEADER_VERSION_STRING \
  174563. " libpng version 1.2.21 - October 4, 2007\n"
  174564. #define PNG_LIBPNG_VER_SONUM 0
  174565. #define PNG_LIBPNG_VER_DLLNUM 13
  174566. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  174567. #define PNG_LIBPNG_VER_MAJOR 1
  174568. #define PNG_LIBPNG_VER_MINOR 2
  174569. #define PNG_LIBPNG_VER_RELEASE 21
  174570. /* This should match the numeric part of the final component of
  174571. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  174572. #define PNG_LIBPNG_VER_BUILD 0
  174573. /* Release Status */
  174574. #define PNG_LIBPNG_BUILD_ALPHA 1
  174575. #define PNG_LIBPNG_BUILD_BETA 2
  174576. #define PNG_LIBPNG_BUILD_RC 3
  174577. #define PNG_LIBPNG_BUILD_STABLE 4
  174578. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  174579. /* Release-Specific Flags */
  174580. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  174581. PNG_LIBPNG_BUILD_STABLE only */
  174582. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  174583. PNG_LIBPNG_BUILD_SPECIAL */
  174584. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  174585. PNG_LIBPNG_BUILD_PRIVATE */
  174586. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  174587. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  174588. * We must not include leading zeros.
  174589. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  174590. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  174591. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  174592. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  174593. #ifndef PNG_VERSION_INFO_ONLY
  174594. /* include the compression library's header */
  174595. #endif
  174596. /* include all user configurable info, including optional assembler routines */
  174597. /********* Start of inlined file: pngconf.h *********/
  174598. /* pngconf.h - machine configurable file for libpng
  174599. *
  174600. * libpng version 1.2.21 - October 4, 2007
  174601. * For conditions of distribution and use, see copyright notice in png.h
  174602. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  174603. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  174604. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  174605. */
  174606. /* Any machine specific code is near the front of this file, so if you
  174607. * are configuring libpng for a machine, you may want to read the section
  174608. * starting here down to where it starts to typedef png_color, png_text,
  174609. * and png_info.
  174610. */
  174611. #ifndef PNGCONF_H
  174612. #define PNGCONF_H
  174613. #define PNG_1_2_X
  174614. // These are some Juce config settings that should remove any unnecessary code bloat..
  174615. #define PNG_NO_STDIO 1
  174616. #define PNG_DEBUG 0
  174617. #define PNG_NO_WARNINGS 1
  174618. #define PNG_NO_ERROR_TEXT 1
  174619. #define PNG_NO_ERROR_NUMBERS 1
  174620. #define PNG_NO_USER_MEM 1
  174621. #define PNG_NO_READ_iCCP 1
  174622. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  174623. #define PNG_NO_READ_USER_CHUNKS 1
  174624. #define PNG_NO_READ_iTXt 1
  174625. #define PNG_NO_READ_sCAL 1
  174626. #define PNG_NO_READ_sPLT 1
  174627. #define png_error(a, b) png_err(a)
  174628. #define png_warning(a, b)
  174629. #define png_chunk_error(a, b) png_err(a)
  174630. #define png_chunk_warning(a, b)
  174631. /*
  174632. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  174633. * includes the resource compiler for Windows DLL configurations.
  174634. */
  174635. #ifdef PNG_USER_CONFIG
  174636. # ifndef PNG_USER_PRIVATEBUILD
  174637. # define PNG_USER_PRIVATEBUILD
  174638. # endif
  174639. #include "pngusr.h"
  174640. #endif
  174641. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  174642. #ifdef PNG_CONFIGURE_LIBPNG
  174643. #ifdef HAVE_CONFIG_H
  174644. #include "config.h"
  174645. #endif
  174646. #endif
  174647. /*
  174648. * Added at libpng-1.2.8
  174649. *
  174650. * If you create a private DLL you need to define in "pngusr.h" the followings:
  174651. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  174652. * the DLL was built>
  174653. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  174654. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  174655. * distinguish your DLL from those of the official release. These
  174656. * correspond to the trailing letters that come after the version
  174657. * number and must match your private DLL name>
  174658. * e.g. // private DLL "libpng13gx.dll"
  174659. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  174660. *
  174661. * The following macros are also at your disposal if you want to complete the
  174662. * DLL VERSIONINFO structure.
  174663. * - PNG_USER_VERSIONINFO_COMMENTS
  174664. * - PNG_USER_VERSIONINFO_COMPANYNAME
  174665. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  174666. */
  174667. #ifdef __STDC__
  174668. #ifdef SPECIALBUILD
  174669. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  174670. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  174671. #endif
  174672. #ifdef PRIVATEBUILD
  174673. # pragma message("PRIVATEBUILD is deprecated.\
  174674. Use PNG_USER_PRIVATEBUILD instead.")
  174675. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  174676. #endif
  174677. #endif /* __STDC__ */
  174678. #ifndef PNG_VERSION_INFO_ONLY
  174679. /* End of material added to libpng-1.2.8 */
  174680. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  174681. Restored at libpng-1.2.21 */
  174682. # define PNG_WARN_UNINITIALIZED_ROW 1
  174683. /* End of material added at libpng-1.2.19/1.2.21 */
  174684. /* This is the size of the compression buffer, and thus the size of
  174685. * an IDAT chunk. Make this whatever size you feel is best for your
  174686. * machine. One of these will be allocated per png_struct. When this
  174687. * is full, it writes the data to the disk, and does some other
  174688. * calculations. Making this an extremely small size will slow
  174689. * the library down, but you may want to experiment to determine
  174690. * where it becomes significant, if you are concerned with memory
  174691. * usage. Note that zlib allocates at least 32Kb also. For readers,
  174692. * this describes the size of the buffer available to read the data in.
  174693. * Unless this gets smaller than the size of a row (compressed),
  174694. * it should not make much difference how big this is.
  174695. */
  174696. #ifndef PNG_ZBUF_SIZE
  174697. # define PNG_ZBUF_SIZE 8192
  174698. #endif
  174699. /* Enable if you want a write-only libpng */
  174700. #ifndef PNG_NO_READ_SUPPORTED
  174701. # define PNG_READ_SUPPORTED
  174702. #endif
  174703. /* Enable if you want a read-only libpng */
  174704. #ifndef PNG_NO_WRITE_SUPPORTED
  174705. # define PNG_WRITE_SUPPORTED
  174706. #endif
  174707. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  174708. support PNGs that are embedded in MNG datastreams */
  174709. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  174710. # ifndef PNG_MNG_FEATURES_SUPPORTED
  174711. # define PNG_MNG_FEATURES_SUPPORTED
  174712. # endif
  174713. #endif
  174714. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  174715. # ifndef PNG_FLOATING_POINT_SUPPORTED
  174716. # define PNG_FLOATING_POINT_SUPPORTED
  174717. # endif
  174718. #endif
  174719. /* If you are running on a machine where you cannot allocate more
  174720. * than 64K of memory at once, uncomment this. While libpng will not
  174721. * normally need that much memory in a chunk (unless you load up a very
  174722. * large file), zlib needs to know how big of a chunk it can use, and
  174723. * libpng thus makes sure to check any memory allocation to verify it
  174724. * will fit into memory.
  174725. #define PNG_MAX_MALLOC_64K
  174726. */
  174727. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  174728. # define PNG_MAX_MALLOC_64K
  174729. #endif
  174730. /* Special munging to support doing things the 'cygwin' way:
  174731. * 'Normal' png-on-win32 defines/defaults:
  174732. * PNG_BUILD_DLL -- building dll
  174733. * PNG_USE_DLL -- building an application, linking to dll
  174734. * (no define) -- building static library, or building an
  174735. * application and linking to the static lib
  174736. * 'Cygwin' defines/defaults:
  174737. * PNG_BUILD_DLL -- (ignored) building the dll
  174738. * (no define) -- (ignored) building an application, linking to the dll
  174739. * PNG_STATIC -- (ignored) building the static lib, or building an
  174740. * application that links to the static lib.
  174741. * ALL_STATIC -- (ignored) building various static libs, or building an
  174742. * application that links to the static libs.
  174743. * Thus,
  174744. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  174745. * this bit of #ifdefs will define the 'correct' config variables based on
  174746. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  174747. * unnecessary.
  174748. *
  174749. * Also, the precedence order is:
  174750. * ALL_STATIC (since we can't #undef something outside our namespace)
  174751. * PNG_BUILD_DLL
  174752. * PNG_STATIC
  174753. * (nothing) == PNG_USE_DLL
  174754. *
  174755. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  174756. * of auto-import in binutils, we no longer need to worry about
  174757. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  174758. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  174759. * to __declspec() stuff. However, we DO need to worry about
  174760. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  174761. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  174762. */
  174763. #if defined(__CYGWIN__)
  174764. # if defined(ALL_STATIC)
  174765. # if defined(PNG_BUILD_DLL)
  174766. # undef PNG_BUILD_DLL
  174767. # endif
  174768. # if defined(PNG_USE_DLL)
  174769. # undef PNG_USE_DLL
  174770. # endif
  174771. # if defined(PNG_DLL)
  174772. # undef PNG_DLL
  174773. # endif
  174774. # if !defined(PNG_STATIC)
  174775. # define PNG_STATIC
  174776. # endif
  174777. # else
  174778. # if defined (PNG_BUILD_DLL)
  174779. # if defined(PNG_STATIC)
  174780. # undef PNG_STATIC
  174781. # endif
  174782. # if defined(PNG_USE_DLL)
  174783. # undef PNG_USE_DLL
  174784. # endif
  174785. # if !defined(PNG_DLL)
  174786. # define PNG_DLL
  174787. # endif
  174788. # else
  174789. # if defined(PNG_STATIC)
  174790. # if defined(PNG_USE_DLL)
  174791. # undef PNG_USE_DLL
  174792. # endif
  174793. # if defined(PNG_DLL)
  174794. # undef PNG_DLL
  174795. # endif
  174796. # else
  174797. # if !defined(PNG_USE_DLL)
  174798. # define PNG_USE_DLL
  174799. # endif
  174800. # if !defined(PNG_DLL)
  174801. # define PNG_DLL
  174802. # endif
  174803. # endif
  174804. # endif
  174805. # endif
  174806. #endif
  174807. /* This protects us against compilers that run on a windowing system
  174808. * and thus don't have or would rather us not use the stdio types:
  174809. * stdin, stdout, and stderr. The only one currently used is stderr
  174810. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  174811. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  174812. * will also prevent these, plus will prevent the entire set of stdio
  174813. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  174814. * unless (PNG_DEBUG > 0) has been #defined.
  174815. *
  174816. * #define PNG_NO_CONSOLE_IO
  174817. * #define PNG_NO_STDIO
  174818. */
  174819. #if defined(_WIN32_WCE)
  174820. # include <windows.h>
  174821. /* Console I/O functions are not supported on WindowsCE */
  174822. # define PNG_NO_CONSOLE_IO
  174823. # ifdef PNG_DEBUG
  174824. # undef PNG_DEBUG
  174825. # endif
  174826. #endif
  174827. #ifdef PNG_BUILD_DLL
  174828. # ifndef PNG_CONSOLE_IO_SUPPORTED
  174829. # ifndef PNG_NO_CONSOLE_IO
  174830. # define PNG_NO_CONSOLE_IO
  174831. # endif
  174832. # endif
  174833. #endif
  174834. # ifdef PNG_NO_STDIO
  174835. # ifndef PNG_NO_CONSOLE_IO
  174836. # define PNG_NO_CONSOLE_IO
  174837. # endif
  174838. # ifdef PNG_DEBUG
  174839. # if (PNG_DEBUG > 0)
  174840. # include <stdio.h>
  174841. # endif
  174842. # endif
  174843. # else
  174844. # if !defined(_WIN32_WCE)
  174845. /* "stdio.h" functions are not supported on WindowsCE */
  174846. # include <stdio.h>
  174847. # endif
  174848. # endif
  174849. /* This macro protects us against machines that don't have function
  174850. * prototypes (ie K&R style headers). If your compiler does not handle
  174851. * function prototypes, define this macro and use the included ansi2knr.
  174852. * I've always been able to use _NO_PROTO as the indicator, but you may
  174853. * need to drag the empty declaration out in front of here, or change the
  174854. * ifdef to suit your own needs.
  174855. */
  174856. #ifndef PNGARG
  174857. #ifdef OF /* zlib prototype munger */
  174858. # define PNGARG(arglist) OF(arglist)
  174859. #else
  174860. #ifdef _NO_PROTO
  174861. # define PNGARG(arglist) ()
  174862. # ifndef PNG_TYPECAST_NULL
  174863. # define PNG_TYPECAST_NULL
  174864. # endif
  174865. #else
  174866. # define PNGARG(arglist) arglist
  174867. #endif /* _NO_PROTO */
  174868. #endif /* OF */
  174869. #endif /* PNGARG */
  174870. /* Try to determine if we are compiling on a Mac. Note that testing for
  174871. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  174872. * on non-Mac platforms.
  174873. */
  174874. #ifndef MACOS
  174875. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  174876. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  174877. # define MACOS
  174878. # endif
  174879. #endif
  174880. /* enough people need this for various reasons to include it here */
  174881. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  174882. # include <sys/types.h>
  174883. #endif
  174884. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  174885. # define PNG_SETJMP_SUPPORTED
  174886. #endif
  174887. #ifdef PNG_SETJMP_SUPPORTED
  174888. /* This is an attempt to force a single setjmp behaviour on Linux. If
  174889. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  174890. */
  174891. # ifdef __linux__
  174892. # ifdef _BSD_SOURCE
  174893. # define PNG_SAVE_BSD_SOURCE
  174894. # undef _BSD_SOURCE
  174895. # endif
  174896. # ifdef _SETJMP_H
  174897. /* If you encounter a compiler error here, see the explanation
  174898. * near the end of INSTALL.
  174899. */
  174900. __png.h__ already includes setjmp.h;
  174901. __dont__ include it again.;
  174902. # endif
  174903. # endif /* __linux__ */
  174904. /* include setjmp.h for error handling */
  174905. # include <setjmp.h>
  174906. # ifdef __linux__
  174907. # ifdef PNG_SAVE_BSD_SOURCE
  174908. # define _BSD_SOURCE
  174909. # undef PNG_SAVE_BSD_SOURCE
  174910. # endif
  174911. # endif /* __linux__ */
  174912. #endif /* PNG_SETJMP_SUPPORTED */
  174913. #ifdef BSD
  174914. # include <strings.h>
  174915. #else
  174916. # include <string.h>
  174917. #endif
  174918. /* Other defines for things like memory and the like can go here. */
  174919. #ifdef PNG_INTERNAL
  174920. #include <stdlib.h>
  174921. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  174922. * aren't usually used outside the library (as far as I know), so it is
  174923. * debatable if they should be exported at all. In the future, when it is
  174924. * possible to have run-time registry of chunk-handling functions, some of
  174925. * these will be made available again.
  174926. #define PNG_EXTERN extern
  174927. */
  174928. #define PNG_EXTERN
  174929. /* Other defines specific to compilers can go here. Try to keep
  174930. * them inside an appropriate ifdef/endif pair for portability.
  174931. */
  174932. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  174933. # if defined(MACOS)
  174934. /* We need to check that <math.h> hasn't already been included earlier
  174935. * as it seems it doesn't agree with <fp.h>, yet we should really use
  174936. * <fp.h> if possible.
  174937. */
  174938. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  174939. # include <fp.h>
  174940. # endif
  174941. # else
  174942. # include <math.h>
  174943. # endif
  174944. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  174945. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  174946. * MATH=68881
  174947. */
  174948. # include <m68881.h>
  174949. # endif
  174950. #endif
  174951. /* Codewarrior on NT has linking problems without this. */
  174952. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  174953. # define PNG_ALWAYS_EXTERN
  174954. #endif
  174955. /* This provides the non-ANSI (far) memory allocation routines. */
  174956. #if defined(__TURBOC__) && defined(__MSDOS__)
  174957. # include <mem.h>
  174958. # include <alloc.h>
  174959. #endif
  174960. /* I have no idea why is this necessary... */
  174961. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  174962. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  174963. # include <malloc.h>
  174964. #endif
  174965. /* This controls how fine the dithering gets. As this allocates
  174966. * a largish chunk of memory (32K), those who are not as concerned
  174967. * with dithering quality can decrease some or all of these.
  174968. */
  174969. #ifndef PNG_DITHER_RED_BITS
  174970. # define PNG_DITHER_RED_BITS 5
  174971. #endif
  174972. #ifndef PNG_DITHER_GREEN_BITS
  174973. # define PNG_DITHER_GREEN_BITS 5
  174974. #endif
  174975. #ifndef PNG_DITHER_BLUE_BITS
  174976. # define PNG_DITHER_BLUE_BITS 5
  174977. #endif
  174978. /* This controls how fine the gamma correction becomes when you
  174979. * are only interested in 8 bits anyway. Increasing this value
  174980. * results in more memory being used, and more pow() functions
  174981. * being called to fill in the gamma tables. Don't set this value
  174982. * less then 8, and even that may not work (I haven't tested it).
  174983. */
  174984. #ifndef PNG_MAX_GAMMA_8
  174985. # define PNG_MAX_GAMMA_8 11
  174986. #endif
  174987. /* This controls how much a difference in gamma we can tolerate before
  174988. * we actually start doing gamma conversion.
  174989. */
  174990. #ifndef PNG_GAMMA_THRESHOLD
  174991. # define PNG_GAMMA_THRESHOLD 0.05
  174992. #endif
  174993. #endif /* PNG_INTERNAL */
  174994. /* The following uses const char * instead of char * for error
  174995. * and warning message functions, so some compilers won't complain.
  174996. * If you do not want to use const, define PNG_NO_CONST here.
  174997. */
  174998. #ifndef PNG_NO_CONST
  174999. # define PNG_CONST const
  175000. #else
  175001. # define PNG_CONST
  175002. #endif
  175003. /* The following defines give you the ability to remove code from the
  175004. * library that you will not be using. I wish I could figure out how to
  175005. * automate this, but I can't do that without making it seriously hard
  175006. * on the users. So if you are not using an ability, change the #define
  175007. * to and #undef, and that part of the library will not be compiled. If
  175008. * your linker can't find a function, you may want to make sure the
  175009. * ability is defined here. Some of these depend upon some others being
  175010. * defined. I haven't figured out all the interactions here, so you may
  175011. * have to experiment awhile to get everything to compile. If you are
  175012. * creating or using a shared library, you probably shouldn't touch this,
  175013. * as it will affect the size of the structures, and this will cause bad
  175014. * things to happen if the library and/or application ever change.
  175015. */
  175016. /* Any features you will not be using can be undef'ed here */
  175017. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  175018. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  175019. * on the compile line, then pick and choose which ones to define without
  175020. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  175021. * if you only want to have a png-compliant reader/writer but don't need
  175022. * any of the extra transformations. This saves about 80 kbytes in a
  175023. * typical installation of the library. (PNG_NO_* form added in version
  175024. * 1.0.1c, for consistency)
  175025. */
  175026. /* The size of the png_text structure changed in libpng-1.0.6 when
  175027. * iTXt support was added. iTXt support was turned off by default through
  175028. * libpng-1.2.x, to support old apps that malloc the png_text structure
  175029. * instead of calling png_set_text() and letting libpng malloc it. It
  175030. * was turned on by default in libpng-1.3.0.
  175031. */
  175032. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  175033. # ifndef PNG_NO_iTXt_SUPPORTED
  175034. # define PNG_NO_iTXt_SUPPORTED
  175035. # endif
  175036. # ifndef PNG_NO_READ_iTXt
  175037. # define PNG_NO_READ_iTXt
  175038. # endif
  175039. # ifndef PNG_NO_WRITE_iTXt
  175040. # define PNG_NO_WRITE_iTXt
  175041. # endif
  175042. #endif
  175043. #if !defined(PNG_NO_iTXt_SUPPORTED)
  175044. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  175045. # define PNG_READ_iTXt
  175046. # endif
  175047. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  175048. # define PNG_WRITE_iTXt
  175049. # endif
  175050. #endif
  175051. /* The following support, added after version 1.0.0, can be turned off here en
  175052. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  175053. * with old applications that require the length of png_struct and png_info
  175054. * to remain unchanged.
  175055. */
  175056. #ifdef PNG_LEGACY_SUPPORTED
  175057. # define PNG_NO_FREE_ME
  175058. # define PNG_NO_READ_UNKNOWN_CHUNKS
  175059. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  175060. # define PNG_NO_READ_USER_CHUNKS
  175061. # define PNG_NO_READ_iCCP
  175062. # define PNG_NO_WRITE_iCCP
  175063. # define PNG_NO_READ_iTXt
  175064. # define PNG_NO_WRITE_iTXt
  175065. # define PNG_NO_READ_sCAL
  175066. # define PNG_NO_WRITE_sCAL
  175067. # define PNG_NO_READ_sPLT
  175068. # define PNG_NO_WRITE_sPLT
  175069. # define PNG_NO_INFO_IMAGE
  175070. # define PNG_NO_READ_RGB_TO_GRAY
  175071. # define PNG_NO_READ_USER_TRANSFORM
  175072. # define PNG_NO_WRITE_USER_TRANSFORM
  175073. # define PNG_NO_USER_MEM
  175074. # define PNG_NO_READ_EMPTY_PLTE
  175075. # define PNG_NO_MNG_FEATURES
  175076. # define PNG_NO_FIXED_POINT_SUPPORTED
  175077. #endif
  175078. /* Ignore attempt to turn off both floating and fixed point support */
  175079. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  175080. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  175081. # define PNG_FIXED_POINT_SUPPORTED
  175082. #endif
  175083. #ifndef PNG_NO_FREE_ME
  175084. # define PNG_FREE_ME_SUPPORTED
  175085. #endif
  175086. #if defined(PNG_READ_SUPPORTED)
  175087. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  175088. !defined(PNG_NO_READ_TRANSFORMS)
  175089. # define PNG_READ_TRANSFORMS_SUPPORTED
  175090. #endif
  175091. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  175092. # ifndef PNG_NO_READ_EXPAND
  175093. # define PNG_READ_EXPAND_SUPPORTED
  175094. # endif
  175095. # ifndef PNG_NO_READ_SHIFT
  175096. # define PNG_READ_SHIFT_SUPPORTED
  175097. # endif
  175098. # ifndef PNG_NO_READ_PACK
  175099. # define PNG_READ_PACK_SUPPORTED
  175100. # endif
  175101. # ifndef PNG_NO_READ_BGR
  175102. # define PNG_READ_BGR_SUPPORTED
  175103. # endif
  175104. # ifndef PNG_NO_READ_SWAP
  175105. # define PNG_READ_SWAP_SUPPORTED
  175106. # endif
  175107. # ifndef PNG_NO_READ_PACKSWAP
  175108. # define PNG_READ_PACKSWAP_SUPPORTED
  175109. # endif
  175110. # ifndef PNG_NO_READ_INVERT
  175111. # define PNG_READ_INVERT_SUPPORTED
  175112. # endif
  175113. # ifndef PNG_NO_READ_DITHER
  175114. # define PNG_READ_DITHER_SUPPORTED
  175115. # endif
  175116. # ifndef PNG_NO_READ_BACKGROUND
  175117. # define PNG_READ_BACKGROUND_SUPPORTED
  175118. # endif
  175119. # ifndef PNG_NO_READ_16_TO_8
  175120. # define PNG_READ_16_TO_8_SUPPORTED
  175121. # endif
  175122. # ifndef PNG_NO_READ_FILLER
  175123. # define PNG_READ_FILLER_SUPPORTED
  175124. # endif
  175125. # ifndef PNG_NO_READ_GAMMA
  175126. # define PNG_READ_GAMMA_SUPPORTED
  175127. # endif
  175128. # ifndef PNG_NO_READ_GRAY_TO_RGB
  175129. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  175130. # endif
  175131. # ifndef PNG_NO_READ_SWAP_ALPHA
  175132. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  175133. # endif
  175134. # ifndef PNG_NO_READ_INVERT_ALPHA
  175135. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  175136. # endif
  175137. # ifndef PNG_NO_READ_STRIP_ALPHA
  175138. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  175139. # endif
  175140. # ifndef PNG_NO_READ_USER_TRANSFORM
  175141. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  175142. # endif
  175143. # ifndef PNG_NO_READ_RGB_TO_GRAY
  175144. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  175145. # endif
  175146. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  175147. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  175148. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  175149. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  175150. #endif /* about interlacing capability! You'll */
  175151. /* still have interlacing unless you change the following line: */
  175152. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  175153. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  175154. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  175155. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  175156. # endif
  175157. #endif
  175158. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  175159. /* Deprecated, will be removed from version 2.0.0.
  175160. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  175161. #ifndef PNG_NO_READ_EMPTY_PLTE
  175162. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  175163. #endif
  175164. #endif
  175165. #endif /* PNG_READ_SUPPORTED */
  175166. #if defined(PNG_WRITE_SUPPORTED)
  175167. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  175168. !defined(PNG_NO_WRITE_TRANSFORMS)
  175169. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  175170. #endif
  175171. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  175172. # ifndef PNG_NO_WRITE_SHIFT
  175173. # define PNG_WRITE_SHIFT_SUPPORTED
  175174. # endif
  175175. # ifndef PNG_NO_WRITE_PACK
  175176. # define PNG_WRITE_PACK_SUPPORTED
  175177. # endif
  175178. # ifndef PNG_NO_WRITE_BGR
  175179. # define PNG_WRITE_BGR_SUPPORTED
  175180. # endif
  175181. # ifndef PNG_NO_WRITE_SWAP
  175182. # define PNG_WRITE_SWAP_SUPPORTED
  175183. # endif
  175184. # ifndef PNG_NO_WRITE_PACKSWAP
  175185. # define PNG_WRITE_PACKSWAP_SUPPORTED
  175186. # endif
  175187. # ifndef PNG_NO_WRITE_INVERT
  175188. # define PNG_WRITE_INVERT_SUPPORTED
  175189. # endif
  175190. # ifndef PNG_NO_WRITE_FILLER
  175191. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  175192. # endif
  175193. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  175194. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  175195. # endif
  175196. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  175197. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  175198. # endif
  175199. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  175200. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  175201. # endif
  175202. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  175203. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  175204. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  175205. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  175206. encoders, but can cause trouble
  175207. if left undefined */
  175208. #endif
  175209. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  175210. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  175211. defined(PNG_FLOATING_POINT_SUPPORTED)
  175212. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  175213. #endif
  175214. #ifndef PNG_NO_WRITE_FLUSH
  175215. # define PNG_WRITE_FLUSH_SUPPORTED
  175216. #endif
  175217. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  175218. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  175219. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  175220. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  175221. #endif
  175222. #endif
  175223. #endif /* PNG_WRITE_SUPPORTED */
  175224. #ifndef PNG_1_0_X
  175225. # ifndef PNG_NO_ERROR_NUMBERS
  175226. # define PNG_ERROR_NUMBERS_SUPPORTED
  175227. # endif
  175228. #endif /* PNG_1_0_X */
  175229. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  175230. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  175231. # ifndef PNG_NO_USER_TRANSFORM_PTR
  175232. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  175233. # endif
  175234. #endif
  175235. #ifndef PNG_NO_STDIO
  175236. # define PNG_TIME_RFC1123_SUPPORTED
  175237. #endif
  175238. /* This adds extra functions in pngget.c for accessing data from the
  175239. * info pointer (added in version 0.99)
  175240. * png_get_image_width()
  175241. * png_get_image_height()
  175242. * png_get_bit_depth()
  175243. * png_get_color_type()
  175244. * png_get_compression_type()
  175245. * png_get_filter_type()
  175246. * png_get_interlace_type()
  175247. * png_get_pixel_aspect_ratio()
  175248. * png_get_pixels_per_meter()
  175249. * png_get_x_offset_pixels()
  175250. * png_get_y_offset_pixels()
  175251. * png_get_x_offset_microns()
  175252. * png_get_y_offset_microns()
  175253. */
  175254. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  175255. # define PNG_EASY_ACCESS_SUPPORTED
  175256. #endif
  175257. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  175258. * and removed from version 1.2.20. The following will be removed
  175259. * from libpng-1.4.0
  175260. */
  175261. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  175262. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  175263. # define PNG_OPTIMIZED_CODE_SUPPORTED
  175264. # endif
  175265. #endif
  175266. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  175267. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  175268. # define PNG_ASSEMBLER_CODE_SUPPORTED
  175269. # endif
  175270. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  175271. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  175272. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  175273. # define PNG_NO_MMX_CODE
  175274. # endif
  175275. # endif
  175276. # if defined(__APPLE__)
  175277. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  175278. # define PNG_NO_MMX_CODE
  175279. # endif
  175280. # endif
  175281. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  175282. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  175283. # define PNG_NO_MMX_CODE
  175284. # endif
  175285. # endif
  175286. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  175287. # define PNG_MMX_CODE_SUPPORTED
  175288. # endif
  175289. #endif
  175290. /* end of obsolete code to be removed from libpng-1.4.0 */
  175291. #if !defined(PNG_1_0_X)
  175292. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  175293. # define PNG_USER_MEM_SUPPORTED
  175294. #endif
  175295. #endif /* PNG_1_0_X */
  175296. /* Added at libpng-1.2.6 */
  175297. #if !defined(PNG_1_0_X)
  175298. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  175299. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  175300. # define PNG_SET_USER_LIMITS_SUPPORTED
  175301. #endif
  175302. #endif
  175303. #endif /* PNG_1_0_X */
  175304. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  175305. * how large, set these limits to 0x7fffffffL
  175306. */
  175307. #ifndef PNG_USER_WIDTH_MAX
  175308. # define PNG_USER_WIDTH_MAX 1000000L
  175309. #endif
  175310. #ifndef PNG_USER_HEIGHT_MAX
  175311. # define PNG_USER_HEIGHT_MAX 1000000L
  175312. #endif
  175313. /* These are currently experimental features, define them if you want */
  175314. /* very little testing */
  175315. /*
  175316. #ifdef PNG_READ_SUPPORTED
  175317. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  175318. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  175319. # endif
  175320. #endif
  175321. */
  175322. /* This is only for PowerPC big-endian and 680x0 systems */
  175323. /* some testing */
  175324. /*
  175325. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  175326. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  175327. #endif
  175328. */
  175329. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  175330. /*
  175331. #define PNG_NO_POINTER_INDEXING
  175332. */
  175333. /* These functions are turned off by default, as they will be phased out. */
  175334. /*
  175335. #define PNG_USELESS_TESTS_SUPPORTED
  175336. #define PNG_CORRECT_PALETTE_SUPPORTED
  175337. */
  175338. /* Any chunks you are not interested in, you can undef here. The
  175339. * ones that allocate memory may be expecially important (hIST,
  175340. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  175341. * a bit smaller.
  175342. */
  175343. #if defined(PNG_READ_SUPPORTED) && \
  175344. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  175345. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  175346. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  175347. #endif
  175348. #if defined(PNG_WRITE_SUPPORTED) && \
  175349. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  175350. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  175351. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  175352. #endif
  175353. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  175354. #ifdef PNG_NO_READ_TEXT
  175355. # define PNG_NO_READ_iTXt
  175356. # define PNG_NO_READ_tEXt
  175357. # define PNG_NO_READ_zTXt
  175358. #endif
  175359. #ifndef PNG_NO_READ_bKGD
  175360. # define PNG_READ_bKGD_SUPPORTED
  175361. # define PNG_bKGD_SUPPORTED
  175362. #endif
  175363. #ifndef PNG_NO_READ_cHRM
  175364. # define PNG_READ_cHRM_SUPPORTED
  175365. # define PNG_cHRM_SUPPORTED
  175366. #endif
  175367. #ifndef PNG_NO_READ_gAMA
  175368. # define PNG_READ_gAMA_SUPPORTED
  175369. # define PNG_gAMA_SUPPORTED
  175370. #endif
  175371. #ifndef PNG_NO_READ_hIST
  175372. # define PNG_READ_hIST_SUPPORTED
  175373. # define PNG_hIST_SUPPORTED
  175374. #endif
  175375. #ifndef PNG_NO_READ_iCCP
  175376. # define PNG_READ_iCCP_SUPPORTED
  175377. # define PNG_iCCP_SUPPORTED
  175378. #endif
  175379. #ifndef PNG_NO_READ_iTXt
  175380. # ifndef PNG_READ_iTXt_SUPPORTED
  175381. # define PNG_READ_iTXt_SUPPORTED
  175382. # endif
  175383. # ifndef PNG_iTXt_SUPPORTED
  175384. # define PNG_iTXt_SUPPORTED
  175385. # endif
  175386. #endif
  175387. #ifndef PNG_NO_READ_oFFs
  175388. # define PNG_READ_oFFs_SUPPORTED
  175389. # define PNG_oFFs_SUPPORTED
  175390. #endif
  175391. #ifndef PNG_NO_READ_pCAL
  175392. # define PNG_READ_pCAL_SUPPORTED
  175393. # define PNG_pCAL_SUPPORTED
  175394. #endif
  175395. #ifndef PNG_NO_READ_sCAL
  175396. # define PNG_READ_sCAL_SUPPORTED
  175397. # define PNG_sCAL_SUPPORTED
  175398. #endif
  175399. #ifndef PNG_NO_READ_pHYs
  175400. # define PNG_READ_pHYs_SUPPORTED
  175401. # define PNG_pHYs_SUPPORTED
  175402. #endif
  175403. #ifndef PNG_NO_READ_sBIT
  175404. # define PNG_READ_sBIT_SUPPORTED
  175405. # define PNG_sBIT_SUPPORTED
  175406. #endif
  175407. #ifndef PNG_NO_READ_sPLT
  175408. # define PNG_READ_sPLT_SUPPORTED
  175409. # define PNG_sPLT_SUPPORTED
  175410. #endif
  175411. #ifndef PNG_NO_READ_sRGB
  175412. # define PNG_READ_sRGB_SUPPORTED
  175413. # define PNG_sRGB_SUPPORTED
  175414. #endif
  175415. #ifndef PNG_NO_READ_tEXt
  175416. # define PNG_READ_tEXt_SUPPORTED
  175417. # define PNG_tEXt_SUPPORTED
  175418. #endif
  175419. #ifndef PNG_NO_READ_tIME
  175420. # define PNG_READ_tIME_SUPPORTED
  175421. # define PNG_tIME_SUPPORTED
  175422. #endif
  175423. #ifndef PNG_NO_READ_tRNS
  175424. # define PNG_READ_tRNS_SUPPORTED
  175425. # define PNG_tRNS_SUPPORTED
  175426. #endif
  175427. #ifndef PNG_NO_READ_zTXt
  175428. # define PNG_READ_zTXt_SUPPORTED
  175429. # define PNG_zTXt_SUPPORTED
  175430. #endif
  175431. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  175432. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  175433. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  175434. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  175435. # endif
  175436. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  175437. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  175438. # endif
  175439. #endif
  175440. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  175441. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  175442. # define PNG_READ_USER_CHUNKS_SUPPORTED
  175443. # define PNG_USER_CHUNKS_SUPPORTED
  175444. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  175445. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  175446. # endif
  175447. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  175448. # undef PNG_NO_HANDLE_AS_UNKNOWN
  175449. # endif
  175450. #endif
  175451. #ifndef PNG_NO_READ_OPT_PLTE
  175452. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  175453. #endif /* optional PLTE chunk in RGB and RGBA images */
  175454. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  175455. defined(PNG_READ_zTXt_SUPPORTED)
  175456. # define PNG_READ_TEXT_SUPPORTED
  175457. # define PNG_TEXT_SUPPORTED
  175458. #endif
  175459. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  175460. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  175461. #ifdef PNG_NO_WRITE_TEXT
  175462. # define PNG_NO_WRITE_iTXt
  175463. # define PNG_NO_WRITE_tEXt
  175464. # define PNG_NO_WRITE_zTXt
  175465. #endif
  175466. #ifndef PNG_NO_WRITE_bKGD
  175467. # define PNG_WRITE_bKGD_SUPPORTED
  175468. # ifndef PNG_bKGD_SUPPORTED
  175469. # define PNG_bKGD_SUPPORTED
  175470. # endif
  175471. #endif
  175472. #ifndef PNG_NO_WRITE_cHRM
  175473. # define PNG_WRITE_cHRM_SUPPORTED
  175474. # ifndef PNG_cHRM_SUPPORTED
  175475. # define PNG_cHRM_SUPPORTED
  175476. # endif
  175477. #endif
  175478. #ifndef PNG_NO_WRITE_gAMA
  175479. # define PNG_WRITE_gAMA_SUPPORTED
  175480. # ifndef PNG_gAMA_SUPPORTED
  175481. # define PNG_gAMA_SUPPORTED
  175482. # endif
  175483. #endif
  175484. #ifndef PNG_NO_WRITE_hIST
  175485. # define PNG_WRITE_hIST_SUPPORTED
  175486. # ifndef PNG_hIST_SUPPORTED
  175487. # define PNG_hIST_SUPPORTED
  175488. # endif
  175489. #endif
  175490. #ifndef PNG_NO_WRITE_iCCP
  175491. # define PNG_WRITE_iCCP_SUPPORTED
  175492. # ifndef PNG_iCCP_SUPPORTED
  175493. # define PNG_iCCP_SUPPORTED
  175494. # endif
  175495. #endif
  175496. #ifndef PNG_NO_WRITE_iTXt
  175497. # ifndef PNG_WRITE_iTXt_SUPPORTED
  175498. # define PNG_WRITE_iTXt_SUPPORTED
  175499. # endif
  175500. # ifndef PNG_iTXt_SUPPORTED
  175501. # define PNG_iTXt_SUPPORTED
  175502. # endif
  175503. #endif
  175504. #ifndef PNG_NO_WRITE_oFFs
  175505. # define PNG_WRITE_oFFs_SUPPORTED
  175506. # ifndef PNG_oFFs_SUPPORTED
  175507. # define PNG_oFFs_SUPPORTED
  175508. # endif
  175509. #endif
  175510. #ifndef PNG_NO_WRITE_pCAL
  175511. # define PNG_WRITE_pCAL_SUPPORTED
  175512. # ifndef PNG_pCAL_SUPPORTED
  175513. # define PNG_pCAL_SUPPORTED
  175514. # endif
  175515. #endif
  175516. #ifndef PNG_NO_WRITE_sCAL
  175517. # define PNG_WRITE_sCAL_SUPPORTED
  175518. # ifndef PNG_sCAL_SUPPORTED
  175519. # define PNG_sCAL_SUPPORTED
  175520. # endif
  175521. #endif
  175522. #ifndef PNG_NO_WRITE_pHYs
  175523. # define PNG_WRITE_pHYs_SUPPORTED
  175524. # ifndef PNG_pHYs_SUPPORTED
  175525. # define PNG_pHYs_SUPPORTED
  175526. # endif
  175527. #endif
  175528. #ifndef PNG_NO_WRITE_sBIT
  175529. # define PNG_WRITE_sBIT_SUPPORTED
  175530. # ifndef PNG_sBIT_SUPPORTED
  175531. # define PNG_sBIT_SUPPORTED
  175532. # endif
  175533. #endif
  175534. #ifndef PNG_NO_WRITE_sPLT
  175535. # define PNG_WRITE_sPLT_SUPPORTED
  175536. # ifndef PNG_sPLT_SUPPORTED
  175537. # define PNG_sPLT_SUPPORTED
  175538. # endif
  175539. #endif
  175540. #ifndef PNG_NO_WRITE_sRGB
  175541. # define PNG_WRITE_sRGB_SUPPORTED
  175542. # ifndef PNG_sRGB_SUPPORTED
  175543. # define PNG_sRGB_SUPPORTED
  175544. # endif
  175545. #endif
  175546. #ifndef PNG_NO_WRITE_tEXt
  175547. # define PNG_WRITE_tEXt_SUPPORTED
  175548. # ifndef PNG_tEXt_SUPPORTED
  175549. # define PNG_tEXt_SUPPORTED
  175550. # endif
  175551. #endif
  175552. #ifndef PNG_NO_WRITE_tIME
  175553. # define PNG_WRITE_tIME_SUPPORTED
  175554. # ifndef PNG_tIME_SUPPORTED
  175555. # define PNG_tIME_SUPPORTED
  175556. # endif
  175557. #endif
  175558. #ifndef PNG_NO_WRITE_tRNS
  175559. # define PNG_WRITE_tRNS_SUPPORTED
  175560. # ifndef PNG_tRNS_SUPPORTED
  175561. # define PNG_tRNS_SUPPORTED
  175562. # endif
  175563. #endif
  175564. #ifndef PNG_NO_WRITE_zTXt
  175565. # define PNG_WRITE_zTXt_SUPPORTED
  175566. # ifndef PNG_zTXt_SUPPORTED
  175567. # define PNG_zTXt_SUPPORTED
  175568. # endif
  175569. #endif
  175570. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  175571. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  175572. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  175573. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  175574. # endif
  175575. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  175576. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  175577. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  175578. # endif
  175579. # endif
  175580. #endif
  175581. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  175582. defined(PNG_WRITE_zTXt_SUPPORTED)
  175583. # define PNG_WRITE_TEXT_SUPPORTED
  175584. # ifndef PNG_TEXT_SUPPORTED
  175585. # define PNG_TEXT_SUPPORTED
  175586. # endif
  175587. #endif
  175588. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  175589. /* Turn this off to disable png_read_png() and
  175590. * png_write_png() and leave the row_pointers member
  175591. * out of the info structure.
  175592. */
  175593. #ifndef PNG_NO_INFO_IMAGE
  175594. # define PNG_INFO_IMAGE_SUPPORTED
  175595. #endif
  175596. /* need the time information for reading tIME chunks */
  175597. #if defined(PNG_tIME_SUPPORTED)
  175598. # if !defined(_WIN32_WCE)
  175599. /* "time.h" functions are not supported on WindowsCE */
  175600. # include <time.h>
  175601. # endif
  175602. #endif
  175603. /* Some typedefs to get us started. These should be safe on most of the
  175604. * common platforms. The typedefs should be at least as large as the
  175605. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  175606. * don't have to be exactly that size. Some compilers dislike passing
  175607. * unsigned shorts as function parameters, so you may be better off using
  175608. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  175609. * want to have unsigned int for png_uint_32 instead of unsigned long.
  175610. */
  175611. typedef unsigned long png_uint_32;
  175612. typedef long png_int_32;
  175613. typedef unsigned short png_uint_16;
  175614. typedef short png_int_16;
  175615. typedef unsigned char png_byte;
  175616. /* This is usually size_t. It is typedef'ed just in case you need it to
  175617. change (I'm not sure if you will or not, so I thought I'd be safe) */
  175618. #ifdef PNG_SIZE_T
  175619. typedef PNG_SIZE_T png_size_t;
  175620. # define png_sizeof(x) png_convert_size(sizeof (x))
  175621. #else
  175622. typedef size_t png_size_t;
  175623. # define png_sizeof(x) sizeof (x)
  175624. #endif
  175625. /* The following is needed for medium model support. It cannot be in the
  175626. * PNG_INTERNAL section. Needs modification for other compilers besides
  175627. * MSC. Model independent support declares all arrays and pointers to be
  175628. * large using the far keyword. The zlib version used must also support
  175629. * model independent data. As of version zlib 1.0.4, the necessary changes
  175630. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  175631. * changes that are needed. (Tim Wegner)
  175632. */
  175633. /* Separate compiler dependencies (problem here is that zlib.h always
  175634. defines FAR. (SJT) */
  175635. #ifdef __BORLANDC__
  175636. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  175637. # define LDATA 1
  175638. # else
  175639. # define LDATA 0
  175640. # endif
  175641. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  175642. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  175643. # define PNG_MAX_MALLOC_64K
  175644. # if (LDATA != 1)
  175645. # ifndef FAR
  175646. # define FAR __far
  175647. # endif
  175648. # define USE_FAR_KEYWORD
  175649. # endif /* LDATA != 1 */
  175650. /* Possibly useful for moving data out of default segment.
  175651. * Uncomment it if you want. Could also define FARDATA as
  175652. * const if your compiler supports it. (SJT)
  175653. # define FARDATA FAR
  175654. */
  175655. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  175656. #endif /* __BORLANDC__ */
  175657. /* Suggest testing for specific compiler first before testing for
  175658. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  175659. * making reliance oncertain keywords suspect. (SJT)
  175660. */
  175661. /* MSC Medium model */
  175662. #if defined(FAR)
  175663. # if defined(M_I86MM)
  175664. # define USE_FAR_KEYWORD
  175665. # define FARDATA FAR
  175666. # include <dos.h>
  175667. # endif
  175668. #endif
  175669. /* SJT: default case */
  175670. #ifndef FAR
  175671. # define FAR
  175672. #endif
  175673. /* At this point FAR is always defined */
  175674. #ifndef FARDATA
  175675. # define FARDATA
  175676. #endif
  175677. /* Typedef for floating-point numbers that are converted
  175678. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  175679. typedef png_int_32 png_fixed_point;
  175680. /* Add typedefs for pointers */
  175681. typedef void FAR * png_voidp;
  175682. typedef png_byte FAR * png_bytep;
  175683. typedef png_uint_32 FAR * png_uint_32p;
  175684. typedef png_int_32 FAR * png_int_32p;
  175685. typedef png_uint_16 FAR * png_uint_16p;
  175686. typedef png_int_16 FAR * png_int_16p;
  175687. typedef PNG_CONST char FAR * png_const_charp;
  175688. typedef char FAR * png_charp;
  175689. typedef png_fixed_point FAR * png_fixed_point_p;
  175690. #ifndef PNG_NO_STDIO
  175691. #if defined(_WIN32_WCE)
  175692. typedef HANDLE png_FILE_p;
  175693. #else
  175694. typedef FILE * png_FILE_p;
  175695. #endif
  175696. #endif
  175697. #ifdef PNG_FLOATING_POINT_SUPPORTED
  175698. typedef double FAR * png_doublep;
  175699. #endif
  175700. /* Pointers to pointers; i.e. arrays */
  175701. typedef png_byte FAR * FAR * png_bytepp;
  175702. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  175703. typedef png_int_32 FAR * FAR * png_int_32pp;
  175704. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  175705. typedef png_int_16 FAR * FAR * png_int_16pp;
  175706. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  175707. typedef char FAR * FAR * png_charpp;
  175708. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  175709. #ifdef PNG_FLOATING_POINT_SUPPORTED
  175710. typedef double FAR * FAR * png_doublepp;
  175711. #endif
  175712. /* Pointers to pointers to pointers; i.e., pointer to array */
  175713. typedef char FAR * FAR * FAR * png_charppp;
  175714. #if 0
  175715. /* SPC - Is this stuff deprecated? */
  175716. /* It'll be removed as of libpng-1.3.0 - GR-P */
  175717. /* libpng typedefs for types in zlib. If zlib changes
  175718. * or another compression library is used, then change these.
  175719. * Eliminates need to change all the source files.
  175720. */
  175721. typedef charf * png_zcharp;
  175722. typedef charf * FAR * png_zcharpp;
  175723. typedef z_stream FAR * png_zstreamp;
  175724. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  175725. /*
  175726. * Define PNG_BUILD_DLL if the module being built is a Windows
  175727. * LIBPNG DLL.
  175728. *
  175729. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  175730. * It is equivalent to Microsoft predefined macro _DLL that is
  175731. * automatically defined when you compile using the share
  175732. * version of the CRT (C Run-Time library)
  175733. *
  175734. * The cygwin mods make this behavior a little different:
  175735. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  175736. * Define PNG_STATIC if you are building a static library for use with cygwin,
  175737. * -or- if you are building an application that you want to link to the
  175738. * static library.
  175739. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  175740. * the other flags is defined.
  175741. */
  175742. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  175743. # define PNG_DLL
  175744. #endif
  175745. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  175746. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  175747. * command-line override
  175748. */
  175749. #if defined(__CYGWIN__)
  175750. # if !defined(PNG_STATIC)
  175751. # if defined(PNG_USE_GLOBAL_ARRAYS)
  175752. # undef PNG_USE_GLOBAL_ARRAYS
  175753. # endif
  175754. # if !defined(PNG_USE_LOCAL_ARRAYS)
  175755. # define PNG_USE_LOCAL_ARRAYS
  175756. # endif
  175757. # else
  175758. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  175759. # if defined(PNG_USE_GLOBAL_ARRAYS)
  175760. # undef PNG_USE_GLOBAL_ARRAYS
  175761. # endif
  175762. # endif
  175763. # endif
  175764. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  175765. # define PNG_USE_LOCAL_ARRAYS
  175766. # endif
  175767. #endif
  175768. /* Do not use global arrays (helps with building DLL's)
  175769. * They are no longer used in libpng itself, since version 1.0.5c,
  175770. * but might be required for some pre-1.0.5c applications.
  175771. */
  175772. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  175773. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  175774. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  175775. # define PNG_USE_LOCAL_ARRAYS
  175776. # else
  175777. # define PNG_USE_GLOBAL_ARRAYS
  175778. # endif
  175779. #endif
  175780. #if defined(__CYGWIN__)
  175781. # undef PNGAPI
  175782. # define PNGAPI __cdecl
  175783. # undef PNG_IMPEXP
  175784. # define PNG_IMPEXP
  175785. #endif
  175786. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  175787. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  175788. * Don't ignore those warnings; you must also reset the default calling
  175789. * convention in your compiler to match your PNGAPI, and you must build
  175790. * zlib and your applications the same way you build libpng.
  175791. */
  175792. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  175793. # ifndef PNG_NO_MODULEDEF
  175794. # define PNG_NO_MODULEDEF
  175795. # endif
  175796. #endif
  175797. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  175798. # define PNG_IMPEXP
  175799. #endif
  175800. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  175801. (( defined(_Windows) || defined(_WINDOWS) || \
  175802. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  175803. # ifndef PNGAPI
  175804. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  175805. # define PNGAPI __cdecl
  175806. # else
  175807. # define PNGAPI _cdecl
  175808. # endif
  175809. # endif
  175810. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  175811. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  175812. # define PNG_IMPEXP
  175813. # endif
  175814. # if !defined(PNG_IMPEXP)
  175815. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  175816. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  175817. /* Borland/Microsoft */
  175818. # if defined(_MSC_VER) || defined(__BORLANDC__)
  175819. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  175820. # define PNG_EXPORT PNG_EXPORT_TYPE1
  175821. # else
  175822. # define PNG_EXPORT PNG_EXPORT_TYPE2
  175823. # if defined(PNG_BUILD_DLL)
  175824. # define PNG_IMPEXP __export
  175825. # else
  175826. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  175827. VC++ */
  175828. # endif /* Exists in Borland C++ for
  175829. C++ classes (== huge) */
  175830. # endif
  175831. # endif
  175832. # if !defined(PNG_IMPEXP)
  175833. # if defined(PNG_BUILD_DLL)
  175834. # define PNG_IMPEXP __declspec(dllexport)
  175835. # else
  175836. # define PNG_IMPEXP __declspec(dllimport)
  175837. # endif
  175838. # endif
  175839. # endif /* PNG_IMPEXP */
  175840. #else /* !(DLL || non-cygwin WINDOWS) */
  175841. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  175842. # ifndef PNGAPI
  175843. # define PNGAPI _System
  175844. # endif
  175845. # else
  175846. # if 0 /* ... other platforms, with other meanings */
  175847. # endif
  175848. # endif
  175849. #endif
  175850. #ifndef PNGAPI
  175851. # define PNGAPI
  175852. #endif
  175853. #ifndef PNG_IMPEXP
  175854. # define PNG_IMPEXP
  175855. #endif
  175856. #ifdef PNG_BUILDSYMS
  175857. # ifndef PNG_EXPORT
  175858. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  175859. # endif
  175860. # ifdef PNG_USE_GLOBAL_ARRAYS
  175861. # ifndef PNG_EXPORT_VAR
  175862. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  175863. # endif
  175864. # endif
  175865. #endif
  175866. #ifndef PNG_EXPORT
  175867. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  175868. #endif
  175869. #ifdef PNG_USE_GLOBAL_ARRAYS
  175870. # ifndef PNG_EXPORT_VAR
  175871. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  175872. # endif
  175873. #endif
  175874. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  175875. * functions that are passed far data must be model independent.
  175876. */
  175877. #ifndef PNG_ABORT
  175878. # define PNG_ABORT() abort()
  175879. #endif
  175880. #ifdef PNG_SETJMP_SUPPORTED
  175881. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  175882. #else
  175883. # define png_jmpbuf(png_ptr) \
  175884. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  175885. #endif
  175886. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  175887. /* use this to make far-to-near assignments */
  175888. # define CHECK 1
  175889. # define NOCHECK 0
  175890. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  175891. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  175892. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  175893. # define png_strcpy _fstrcpy
  175894. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  175895. # define png_strlen _fstrlen
  175896. # define png_memcmp _fmemcmp /* SJT: added */
  175897. # define png_memcpy _fmemcpy
  175898. # define png_memset _fmemset
  175899. #else /* use the usual functions */
  175900. # define CVT_PTR(ptr) (ptr)
  175901. # define CVT_PTR_NOCHECK(ptr) (ptr)
  175902. # ifndef PNG_NO_SNPRINTF
  175903. # ifdef _MSC_VER
  175904. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  175905. # define png_snprintf2 _snprintf
  175906. # define png_snprintf6 _snprintf
  175907. # else
  175908. # define png_snprintf snprintf /* Added to v 1.2.19 */
  175909. # define png_snprintf2 snprintf
  175910. # define png_snprintf6 snprintf
  175911. # endif
  175912. # else
  175913. /* You don't have or don't want to use snprintf(). Caution: Using
  175914. * sprintf instead of snprintf exposes your application to accidental
  175915. * or malevolent buffer overflows. If you don't have snprintf()
  175916. * as a general rule you should provide one (you can get one from
  175917. * Portable OpenSSH). */
  175918. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  175919. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  175920. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  175921. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  175922. # endif
  175923. # define png_strcpy strcpy
  175924. # define png_strncpy strncpy /* Added to v 1.2.6 */
  175925. # define png_strlen strlen
  175926. # define png_memcmp memcmp /* SJT: added */
  175927. # define png_memcpy memcpy
  175928. # define png_memset memset
  175929. #endif
  175930. /* End of memory model independent support */
  175931. /* Just a little check that someone hasn't tried to define something
  175932. * contradictory.
  175933. */
  175934. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  175935. # undef PNG_ZBUF_SIZE
  175936. # define PNG_ZBUF_SIZE 65536L
  175937. #endif
  175938. /* Added at libpng-1.2.8 */
  175939. #endif /* PNG_VERSION_INFO_ONLY */
  175940. #endif /* PNGCONF_H */
  175941. /********* End of inlined file: pngconf.h *********/
  175942. #ifdef _MSC_VER
  175943. #pragma warning (disable: 4996 4100)
  175944. #endif
  175945. /*
  175946. * Added at libpng-1.2.8 */
  175947. /* Ref MSDN: Private as priority over Special
  175948. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  175949. * procedures. If this value is given, the StringFileInfo block must
  175950. * contain a PrivateBuild string.
  175951. *
  175952. * VS_FF_SPECIALBUILD File *was* built by the original company using
  175953. * standard release procedures but is a variation of the standard
  175954. * file of the same version number. If this value is given, the
  175955. * StringFileInfo block must contain a SpecialBuild string.
  175956. */
  175957. #if defined(PNG_USER_PRIVATEBUILD)
  175958. # define PNG_LIBPNG_BUILD_TYPE \
  175959. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  175960. #else
  175961. # if defined(PNG_LIBPNG_SPECIALBUILD)
  175962. # define PNG_LIBPNG_BUILD_TYPE \
  175963. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  175964. # else
  175965. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  175966. # endif
  175967. #endif
  175968. #ifndef PNG_VERSION_INFO_ONLY
  175969. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  175970. #ifdef __cplusplus
  175971. extern "C" {
  175972. #endif /* __cplusplus */
  175973. /* This file is arranged in several sections. The first section contains
  175974. * structure and type definitions. The second section contains the external
  175975. * library functions, while the third has the internal library functions,
  175976. * which applications aren't expected to use directly.
  175977. */
  175978. #ifndef PNG_NO_TYPECAST_NULL
  175979. #define int_p_NULL (int *)NULL
  175980. #define png_bytep_NULL (png_bytep)NULL
  175981. #define png_bytepp_NULL (png_bytepp)NULL
  175982. #define png_doublep_NULL (png_doublep)NULL
  175983. #define png_error_ptr_NULL (png_error_ptr)NULL
  175984. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  175985. #define png_free_ptr_NULL (png_free_ptr)NULL
  175986. #define png_infopp_NULL (png_infopp)NULL
  175987. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  175988. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  175989. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  175990. #define png_structp_NULL (png_structp)NULL
  175991. #define png_uint_16p_NULL (png_uint_16p)NULL
  175992. #define png_voidp_NULL (png_voidp)NULL
  175993. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  175994. #else
  175995. #define int_p_NULL NULL
  175996. #define png_bytep_NULL NULL
  175997. #define png_bytepp_NULL NULL
  175998. #define png_doublep_NULL NULL
  175999. #define png_error_ptr_NULL NULL
  176000. #define png_flush_ptr_NULL NULL
  176001. #define png_free_ptr_NULL NULL
  176002. #define png_infopp_NULL NULL
  176003. #define png_malloc_ptr_NULL NULL
  176004. #define png_read_status_ptr_NULL NULL
  176005. #define png_rw_ptr_NULL NULL
  176006. #define png_structp_NULL NULL
  176007. #define png_uint_16p_NULL NULL
  176008. #define png_voidp_NULL NULL
  176009. #define png_write_status_ptr_NULL NULL
  176010. #endif
  176011. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  176012. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  176013. /* Version information for C files, stored in png.c. This had better match
  176014. * the version above.
  176015. */
  176016. #ifdef PNG_USE_GLOBAL_ARRAYS
  176017. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  176018. /* need room for 99.99.99beta99z */
  176019. #else
  176020. #define png_libpng_ver png_get_header_ver(NULL)
  176021. #endif
  176022. #ifdef PNG_USE_GLOBAL_ARRAYS
  176023. /* This was removed in version 1.0.5c */
  176024. /* Structures to facilitate easy interlacing. See png.c for more details */
  176025. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  176026. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  176027. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  176028. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  176029. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  176030. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  176031. /* This isn't currently used. If you need it, see png.c for more details.
  176032. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  176033. */
  176034. #endif
  176035. #endif /* PNG_NO_EXTERN */
  176036. /* Three color definitions. The order of the red, green, and blue, (and the
  176037. * exact size) is not important, although the size of the fields need to
  176038. * be png_byte or png_uint_16 (as defined below).
  176039. */
  176040. typedef struct png_color_struct
  176041. {
  176042. png_byte red;
  176043. png_byte green;
  176044. png_byte blue;
  176045. } png_color;
  176046. typedef png_color FAR * png_colorp;
  176047. typedef png_color FAR * FAR * png_colorpp;
  176048. typedef struct png_color_16_struct
  176049. {
  176050. png_byte index; /* used for palette files */
  176051. png_uint_16 red; /* for use in red green blue files */
  176052. png_uint_16 green;
  176053. png_uint_16 blue;
  176054. png_uint_16 gray; /* for use in grayscale files */
  176055. } png_color_16;
  176056. typedef png_color_16 FAR * png_color_16p;
  176057. typedef png_color_16 FAR * FAR * png_color_16pp;
  176058. typedef struct png_color_8_struct
  176059. {
  176060. png_byte red; /* for use in red green blue files */
  176061. png_byte green;
  176062. png_byte blue;
  176063. png_byte gray; /* for use in grayscale files */
  176064. png_byte alpha; /* for alpha channel files */
  176065. } png_color_8;
  176066. typedef png_color_8 FAR * png_color_8p;
  176067. typedef png_color_8 FAR * FAR * png_color_8pp;
  176068. /*
  176069. * The following two structures are used for the in-core representation
  176070. * of sPLT chunks.
  176071. */
  176072. typedef struct png_sPLT_entry_struct
  176073. {
  176074. png_uint_16 red;
  176075. png_uint_16 green;
  176076. png_uint_16 blue;
  176077. png_uint_16 alpha;
  176078. png_uint_16 frequency;
  176079. } png_sPLT_entry;
  176080. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  176081. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  176082. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  176083. * occupy the LSB of their respective members, and the MSB of each member
  176084. * is zero-filled. The frequency member always occupies the full 16 bits.
  176085. */
  176086. typedef struct png_sPLT_struct
  176087. {
  176088. png_charp name; /* palette name */
  176089. png_byte depth; /* depth of palette samples */
  176090. png_sPLT_entryp entries; /* palette entries */
  176091. png_int_32 nentries; /* number of palette entries */
  176092. } png_sPLT_t;
  176093. typedef png_sPLT_t FAR * png_sPLT_tp;
  176094. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  176095. #ifdef PNG_TEXT_SUPPORTED
  176096. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  176097. * and whether that contents is compressed or not. The "key" field
  176098. * points to a regular zero-terminated C string. The "text", "lang", and
  176099. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  176100. * However, the * structure returned by png_get_text() will always contain
  176101. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  176102. * so they can be safely used in printf() and other string-handling functions.
  176103. */
  176104. typedef struct png_text_struct
  176105. {
  176106. int compression; /* compression value:
  176107. -1: tEXt, none
  176108. 0: zTXt, deflate
  176109. 1: iTXt, none
  176110. 2: iTXt, deflate */
  176111. png_charp key; /* keyword, 1-79 character description of "text" */
  176112. png_charp text; /* comment, may be an empty string (ie "")
  176113. or a NULL pointer */
  176114. png_size_t text_length; /* length of the text string */
  176115. #ifdef PNG_iTXt_SUPPORTED
  176116. png_size_t itxt_length; /* length of the itxt string */
  176117. png_charp lang; /* language code, 0-79 characters
  176118. or a NULL pointer */
  176119. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  176120. chars or a NULL pointer */
  176121. #endif
  176122. } png_text;
  176123. typedef png_text FAR * png_textp;
  176124. typedef png_text FAR * FAR * png_textpp;
  176125. #endif
  176126. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  176127. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  176128. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  176129. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  176130. #define PNG_TEXT_COMPRESSION_NONE -1
  176131. #define PNG_TEXT_COMPRESSION_zTXt 0
  176132. #define PNG_ITXT_COMPRESSION_NONE 1
  176133. #define PNG_ITXT_COMPRESSION_zTXt 2
  176134. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  176135. /* png_time is a way to hold the time in an machine independent way.
  176136. * Two conversions are provided, both from time_t and struct tm. There
  176137. * is no portable way to convert to either of these structures, as far
  176138. * as I know. If you know of a portable way, send it to me. As a side
  176139. * note - PNG has always been Year 2000 compliant!
  176140. */
  176141. typedef struct png_time_struct
  176142. {
  176143. png_uint_16 year; /* full year, as in, 1995 */
  176144. png_byte month; /* month of year, 1 - 12 */
  176145. png_byte day; /* day of month, 1 - 31 */
  176146. png_byte hour; /* hour of day, 0 - 23 */
  176147. png_byte minute; /* minute of hour, 0 - 59 */
  176148. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  176149. } png_time;
  176150. typedef png_time FAR * png_timep;
  176151. typedef png_time FAR * FAR * png_timepp;
  176152. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176153. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  176154. * no specific support. The idea is that we can use this to queue
  176155. * up private chunks for output even though the library doesn't actually
  176156. * know about their semantics.
  176157. */
  176158. typedef struct png_unknown_chunk_t
  176159. {
  176160. png_byte name[5];
  176161. png_byte *data;
  176162. png_size_t size;
  176163. /* libpng-using applications should NOT directly modify this byte. */
  176164. png_byte location; /* mode of operation at read time */
  176165. }
  176166. png_unknown_chunk;
  176167. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  176168. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  176169. #endif
  176170. /* png_info is a structure that holds the information in a PNG file so
  176171. * that the application can find out the characteristics of the image.
  176172. * If you are reading the file, this structure will tell you what is
  176173. * in the PNG file. If you are writing the file, fill in the information
  176174. * you want to put into the PNG file, then call png_write_info().
  176175. * The names chosen should be very close to the PNG specification, so
  176176. * consult that document for information about the meaning of each field.
  176177. *
  176178. * With libpng < 0.95, it was only possible to directly set and read the
  176179. * the values in the png_info_struct, which meant that the contents and
  176180. * order of the values had to remain fixed. With libpng 0.95 and later,
  176181. * however, there are now functions that abstract the contents of
  176182. * png_info_struct from the application, so this makes it easier to use
  176183. * libpng with dynamic libraries, and even makes it possible to use
  176184. * libraries that don't have all of the libpng ancillary chunk-handing
  176185. * functionality.
  176186. *
  176187. * In any case, the order of the parameters in png_info_struct should NOT
  176188. * be changed for as long as possible to keep compatibility with applications
  176189. * that use the old direct-access method with png_info_struct.
  176190. *
  176191. * The following members may have allocated storage attached that should be
  176192. * cleaned up before the structure is discarded: palette, trans, text,
  176193. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  176194. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  176195. * are automatically freed when the info structure is deallocated, if they were
  176196. * allocated internally by libpng. This behavior can be changed by means
  176197. * of the png_data_freer() function.
  176198. *
  176199. * More allocation details: all the chunk-reading functions that
  176200. * change these members go through the corresponding png_set_*
  176201. * functions. A function to clear these members is available: see
  176202. * png_free_data(). The png_set_* functions do not depend on being
  176203. * able to point info structure members to any of the storage they are
  176204. * passed (they make their own copies), EXCEPT that the png_set_text
  176205. * functions use the same storage passed to them in the text_ptr or
  176206. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  176207. * functions do not make their own copies.
  176208. */
  176209. typedef struct png_info_struct
  176210. {
  176211. /* the following are necessary for every PNG file */
  176212. png_uint_32 width; /* width of image in pixels (from IHDR) */
  176213. png_uint_32 height; /* height of image in pixels (from IHDR) */
  176214. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  176215. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  176216. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  176217. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  176218. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  176219. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  176220. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  176221. /* The following three should have been named *_method not *_type */
  176222. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  176223. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  176224. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  176225. /* The following is informational only on read, and not used on writes. */
  176226. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  176227. png_byte pixel_depth; /* number of bits per pixel */
  176228. png_byte spare_byte; /* to align the data, and for future use */
  176229. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  176230. /* The rest of the data is optional. If you are reading, check the
  176231. * valid field to see if the information in these are valid. If you
  176232. * are writing, set the valid field to those chunks you want written,
  176233. * and initialize the appropriate fields below.
  176234. */
  176235. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  176236. /* The gAMA chunk describes the gamma characteristics of the system
  176237. * on which the image was created, normally in the range [1.0, 2.5].
  176238. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  176239. */
  176240. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  176241. #endif
  176242. #if defined(PNG_sRGB_SUPPORTED)
  176243. /* GR-P, 0.96a */
  176244. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  176245. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  176246. #endif
  176247. #if defined(PNG_TEXT_SUPPORTED)
  176248. /* The tEXt, and zTXt chunks contain human-readable textual data in
  176249. * uncompressed, compressed, and optionally compressed forms, respectively.
  176250. * The data in "text" is an array of pointers to uncompressed,
  176251. * null-terminated C strings. Each chunk has a keyword that describes the
  176252. * textual data contained in that chunk. Keywords are not required to be
  176253. * unique, and the text string may be empty. Any number of text chunks may
  176254. * be in an image.
  176255. */
  176256. int num_text; /* number of comments read/to write */
  176257. int max_text; /* current size of text array */
  176258. png_textp text; /* array of comments read/to write */
  176259. #endif /* PNG_TEXT_SUPPORTED */
  176260. #if defined(PNG_tIME_SUPPORTED)
  176261. /* The tIME chunk holds the last time the displayed image data was
  176262. * modified. See the png_time struct for the contents of this struct.
  176263. */
  176264. png_time mod_time;
  176265. #endif
  176266. #if defined(PNG_sBIT_SUPPORTED)
  176267. /* The sBIT chunk specifies the number of significant high-order bits
  176268. * in the pixel data. Values are in the range [1, bit_depth], and are
  176269. * only specified for the channels in the pixel data. The contents of
  176270. * the low-order bits is not specified. Data is valid if
  176271. * (valid & PNG_INFO_sBIT) is non-zero.
  176272. */
  176273. png_color_8 sig_bit; /* significant bits in color channels */
  176274. #endif
  176275. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  176276. defined(PNG_READ_BACKGROUND_SUPPORTED)
  176277. /* The tRNS chunk supplies transparency data for paletted images and
  176278. * other image types that don't need a full alpha channel. There are
  176279. * "num_trans" transparency values for a paletted image, stored in the
  176280. * same order as the palette colors, starting from index 0. Values
  176281. * for the data are in the range [0, 255], ranging from fully transparent
  176282. * to fully opaque, respectively. For non-paletted images, there is a
  176283. * single color specified that should be treated as fully transparent.
  176284. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  176285. */
  176286. png_bytep trans; /* transparent values for paletted image */
  176287. png_color_16 trans_values; /* transparent color for non-palette image */
  176288. #endif
  176289. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  176290. /* The bKGD chunk gives the suggested image background color if the
  176291. * display program does not have its own background color and the image
  176292. * is needs to composited onto a background before display. The colors
  176293. * in "background" are normally in the same color space/depth as the
  176294. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  176295. */
  176296. png_color_16 background;
  176297. #endif
  176298. #if defined(PNG_oFFs_SUPPORTED)
  176299. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  176300. * and downwards from the top-left corner of the display, page, or other
  176301. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  176302. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  176303. */
  176304. png_int_32 x_offset; /* x offset on page */
  176305. png_int_32 y_offset; /* y offset on page */
  176306. png_byte offset_unit_type; /* offset units type */
  176307. #endif
  176308. #if defined(PNG_pHYs_SUPPORTED)
  176309. /* The pHYs chunk gives the physical pixel density of the image for
  176310. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  176311. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  176312. */
  176313. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  176314. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  176315. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  176316. #endif
  176317. #if defined(PNG_hIST_SUPPORTED)
  176318. /* The hIST chunk contains the relative frequency or importance of the
  176319. * various palette entries, so that a viewer can intelligently select a
  176320. * reduced-color palette, if required. Data is an array of "num_palette"
  176321. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  176322. * is non-zero.
  176323. */
  176324. png_uint_16p hist;
  176325. #endif
  176326. #ifdef PNG_cHRM_SUPPORTED
  176327. /* The cHRM chunk describes the CIE color characteristics of the monitor
  176328. * on which the PNG was created. This data allows the viewer to do gamut
  176329. * mapping of the input image to ensure that the viewer sees the same
  176330. * colors in the image as the creator. Values are in the range
  176331. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  176332. */
  176333. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176334. float x_white;
  176335. float y_white;
  176336. float x_red;
  176337. float y_red;
  176338. float x_green;
  176339. float y_green;
  176340. float x_blue;
  176341. float y_blue;
  176342. #endif
  176343. #endif
  176344. #if defined(PNG_pCAL_SUPPORTED)
  176345. /* The pCAL chunk describes a transformation between the stored pixel
  176346. * values and original physical data values used to create the image.
  176347. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  176348. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  176349. * (possibly non-linear) transformation function given by "pcal_type"
  176350. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  176351. * defines below, and the PNG-Group's PNG extensions document for a
  176352. * complete description of the transformations and how they should be
  176353. * implemented, and for a description of the ASCII parameter strings.
  176354. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  176355. */
  176356. png_charp pcal_purpose; /* pCAL chunk description string */
  176357. png_int_32 pcal_X0; /* minimum value */
  176358. png_int_32 pcal_X1; /* maximum value */
  176359. png_charp pcal_units; /* Latin-1 string giving physical units */
  176360. png_charpp pcal_params; /* ASCII strings containing parameter values */
  176361. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  176362. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  176363. #endif
  176364. /* New members added in libpng-1.0.6 */
  176365. #ifdef PNG_FREE_ME_SUPPORTED
  176366. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  176367. #endif
  176368. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176369. /* storage for unknown chunks that the library doesn't recognize. */
  176370. png_unknown_chunkp unknown_chunks;
  176371. png_size_t unknown_chunks_num;
  176372. #endif
  176373. #if defined(PNG_iCCP_SUPPORTED)
  176374. /* iCCP chunk data. */
  176375. png_charp iccp_name; /* profile name */
  176376. png_charp iccp_profile; /* International Color Consortium profile data */
  176377. /* Note to maintainer: should be png_bytep */
  176378. png_uint_32 iccp_proflen; /* ICC profile data length */
  176379. png_byte iccp_compression; /* Always zero */
  176380. #endif
  176381. #if defined(PNG_sPLT_SUPPORTED)
  176382. /* data on sPLT chunks (there may be more than one). */
  176383. png_sPLT_tp splt_palettes;
  176384. png_uint_32 splt_palettes_num;
  176385. #endif
  176386. #if defined(PNG_sCAL_SUPPORTED)
  176387. /* The sCAL chunk describes the actual physical dimensions of the
  176388. * subject matter of the graphic. The chunk contains a unit specification
  176389. * a byte value, and two ASCII strings representing floating-point
  176390. * values. The values are width and height corresponsing to one pixel
  176391. * in the image. This external representation is converted to double
  176392. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  176393. */
  176394. png_byte scal_unit; /* unit of physical scale */
  176395. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176396. double scal_pixel_width; /* width of one pixel */
  176397. double scal_pixel_height; /* height of one pixel */
  176398. #endif
  176399. #ifdef PNG_FIXED_POINT_SUPPORTED
  176400. png_charp scal_s_width; /* string containing height */
  176401. png_charp scal_s_height; /* string containing width */
  176402. #endif
  176403. #endif
  176404. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  176405. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  176406. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  176407. png_bytepp row_pointers; /* the image bits */
  176408. #endif
  176409. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  176410. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  176411. #endif
  176412. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  176413. png_fixed_point int_x_white;
  176414. png_fixed_point int_y_white;
  176415. png_fixed_point int_x_red;
  176416. png_fixed_point int_y_red;
  176417. png_fixed_point int_x_green;
  176418. png_fixed_point int_y_green;
  176419. png_fixed_point int_x_blue;
  176420. png_fixed_point int_y_blue;
  176421. #endif
  176422. } png_info;
  176423. typedef png_info FAR * png_infop;
  176424. typedef png_info FAR * FAR * png_infopp;
  176425. /* Maximum positive integer used in PNG is (2^31)-1 */
  176426. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  176427. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  176428. #define PNG_SIZE_MAX ((png_size_t)(-1))
  176429. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176430. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  176431. #define PNG_MAX_UINT PNG_UINT_31_MAX
  176432. #endif
  176433. /* These describe the color_type field in png_info. */
  176434. /* color type masks */
  176435. #define PNG_COLOR_MASK_PALETTE 1
  176436. #define PNG_COLOR_MASK_COLOR 2
  176437. #define PNG_COLOR_MASK_ALPHA 4
  176438. /* color types. Note that not all combinations are legal */
  176439. #define PNG_COLOR_TYPE_GRAY 0
  176440. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  176441. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  176442. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  176443. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  176444. /* aliases */
  176445. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  176446. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  176447. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  176448. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  176449. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  176450. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  176451. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  176452. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  176453. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  176454. /* These are for the interlacing type. These values should NOT be changed. */
  176455. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  176456. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  176457. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  176458. /* These are for the oFFs chunk. These values should NOT be changed. */
  176459. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  176460. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  176461. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  176462. /* These are for the pCAL chunk. These values should NOT be changed. */
  176463. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  176464. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  176465. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  176466. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  176467. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  176468. /* These are for the sCAL chunk. These values should NOT be changed. */
  176469. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  176470. #define PNG_SCALE_METER 1 /* meters per pixel */
  176471. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  176472. #define PNG_SCALE_LAST 3 /* Not a valid value */
  176473. /* These are for the pHYs chunk. These values should NOT be changed. */
  176474. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  176475. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  176476. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  176477. /* These are for the sRGB chunk. These values should NOT be changed. */
  176478. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  176479. #define PNG_sRGB_INTENT_RELATIVE 1
  176480. #define PNG_sRGB_INTENT_SATURATION 2
  176481. #define PNG_sRGB_INTENT_ABSOLUTE 3
  176482. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  176483. /* This is for text chunks */
  176484. #define PNG_KEYWORD_MAX_LENGTH 79
  176485. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  176486. #define PNG_MAX_PALETTE_LENGTH 256
  176487. /* These determine if an ancillary chunk's data has been successfully read
  176488. * from the PNG header, or if the application has filled in the corresponding
  176489. * data in the info_struct to be written into the output file. The values
  176490. * of the PNG_INFO_<chunk> defines should NOT be changed.
  176491. */
  176492. #define PNG_INFO_gAMA 0x0001
  176493. #define PNG_INFO_sBIT 0x0002
  176494. #define PNG_INFO_cHRM 0x0004
  176495. #define PNG_INFO_PLTE 0x0008
  176496. #define PNG_INFO_tRNS 0x0010
  176497. #define PNG_INFO_bKGD 0x0020
  176498. #define PNG_INFO_hIST 0x0040
  176499. #define PNG_INFO_pHYs 0x0080
  176500. #define PNG_INFO_oFFs 0x0100
  176501. #define PNG_INFO_tIME 0x0200
  176502. #define PNG_INFO_pCAL 0x0400
  176503. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  176504. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  176505. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  176506. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  176507. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  176508. /* This is used for the transformation routines, as some of them
  176509. * change these values for the row. It also should enable using
  176510. * the routines for other purposes.
  176511. */
  176512. typedef struct png_row_info_struct
  176513. {
  176514. png_uint_32 width; /* width of row */
  176515. png_uint_32 rowbytes; /* number of bytes in row */
  176516. png_byte color_type; /* color type of row */
  176517. png_byte bit_depth; /* bit depth of row */
  176518. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  176519. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  176520. } png_row_info;
  176521. typedef png_row_info FAR * png_row_infop;
  176522. typedef png_row_info FAR * FAR * png_row_infopp;
  176523. /* These are the function types for the I/O functions and for the functions
  176524. * that allow the user to override the default I/O functions with his or her
  176525. * own. The png_error_ptr type should match that of user-supplied warning
  176526. * and error functions, while the png_rw_ptr type should match that of the
  176527. * user read/write data functions.
  176528. */
  176529. typedef struct png_struct_def png_struct;
  176530. typedef png_struct FAR * png_structp;
  176531. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  176532. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  176533. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  176534. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  176535. int));
  176536. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  176537. int));
  176538. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  176539. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  176540. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  176541. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  176542. png_uint_32, int));
  176543. #endif
  176544. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  176545. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  176546. defined(PNG_LEGACY_SUPPORTED)
  176547. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  176548. png_row_infop, png_bytep));
  176549. #endif
  176550. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  176551. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  176552. #endif
  176553. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176554. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  176555. #endif
  176556. /* Transform masks for the high-level interface */
  176557. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  176558. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  176559. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  176560. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  176561. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  176562. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  176563. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  176564. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  176565. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  176566. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  176567. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  176568. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  176569. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  176570. /* Flags for MNG supported features */
  176571. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  176572. #define PNG_FLAG_MNG_FILTER_64 0x04
  176573. #define PNG_ALL_MNG_FEATURES 0x05
  176574. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  176575. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  176576. /* The structure that holds the information to read and write PNG files.
  176577. * The only people who need to care about what is inside of this are the
  176578. * people who will be modifying the library for their own special needs.
  176579. * It should NOT be accessed directly by an application, except to store
  176580. * the jmp_buf.
  176581. */
  176582. struct png_struct_def
  176583. {
  176584. #ifdef PNG_SETJMP_SUPPORTED
  176585. jmp_buf jmpbuf; /* used in png_error */
  176586. #endif
  176587. png_error_ptr error_fn; /* function for printing errors and aborting */
  176588. png_error_ptr warning_fn; /* function for printing warnings */
  176589. png_voidp error_ptr; /* user supplied struct for error functions */
  176590. png_rw_ptr write_data_fn; /* function for writing output data */
  176591. png_rw_ptr read_data_fn; /* function for reading input data */
  176592. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  176593. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  176594. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  176595. #endif
  176596. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  176597. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  176598. #endif
  176599. /* These were added in libpng-1.0.2 */
  176600. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  176601. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  176602. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  176603. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  176604. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  176605. png_byte user_transform_channels; /* channels in user transformed pixels */
  176606. #endif
  176607. #endif
  176608. png_uint_32 mode; /* tells us where we are in the PNG file */
  176609. png_uint_32 flags; /* flags indicating various things to libpng */
  176610. png_uint_32 transformations; /* which transformations to perform */
  176611. z_stream zstream; /* pointer to decompression structure (below) */
  176612. png_bytep zbuf; /* buffer for zlib */
  176613. png_size_t zbuf_size; /* size of zbuf */
  176614. int zlib_level; /* holds zlib compression level */
  176615. int zlib_method; /* holds zlib compression method */
  176616. int zlib_window_bits; /* holds zlib compression window bits */
  176617. int zlib_mem_level; /* holds zlib compression memory level */
  176618. int zlib_strategy; /* holds zlib compression strategy */
  176619. png_uint_32 width; /* width of image in pixels */
  176620. png_uint_32 height; /* height of image in pixels */
  176621. png_uint_32 num_rows; /* number of rows in current pass */
  176622. png_uint_32 usr_width; /* width of row at start of write */
  176623. png_uint_32 rowbytes; /* size of row in bytes */
  176624. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  176625. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  176626. png_uint_32 row_number; /* current row in interlace pass */
  176627. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  176628. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  176629. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  176630. png_bytep up_row; /* buffer to save "up" row when filtering */
  176631. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  176632. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  176633. png_row_info row_info; /* used for transformation routines */
  176634. png_uint_32 idat_size; /* current IDAT size for read */
  176635. png_uint_32 crc; /* current chunk CRC value */
  176636. png_colorp palette; /* palette from the input file */
  176637. png_uint_16 num_palette; /* number of color entries in palette */
  176638. png_uint_16 num_trans; /* number of transparency values */
  176639. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  176640. png_byte compression; /* file compression type (always 0) */
  176641. png_byte filter; /* file filter type (always 0) */
  176642. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  176643. png_byte pass; /* current interlace pass (0 - 6) */
  176644. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  176645. png_byte color_type; /* color type of file */
  176646. png_byte bit_depth; /* bit depth of file */
  176647. png_byte usr_bit_depth; /* bit depth of users row */
  176648. png_byte pixel_depth; /* number of bits per pixel */
  176649. png_byte channels; /* number of channels in file */
  176650. png_byte usr_channels; /* channels at start of write */
  176651. png_byte sig_bytes; /* magic bytes read/written from start of file */
  176652. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  176653. #ifdef PNG_LEGACY_SUPPORTED
  176654. png_byte filler; /* filler byte for pixel expansion */
  176655. #else
  176656. png_uint_16 filler; /* filler bytes for pixel expansion */
  176657. #endif
  176658. #endif
  176659. #if defined(PNG_bKGD_SUPPORTED)
  176660. png_byte background_gamma_type;
  176661. # ifdef PNG_FLOATING_POINT_SUPPORTED
  176662. float background_gamma;
  176663. # endif
  176664. png_color_16 background; /* background color in screen gamma space */
  176665. #if defined(PNG_READ_GAMMA_SUPPORTED)
  176666. png_color_16 background_1; /* background normalized to gamma 1.0 */
  176667. #endif
  176668. #endif /* PNG_bKGD_SUPPORTED */
  176669. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  176670. png_flush_ptr output_flush_fn;/* Function for flushing output */
  176671. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  176672. png_uint_32 flush_rows; /* number of rows written since last flush */
  176673. #endif
  176674. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  176675. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  176676. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176677. float gamma; /* file gamma value */
  176678. float screen_gamma; /* screen gamma value (display_exponent) */
  176679. #endif
  176680. #endif
  176681. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  176682. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  176683. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  176684. png_bytep gamma_to_1; /* converts from file to 1.0 */
  176685. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  176686. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  176687. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  176688. #endif
  176689. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  176690. png_color_8 sig_bit; /* significant bits in each available channel */
  176691. #endif
  176692. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  176693. png_color_8 shift; /* shift for significant bit tranformation */
  176694. #endif
  176695. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  176696. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  176697. png_bytep trans; /* transparency values for paletted files */
  176698. png_color_16 trans_values; /* transparency values for non-paletted files */
  176699. #endif
  176700. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  176701. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  176702. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  176703. png_progressive_info_ptr info_fn; /* called after header data fully read */
  176704. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  176705. png_progressive_end_ptr end_fn; /* called after image is complete */
  176706. png_bytep save_buffer_ptr; /* current location in save_buffer */
  176707. png_bytep save_buffer; /* buffer for previously read data */
  176708. png_bytep current_buffer_ptr; /* current location in current_buffer */
  176709. png_bytep current_buffer; /* buffer for recently used data */
  176710. png_uint_32 push_length; /* size of current input chunk */
  176711. png_uint_32 skip_length; /* bytes to skip in input data */
  176712. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  176713. png_size_t save_buffer_max; /* total size of save_buffer */
  176714. png_size_t buffer_size; /* total amount of available input data */
  176715. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  176716. int process_mode; /* what push library is currently doing */
  176717. int cur_palette; /* current push library palette index */
  176718. # if defined(PNG_TEXT_SUPPORTED)
  176719. png_size_t current_text_size; /* current size of text input data */
  176720. png_size_t current_text_left; /* how much text left to read in input */
  176721. png_charp current_text; /* current text chunk buffer */
  176722. png_charp current_text_ptr; /* current location in current_text */
  176723. # endif /* PNG_TEXT_SUPPORTED */
  176724. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  176725. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  176726. /* for the Borland special 64K segment handler */
  176727. png_bytepp offset_table_ptr;
  176728. png_bytep offset_table;
  176729. png_uint_16 offset_table_number;
  176730. png_uint_16 offset_table_count;
  176731. png_uint_16 offset_table_count_free;
  176732. #endif
  176733. #if defined(PNG_READ_DITHER_SUPPORTED)
  176734. png_bytep palette_lookup; /* lookup table for dithering */
  176735. png_bytep dither_index; /* index translation for palette files */
  176736. #endif
  176737. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  176738. png_uint_16p hist; /* histogram */
  176739. #endif
  176740. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  176741. png_byte heuristic_method; /* heuristic for row filter selection */
  176742. png_byte num_prev_filters; /* number of weights for previous rows */
  176743. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  176744. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  176745. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  176746. png_uint_16p filter_costs; /* relative filter calculation cost */
  176747. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  176748. #endif
  176749. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  176750. png_charp time_buffer; /* String to hold RFC 1123 time text */
  176751. #endif
  176752. /* New members added in libpng-1.0.6 */
  176753. #ifdef PNG_FREE_ME_SUPPORTED
  176754. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  176755. #endif
  176756. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  176757. png_voidp user_chunk_ptr;
  176758. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  176759. #endif
  176760. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176761. int num_chunk_list;
  176762. png_bytep chunk_list;
  176763. #endif
  176764. /* New members added in libpng-1.0.3 */
  176765. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  176766. png_byte rgb_to_gray_status;
  176767. /* These were changed from png_byte in libpng-1.0.6 */
  176768. png_uint_16 rgb_to_gray_red_coeff;
  176769. png_uint_16 rgb_to_gray_green_coeff;
  176770. png_uint_16 rgb_to_gray_blue_coeff;
  176771. #endif
  176772. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  176773. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  176774. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  176775. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  176776. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  176777. #ifdef PNG_1_0_X
  176778. png_byte mng_features_permitted;
  176779. #else
  176780. png_uint_32 mng_features_permitted;
  176781. #endif /* PNG_1_0_X */
  176782. #endif
  176783. /* New member added in libpng-1.0.7 */
  176784. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  176785. png_fixed_point int_gamma;
  176786. #endif
  176787. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  176788. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  176789. png_byte filter_type;
  176790. #endif
  176791. #if defined(PNG_1_0_X)
  176792. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  176793. png_uint_32 row_buf_size;
  176794. #endif
  176795. /* New members added in libpng-1.2.0 */
  176796. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  176797. # if !defined(PNG_1_0_X)
  176798. # if defined(PNG_MMX_CODE_SUPPORTED)
  176799. png_byte mmx_bitdepth_threshold;
  176800. png_uint_32 mmx_rowbytes_threshold;
  176801. # endif
  176802. png_uint_32 asm_flags;
  176803. # endif
  176804. #endif
  176805. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  176806. #ifdef PNG_USER_MEM_SUPPORTED
  176807. png_voidp mem_ptr; /* user supplied struct for mem functions */
  176808. png_malloc_ptr malloc_fn; /* function for allocating memory */
  176809. png_free_ptr free_fn; /* function for freeing memory */
  176810. #endif
  176811. /* New member added in libpng-1.0.13 and 1.2.0 */
  176812. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  176813. #if defined(PNG_READ_DITHER_SUPPORTED)
  176814. /* The following three members were added at version 1.0.14 and 1.2.4 */
  176815. png_bytep dither_sort; /* working sort array */
  176816. png_bytep index_to_palette; /* where the original index currently is */
  176817. /* in the palette */
  176818. png_bytep palette_to_index; /* which original index points to this */
  176819. /* palette color */
  176820. #endif
  176821. /* New members added in libpng-1.0.16 and 1.2.6 */
  176822. png_byte compression_type;
  176823. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  176824. png_uint_32 user_width_max;
  176825. png_uint_32 user_height_max;
  176826. #endif
  176827. /* New member added in libpng-1.0.25 and 1.2.17 */
  176828. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176829. /* storage for unknown chunk that the library doesn't recognize. */
  176830. png_unknown_chunk unknown_chunk;
  176831. #endif
  176832. };
  176833. /* This triggers a compiler error in png.c, if png.c and png.h
  176834. * do not agree upon the version number.
  176835. */
  176836. typedef png_structp version_1_2_21;
  176837. typedef png_struct FAR * FAR * png_structpp;
  176838. /* Here are the function definitions most commonly used. This is not
  176839. * the place to find out how to use libpng. See libpng.txt for the
  176840. * full explanation, see example.c for the summary. This just provides
  176841. * a simple one line description of the use of each function.
  176842. */
  176843. /* Returns the version number of the library */
  176844. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  176845. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  176846. * Handling more than 8 bytes from the beginning of the file is an error.
  176847. */
  176848. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  176849. int num_bytes));
  176850. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  176851. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  176852. * signature, and non-zero otherwise. Having num_to_check == 0 or
  176853. * start > 7 will always fail (ie return non-zero).
  176854. */
  176855. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  176856. png_size_t num_to_check));
  176857. /* Simple signature checking function. This is the same as calling
  176858. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  176859. */
  176860. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  176861. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  176862. extern PNG_EXPORT(png_structp,png_create_read_struct)
  176863. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176864. png_error_ptr error_fn, png_error_ptr warn_fn));
  176865. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  176866. extern PNG_EXPORT(png_structp,png_create_write_struct)
  176867. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176868. png_error_ptr error_fn, png_error_ptr warn_fn));
  176869. #ifdef PNG_WRITE_SUPPORTED
  176870. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  176871. PNGARG((png_structp png_ptr));
  176872. #endif
  176873. #ifdef PNG_WRITE_SUPPORTED
  176874. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  176875. PNGARG((png_structp png_ptr, png_uint_32 size));
  176876. #endif
  176877. /* Reset the compression stream */
  176878. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  176879. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  176880. #ifdef PNG_USER_MEM_SUPPORTED
  176881. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  176882. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176883. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  176884. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  176885. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  176886. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176887. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  176888. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  176889. #endif
  176890. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  176891. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  176892. png_bytep chunk_name, png_bytep data, png_size_t length));
  176893. /* Write the start of a PNG chunk - length and chunk name. */
  176894. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  176895. png_bytep chunk_name, png_uint_32 length));
  176896. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  176897. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  176898. png_bytep data, png_size_t length));
  176899. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  176900. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  176901. /* Allocate and initialize the info structure */
  176902. extern PNG_EXPORT(png_infop,png_create_info_struct)
  176903. PNGARG((png_structp png_ptr));
  176904. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176905. /* Initialize the info structure (old interface - DEPRECATED) */
  176906. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  176907. #undef png_info_init
  176908. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  176909. png_sizeof(png_info));
  176910. #endif
  176911. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  176912. png_size_t png_info_struct_size));
  176913. /* Writes all the PNG information before the image. */
  176914. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  176915. png_infop info_ptr));
  176916. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  176917. png_infop info_ptr));
  176918. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  176919. /* read the information before the actual image data. */
  176920. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  176921. png_infop info_ptr));
  176922. #endif
  176923. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  176924. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  176925. PNGARG((png_structp png_ptr, png_timep ptime));
  176926. #endif
  176927. #if !defined(_WIN32_WCE)
  176928. /* "time.h" functions are not supported on WindowsCE */
  176929. #if defined(PNG_WRITE_tIME_SUPPORTED)
  176930. /* convert from a struct tm to png_time */
  176931. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  176932. struct tm FAR * ttime));
  176933. /* convert from time_t to png_time. Uses gmtime() */
  176934. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  176935. time_t ttime));
  176936. #endif /* PNG_WRITE_tIME_SUPPORTED */
  176937. #endif /* _WIN32_WCE */
  176938. #if defined(PNG_READ_EXPAND_SUPPORTED)
  176939. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  176940. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  176941. #if !defined(PNG_1_0_X)
  176942. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  176943. png_ptr));
  176944. #endif
  176945. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  176946. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  176947. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176948. /* Deprecated */
  176949. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  176950. #endif
  176951. #endif
  176952. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  176953. /* Use blue, green, red order for pixels. */
  176954. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  176955. #endif
  176956. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  176957. /* Expand the grayscale to 24-bit RGB if necessary. */
  176958. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  176959. #endif
  176960. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  176961. /* Reduce RGB to grayscale. */
  176962. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176963. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  176964. int error_action, double red, double green ));
  176965. #endif
  176966. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  176967. int error_action, png_fixed_point red, png_fixed_point green ));
  176968. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  176969. png_ptr));
  176970. #endif
  176971. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  176972. png_colorp palette));
  176973. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  176974. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  176975. #endif
  176976. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  176977. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  176978. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  176979. #endif
  176980. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  176981. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  176982. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  176983. #endif
  176984. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  176985. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  176986. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  176987. png_uint_32 filler, int flags));
  176988. /* The values of the PNG_FILLER_ defines should NOT be changed */
  176989. #define PNG_FILLER_BEFORE 0
  176990. #define PNG_FILLER_AFTER 1
  176991. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  176992. #if !defined(PNG_1_0_X)
  176993. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  176994. png_uint_32 filler, int flags));
  176995. #endif
  176996. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  176997. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  176998. /* Swap bytes in 16-bit depth files. */
  176999. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  177000. #endif
  177001. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  177002. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  177003. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  177004. #endif
  177005. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  177006. /* Swap packing order of pixels in bytes. */
  177007. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  177008. #endif
  177009. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  177010. /* Converts files to legal bit depths. */
  177011. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  177012. png_color_8p true_bits));
  177013. #endif
  177014. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  177015. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  177016. /* Have the code handle the interlacing. Returns the number of passes. */
  177017. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  177018. #endif
  177019. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  177020. /* Invert monochrome files */
  177021. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  177022. #endif
  177023. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  177024. /* Handle alpha and tRNS by replacing with a background color. */
  177025. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177026. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  177027. png_color_16p background_color, int background_gamma_code,
  177028. int need_expand, double background_gamma));
  177029. #endif
  177030. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  177031. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  177032. #define PNG_BACKGROUND_GAMMA_FILE 2
  177033. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  177034. #endif
  177035. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  177036. /* strip the second byte of information from a 16-bit depth file. */
  177037. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  177038. #endif
  177039. #if defined(PNG_READ_DITHER_SUPPORTED)
  177040. /* Turn on dithering, and reduce the palette to the number of colors available. */
  177041. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  177042. png_colorp palette, int num_palette, int maximum_colors,
  177043. png_uint_16p histogram, int full_dither));
  177044. #endif
  177045. #if defined(PNG_READ_GAMMA_SUPPORTED)
  177046. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  177047. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177048. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  177049. double screen_gamma, double default_file_gamma));
  177050. #endif
  177051. #endif
  177052. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177053. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  177054. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  177055. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  177056. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  177057. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  177058. int empty_plte_permitted));
  177059. #endif
  177060. #endif
  177061. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  177062. /* Set how many lines between output flushes - 0 for no flushing */
  177063. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  177064. /* Flush the current PNG output buffer */
  177065. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  177066. #endif
  177067. /* optional update palette with requested transformations */
  177068. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  177069. /* optional call to update the users info structure */
  177070. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  177071. png_infop info_ptr));
  177072. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  177073. /* read one or more rows of image data. */
  177074. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  177075. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  177076. #endif
  177077. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  177078. /* read a row of data. */
  177079. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  177080. png_bytep row,
  177081. png_bytep display_row));
  177082. #endif
  177083. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  177084. /* read the whole image into memory at once. */
  177085. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  177086. png_bytepp image));
  177087. #endif
  177088. /* write a row of image data */
  177089. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  177090. png_bytep row));
  177091. /* write a few rows of image data */
  177092. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  177093. png_bytepp row, png_uint_32 num_rows));
  177094. /* write the image data */
  177095. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  177096. png_bytepp image));
  177097. /* writes the end of the PNG file. */
  177098. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  177099. png_infop info_ptr));
  177100. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  177101. /* read the end of the PNG file. */
  177102. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  177103. png_infop info_ptr));
  177104. #endif
  177105. /* free any memory associated with the png_info_struct */
  177106. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  177107. png_infopp info_ptr_ptr));
  177108. /* free any memory associated with the png_struct and the png_info_structs */
  177109. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  177110. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  177111. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  177112. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  177113. png_infop end_info_ptr));
  177114. /* free any memory associated with the png_struct and the png_info_structs */
  177115. extern PNG_EXPORT(void,png_destroy_write_struct)
  177116. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  177117. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  177118. extern void png_write_destroy PNGARG((png_structp png_ptr));
  177119. /* set the libpng method of handling chunk CRC errors */
  177120. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  177121. int crit_action, int ancil_action));
  177122. /* Values for png_set_crc_action() to say how to handle CRC errors in
  177123. * ancillary and critical chunks, and whether to use the data contained
  177124. * therein. Note that it is impossible to "discard" data in a critical
  177125. * chunk. For versions prior to 0.90, the action was always error/quit,
  177126. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  177127. * chunks is warn/discard. These values should NOT be changed.
  177128. *
  177129. * value action:critical action:ancillary
  177130. */
  177131. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  177132. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  177133. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  177134. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  177135. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  177136. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  177137. /* These functions give the user control over the scan-line filtering in
  177138. * libpng and the compression methods used by zlib. These functions are
  177139. * mainly useful for testing, as the defaults should work with most users.
  177140. * Those users who are tight on memory or want faster performance at the
  177141. * expense of compression can modify them. See the compression library
  177142. * header file (zlib.h) for an explination of the compression functions.
  177143. */
  177144. /* set the filtering method(s) used by libpng. Currently, the only valid
  177145. * value for "method" is 0.
  177146. */
  177147. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  177148. int filters));
  177149. /* Flags for png_set_filter() to say which filters to use. The flags
  177150. * are chosen so that they don't conflict with real filter types
  177151. * below, in case they are supplied instead of the #defined constants.
  177152. * These values should NOT be changed.
  177153. */
  177154. #define PNG_NO_FILTERS 0x00
  177155. #define PNG_FILTER_NONE 0x08
  177156. #define PNG_FILTER_SUB 0x10
  177157. #define PNG_FILTER_UP 0x20
  177158. #define PNG_FILTER_AVG 0x40
  177159. #define PNG_FILTER_PAETH 0x80
  177160. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  177161. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  177162. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  177163. * These defines should NOT be changed.
  177164. */
  177165. #define PNG_FILTER_VALUE_NONE 0
  177166. #define PNG_FILTER_VALUE_SUB 1
  177167. #define PNG_FILTER_VALUE_UP 2
  177168. #define PNG_FILTER_VALUE_AVG 3
  177169. #define PNG_FILTER_VALUE_PAETH 4
  177170. #define PNG_FILTER_VALUE_LAST 5
  177171. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  177172. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  177173. * defines, either the default (minimum-sum-of-absolute-differences), or
  177174. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  177175. *
  177176. * Weights are factors >= 1.0, indicating how important it is to keep the
  177177. * filter type consistent between rows. Larger numbers mean the current
  177178. * filter is that many times as likely to be the same as the "num_weights"
  177179. * previous filters. This is cumulative for each previous row with a weight.
  177180. * There needs to be "num_weights" values in "filter_weights", or it can be
  177181. * NULL if the weights aren't being specified. Weights have no influence on
  177182. * the selection of the first row filter. Well chosen weights can (in theory)
  177183. * improve the compression for a given image.
  177184. *
  177185. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  177186. * filter type. Higher costs indicate more decoding expense, and are
  177187. * therefore less likely to be selected over a filter with lower computational
  177188. * costs. There needs to be a value in "filter_costs" for each valid filter
  177189. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  177190. * setting the costs. Costs try to improve the speed of decompression without
  177191. * unduly increasing the compressed image size.
  177192. *
  177193. * A negative weight or cost indicates the default value is to be used, and
  177194. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  177195. * The default values for both weights and costs are currently 1.0, but may
  177196. * change if good general weighting/cost heuristics can be found. If both
  177197. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  177198. * to the UNWEIGHTED method, but with added encoding time/computation.
  177199. */
  177200. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177201. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  177202. int heuristic_method, int num_weights, png_doublep filter_weights,
  177203. png_doublep filter_costs));
  177204. #endif
  177205. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  177206. /* Heuristic used for row filter selection. These defines should NOT be
  177207. * changed.
  177208. */
  177209. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  177210. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  177211. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  177212. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  177213. /* Set the library compression level. Currently, valid values range from
  177214. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  177215. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  177216. * shown that zlib compression levels 3-6 usually perform as well as level 9
  177217. * for PNG images, and do considerably fewer caclulations. In the future,
  177218. * these values may not correspond directly to the zlib compression levels.
  177219. */
  177220. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  177221. int level));
  177222. extern PNG_EXPORT(void,png_set_compression_mem_level)
  177223. PNGARG((png_structp png_ptr, int mem_level));
  177224. extern PNG_EXPORT(void,png_set_compression_strategy)
  177225. PNGARG((png_structp png_ptr, int strategy));
  177226. extern PNG_EXPORT(void,png_set_compression_window_bits)
  177227. PNGARG((png_structp png_ptr, int window_bits));
  177228. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  177229. int method));
  177230. /* These next functions are called for input/output, memory, and error
  177231. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  177232. * and call standard C I/O routines such as fread(), fwrite(), and
  177233. * fprintf(). These functions can be made to use other I/O routines
  177234. * at run time for those applications that need to handle I/O in a
  177235. * different manner by calling png_set_???_fn(). See libpng.txt for
  177236. * more information.
  177237. */
  177238. #if !defined(PNG_NO_STDIO)
  177239. /* Initialize the input/output for the PNG file to the default functions. */
  177240. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  177241. #endif
  177242. /* Replace the (error and abort), and warning functions with user
  177243. * supplied functions. If no messages are to be printed you must still
  177244. * write and use replacement functions. The replacement error_fn should
  177245. * still do a longjmp to the last setjmp location if you are using this
  177246. * method of error handling. If error_fn or warning_fn is NULL, the
  177247. * default function will be used.
  177248. */
  177249. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  177250. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  177251. /* Return the user pointer associated with the error functions */
  177252. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  177253. /* Replace the default data output functions with a user supplied one(s).
  177254. * If buffered output is not used, then output_flush_fn can be set to NULL.
  177255. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  177256. * output_flush_fn will be ignored (and thus can be NULL).
  177257. */
  177258. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  177259. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  177260. /* Replace the default data input function with a user supplied one. */
  177261. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  177262. png_voidp io_ptr, png_rw_ptr read_data_fn));
  177263. /* Return the user pointer associated with the I/O functions */
  177264. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  177265. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  177266. png_read_status_ptr read_row_fn));
  177267. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  177268. png_write_status_ptr write_row_fn));
  177269. #ifdef PNG_USER_MEM_SUPPORTED
  177270. /* Replace the default memory allocation functions with user supplied one(s). */
  177271. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  177272. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  177273. /* Return the user pointer associated with the memory functions */
  177274. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  177275. #endif
  177276. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  177277. defined(PNG_LEGACY_SUPPORTED)
  177278. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  177279. png_ptr, png_user_transform_ptr read_user_transform_fn));
  177280. #endif
  177281. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  177282. defined(PNG_LEGACY_SUPPORTED)
  177283. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  177284. png_ptr, png_user_transform_ptr write_user_transform_fn));
  177285. #endif
  177286. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  177287. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  177288. defined(PNG_LEGACY_SUPPORTED)
  177289. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  177290. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  177291. int user_transform_channels));
  177292. /* Return the user pointer associated with the user transform functions */
  177293. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  177294. PNGARG((png_structp png_ptr));
  177295. #endif
  177296. #ifdef PNG_USER_CHUNKS_SUPPORTED
  177297. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  177298. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  177299. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  177300. png_ptr));
  177301. #endif
  177302. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  177303. /* Sets the function callbacks for the push reader, and a pointer to a
  177304. * user-defined structure available to the callback functions.
  177305. */
  177306. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  177307. png_voidp progressive_ptr,
  177308. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  177309. png_progressive_end_ptr end_fn));
  177310. /* returns the user pointer associated with the push read functions */
  177311. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  177312. PNGARG((png_structp png_ptr));
  177313. /* function to be called when data becomes available */
  177314. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  177315. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  177316. /* function that combines rows. Not very much different than the
  177317. * png_combine_row() call. Is this even used?????
  177318. */
  177319. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  177320. png_bytep old_row, png_bytep new_row));
  177321. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  177322. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  177323. png_uint_32 size));
  177324. #if defined(PNG_1_0_X)
  177325. # define png_malloc_warn png_malloc
  177326. #else
  177327. /* Added at libpng version 1.2.4 */
  177328. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  177329. png_uint_32 size));
  177330. #endif
  177331. /* frees a pointer allocated by png_malloc() */
  177332. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  177333. #if defined(PNG_1_0_X)
  177334. /* Function to allocate memory for zlib. */
  177335. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  177336. uInt size));
  177337. /* Function to free memory for zlib */
  177338. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  177339. #endif
  177340. /* Free data that was allocated internally */
  177341. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  177342. png_infop info_ptr, png_uint_32 free_me, int num));
  177343. #ifdef PNG_FREE_ME_SUPPORTED
  177344. /* Reassign responsibility for freeing existing data, whether allocated
  177345. * by libpng or by the application */
  177346. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  177347. png_infop info_ptr, int freer, png_uint_32 mask));
  177348. #endif
  177349. /* assignments for png_data_freer */
  177350. #define PNG_DESTROY_WILL_FREE_DATA 1
  177351. #define PNG_SET_WILL_FREE_DATA 1
  177352. #define PNG_USER_WILL_FREE_DATA 2
  177353. /* Flags for png_ptr->free_me and info_ptr->free_me */
  177354. #define PNG_FREE_HIST 0x0008
  177355. #define PNG_FREE_ICCP 0x0010
  177356. #define PNG_FREE_SPLT 0x0020
  177357. #define PNG_FREE_ROWS 0x0040
  177358. #define PNG_FREE_PCAL 0x0080
  177359. #define PNG_FREE_SCAL 0x0100
  177360. #define PNG_FREE_UNKN 0x0200
  177361. #define PNG_FREE_LIST 0x0400
  177362. #define PNG_FREE_PLTE 0x1000
  177363. #define PNG_FREE_TRNS 0x2000
  177364. #define PNG_FREE_TEXT 0x4000
  177365. #define PNG_FREE_ALL 0x7fff
  177366. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  177367. #ifdef PNG_USER_MEM_SUPPORTED
  177368. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  177369. png_uint_32 size));
  177370. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  177371. png_voidp ptr));
  177372. #endif
  177373. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  177374. png_voidp s1, png_voidp s2, png_uint_32 size));
  177375. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  177376. png_voidp s1, int value, png_uint_32 size));
  177377. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  177378. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  177379. int check));
  177380. #endif /* USE_FAR_KEYWORD */
  177381. #ifndef PNG_NO_ERROR_TEXT
  177382. /* Fatal error in PNG image of libpng - can't continue */
  177383. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  177384. png_const_charp error_message));
  177385. /* The same, but the chunk name is prepended to the error string. */
  177386. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  177387. png_const_charp error_message));
  177388. #else
  177389. /* Fatal error in PNG image of libpng - can't continue */
  177390. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  177391. #endif
  177392. #ifndef PNG_NO_WARNINGS
  177393. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  177394. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  177395. png_const_charp warning_message));
  177396. #ifdef PNG_READ_SUPPORTED
  177397. /* Non-fatal error in libpng, chunk name is prepended to message. */
  177398. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  177399. png_const_charp warning_message));
  177400. #endif /* PNG_READ_SUPPORTED */
  177401. #endif /* PNG_NO_WARNINGS */
  177402. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  177403. * Similarly, the png_get_<chunk> calls are used to read values from the
  177404. * png_info_struct, either storing the parameters in the passed variables, or
  177405. * setting pointers into the png_info_struct where the data is stored. The
  177406. * png_get_<chunk> functions return a non-zero value if the data was available
  177407. * in info_ptr, or return zero and do not change any of the parameters if the
  177408. * data was not available.
  177409. *
  177410. * These functions should be used instead of directly accessing png_info
  177411. * to avoid problems with future changes in the size and internal layout of
  177412. * png_info_struct.
  177413. */
  177414. /* Returns "flag" if chunk data is valid in info_ptr. */
  177415. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  177416. png_infop info_ptr, png_uint_32 flag));
  177417. /* Returns number of bytes needed to hold a transformed row. */
  177418. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  177419. png_infop info_ptr));
  177420. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  177421. /* Returns row_pointers, which is an array of pointers to scanlines that was
  177422. returned from png_read_png(). */
  177423. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  177424. png_infop info_ptr));
  177425. /* Set row_pointers, which is an array of pointers to scanlines for use
  177426. by png_write_png(). */
  177427. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  177428. png_infop info_ptr, png_bytepp row_pointers));
  177429. #endif
  177430. /* Returns number of color channels in image. */
  177431. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  177432. png_infop info_ptr));
  177433. #ifdef PNG_EASY_ACCESS_SUPPORTED
  177434. /* Returns image width in pixels. */
  177435. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  177436. png_ptr, png_infop info_ptr));
  177437. /* Returns image height in pixels. */
  177438. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  177439. png_ptr, png_infop info_ptr));
  177440. /* Returns image bit_depth. */
  177441. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  177442. png_ptr, png_infop info_ptr));
  177443. /* Returns image color_type. */
  177444. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  177445. png_ptr, png_infop info_ptr));
  177446. /* Returns image filter_type. */
  177447. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  177448. png_ptr, png_infop info_ptr));
  177449. /* Returns image interlace_type. */
  177450. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  177451. png_ptr, png_infop info_ptr));
  177452. /* Returns image compression_type. */
  177453. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  177454. png_ptr, png_infop info_ptr));
  177455. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  177456. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  177457. png_ptr, png_infop info_ptr));
  177458. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  177459. png_ptr, png_infop info_ptr));
  177460. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  177461. png_ptr, png_infop info_ptr));
  177462. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  177463. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177464. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  177465. png_ptr, png_infop info_ptr));
  177466. #endif
  177467. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  177468. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  177469. png_ptr, png_infop info_ptr));
  177470. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  177471. png_ptr, png_infop info_ptr));
  177472. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  177473. png_ptr, png_infop info_ptr));
  177474. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  177475. png_ptr, png_infop info_ptr));
  177476. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  177477. /* Returns pointer to signature string read from PNG header */
  177478. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  177479. png_infop info_ptr));
  177480. #if defined(PNG_bKGD_SUPPORTED)
  177481. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  177482. png_infop info_ptr, png_color_16p *background));
  177483. #endif
  177484. #if defined(PNG_bKGD_SUPPORTED)
  177485. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  177486. png_infop info_ptr, png_color_16p background));
  177487. #endif
  177488. #if defined(PNG_cHRM_SUPPORTED)
  177489. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177490. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  177491. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  177492. double *red_y, double *green_x, double *green_y, double *blue_x,
  177493. double *blue_y));
  177494. #endif
  177495. #ifdef PNG_FIXED_POINT_SUPPORTED
  177496. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  177497. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  177498. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  177499. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  177500. *int_blue_x, png_fixed_point *int_blue_y));
  177501. #endif
  177502. #endif
  177503. #if defined(PNG_cHRM_SUPPORTED)
  177504. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177505. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  177506. png_infop info_ptr, double white_x, double white_y, double red_x,
  177507. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  177508. #endif
  177509. #ifdef PNG_FIXED_POINT_SUPPORTED
  177510. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  177511. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  177512. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  177513. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  177514. png_fixed_point int_blue_y));
  177515. #endif
  177516. #endif
  177517. #if defined(PNG_gAMA_SUPPORTED)
  177518. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177519. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  177520. png_infop info_ptr, double *file_gamma));
  177521. #endif
  177522. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  177523. png_infop info_ptr, png_fixed_point *int_file_gamma));
  177524. #endif
  177525. #if defined(PNG_gAMA_SUPPORTED)
  177526. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177527. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  177528. png_infop info_ptr, double file_gamma));
  177529. #endif
  177530. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  177531. png_infop info_ptr, png_fixed_point int_file_gamma));
  177532. #endif
  177533. #if defined(PNG_hIST_SUPPORTED)
  177534. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  177535. png_infop info_ptr, png_uint_16p *hist));
  177536. #endif
  177537. #if defined(PNG_hIST_SUPPORTED)
  177538. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  177539. png_infop info_ptr, png_uint_16p hist));
  177540. #endif
  177541. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  177542. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  177543. int *bit_depth, int *color_type, int *interlace_method,
  177544. int *compression_method, int *filter_method));
  177545. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  177546. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  177547. int color_type, int interlace_method, int compression_method,
  177548. int filter_method));
  177549. #if defined(PNG_oFFs_SUPPORTED)
  177550. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  177551. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  177552. int *unit_type));
  177553. #endif
  177554. #if defined(PNG_oFFs_SUPPORTED)
  177555. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  177556. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  177557. int unit_type));
  177558. #endif
  177559. #if defined(PNG_pCAL_SUPPORTED)
  177560. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  177561. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  177562. int *type, int *nparams, png_charp *units, png_charpp *params));
  177563. #endif
  177564. #if defined(PNG_pCAL_SUPPORTED)
  177565. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  177566. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  177567. int type, int nparams, png_charp units, png_charpp params));
  177568. #endif
  177569. #if defined(PNG_pHYs_SUPPORTED)
  177570. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  177571. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  177572. #endif
  177573. #if defined(PNG_pHYs_SUPPORTED)
  177574. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  177575. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  177576. #endif
  177577. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  177578. png_infop info_ptr, png_colorp *palette, int *num_palette));
  177579. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  177580. png_infop info_ptr, png_colorp palette, int num_palette));
  177581. #if defined(PNG_sBIT_SUPPORTED)
  177582. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  177583. png_infop info_ptr, png_color_8p *sig_bit));
  177584. #endif
  177585. #if defined(PNG_sBIT_SUPPORTED)
  177586. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  177587. png_infop info_ptr, png_color_8p sig_bit));
  177588. #endif
  177589. #if defined(PNG_sRGB_SUPPORTED)
  177590. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  177591. png_infop info_ptr, int *intent));
  177592. #endif
  177593. #if defined(PNG_sRGB_SUPPORTED)
  177594. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  177595. png_infop info_ptr, int intent));
  177596. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  177597. png_infop info_ptr, int intent));
  177598. #endif
  177599. #if defined(PNG_iCCP_SUPPORTED)
  177600. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  177601. png_infop info_ptr, png_charpp name, int *compression_type,
  177602. png_charpp profile, png_uint_32 *proflen));
  177603. /* Note to maintainer: profile should be png_bytepp */
  177604. #endif
  177605. #if defined(PNG_iCCP_SUPPORTED)
  177606. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  177607. png_infop info_ptr, png_charp name, int compression_type,
  177608. png_charp profile, png_uint_32 proflen));
  177609. /* Note to maintainer: profile should be png_bytep */
  177610. #endif
  177611. #if defined(PNG_sPLT_SUPPORTED)
  177612. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  177613. png_infop info_ptr, png_sPLT_tpp entries));
  177614. #endif
  177615. #if defined(PNG_sPLT_SUPPORTED)
  177616. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  177617. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  177618. #endif
  177619. #if defined(PNG_TEXT_SUPPORTED)
  177620. /* png_get_text also returns the number of text chunks in *num_text */
  177621. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  177622. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  177623. #endif
  177624. /*
  177625. * Note while png_set_text() will accept a structure whose text,
  177626. * language, and translated keywords are NULL pointers, the structure
  177627. * returned by png_get_text will always contain regular
  177628. * zero-terminated C strings. They might be empty strings but
  177629. * they will never be NULL pointers.
  177630. */
  177631. #if defined(PNG_TEXT_SUPPORTED)
  177632. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  177633. png_infop info_ptr, png_textp text_ptr, int num_text));
  177634. #endif
  177635. #if defined(PNG_tIME_SUPPORTED)
  177636. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  177637. png_infop info_ptr, png_timep *mod_time));
  177638. #endif
  177639. #if defined(PNG_tIME_SUPPORTED)
  177640. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  177641. png_infop info_ptr, png_timep mod_time));
  177642. #endif
  177643. #if defined(PNG_tRNS_SUPPORTED)
  177644. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  177645. png_infop info_ptr, png_bytep *trans, int *num_trans,
  177646. png_color_16p *trans_values));
  177647. #endif
  177648. #if defined(PNG_tRNS_SUPPORTED)
  177649. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  177650. png_infop info_ptr, png_bytep trans, int num_trans,
  177651. png_color_16p trans_values));
  177652. #endif
  177653. #if defined(PNG_tRNS_SUPPORTED)
  177654. #endif
  177655. #if defined(PNG_sCAL_SUPPORTED)
  177656. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177657. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  177658. png_infop info_ptr, int *unit, double *width, double *height));
  177659. #else
  177660. #ifdef PNG_FIXED_POINT_SUPPORTED
  177661. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  177662. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  177663. #endif
  177664. #endif
  177665. #endif /* PNG_sCAL_SUPPORTED */
  177666. #if defined(PNG_sCAL_SUPPORTED)
  177667. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177668. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  177669. png_infop info_ptr, int unit, double width, double height));
  177670. #else
  177671. #ifdef PNG_FIXED_POINT_SUPPORTED
  177672. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  177673. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  177674. #endif
  177675. #endif
  177676. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  177677. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  177678. /* provide a list of chunks and how they are to be handled, if the built-in
  177679. handling or default unknown chunk handling is not desired. Any chunks not
  177680. listed will be handled in the default manner. The IHDR and IEND chunks
  177681. must not be listed.
  177682. keep = 0: follow default behaviour
  177683. = 1: do not keep
  177684. = 2: keep only if safe-to-copy
  177685. = 3: keep even if unsafe-to-copy
  177686. */
  177687. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  177688. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  177689. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  177690. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  177691. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  177692. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  177693. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  177694. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  177695. #endif
  177696. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  177697. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  177698. chunk_name));
  177699. #endif
  177700. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  177701. If you need to turn it off for a chunk that your application has freed,
  177702. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  177703. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  177704. png_infop info_ptr, int mask));
  177705. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  177706. /* The "params" pointer is currently not used and is for future expansion. */
  177707. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  177708. png_infop info_ptr,
  177709. int transforms,
  177710. png_voidp params));
  177711. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  177712. png_infop info_ptr,
  177713. int transforms,
  177714. png_voidp params));
  177715. #endif
  177716. /* Define PNG_DEBUG at compile time for debugging information. Higher
  177717. * numbers for PNG_DEBUG mean more debugging information. This has
  177718. * only been added since version 0.95 so it is not implemented throughout
  177719. * libpng yet, but more support will be added as needed.
  177720. */
  177721. #ifdef PNG_DEBUG
  177722. #if (PNG_DEBUG > 0)
  177723. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  177724. #include <crtdbg.h>
  177725. #if (PNG_DEBUG > 1)
  177726. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  177727. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  177728. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  177729. #endif
  177730. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  177731. #ifndef PNG_DEBUG_FILE
  177732. #define PNG_DEBUG_FILE stderr
  177733. #endif /* PNG_DEBUG_FILE */
  177734. #if (PNG_DEBUG > 1)
  177735. #define png_debug(l,m) \
  177736. { \
  177737. int num_tabs=l; \
  177738. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  177739. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  177740. }
  177741. #define png_debug1(l,m,p1) \
  177742. { \
  177743. int num_tabs=l; \
  177744. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  177745. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  177746. }
  177747. #define png_debug2(l,m,p1,p2) \
  177748. { \
  177749. int num_tabs=l; \
  177750. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  177751. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  177752. }
  177753. #endif /* (PNG_DEBUG > 1) */
  177754. #endif /* _MSC_VER */
  177755. #endif /* (PNG_DEBUG > 0) */
  177756. #endif /* PNG_DEBUG */
  177757. #ifndef png_debug
  177758. #define png_debug(l, m)
  177759. #endif
  177760. #ifndef png_debug1
  177761. #define png_debug1(l, m, p1)
  177762. #endif
  177763. #ifndef png_debug2
  177764. #define png_debug2(l, m, p1, p2)
  177765. #endif
  177766. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  177767. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  177768. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  177769. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  177770. #ifdef PNG_MNG_FEATURES_SUPPORTED
  177771. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  177772. png_ptr, png_uint_32 mng_features_permitted));
  177773. #endif
  177774. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  177775. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  177776. #define PNG_HANDLE_CHUNK_NEVER 1
  177777. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  177778. #define PNG_HANDLE_CHUNK_ALWAYS 3
  177779. /* Added to version 1.2.0 */
  177780. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  177781. #if defined(PNG_MMX_CODE_SUPPORTED)
  177782. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  177783. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  177784. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  177785. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  177786. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  177787. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  177788. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  177789. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  177790. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  177791. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  177792. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  177793. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  177794. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  177795. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  177796. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  177797. #define PNG_MMX_WRITE_FLAGS ( 0 )
  177798. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  177799. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  177800. | PNG_MMX_READ_FLAGS \
  177801. | PNG_MMX_WRITE_FLAGS )
  177802. #define PNG_SELECT_READ 1
  177803. #define PNG_SELECT_WRITE 2
  177804. #endif /* PNG_MMX_CODE_SUPPORTED */
  177805. #if !defined(PNG_1_0_X)
  177806. /* pngget.c */
  177807. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  177808. PNGARG((int flag_select, int *compilerID));
  177809. /* pngget.c */
  177810. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  177811. PNGARG((int flag_select));
  177812. /* pngget.c */
  177813. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  177814. PNGARG((png_structp png_ptr));
  177815. /* pngget.c */
  177816. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  177817. PNGARG((png_structp png_ptr));
  177818. /* pngget.c */
  177819. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  177820. PNGARG((png_structp png_ptr));
  177821. /* pngset.c */
  177822. extern PNG_EXPORT(void,png_set_asm_flags)
  177823. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  177824. /* pngset.c */
  177825. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  177826. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  177827. png_uint_32 mmx_rowbytes_threshold));
  177828. #endif /* PNG_1_0_X */
  177829. #if !defined(PNG_1_0_X)
  177830. /* png.c, pnggccrd.c, or pngvcrd.c */
  177831. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  177832. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  177833. /* Strip the prepended error numbers ("#nnn ") from error and warning
  177834. * messages before passing them to the error or warning handler. */
  177835. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  177836. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  177837. png_ptr, png_uint_32 strip_mode));
  177838. #endif
  177839. #endif /* PNG_1_0_X */
  177840. /* Added at libpng-1.2.6 */
  177841. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  177842. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  177843. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  177844. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  177845. png_ptr));
  177846. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  177847. png_ptr));
  177848. #endif
  177849. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  177850. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  177851. /* With these routines we avoid an integer divide, which will be slower on
  177852. * most machines. However, it does take more operations than the corresponding
  177853. * divide method, so it may be slower on a few RISC systems. There are two
  177854. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  177855. *
  177856. * Note that the rounding factors are NOT supposed to be the same! 128 and
  177857. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  177858. * standard method.
  177859. *
  177860. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  177861. */
  177862. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  177863. # define png_composite(composite, fg, alpha, bg) \
  177864. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  177865. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  177866. (png_uint_16)(alpha)) + (png_uint_16)128); \
  177867. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  177868. # define png_composite_16(composite, fg, alpha, bg) \
  177869. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  177870. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  177871. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  177872. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  177873. #else /* standard method using integer division */
  177874. # define png_composite(composite, fg, alpha, bg) \
  177875. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  177876. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  177877. (png_uint_16)127) / 255)
  177878. # define png_composite_16(composite, fg, alpha, bg) \
  177879. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  177880. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  177881. (png_uint_32)32767) / (png_uint_32)65535L)
  177882. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  177883. /* Inline macros to do direct reads of bytes from the input buffer. These
  177884. * require that you are using an architecture that uses PNG byte ordering
  177885. * (MSB first) and supports unaligned data storage. I think that PowerPC
  177886. * in big-endian mode and 680x0 are the only ones that will support this.
  177887. * The x86 line of processors definitely do not. The png_get_int_32()
  177888. * routine also assumes we are using two's complement format for negative
  177889. * values, which is almost certainly true.
  177890. */
  177891. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  177892. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  177893. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  177894. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  177895. #else
  177896. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  177897. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  177898. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  177899. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  177900. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  177901. PNGARG((png_structp png_ptr, png_bytep buf));
  177902. /* No png_get_int_16 -- may be added if there's a real need for it. */
  177903. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  177904. */
  177905. extern PNG_EXPORT(void,png_save_uint_32)
  177906. PNGARG((png_bytep buf, png_uint_32 i));
  177907. extern PNG_EXPORT(void,png_save_int_32)
  177908. PNGARG((png_bytep buf, png_int_32 i));
  177909. /* Place a 16-bit number into a buffer in PNG byte order.
  177910. * The parameter is declared unsigned int, not png_uint_16,
  177911. * just to avoid potential problems on pre-ANSI C compilers.
  177912. */
  177913. extern PNG_EXPORT(void,png_save_uint_16)
  177914. PNGARG((png_bytep buf, unsigned int i));
  177915. /* No png_save_int_16 -- may be added if there's a real need for it. */
  177916. /* ************************************************************************* */
  177917. /* These next functions are used internally in the code. They generally
  177918. * shouldn't be used unless you are writing code to add or replace some
  177919. * functionality in libpng. More information about most functions can
  177920. * be found in the files where the functions are located.
  177921. */
  177922. /* Various modes of operation, that are visible to applications because
  177923. * they are used for unknown chunk location.
  177924. */
  177925. #define PNG_HAVE_IHDR 0x01
  177926. #define PNG_HAVE_PLTE 0x02
  177927. #define PNG_HAVE_IDAT 0x04
  177928. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  177929. #define PNG_HAVE_IEND 0x10
  177930. #if defined(PNG_INTERNAL)
  177931. /* More modes of operation. Note that after an init, mode is set to
  177932. * zero automatically when the structure is created.
  177933. */
  177934. #define PNG_HAVE_gAMA 0x20
  177935. #define PNG_HAVE_cHRM 0x40
  177936. #define PNG_HAVE_sRGB 0x80
  177937. #define PNG_HAVE_CHUNK_HEADER 0x100
  177938. #define PNG_WROTE_tIME 0x200
  177939. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  177940. #define PNG_BACKGROUND_IS_GRAY 0x800
  177941. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  177942. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  177943. /* flags for the transformations the PNG library does on the image data */
  177944. #define PNG_BGR 0x0001
  177945. #define PNG_INTERLACE 0x0002
  177946. #define PNG_PACK 0x0004
  177947. #define PNG_SHIFT 0x0008
  177948. #define PNG_SWAP_BYTES 0x0010
  177949. #define PNG_INVERT_MONO 0x0020
  177950. #define PNG_DITHER 0x0040
  177951. #define PNG_BACKGROUND 0x0080
  177952. #define PNG_BACKGROUND_EXPAND 0x0100
  177953. /* 0x0200 unused */
  177954. #define PNG_16_TO_8 0x0400
  177955. #define PNG_RGBA 0x0800
  177956. #define PNG_EXPAND 0x1000
  177957. #define PNG_GAMMA 0x2000
  177958. #define PNG_GRAY_TO_RGB 0x4000
  177959. #define PNG_FILLER 0x8000L
  177960. #define PNG_PACKSWAP 0x10000L
  177961. #define PNG_SWAP_ALPHA 0x20000L
  177962. #define PNG_STRIP_ALPHA 0x40000L
  177963. #define PNG_INVERT_ALPHA 0x80000L
  177964. #define PNG_USER_TRANSFORM 0x100000L
  177965. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  177966. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  177967. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  177968. /* 0x800000L Unused */
  177969. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  177970. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  177971. /* 0x4000000L unused */
  177972. /* 0x8000000L unused */
  177973. /* 0x10000000L unused */
  177974. /* 0x20000000L unused */
  177975. /* 0x40000000L unused */
  177976. /* flags for png_create_struct */
  177977. #define PNG_STRUCT_PNG 0x0001
  177978. #define PNG_STRUCT_INFO 0x0002
  177979. /* Scaling factor for filter heuristic weighting calculations */
  177980. #define PNG_WEIGHT_SHIFT 8
  177981. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  177982. #define PNG_COST_SHIFT 3
  177983. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  177984. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  177985. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  177986. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  177987. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  177988. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  177989. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  177990. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  177991. #define PNG_FLAG_ROW_INIT 0x0040
  177992. #define PNG_FLAG_FILLER_AFTER 0x0080
  177993. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  177994. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  177995. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  177996. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  177997. #define PNG_FLAG_FREE_PLTE 0x1000
  177998. #define PNG_FLAG_FREE_TRNS 0x2000
  177999. #define PNG_FLAG_FREE_HIST 0x4000
  178000. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  178001. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  178002. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  178003. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  178004. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  178005. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  178006. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  178007. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  178008. /* 0x800000L unused */
  178009. /* 0x1000000L unused */
  178010. /* 0x2000000L unused */
  178011. /* 0x4000000L unused */
  178012. /* 0x8000000L unused */
  178013. /* 0x10000000L unused */
  178014. /* 0x20000000L unused */
  178015. /* 0x40000000L unused */
  178016. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  178017. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  178018. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  178019. PNG_FLAG_CRC_CRITICAL_IGNORE)
  178020. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  178021. PNG_FLAG_CRC_CRITICAL_MASK)
  178022. /* save typing and make code easier to understand */
  178023. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  178024. abs((int)((c1).green) - (int)((c2).green)) + \
  178025. abs((int)((c1).blue) - (int)((c2).blue)))
  178026. /* Added to libpng-1.2.6 JB */
  178027. #define PNG_ROWBYTES(pixel_bits, width) \
  178028. ((pixel_bits) >= 8 ? \
  178029. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  178030. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  178031. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  178032. ideal-delta..ideal+delta. Each argument is evaluated twice.
  178033. "ideal" and "delta" should be constants, normally simple
  178034. integers, "value" a variable. Added to libpng-1.2.6 JB */
  178035. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  178036. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  178037. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  178038. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  178039. /* place to hold the signature string for a PNG file. */
  178040. #ifdef PNG_USE_GLOBAL_ARRAYS
  178041. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  178042. #else
  178043. #endif
  178044. #endif /* PNG_NO_EXTERN */
  178045. /* Constant strings for known chunk types. If you need to add a chunk,
  178046. * define the name here, and add an invocation of the macro in png.c and
  178047. * wherever it's needed.
  178048. */
  178049. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  178050. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  178051. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  178052. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  178053. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  178054. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  178055. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  178056. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  178057. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  178058. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  178059. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  178060. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  178061. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  178062. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  178063. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  178064. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  178065. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  178066. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  178067. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  178068. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  178069. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  178070. #ifdef PNG_USE_GLOBAL_ARRAYS
  178071. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  178072. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  178073. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  178074. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  178075. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  178076. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  178077. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  178078. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  178079. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  178080. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  178081. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  178082. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  178083. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  178084. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  178085. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  178086. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  178087. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  178088. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  178089. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  178090. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  178091. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  178092. #endif /* PNG_USE_GLOBAL_ARRAYS */
  178093. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178094. /* Initialize png_ptr struct for reading, and allocate any other memory.
  178095. * (old interface - DEPRECATED - use png_create_read_struct instead).
  178096. */
  178097. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  178098. #undef png_read_init
  178099. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  178100. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  178101. #endif
  178102. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  178103. png_const_charp user_png_ver, png_size_t png_struct_size));
  178104. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178105. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  178106. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  178107. png_info_size));
  178108. #endif
  178109. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178110. /* Initialize png_ptr struct for writing, and allocate any other memory.
  178111. * (old interface - DEPRECATED - use png_create_write_struct instead).
  178112. */
  178113. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  178114. #undef png_write_init
  178115. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  178116. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  178117. #endif
  178118. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  178119. png_const_charp user_png_ver, png_size_t png_struct_size));
  178120. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  178121. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  178122. png_info_size));
  178123. /* Allocate memory for an internal libpng struct */
  178124. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  178125. /* Free memory from internal libpng struct */
  178126. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  178127. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  178128. malloc_fn, png_voidp mem_ptr));
  178129. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  178130. png_free_ptr free_fn, png_voidp mem_ptr));
  178131. /* Free any memory that info_ptr points to and reset struct. */
  178132. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  178133. png_infop info_ptr));
  178134. #ifndef PNG_1_0_X
  178135. /* Function to allocate memory for zlib. */
  178136. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  178137. /* Function to free memory for zlib */
  178138. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  178139. #ifdef PNG_SIZE_T
  178140. /* Function to convert a sizeof an item to png_sizeof item */
  178141. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  178142. #endif
  178143. /* Next four functions are used internally as callbacks. PNGAPI is required
  178144. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  178145. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  178146. png_bytep data, png_size_t length));
  178147. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178148. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  178149. png_bytep buffer, png_size_t length));
  178150. #endif
  178151. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  178152. png_bytep data, png_size_t length));
  178153. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  178154. #if !defined(PNG_NO_STDIO)
  178155. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  178156. #endif
  178157. #endif
  178158. #else /* PNG_1_0_X */
  178159. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178160. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  178161. png_bytep buffer, png_size_t length));
  178162. #endif
  178163. #endif /* PNG_1_0_X */
  178164. /* Reset the CRC variable */
  178165. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  178166. /* Write the "data" buffer to whatever output you are using. */
  178167. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  178168. png_size_t length));
  178169. /* Read data from whatever input you are using into the "data" buffer */
  178170. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  178171. png_size_t length));
  178172. /* Read bytes into buf, and update png_ptr->crc */
  178173. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  178174. png_size_t length));
  178175. /* Decompress data in a chunk that uses compression */
  178176. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  178177. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  178178. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  178179. int comp_type, png_charp chunkdata, png_size_t chunklength,
  178180. png_size_t prefix_length, png_size_t *data_length));
  178181. #endif
  178182. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  178183. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  178184. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  178185. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  178186. /* Calculate the CRC over a section of data. Note that we are only
  178187. * passing a maximum of 64K on systems that have this as a memory limit,
  178188. * since this is the maximum buffer size we can specify.
  178189. */
  178190. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  178191. png_size_t length));
  178192. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  178193. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  178194. #endif
  178195. /* simple function to write the signature */
  178196. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  178197. /* write various chunks */
  178198. /* Write the IHDR chunk, and update the png_struct with the necessary
  178199. * information.
  178200. */
  178201. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  178202. png_uint_32 height,
  178203. int bit_depth, int color_type, int compression_method, int filter_method,
  178204. int interlace_method));
  178205. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  178206. png_uint_32 num_pal));
  178207. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  178208. png_size_t length));
  178209. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  178210. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  178211. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178212. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  178213. #endif
  178214. #ifdef PNG_FIXED_POINT_SUPPORTED
  178215. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  178216. file_gamma));
  178217. #endif
  178218. #endif
  178219. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  178220. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  178221. int color_type));
  178222. #endif
  178223. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  178224. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178225. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  178226. double white_x, double white_y,
  178227. double red_x, double red_y, double green_x, double green_y,
  178228. double blue_x, double blue_y));
  178229. #endif
  178230. #ifdef PNG_FIXED_POINT_SUPPORTED
  178231. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  178232. png_fixed_point int_white_x, png_fixed_point int_white_y,
  178233. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  178234. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  178235. png_fixed_point int_blue_y));
  178236. #endif
  178237. #endif
  178238. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  178239. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  178240. int intent));
  178241. #endif
  178242. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  178243. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  178244. png_charp name, int compression_type,
  178245. png_charp profile, int proflen));
  178246. /* Note to maintainer: profile should be png_bytep */
  178247. #endif
  178248. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  178249. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  178250. png_sPLT_tp palette));
  178251. #endif
  178252. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  178253. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  178254. png_color_16p values, int number, int color_type));
  178255. #endif
  178256. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  178257. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  178258. png_color_16p values, int color_type));
  178259. #endif
  178260. #if defined(PNG_WRITE_hIST_SUPPORTED)
  178261. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  178262. int num_hist));
  178263. #endif
  178264. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  178265. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  178266. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  178267. png_charp key, png_charpp new_key));
  178268. #endif
  178269. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  178270. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  178271. png_charp text, png_size_t text_len));
  178272. #endif
  178273. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  178274. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  178275. png_charp text, png_size_t text_len, int compression));
  178276. #endif
  178277. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  178278. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  178279. int compression, png_charp key, png_charp lang, png_charp lang_key,
  178280. png_charp text));
  178281. #endif
  178282. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  178283. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  178284. png_infop info_ptr, png_textp text_ptr, int num_text));
  178285. #endif
  178286. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  178287. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  178288. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  178289. #endif
  178290. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  178291. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  178292. png_int_32 X0, png_int_32 X1, int type, int nparams,
  178293. png_charp units, png_charpp params));
  178294. #endif
  178295. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  178296. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  178297. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  178298. int unit_type));
  178299. #endif
  178300. #if defined(PNG_WRITE_tIME_SUPPORTED)
  178301. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  178302. png_timep mod_time));
  178303. #endif
  178304. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  178305. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  178306. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  178307. int unit, double width, double height));
  178308. #else
  178309. #ifdef PNG_FIXED_POINT_SUPPORTED
  178310. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  178311. int unit, png_charp width, png_charp height));
  178312. #endif
  178313. #endif
  178314. #endif
  178315. /* Called when finished processing a row of data */
  178316. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  178317. /* Internal use only. Called before first row of data */
  178318. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  178319. #if defined(PNG_READ_GAMMA_SUPPORTED)
  178320. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  178321. #endif
  178322. /* combine a row of data, dealing with alpha, etc. if requested */
  178323. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  178324. int mask));
  178325. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  178326. /* expand an interlaced row */
  178327. /* OLD pre-1.0.9 interface:
  178328. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  178329. png_bytep row, int pass, png_uint_32 transformations));
  178330. */
  178331. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  178332. #endif
  178333. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  178334. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  178335. /* grab pixels out of a row for an interlaced pass */
  178336. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  178337. png_bytep row, int pass));
  178338. #endif
  178339. /* unfilter a row */
  178340. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  178341. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  178342. /* Choose the best filter to use and filter the row data */
  178343. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  178344. png_row_infop row_info));
  178345. /* Write out the filtered row. */
  178346. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  178347. png_bytep filtered_row));
  178348. /* finish a row while reading, dealing with interlacing passes, etc. */
  178349. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  178350. /* initialize the row buffers, etc. */
  178351. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  178352. /* optional call to update the users info structure */
  178353. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  178354. png_infop info_ptr));
  178355. /* these are the functions that do the transformations */
  178356. #if defined(PNG_READ_FILLER_SUPPORTED)
  178357. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  178358. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  178359. #endif
  178360. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  178361. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  178362. png_bytep row));
  178363. #endif
  178364. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  178365. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  178366. png_bytep row));
  178367. #endif
  178368. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  178369. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  178370. png_bytep row));
  178371. #endif
  178372. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  178373. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  178374. png_bytep row));
  178375. #endif
  178376. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  178377. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  178378. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  178379. png_bytep row, png_uint_32 flags));
  178380. #endif
  178381. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  178382. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  178383. #endif
  178384. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  178385. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  178386. #endif
  178387. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  178388. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  178389. row_info, png_bytep row));
  178390. #endif
  178391. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  178392. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  178393. png_bytep row));
  178394. #endif
  178395. #if defined(PNG_READ_PACK_SUPPORTED)
  178396. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  178397. #endif
  178398. #if defined(PNG_READ_SHIFT_SUPPORTED)
  178399. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  178400. png_color_8p sig_bits));
  178401. #endif
  178402. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  178403. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  178404. #endif
  178405. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  178406. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  178407. #endif
  178408. #if defined(PNG_READ_DITHER_SUPPORTED)
  178409. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  178410. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  178411. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  178412. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  178413. png_colorp palette, int num_palette));
  178414. # endif
  178415. #endif
  178416. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  178417. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  178418. #endif
  178419. #if defined(PNG_WRITE_PACK_SUPPORTED)
  178420. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  178421. png_bytep row, png_uint_32 bit_depth));
  178422. #endif
  178423. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  178424. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  178425. png_color_8p bit_depth));
  178426. #endif
  178427. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  178428. #if defined(PNG_READ_GAMMA_SUPPORTED)
  178429. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  178430. png_color_16p trans_values, png_color_16p background,
  178431. png_color_16p background_1,
  178432. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  178433. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  178434. png_uint_16pp gamma_16_to_1, int gamma_shift));
  178435. #else
  178436. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  178437. png_color_16p trans_values, png_color_16p background));
  178438. #endif
  178439. #endif
  178440. #if defined(PNG_READ_GAMMA_SUPPORTED)
  178441. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  178442. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  178443. int gamma_shift));
  178444. #endif
  178445. #if defined(PNG_READ_EXPAND_SUPPORTED)
  178446. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  178447. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  178448. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  178449. png_bytep row, png_color_16p trans_value));
  178450. #endif
  178451. /* The following decodes the appropriate chunks, and does error correction,
  178452. * then calls the appropriate callback for the chunk if it is valid.
  178453. */
  178454. /* decode the IHDR chunk */
  178455. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  178456. png_uint_32 length));
  178457. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  178458. png_uint_32 length));
  178459. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  178460. png_uint_32 length));
  178461. #if defined(PNG_READ_bKGD_SUPPORTED)
  178462. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  178463. png_uint_32 length));
  178464. #endif
  178465. #if defined(PNG_READ_cHRM_SUPPORTED)
  178466. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  178467. png_uint_32 length));
  178468. #endif
  178469. #if defined(PNG_READ_gAMA_SUPPORTED)
  178470. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  178471. png_uint_32 length));
  178472. #endif
  178473. #if defined(PNG_READ_hIST_SUPPORTED)
  178474. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  178475. png_uint_32 length));
  178476. #endif
  178477. #if defined(PNG_READ_iCCP_SUPPORTED)
  178478. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  178479. png_uint_32 length));
  178480. #endif /* PNG_READ_iCCP_SUPPORTED */
  178481. #if defined(PNG_READ_iTXt_SUPPORTED)
  178482. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  178483. png_uint_32 length));
  178484. #endif
  178485. #if defined(PNG_READ_oFFs_SUPPORTED)
  178486. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  178487. png_uint_32 length));
  178488. #endif
  178489. #if defined(PNG_READ_pCAL_SUPPORTED)
  178490. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  178491. png_uint_32 length));
  178492. #endif
  178493. #if defined(PNG_READ_pHYs_SUPPORTED)
  178494. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  178495. png_uint_32 length));
  178496. #endif
  178497. #if defined(PNG_READ_sBIT_SUPPORTED)
  178498. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  178499. png_uint_32 length));
  178500. #endif
  178501. #if defined(PNG_READ_sCAL_SUPPORTED)
  178502. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  178503. png_uint_32 length));
  178504. #endif
  178505. #if defined(PNG_READ_sPLT_SUPPORTED)
  178506. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  178507. png_uint_32 length));
  178508. #endif /* PNG_READ_sPLT_SUPPORTED */
  178509. #if defined(PNG_READ_sRGB_SUPPORTED)
  178510. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  178511. png_uint_32 length));
  178512. #endif
  178513. #if defined(PNG_READ_tEXt_SUPPORTED)
  178514. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  178515. png_uint_32 length));
  178516. #endif
  178517. #if defined(PNG_READ_tIME_SUPPORTED)
  178518. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  178519. png_uint_32 length));
  178520. #endif
  178521. #if defined(PNG_READ_tRNS_SUPPORTED)
  178522. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  178523. png_uint_32 length));
  178524. #endif
  178525. #if defined(PNG_READ_zTXt_SUPPORTED)
  178526. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  178527. png_uint_32 length));
  178528. #endif
  178529. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  178530. png_infop info_ptr, png_uint_32 length));
  178531. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  178532. png_bytep chunk_name));
  178533. /* handle the transformations for reading and writing */
  178534. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  178535. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  178536. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  178537. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178538. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  178539. png_infop info_ptr));
  178540. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  178541. png_infop info_ptr));
  178542. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  178543. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  178544. png_uint_32 length));
  178545. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  178546. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  178547. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  178548. png_bytep buffer, png_size_t buffer_length));
  178549. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  178550. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  178551. png_bytep buffer, png_size_t buffer_length));
  178552. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  178553. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  178554. png_infop info_ptr, png_uint_32 length));
  178555. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  178556. png_infop info_ptr));
  178557. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  178558. png_infop info_ptr));
  178559. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  178560. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  178561. png_infop info_ptr));
  178562. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  178563. png_infop info_ptr));
  178564. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  178565. #if defined(PNG_READ_tEXt_SUPPORTED)
  178566. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  178567. png_infop info_ptr, png_uint_32 length));
  178568. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  178569. png_infop info_ptr));
  178570. #endif
  178571. #if defined(PNG_READ_zTXt_SUPPORTED)
  178572. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  178573. png_infop info_ptr, png_uint_32 length));
  178574. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  178575. png_infop info_ptr));
  178576. #endif
  178577. #if defined(PNG_READ_iTXt_SUPPORTED)
  178578. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  178579. png_infop info_ptr, png_uint_32 length));
  178580. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  178581. png_infop info_ptr));
  178582. #endif
  178583. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  178584. #ifdef PNG_MNG_FEATURES_SUPPORTED
  178585. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  178586. png_bytep row));
  178587. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  178588. png_bytep row));
  178589. #endif
  178590. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  178591. #if defined(PNG_MMX_CODE_SUPPORTED)
  178592. /* png.c */ /* PRIVATE */
  178593. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  178594. #endif
  178595. #endif
  178596. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  178597. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  178598. png_infop info_ptr));
  178599. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  178600. png_infop info_ptr));
  178601. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  178602. png_infop info_ptr));
  178603. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  178604. png_infop info_ptr));
  178605. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  178606. png_infop info_ptr));
  178607. #if defined(PNG_pHYs_SUPPORTED)
  178608. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  178609. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  178610. #endif /* PNG_pHYs_SUPPORTED */
  178611. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  178612. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  178613. #endif /* PNG_INTERNAL */
  178614. #ifdef __cplusplus
  178615. }
  178616. #endif
  178617. #endif /* PNG_VERSION_INFO_ONLY */
  178618. /* do not put anything past this line */
  178619. #endif /* PNG_H */
  178620. /********* End of inlined file: png.h *********/
  178621. #define PNG_NO_EXTERN
  178622. /********* Start of inlined file: png.c *********/
  178623. /* png.c - location for general purpose libpng functions
  178624. *
  178625. * Last changed in libpng 1.2.21 [October 4, 2007]
  178626. * For conditions of distribution and use, see copyright notice in png.h
  178627. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  178628. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  178629. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  178630. */
  178631. #define PNG_INTERNAL
  178632. #define PNG_NO_EXTERN
  178633. /* Generate a compiler error if there is an old png.h in the search path. */
  178634. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  178635. /* Version information for C files. This had better match the version
  178636. * string defined in png.h. */
  178637. #ifdef PNG_USE_GLOBAL_ARRAYS
  178638. /* png_libpng_ver was changed to a function in version 1.0.5c */
  178639. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  178640. #ifdef PNG_READ_SUPPORTED
  178641. /* png_sig was changed to a function in version 1.0.5c */
  178642. /* Place to hold the signature string for a PNG file. */
  178643. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  178644. #endif /* PNG_READ_SUPPORTED */
  178645. /* Invoke global declarations for constant strings for known chunk types */
  178646. PNG_IHDR;
  178647. PNG_IDAT;
  178648. PNG_IEND;
  178649. PNG_PLTE;
  178650. PNG_bKGD;
  178651. PNG_cHRM;
  178652. PNG_gAMA;
  178653. PNG_hIST;
  178654. PNG_iCCP;
  178655. PNG_iTXt;
  178656. PNG_oFFs;
  178657. PNG_pCAL;
  178658. PNG_sCAL;
  178659. PNG_pHYs;
  178660. PNG_sBIT;
  178661. PNG_sPLT;
  178662. PNG_sRGB;
  178663. PNG_tEXt;
  178664. PNG_tIME;
  178665. PNG_tRNS;
  178666. PNG_zTXt;
  178667. #ifdef PNG_READ_SUPPORTED
  178668. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  178669. /* start of interlace block */
  178670. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  178671. /* offset to next interlace block */
  178672. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  178673. /* start of interlace block in the y direction */
  178674. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  178675. /* offset to next interlace block in the y direction */
  178676. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  178677. /* Height of interlace block. This is not currently used - if you need
  178678. * it, uncomment it here and in png.h
  178679. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  178680. */
  178681. /* Mask to determine which pixels are valid in a pass */
  178682. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  178683. /* Mask to determine which pixels to overwrite while displaying */
  178684. PNG_CONST int FARDATA png_pass_dsp_mask[]
  178685. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  178686. #endif /* PNG_READ_SUPPORTED */
  178687. #endif /* PNG_USE_GLOBAL_ARRAYS */
  178688. /* Tells libpng that we have already handled the first "num_bytes" bytes
  178689. * of the PNG file signature. If the PNG data is embedded into another
  178690. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  178691. * or write any of the magic bytes before it starts on the IHDR.
  178692. */
  178693. #ifdef PNG_READ_SUPPORTED
  178694. void PNGAPI
  178695. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  178696. {
  178697. if(png_ptr == NULL) return;
  178698. png_debug(1, "in png_set_sig_bytes\n");
  178699. if (num_bytes > 8)
  178700. png_error(png_ptr, "Too many bytes for PNG signature.");
  178701. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  178702. }
  178703. /* Checks whether the supplied bytes match the PNG signature. We allow
  178704. * checking less than the full 8-byte signature so that those apps that
  178705. * already read the first few bytes of a file to determine the file type
  178706. * can simply check the remaining bytes for extra assurance. Returns
  178707. * an integer less than, equal to, or greater than zero if sig is found,
  178708. * respectively, to be less than, to match, or be greater than the correct
  178709. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  178710. */
  178711. int PNGAPI
  178712. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  178713. {
  178714. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  178715. if (num_to_check > 8)
  178716. num_to_check = 8;
  178717. else if (num_to_check < 1)
  178718. return (-1);
  178719. if (start > 7)
  178720. return (-1);
  178721. if (start + num_to_check > 8)
  178722. num_to_check = 8 - start;
  178723. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  178724. }
  178725. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  178726. /* (Obsolete) function to check signature bytes. It does not allow one
  178727. * to check a partial signature. This function might be removed in the
  178728. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  178729. */
  178730. int PNGAPI
  178731. png_check_sig(png_bytep sig, int num)
  178732. {
  178733. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  178734. }
  178735. #endif
  178736. #endif /* PNG_READ_SUPPORTED */
  178737. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  178738. /* Function to allocate memory for zlib and clear it to 0. */
  178739. #ifdef PNG_1_0_X
  178740. voidpf PNGAPI
  178741. #else
  178742. voidpf /* private */
  178743. #endif
  178744. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  178745. {
  178746. png_voidp ptr;
  178747. png_structp p=(png_structp)png_ptr;
  178748. png_uint_32 save_flags=p->flags;
  178749. png_uint_32 num_bytes;
  178750. if(png_ptr == NULL) return (NULL);
  178751. if (items > PNG_UINT_32_MAX/size)
  178752. {
  178753. png_warning (p, "Potential overflow in png_zalloc()");
  178754. return (NULL);
  178755. }
  178756. num_bytes = (png_uint_32)items * size;
  178757. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  178758. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  178759. p->flags=save_flags;
  178760. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  178761. if (ptr == NULL)
  178762. return ((voidpf)ptr);
  178763. if (num_bytes > (png_uint_32)0x8000L)
  178764. {
  178765. png_memset(ptr, 0, (png_size_t)0x8000L);
  178766. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  178767. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  178768. }
  178769. else
  178770. {
  178771. png_memset(ptr, 0, (png_size_t)num_bytes);
  178772. }
  178773. #endif
  178774. return ((voidpf)ptr);
  178775. }
  178776. /* function to free memory for zlib */
  178777. #ifdef PNG_1_0_X
  178778. void PNGAPI
  178779. #else
  178780. void /* private */
  178781. #endif
  178782. png_zfree(voidpf png_ptr, voidpf ptr)
  178783. {
  178784. png_free((png_structp)png_ptr, (png_voidp)ptr);
  178785. }
  178786. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  178787. * in case CRC is > 32 bits to leave the top bits 0.
  178788. */
  178789. void /* PRIVATE */
  178790. png_reset_crc(png_structp png_ptr)
  178791. {
  178792. png_ptr->crc = crc32(0, Z_NULL, 0);
  178793. }
  178794. /* Calculate the CRC over a section of data. We can only pass as
  178795. * much data to this routine as the largest single buffer size. We
  178796. * also check that this data will actually be used before going to the
  178797. * trouble of calculating it.
  178798. */
  178799. void /* PRIVATE */
  178800. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  178801. {
  178802. int need_crc = 1;
  178803. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  178804. {
  178805. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  178806. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  178807. need_crc = 0;
  178808. }
  178809. else /* critical */
  178810. {
  178811. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  178812. need_crc = 0;
  178813. }
  178814. if (need_crc)
  178815. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  178816. }
  178817. /* Allocate the memory for an info_struct for the application. We don't
  178818. * really need the png_ptr, but it could potentially be useful in the
  178819. * future. This should be used in favour of malloc(png_sizeof(png_info))
  178820. * and png_info_init() so that applications that want to use a shared
  178821. * libpng don't have to be recompiled if png_info changes size.
  178822. */
  178823. png_infop PNGAPI
  178824. png_create_info_struct(png_structp png_ptr)
  178825. {
  178826. png_infop info_ptr;
  178827. png_debug(1, "in png_create_info_struct\n");
  178828. if(png_ptr == NULL) return (NULL);
  178829. #ifdef PNG_USER_MEM_SUPPORTED
  178830. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  178831. png_ptr->malloc_fn, png_ptr->mem_ptr);
  178832. #else
  178833. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  178834. #endif
  178835. if (info_ptr != NULL)
  178836. png_info_init_3(&info_ptr, png_sizeof(png_info));
  178837. return (info_ptr);
  178838. }
  178839. /* This function frees the memory associated with a single info struct.
  178840. * Normally, one would use either png_destroy_read_struct() or
  178841. * png_destroy_write_struct() to free an info struct, but this may be
  178842. * useful for some applications.
  178843. */
  178844. void PNGAPI
  178845. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  178846. {
  178847. png_infop info_ptr = NULL;
  178848. if(png_ptr == NULL) return;
  178849. png_debug(1, "in png_destroy_info_struct\n");
  178850. if (info_ptr_ptr != NULL)
  178851. info_ptr = *info_ptr_ptr;
  178852. if (info_ptr != NULL)
  178853. {
  178854. png_info_destroy(png_ptr, info_ptr);
  178855. #ifdef PNG_USER_MEM_SUPPORTED
  178856. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  178857. png_ptr->mem_ptr);
  178858. #else
  178859. png_destroy_struct((png_voidp)info_ptr);
  178860. #endif
  178861. *info_ptr_ptr = NULL;
  178862. }
  178863. }
  178864. /* Initialize the info structure. This is now an internal function (0.89)
  178865. * and applications using it are urged to use png_create_info_struct()
  178866. * instead.
  178867. */
  178868. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  178869. #undef png_info_init
  178870. void PNGAPI
  178871. png_info_init(png_infop info_ptr)
  178872. {
  178873. /* We only come here via pre-1.0.12-compiled applications */
  178874. png_info_init_3(&info_ptr, 0);
  178875. }
  178876. #endif
  178877. void PNGAPI
  178878. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  178879. {
  178880. png_infop info_ptr = *ptr_ptr;
  178881. if(info_ptr == NULL) return;
  178882. png_debug(1, "in png_info_init_3\n");
  178883. if(png_sizeof(png_info) > png_info_struct_size)
  178884. {
  178885. png_destroy_struct(info_ptr);
  178886. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  178887. *ptr_ptr = info_ptr;
  178888. }
  178889. /* set everything to 0 */
  178890. png_memset(info_ptr, 0, png_sizeof (png_info));
  178891. }
  178892. #ifdef PNG_FREE_ME_SUPPORTED
  178893. void PNGAPI
  178894. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  178895. int freer, png_uint_32 mask)
  178896. {
  178897. png_debug(1, "in png_data_freer\n");
  178898. if (png_ptr == NULL || info_ptr == NULL)
  178899. return;
  178900. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  178901. info_ptr->free_me |= mask;
  178902. else if(freer == PNG_USER_WILL_FREE_DATA)
  178903. info_ptr->free_me &= ~mask;
  178904. else
  178905. png_warning(png_ptr,
  178906. "Unknown freer parameter in png_data_freer.");
  178907. }
  178908. #endif
  178909. void PNGAPI
  178910. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  178911. int num)
  178912. {
  178913. png_debug(1, "in png_free_data\n");
  178914. if (png_ptr == NULL || info_ptr == NULL)
  178915. return;
  178916. #if defined(PNG_TEXT_SUPPORTED)
  178917. /* free text item num or (if num == -1) all text items */
  178918. #ifdef PNG_FREE_ME_SUPPORTED
  178919. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  178920. #else
  178921. if (mask & PNG_FREE_TEXT)
  178922. #endif
  178923. {
  178924. if (num != -1)
  178925. {
  178926. if (info_ptr->text && info_ptr->text[num].key)
  178927. {
  178928. png_free(png_ptr, info_ptr->text[num].key);
  178929. info_ptr->text[num].key = NULL;
  178930. }
  178931. }
  178932. else
  178933. {
  178934. int i;
  178935. for (i = 0; i < info_ptr->num_text; i++)
  178936. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  178937. png_free(png_ptr, info_ptr->text);
  178938. info_ptr->text = NULL;
  178939. info_ptr->num_text=0;
  178940. }
  178941. }
  178942. #endif
  178943. #if defined(PNG_tRNS_SUPPORTED)
  178944. /* free any tRNS entry */
  178945. #ifdef PNG_FREE_ME_SUPPORTED
  178946. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  178947. #else
  178948. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  178949. #endif
  178950. {
  178951. png_free(png_ptr, info_ptr->trans);
  178952. info_ptr->valid &= ~PNG_INFO_tRNS;
  178953. #ifndef PNG_FREE_ME_SUPPORTED
  178954. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  178955. #endif
  178956. info_ptr->trans = NULL;
  178957. }
  178958. #endif
  178959. #if defined(PNG_sCAL_SUPPORTED)
  178960. /* free any sCAL entry */
  178961. #ifdef PNG_FREE_ME_SUPPORTED
  178962. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  178963. #else
  178964. if (mask & PNG_FREE_SCAL)
  178965. #endif
  178966. {
  178967. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  178968. png_free(png_ptr, info_ptr->scal_s_width);
  178969. png_free(png_ptr, info_ptr->scal_s_height);
  178970. info_ptr->scal_s_width = NULL;
  178971. info_ptr->scal_s_height = NULL;
  178972. #endif
  178973. info_ptr->valid &= ~PNG_INFO_sCAL;
  178974. }
  178975. #endif
  178976. #if defined(PNG_pCAL_SUPPORTED)
  178977. /* free any pCAL entry */
  178978. #ifdef PNG_FREE_ME_SUPPORTED
  178979. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  178980. #else
  178981. if (mask & PNG_FREE_PCAL)
  178982. #endif
  178983. {
  178984. png_free(png_ptr, info_ptr->pcal_purpose);
  178985. png_free(png_ptr, info_ptr->pcal_units);
  178986. info_ptr->pcal_purpose = NULL;
  178987. info_ptr->pcal_units = NULL;
  178988. if (info_ptr->pcal_params != NULL)
  178989. {
  178990. int i;
  178991. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  178992. {
  178993. png_free(png_ptr, info_ptr->pcal_params[i]);
  178994. info_ptr->pcal_params[i]=NULL;
  178995. }
  178996. png_free(png_ptr, info_ptr->pcal_params);
  178997. info_ptr->pcal_params = NULL;
  178998. }
  178999. info_ptr->valid &= ~PNG_INFO_pCAL;
  179000. }
  179001. #endif
  179002. #if defined(PNG_iCCP_SUPPORTED)
  179003. /* free any iCCP entry */
  179004. #ifdef PNG_FREE_ME_SUPPORTED
  179005. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  179006. #else
  179007. if (mask & PNG_FREE_ICCP)
  179008. #endif
  179009. {
  179010. png_free(png_ptr, info_ptr->iccp_name);
  179011. png_free(png_ptr, info_ptr->iccp_profile);
  179012. info_ptr->iccp_name = NULL;
  179013. info_ptr->iccp_profile = NULL;
  179014. info_ptr->valid &= ~PNG_INFO_iCCP;
  179015. }
  179016. #endif
  179017. #if defined(PNG_sPLT_SUPPORTED)
  179018. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  179019. #ifdef PNG_FREE_ME_SUPPORTED
  179020. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  179021. #else
  179022. if (mask & PNG_FREE_SPLT)
  179023. #endif
  179024. {
  179025. if (num != -1)
  179026. {
  179027. if(info_ptr->splt_palettes)
  179028. {
  179029. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  179030. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  179031. info_ptr->splt_palettes[num].name = NULL;
  179032. info_ptr->splt_palettes[num].entries = NULL;
  179033. }
  179034. }
  179035. else
  179036. {
  179037. if(info_ptr->splt_palettes_num)
  179038. {
  179039. int i;
  179040. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  179041. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  179042. png_free(png_ptr, info_ptr->splt_palettes);
  179043. info_ptr->splt_palettes = NULL;
  179044. info_ptr->splt_palettes_num = 0;
  179045. }
  179046. info_ptr->valid &= ~PNG_INFO_sPLT;
  179047. }
  179048. }
  179049. #endif
  179050. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179051. if(png_ptr->unknown_chunk.data)
  179052. {
  179053. png_free(png_ptr, png_ptr->unknown_chunk.data);
  179054. png_ptr->unknown_chunk.data = NULL;
  179055. }
  179056. #ifdef PNG_FREE_ME_SUPPORTED
  179057. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  179058. #else
  179059. if (mask & PNG_FREE_UNKN)
  179060. #endif
  179061. {
  179062. if (num != -1)
  179063. {
  179064. if(info_ptr->unknown_chunks)
  179065. {
  179066. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  179067. info_ptr->unknown_chunks[num].data = NULL;
  179068. }
  179069. }
  179070. else
  179071. {
  179072. int i;
  179073. if(info_ptr->unknown_chunks_num)
  179074. {
  179075. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  179076. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  179077. png_free(png_ptr, info_ptr->unknown_chunks);
  179078. info_ptr->unknown_chunks = NULL;
  179079. info_ptr->unknown_chunks_num = 0;
  179080. }
  179081. }
  179082. }
  179083. #endif
  179084. #if defined(PNG_hIST_SUPPORTED)
  179085. /* free any hIST entry */
  179086. #ifdef PNG_FREE_ME_SUPPORTED
  179087. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  179088. #else
  179089. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  179090. #endif
  179091. {
  179092. png_free(png_ptr, info_ptr->hist);
  179093. info_ptr->hist = NULL;
  179094. info_ptr->valid &= ~PNG_INFO_hIST;
  179095. #ifndef PNG_FREE_ME_SUPPORTED
  179096. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  179097. #endif
  179098. }
  179099. #endif
  179100. /* free any PLTE entry that was internally allocated */
  179101. #ifdef PNG_FREE_ME_SUPPORTED
  179102. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  179103. #else
  179104. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  179105. #endif
  179106. {
  179107. png_zfree(png_ptr, info_ptr->palette);
  179108. info_ptr->palette = NULL;
  179109. info_ptr->valid &= ~PNG_INFO_PLTE;
  179110. #ifndef PNG_FREE_ME_SUPPORTED
  179111. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  179112. #endif
  179113. info_ptr->num_palette = 0;
  179114. }
  179115. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  179116. /* free any image bits attached to the info structure */
  179117. #ifdef PNG_FREE_ME_SUPPORTED
  179118. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  179119. #else
  179120. if (mask & PNG_FREE_ROWS)
  179121. #endif
  179122. {
  179123. if(info_ptr->row_pointers)
  179124. {
  179125. int row;
  179126. for (row = 0; row < (int)info_ptr->height; row++)
  179127. {
  179128. png_free(png_ptr, info_ptr->row_pointers[row]);
  179129. info_ptr->row_pointers[row]=NULL;
  179130. }
  179131. png_free(png_ptr, info_ptr->row_pointers);
  179132. info_ptr->row_pointers=NULL;
  179133. }
  179134. info_ptr->valid &= ~PNG_INFO_IDAT;
  179135. }
  179136. #endif
  179137. #ifdef PNG_FREE_ME_SUPPORTED
  179138. if(num == -1)
  179139. info_ptr->free_me &= ~mask;
  179140. else
  179141. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  179142. #endif
  179143. }
  179144. /* This is an internal routine to free any memory that the info struct is
  179145. * pointing to before re-using it or freeing the struct itself. Recall
  179146. * that png_free() checks for NULL pointers for us.
  179147. */
  179148. void /* PRIVATE */
  179149. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  179150. {
  179151. png_debug(1, "in png_info_destroy\n");
  179152. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  179153. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179154. if (png_ptr->num_chunk_list)
  179155. {
  179156. png_free(png_ptr, png_ptr->chunk_list);
  179157. png_ptr->chunk_list=NULL;
  179158. png_ptr->num_chunk_list=0;
  179159. }
  179160. #endif
  179161. png_info_init_3(&info_ptr, png_sizeof(png_info));
  179162. }
  179163. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  179164. /* This function returns a pointer to the io_ptr associated with the user
  179165. * functions. The application should free any memory associated with this
  179166. * pointer before png_write_destroy() or png_read_destroy() are called.
  179167. */
  179168. png_voidp PNGAPI
  179169. png_get_io_ptr(png_structp png_ptr)
  179170. {
  179171. if(png_ptr == NULL) return (NULL);
  179172. return (png_ptr->io_ptr);
  179173. }
  179174. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  179175. #if !defined(PNG_NO_STDIO)
  179176. /* Initialize the default input/output functions for the PNG file. If you
  179177. * use your own read or write routines, you can call either png_set_read_fn()
  179178. * or png_set_write_fn() instead of png_init_io(). If you have defined
  179179. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  179180. * necessarily available.
  179181. */
  179182. void PNGAPI
  179183. png_init_io(png_structp png_ptr, png_FILE_p fp)
  179184. {
  179185. png_debug(1, "in png_init_io\n");
  179186. if(png_ptr == NULL) return;
  179187. png_ptr->io_ptr = (png_voidp)fp;
  179188. }
  179189. #endif
  179190. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  179191. /* Convert the supplied time into an RFC 1123 string suitable for use in
  179192. * a "Creation Time" or other text-based time string.
  179193. */
  179194. png_charp PNGAPI
  179195. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  179196. {
  179197. static PNG_CONST char short_months[12][4] =
  179198. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  179199. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  179200. if(png_ptr == NULL) return (NULL);
  179201. if (png_ptr->time_buffer == NULL)
  179202. {
  179203. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  179204. png_sizeof(char)));
  179205. }
  179206. #if defined(_WIN32_WCE)
  179207. {
  179208. wchar_t time_buf[29];
  179209. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  179210. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  179211. ptime->year, ptime->hour % 24, ptime->minute % 60,
  179212. ptime->second % 61);
  179213. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  179214. NULL, NULL);
  179215. }
  179216. #else
  179217. #ifdef USE_FAR_KEYWORD
  179218. {
  179219. char near_time_buf[29];
  179220. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  179221. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  179222. ptime->year, ptime->hour % 24, ptime->minute % 60,
  179223. ptime->second % 61);
  179224. png_memcpy(png_ptr->time_buffer, near_time_buf,
  179225. 29*png_sizeof(char));
  179226. }
  179227. #else
  179228. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  179229. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  179230. ptime->year, ptime->hour % 24, ptime->minute % 60,
  179231. ptime->second % 61);
  179232. #endif
  179233. #endif /* _WIN32_WCE */
  179234. return ((png_charp)png_ptr->time_buffer);
  179235. }
  179236. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  179237. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  179238. png_charp PNGAPI
  179239. png_get_copyright(png_structp png_ptr)
  179240. {
  179241. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  179242. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  179243. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  179244. Copyright (c) 1996-1997 Andreas Dilger\n\
  179245. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  179246. }
  179247. /* The following return the library version as a short string in the
  179248. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  179249. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  179250. * is defined in png.h.
  179251. * Note: now there is no difference between png_get_libpng_ver() and
  179252. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  179253. * it is guaranteed that png.c uses the correct version of png.h.
  179254. */
  179255. png_charp PNGAPI
  179256. png_get_libpng_ver(png_structp png_ptr)
  179257. {
  179258. /* Version of *.c files used when building libpng */
  179259. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  179260. return ((png_charp) PNG_LIBPNG_VER_STRING);
  179261. }
  179262. png_charp PNGAPI
  179263. png_get_header_ver(png_structp png_ptr)
  179264. {
  179265. /* Version of *.h files used when building libpng */
  179266. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  179267. return ((png_charp) PNG_LIBPNG_VER_STRING);
  179268. }
  179269. png_charp PNGAPI
  179270. png_get_header_version(png_structp png_ptr)
  179271. {
  179272. /* Returns longer string containing both version and date */
  179273. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  179274. return ((png_charp) PNG_HEADER_VERSION_STRING
  179275. #ifndef PNG_READ_SUPPORTED
  179276. " (NO READ SUPPORT)"
  179277. #endif
  179278. "\n");
  179279. }
  179280. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  179281. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  179282. int PNGAPI
  179283. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  179284. {
  179285. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  179286. int i;
  179287. png_bytep p;
  179288. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  179289. return 0;
  179290. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  179291. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  179292. if (!png_memcmp(chunk_name, p, 4))
  179293. return ((int)*(p+4));
  179294. return 0;
  179295. }
  179296. #endif
  179297. /* This function, added to libpng-1.0.6g, is untested. */
  179298. int PNGAPI
  179299. png_reset_zstream(png_structp png_ptr)
  179300. {
  179301. if (png_ptr == NULL) return Z_STREAM_ERROR;
  179302. return (inflateReset(&png_ptr->zstream));
  179303. }
  179304. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  179305. /* This function was added to libpng-1.0.7 */
  179306. png_uint_32 PNGAPI
  179307. png_access_version_number(void)
  179308. {
  179309. /* Version of *.c files used when building libpng */
  179310. return((png_uint_32) PNG_LIBPNG_VER);
  179311. }
  179312. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  179313. #if !defined(PNG_1_0_X)
  179314. /* this function was added to libpng 1.2.0 */
  179315. int PNGAPI
  179316. png_mmx_support(void)
  179317. {
  179318. /* obsolete, to be removed from libpng-1.4.0 */
  179319. return -1;
  179320. }
  179321. #endif /* PNG_1_0_X */
  179322. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  179323. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  179324. #ifdef PNG_SIZE_T
  179325. /* Added at libpng version 1.2.6 */
  179326. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  179327. png_size_t PNGAPI
  179328. png_convert_size(size_t size)
  179329. {
  179330. if (size > (png_size_t)-1)
  179331. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  179332. return ((png_size_t)size);
  179333. }
  179334. #endif /* PNG_SIZE_T */
  179335. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  179336. /********* End of inlined file: png.c *********/
  179337. /********* Start of inlined file: pngerror.c *********/
  179338. /* pngerror.c - stub functions for i/o and memory allocation
  179339. *
  179340. * Last changed in libpng 1.2.20 October 4, 2007
  179341. * For conditions of distribution and use, see copyright notice in png.h
  179342. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179343. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179344. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179345. *
  179346. * This file provides a location for all error handling. Users who
  179347. * need special error handling are expected to write replacement functions
  179348. * and use png_set_error_fn() to use those functions. See the instructions
  179349. * at each function.
  179350. */
  179351. #define PNG_INTERNAL
  179352. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  179353. static void /* PRIVATE */
  179354. png_default_error PNGARG((png_structp png_ptr,
  179355. png_const_charp error_message));
  179356. #ifndef PNG_NO_WARNINGS
  179357. static void /* PRIVATE */
  179358. png_default_warning PNGARG((png_structp png_ptr,
  179359. png_const_charp warning_message));
  179360. #endif /* PNG_NO_WARNINGS */
  179361. /* This function is called whenever there is a fatal error. This function
  179362. * should not be changed. If there is a need to handle errors differently,
  179363. * you should supply a replacement error function and use png_set_error_fn()
  179364. * to replace the error function at run-time.
  179365. */
  179366. #ifndef PNG_NO_ERROR_TEXT
  179367. void PNGAPI
  179368. png_error(png_structp png_ptr, png_const_charp error_message)
  179369. {
  179370. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  179371. char msg[16];
  179372. if (png_ptr != NULL)
  179373. {
  179374. if (png_ptr->flags&
  179375. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  179376. {
  179377. if (*error_message == '#')
  179378. {
  179379. int offset;
  179380. for (offset=1; offset<15; offset++)
  179381. if (*(error_message+offset) == ' ')
  179382. break;
  179383. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  179384. {
  179385. int i;
  179386. for (i=0; i<offset-1; i++)
  179387. msg[i]=error_message[i+1];
  179388. msg[i]='\0';
  179389. error_message=msg;
  179390. }
  179391. else
  179392. error_message+=offset;
  179393. }
  179394. else
  179395. {
  179396. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  179397. {
  179398. msg[0]='0';
  179399. msg[1]='\0';
  179400. error_message=msg;
  179401. }
  179402. }
  179403. }
  179404. }
  179405. #endif
  179406. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  179407. (*(png_ptr->error_fn))(png_ptr, error_message);
  179408. /* If the custom handler doesn't exist, or if it returns,
  179409. use the default handler, which will not return. */
  179410. png_default_error(png_ptr, error_message);
  179411. }
  179412. #else
  179413. void PNGAPI
  179414. png_err(png_structp png_ptr)
  179415. {
  179416. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  179417. (*(png_ptr->error_fn))(png_ptr, '\0');
  179418. /* If the custom handler doesn't exist, or if it returns,
  179419. use the default handler, which will not return. */
  179420. png_default_error(png_ptr, '\0');
  179421. }
  179422. #endif /* PNG_NO_ERROR_TEXT */
  179423. #ifndef PNG_NO_WARNINGS
  179424. /* This function is called whenever there is a non-fatal error. This function
  179425. * should not be changed. If there is a need to handle warnings differently,
  179426. * you should supply a replacement warning function and use
  179427. * png_set_error_fn() to replace the warning function at run-time.
  179428. */
  179429. void PNGAPI
  179430. png_warning(png_structp png_ptr, png_const_charp warning_message)
  179431. {
  179432. int offset = 0;
  179433. if (png_ptr != NULL)
  179434. {
  179435. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  179436. if (png_ptr->flags&
  179437. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  179438. #endif
  179439. {
  179440. if (*warning_message == '#')
  179441. {
  179442. for (offset=1; offset<15; offset++)
  179443. if (*(warning_message+offset) == ' ')
  179444. break;
  179445. }
  179446. }
  179447. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  179448. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  179449. }
  179450. else
  179451. png_default_warning(png_ptr, warning_message+offset);
  179452. }
  179453. #endif /* PNG_NO_WARNINGS */
  179454. /* These utilities are used internally to build an error message that relates
  179455. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  179456. * this is used to prefix the message. The message is limited in length
  179457. * to 63 bytes, the name characters are output as hex digits wrapped in []
  179458. * if the character is invalid.
  179459. */
  179460. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  179461. /*static PNG_CONST char png_digit[16] = {
  179462. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  179463. 'A', 'B', 'C', 'D', 'E', 'F'
  179464. };*/
  179465. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  179466. static void /* PRIVATE */
  179467. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  179468. error_message)
  179469. {
  179470. int iout = 0, iin = 0;
  179471. while (iin < 4)
  179472. {
  179473. int c = png_ptr->chunk_name[iin++];
  179474. if (isnonalpha(c))
  179475. {
  179476. buffer[iout++] = '[';
  179477. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  179478. buffer[iout++] = png_digit[c & 0x0f];
  179479. buffer[iout++] = ']';
  179480. }
  179481. else
  179482. {
  179483. buffer[iout++] = (png_byte)c;
  179484. }
  179485. }
  179486. if (error_message == NULL)
  179487. buffer[iout] = 0;
  179488. else
  179489. {
  179490. buffer[iout++] = ':';
  179491. buffer[iout++] = ' ';
  179492. png_strncpy(buffer+iout, error_message, 63);
  179493. buffer[iout+63] = 0;
  179494. }
  179495. }
  179496. #ifdef PNG_READ_SUPPORTED
  179497. void PNGAPI
  179498. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  179499. {
  179500. char msg[18+64];
  179501. if (png_ptr == NULL)
  179502. png_error(png_ptr, error_message);
  179503. else
  179504. {
  179505. png_format_buffer(png_ptr, msg, error_message);
  179506. png_error(png_ptr, msg);
  179507. }
  179508. }
  179509. #endif /* PNG_READ_SUPPORTED */
  179510. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  179511. #ifndef PNG_NO_WARNINGS
  179512. void PNGAPI
  179513. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  179514. {
  179515. char msg[18+64];
  179516. if (png_ptr == NULL)
  179517. png_warning(png_ptr, warning_message);
  179518. else
  179519. {
  179520. png_format_buffer(png_ptr, msg, warning_message);
  179521. png_warning(png_ptr, msg);
  179522. }
  179523. }
  179524. #endif /* PNG_NO_WARNINGS */
  179525. /* This is the default error handling function. Note that replacements for
  179526. * this function MUST NOT RETURN, or the program will likely crash. This
  179527. * function is used by default, or if the program supplies NULL for the
  179528. * error function pointer in png_set_error_fn().
  179529. */
  179530. static void /* PRIVATE */
  179531. png_default_error(png_structp png_ptr, png_const_charp error_message)
  179532. {
  179533. #ifndef PNG_NO_CONSOLE_IO
  179534. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  179535. if (*error_message == '#')
  179536. {
  179537. int offset;
  179538. char error_number[16];
  179539. for (offset=0; offset<15; offset++)
  179540. {
  179541. error_number[offset] = *(error_message+offset+1);
  179542. if (*(error_message+offset) == ' ')
  179543. break;
  179544. }
  179545. if((offset > 1) && (offset < 15))
  179546. {
  179547. error_number[offset-1]='\0';
  179548. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  179549. error_message+offset);
  179550. }
  179551. else
  179552. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  179553. }
  179554. else
  179555. #endif
  179556. fprintf(stderr, "libpng error: %s\n", error_message);
  179557. #endif
  179558. #ifdef PNG_SETJMP_SUPPORTED
  179559. if (png_ptr)
  179560. {
  179561. # ifdef USE_FAR_KEYWORD
  179562. {
  179563. jmp_buf jmpbuf;
  179564. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  179565. longjmp(jmpbuf, 1);
  179566. }
  179567. # else
  179568. longjmp(png_ptr->jmpbuf, 1);
  179569. # endif
  179570. }
  179571. #else
  179572. PNG_ABORT();
  179573. #endif
  179574. #ifdef PNG_NO_CONSOLE_IO
  179575. error_message = error_message; /* make compiler happy */
  179576. #endif
  179577. }
  179578. #ifndef PNG_NO_WARNINGS
  179579. /* This function is called when there is a warning, but the library thinks
  179580. * it can continue anyway. Replacement functions don't have to do anything
  179581. * here if you don't want them to. In the default configuration, png_ptr is
  179582. * not used, but it is passed in case it may be useful.
  179583. */
  179584. static void /* PRIVATE */
  179585. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  179586. {
  179587. #ifndef PNG_NO_CONSOLE_IO
  179588. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  179589. if (*warning_message == '#')
  179590. {
  179591. int offset;
  179592. char warning_number[16];
  179593. for (offset=0; offset<15; offset++)
  179594. {
  179595. warning_number[offset]=*(warning_message+offset+1);
  179596. if (*(warning_message+offset) == ' ')
  179597. break;
  179598. }
  179599. if((offset > 1) && (offset < 15))
  179600. {
  179601. warning_number[offset-1]='\0';
  179602. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  179603. warning_message+offset);
  179604. }
  179605. else
  179606. fprintf(stderr, "libpng warning: %s\n", warning_message);
  179607. }
  179608. else
  179609. # endif
  179610. fprintf(stderr, "libpng warning: %s\n", warning_message);
  179611. #else
  179612. warning_message = warning_message; /* make compiler happy */
  179613. #endif
  179614. png_ptr = png_ptr; /* make compiler happy */
  179615. }
  179616. #endif /* PNG_NO_WARNINGS */
  179617. /* This function is called when the application wants to use another method
  179618. * of handling errors and warnings. Note that the error function MUST NOT
  179619. * return to the calling routine or serious problems will occur. The return
  179620. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  179621. */
  179622. void PNGAPI
  179623. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  179624. png_error_ptr error_fn, png_error_ptr warning_fn)
  179625. {
  179626. if (png_ptr == NULL)
  179627. return;
  179628. png_ptr->error_ptr = error_ptr;
  179629. png_ptr->error_fn = error_fn;
  179630. png_ptr->warning_fn = warning_fn;
  179631. }
  179632. /* This function returns a pointer to the error_ptr associated with the user
  179633. * functions. The application should free any memory associated with this
  179634. * pointer before png_write_destroy and png_read_destroy are called.
  179635. */
  179636. png_voidp PNGAPI
  179637. png_get_error_ptr(png_structp png_ptr)
  179638. {
  179639. if (png_ptr == NULL)
  179640. return NULL;
  179641. return ((png_voidp)png_ptr->error_ptr);
  179642. }
  179643. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  179644. void PNGAPI
  179645. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  179646. {
  179647. if(png_ptr != NULL)
  179648. {
  179649. png_ptr->flags &=
  179650. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  179651. }
  179652. }
  179653. #endif
  179654. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  179655. /********* End of inlined file: pngerror.c *********/
  179656. /********* Start of inlined file: pngget.c *********/
  179657. /* pngget.c - retrieval of values from info struct
  179658. *
  179659. * Last changed in libpng 1.2.15 January 5, 2007
  179660. * For conditions of distribution and use, see copyright notice in png.h
  179661. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179662. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179663. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179664. */
  179665. #define PNG_INTERNAL
  179666. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  179667. png_uint_32 PNGAPI
  179668. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  179669. {
  179670. if (png_ptr != NULL && info_ptr != NULL)
  179671. return(info_ptr->valid & flag);
  179672. else
  179673. return(0);
  179674. }
  179675. png_uint_32 PNGAPI
  179676. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  179677. {
  179678. if (png_ptr != NULL && info_ptr != NULL)
  179679. return(info_ptr->rowbytes);
  179680. else
  179681. return(0);
  179682. }
  179683. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  179684. png_bytepp PNGAPI
  179685. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  179686. {
  179687. if (png_ptr != NULL && info_ptr != NULL)
  179688. return(info_ptr->row_pointers);
  179689. else
  179690. return(0);
  179691. }
  179692. #endif
  179693. #ifdef PNG_EASY_ACCESS_SUPPORTED
  179694. /* easy access to info, added in libpng-0.99 */
  179695. png_uint_32 PNGAPI
  179696. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  179697. {
  179698. if (png_ptr != NULL && info_ptr != NULL)
  179699. {
  179700. return info_ptr->width;
  179701. }
  179702. return (0);
  179703. }
  179704. png_uint_32 PNGAPI
  179705. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  179706. {
  179707. if (png_ptr != NULL && info_ptr != NULL)
  179708. {
  179709. return info_ptr->height;
  179710. }
  179711. return (0);
  179712. }
  179713. png_byte PNGAPI
  179714. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  179715. {
  179716. if (png_ptr != NULL && info_ptr != NULL)
  179717. {
  179718. return info_ptr->bit_depth;
  179719. }
  179720. return (0);
  179721. }
  179722. png_byte PNGAPI
  179723. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  179724. {
  179725. if (png_ptr != NULL && info_ptr != NULL)
  179726. {
  179727. return info_ptr->color_type;
  179728. }
  179729. return (0);
  179730. }
  179731. png_byte PNGAPI
  179732. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  179733. {
  179734. if (png_ptr != NULL && info_ptr != NULL)
  179735. {
  179736. return info_ptr->filter_type;
  179737. }
  179738. return (0);
  179739. }
  179740. png_byte PNGAPI
  179741. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  179742. {
  179743. if (png_ptr != NULL && info_ptr != NULL)
  179744. {
  179745. return info_ptr->interlace_type;
  179746. }
  179747. return (0);
  179748. }
  179749. png_byte PNGAPI
  179750. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  179751. {
  179752. if (png_ptr != NULL && info_ptr != NULL)
  179753. {
  179754. return info_ptr->compression_type;
  179755. }
  179756. return (0);
  179757. }
  179758. png_uint_32 PNGAPI
  179759. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  179760. {
  179761. if (png_ptr != NULL && info_ptr != NULL)
  179762. #if defined(PNG_pHYs_SUPPORTED)
  179763. if (info_ptr->valid & PNG_INFO_pHYs)
  179764. {
  179765. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  179766. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  179767. return (0);
  179768. else return (info_ptr->x_pixels_per_unit);
  179769. }
  179770. #else
  179771. return (0);
  179772. #endif
  179773. return (0);
  179774. }
  179775. png_uint_32 PNGAPI
  179776. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  179777. {
  179778. if (png_ptr != NULL && info_ptr != NULL)
  179779. #if defined(PNG_pHYs_SUPPORTED)
  179780. if (info_ptr->valid & PNG_INFO_pHYs)
  179781. {
  179782. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  179783. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  179784. return (0);
  179785. else return (info_ptr->y_pixels_per_unit);
  179786. }
  179787. #else
  179788. return (0);
  179789. #endif
  179790. return (0);
  179791. }
  179792. png_uint_32 PNGAPI
  179793. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  179794. {
  179795. if (png_ptr != NULL && info_ptr != NULL)
  179796. #if defined(PNG_pHYs_SUPPORTED)
  179797. if (info_ptr->valid & PNG_INFO_pHYs)
  179798. {
  179799. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  179800. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  179801. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  179802. return (0);
  179803. else return (info_ptr->x_pixels_per_unit);
  179804. }
  179805. #else
  179806. return (0);
  179807. #endif
  179808. return (0);
  179809. }
  179810. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179811. float PNGAPI
  179812. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  179813. {
  179814. if (png_ptr != NULL && info_ptr != NULL)
  179815. #if defined(PNG_pHYs_SUPPORTED)
  179816. if (info_ptr->valid & PNG_INFO_pHYs)
  179817. {
  179818. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  179819. if (info_ptr->x_pixels_per_unit == 0)
  179820. return ((float)0.0);
  179821. else
  179822. return ((float)((float)info_ptr->y_pixels_per_unit
  179823. /(float)info_ptr->x_pixels_per_unit));
  179824. }
  179825. #else
  179826. return (0.0);
  179827. #endif
  179828. return ((float)0.0);
  179829. }
  179830. #endif
  179831. png_int_32 PNGAPI
  179832. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  179833. {
  179834. if (png_ptr != NULL && info_ptr != NULL)
  179835. #if defined(PNG_oFFs_SUPPORTED)
  179836. if (info_ptr->valid & PNG_INFO_oFFs)
  179837. {
  179838. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  179839. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  179840. return (0);
  179841. else return (info_ptr->x_offset);
  179842. }
  179843. #else
  179844. return (0);
  179845. #endif
  179846. return (0);
  179847. }
  179848. png_int_32 PNGAPI
  179849. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  179850. {
  179851. if (png_ptr != NULL && info_ptr != NULL)
  179852. #if defined(PNG_oFFs_SUPPORTED)
  179853. if (info_ptr->valid & PNG_INFO_oFFs)
  179854. {
  179855. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  179856. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  179857. return (0);
  179858. else return (info_ptr->y_offset);
  179859. }
  179860. #else
  179861. return (0);
  179862. #endif
  179863. return (0);
  179864. }
  179865. png_int_32 PNGAPI
  179866. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  179867. {
  179868. if (png_ptr != NULL && info_ptr != NULL)
  179869. #if defined(PNG_oFFs_SUPPORTED)
  179870. if (info_ptr->valid & PNG_INFO_oFFs)
  179871. {
  179872. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  179873. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  179874. return (0);
  179875. else return (info_ptr->x_offset);
  179876. }
  179877. #else
  179878. return (0);
  179879. #endif
  179880. return (0);
  179881. }
  179882. png_int_32 PNGAPI
  179883. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  179884. {
  179885. if (png_ptr != NULL && info_ptr != NULL)
  179886. #if defined(PNG_oFFs_SUPPORTED)
  179887. if (info_ptr->valid & PNG_INFO_oFFs)
  179888. {
  179889. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  179890. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  179891. return (0);
  179892. else return (info_ptr->y_offset);
  179893. }
  179894. #else
  179895. return (0);
  179896. #endif
  179897. return (0);
  179898. }
  179899. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  179900. png_uint_32 PNGAPI
  179901. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  179902. {
  179903. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  179904. *.0254 +.5));
  179905. }
  179906. png_uint_32 PNGAPI
  179907. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  179908. {
  179909. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  179910. *.0254 +.5));
  179911. }
  179912. png_uint_32 PNGAPI
  179913. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  179914. {
  179915. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  179916. *.0254 +.5));
  179917. }
  179918. float PNGAPI
  179919. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  179920. {
  179921. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  179922. *.00003937);
  179923. }
  179924. float PNGAPI
  179925. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  179926. {
  179927. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  179928. *.00003937);
  179929. }
  179930. #if defined(PNG_pHYs_SUPPORTED)
  179931. png_uint_32 PNGAPI
  179932. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  179933. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  179934. {
  179935. png_uint_32 retval = 0;
  179936. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  179937. {
  179938. png_debug1(1, "in %s retrieval function\n", "pHYs");
  179939. if (res_x != NULL)
  179940. {
  179941. *res_x = info_ptr->x_pixels_per_unit;
  179942. retval |= PNG_INFO_pHYs;
  179943. }
  179944. if (res_y != NULL)
  179945. {
  179946. *res_y = info_ptr->y_pixels_per_unit;
  179947. retval |= PNG_INFO_pHYs;
  179948. }
  179949. if (unit_type != NULL)
  179950. {
  179951. *unit_type = (int)info_ptr->phys_unit_type;
  179952. retval |= PNG_INFO_pHYs;
  179953. if(*unit_type == 1)
  179954. {
  179955. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  179956. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  179957. }
  179958. }
  179959. }
  179960. return (retval);
  179961. }
  179962. #endif /* PNG_pHYs_SUPPORTED */
  179963. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  179964. /* png_get_channels really belongs in here, too, but it's been around longer */
  179965. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  179966. png_byte PNGAPI
  179967. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  179968. {
  179969. if (png_ptr != NULL && info_ptr != NULL)
  179970. return(info_ptr->channels);
  179971. else
  179972. return (0);
  179973. }
  179974. png_bytep PNGAPI
  179975. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  179976. {
  179977. if (png_ptr != NULL && info_ptr != NULL)
  179978. return(info_ptr->signature);
  179979. else
  179980. return (NULL);
  179981. }
  179982. #if defined(PNG_bKGD_SUPPORTED)
  179983. png_uint_32 PNGAPI
  179984. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  179985. png_color_16p *background)
  179986. {
  179987. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  179988. && background != NULL)
  179989. {
  179990. png_debug1(1, "in %s retrieval function\n", "bKGD");
  179991. *background = &(info_ptr->background);
  179992. return (PNG_INFO_bKGD);
  179993. }
  179994. return (0);
  179995. }
  179996. #endif
  179997. #if defined(PNG_cHRM_SUPPORTED)
  179998. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179999. png_uint_32 PNGAPI
  180000. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  180001. double *white_x, double *white_y, double *red_x, double *red_y,
  180002. double *green_x, double *green_y, double *blue_x, double *blue_y)
  180003. {
  180004. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  180005. {
  180006. png_debug1(1, "in %s retrieval function\n", "cHRM");
  180007. if (white_x != NULL)
  180008. *white_x = (double)info_ptr->x_white;
  180009. if (white_y != NULL)
  180010. *white_y = (double)info_ptr->y_white;
  180011. if (red_x != NULL)
  180012. *red_x = (double)info_ptr->x_red;
  180013. if (red_y != NULL)
  180014. *red_y = (double)info_ptr->y_red;
  180015. if (green_x != NULL)
  180016. *green_x = (double)info_ptr->x_green;
  180017. if (green_y != NULL)
  180018. *green_y = (double)info_ptr->y_green;
  180019. if (blue_x != NULL)
  180020. *blue_x = (double)info_ptr->x_blue;
  180021. if (blue_y != NULL)
  180022. *blue_y = (double)info_ptr->y_blue;
  180023. return (PNG_INFO_cHRM);
  180024. }
  180025. return (0);
  180026. }
  180027. #endif
  180028. #ifdef PNG_FIXED_POINT_SUPPORTED
  180029. png_uint_32 PNGAPI
  180030. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  180031. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  180032. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  180033. png_fixed_point *blue_x, png_fixed_point *blue_y)
  180034. {
  180035. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  180036. {
  180037. png_debug1(1, "in %s retrieval function\n", "cHRM");
  180038. if (white_x != NULL)
  180039. *white_x = info_ptr->int_x_white;
  180040. if (white_y != NULL)
  180041. *white_y = info_ptr->int_y_white;
  180042. if (red_x != NULL)
  180043. *red_x = info_ptr->int_x_red;
  180044. if (red_y != NULL)
  180045. *red_y = info_ptr->int_y_red;
  180046. if (green_x != NULL)
  180047. *green_x = info_ptr->int_x_green;
  180048. if (green_y != NULL)
  180049. *green_y = info_ptr->int_y_green;
  180050. if (blue_x != NULL)
  180051. *blue_x = info_ptr->int_x_blue;
  180052. if (blue_y != NULL)
  180053. *blue_y = info_ptr->int_y_blue;
  180054. return (PNG_INFO_cHRM);
  180055. }
  180056. return (0);
  180057. }
  180058. #endif
  180059. #endif
  180060. #if defined(PNG_gAMA_SUPPORTED)
  180061. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180062. png_uint_32 PNGAPI
  180063. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  180064. {
  180065. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  180066. && file_gamma != NULL)
  180067. {
  180068. png_debug1(1, "in %s retrieval function\n", "gAMA");
  180069. *file_gamma = (double)info_ptr->gamma;
  180070. return (PNG_INFO_gAMA);
  180071. }
  180072. return (0);
  180073. }
  180074. #endif
  180075. #ifdef PNG_FIXED_POINT_SUPPORTED
  180076. png_uint_32 PNGAPI
  180077. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  180078. png_fixed_point *int_file_gamma)
  180079. {
  180080. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  180081. && int_file_gamma != NULL)
  180082. {
  180083. png_debug1(1, "in %s retrieval function\n", "gAMA");
  180084. *int_file_gamma = info_ptr->int_gamma;
  180085. return (PNG_INFO_gAMA);
  180086. }
  180087. return (0);
  180088. }
  180089. #endif
  180090. #endif
  180091. #if defined(PNG_sRGB_SUPPORTED)
  180092. png_uint_32 PNGAPI
  180093. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  180094. {
  180095. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  180096. && file_srgb_intent != NULL)
  180097. {
  180098. png_debug1(1, "in %s retrieval function\n", "sRGB");
  180099. *file_srgb_intent = (int)info_ptr->srgb_intent;
  180100. return (PNG_INFO_sRGB);
  180101. }
  180102. return (0);
  180103. }
  180104. #endif
  180105. #if defined(PNG_iCCP_SUPPORTED)
  180106. png_uint_32 PNGAPI
  180107. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  180108. png_charpp name, int *compression_type,
  180109. png_charpp profile, png_uint_32 *proflen)
  180110. {
  180111. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  180112. && name != NULL && profile != NULL && proflen != NULL)
  180113. {
  180114. png_debug1(1, "in %s retrieval function\n", "iCCP");
  180115. *name = info_ptr->iccp_name;
  180116. *profile = info_ptr->iccp_profile;
  180117. /* compression_type is a dummy so the API won't have to change
  180118. if we introduce multiple compression types later. */
  180119. *proflen = (int)info_ptr->iccp_proflen;
  180120. *compression_type = (int)info_ptr->iccp_compression;
  180121. return (PNG_INFO_iCCP);
  180122. }
  180123. return (0);
  180124. }
  180125. #endif
  180126. #if defined(PNG_sPLT_SUPPORTED)
  180127. png_uint_32 PNGAPI
  180128. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  180129. png_sPLT_tpp spalettes)
  180130. {
  180131. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  180132. {
  180133. *spalettes = info_ptr->splt_palettes;
  180134. return ((png_uint_32)info_ptr->splt_palettes_num);
  180135. }
  180136. return (0);
  180137. }
  180138. #endif
  180139. #if defined(PNG_hIST_SUPPORTED)
  180140. png_uint_32 PNGAPI
  180141. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  180142. {
  180143. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  180144. && hist != NULL)
  180145. {
  180146. png_debug1(1, "in %s retrieval function\n", "hIST");
  180147. *hist = info_ptr->hist;
  180148. return (PNG_INFO_hIST);
  180149. }
  180150. return (0);
  180151. }
  180152. #endif
  180153. png_uint_32 PNGAPI
  180154. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  180155. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  180156. int *color_type, int *interlace_type, int *compression_type,
  180157. int *filter_type)
  180158. {
  180159. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  180160. bit_depth != NULL && color_type != NULL)
  180161. {
  180162. png_debug1(1, "in %s retrieval function\n", "IHDR");
  180163. *width = info_ptr->width;
  180164. *height = info_ptr->height;
  180165. *bit_depth = info_ptr->bit_depth;
  180166. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  180167. png_error(png_ptr, "Invalid bit depth");
  180168. *color_type = info_ptr->color_type;
  180169. if (info_ptr->color_type > 6)
  180170. png_error(png_ptr, "Invalid color type");
  180171. if (compression_type != NULL)
  180172. *compression_type = info_ptr->compression_type;
  180173. if (filter_type != NULL)
  180174. *filter_type = info_ptr->filter_type;
  180175. if (interlace_type != NULL)
  180176. *interlace_type = info_ptr->interlace_type;
  180177. /* check for potential overflow of rowbytes */
  180178. if (*width == 0 || *width > PNG_UINT_31_MAX)
  180179. png_error(png_ptr, "Invalid image width");
  180180. if (*height == 0 || *height > PNG_UINT_31_MAX)
  180181. png_error(png_ptr, "Invalid image height");
  180182. if (info_ptr->width > (PNG_UINT_32_MAX
  180183. >> 3) /* 8-byte RGBA pixels */
  180184. - 64 /* bigrowbuf hack */
  180185. - 1 /* filter byte */
  180186. - 7*8 /* rounding of width to multiple of 8 pixels */
  180187. - 8) /* extra max_pixel_depth pad */
  180188. {
  180189. png_warning(png_ptr,
  180190. "Width too large for libpng to process image data.");
  180191. }
  180192. return (1);
  180193. }
  180194. return (0);
  180195. }
  180196. #if defined(PNG_oFFs_SUPPORTED)
  180197. png_uint_32 PNGAPI
  180198. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  180199. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  180200. {
  180201. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  180202. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  180203. {
  180204. png_debug1(1, "in %s retrieval function\n", "oFFs");
  180205. *offset_x = info_ptr->x_offset;
  180206. *offset_y = info_ptr->y_offset;
  180207. *unit_type = (int)info_ptr->offset_unit_type;
  180208. return (PNG_INFO_oFFs);
  180209. }
  180210. return (0);
  180211. }
  180212. #endif
  180213. #if defined(PNG_pCAL_SUPPORTED)
  180214. png_uint_32 PNGAPI
  180215. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  180216. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  180217. png_charp *units, png_charpp *params)
  180218. {
  180219. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  180220. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  180221. nparams != NULL && units != NULL && params != NULL)
  180222. {
  180223. png_debug1(1, "in %s retrieval function\n", "pCAL");
  180224. *purpose = info_ptr->pcal_purpose;
  180225. *X0 = info_ptr->pcal_X0;
  180226. *X1 = info_ptr->pcal_X1;
  180227. *type = (int)info_ptr->pcal_type;
  180228. *nparams = (int)info_ptr->pcal_nparams;
  180229. *units = info_ptr->pcal_units;
  180230. *params = info_ptr->pcal_params;
  180231. return (PNG_INFO_pCAL);
  180232. }
  180233. return (0);
  180234. }
  180235. #endif
  180236. #if defined(PNG_sCAL_SUPPORTED)
  180237. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180238. png_uint_32 PNGAPI
  180239. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  180240. int *unit, double *width, double *height)
  180241. {
  180242. if (png_ptr != NULL && info_ptr != NULL &&
  180243. (info_ptr->valid & PNG_INFO_sCAL))
  180244. {
  180245. *unit = info_ptr->scal_unit;
  180246. *width = info_ptr->scal_pixel_width;
  180247. *height = info_ptr->scal_pixel_height;
  180248. return (PNG_INFO_sCAL);
  180249. }
  180250. return(0);
  180251. }
  180252. #else
  180253. #ifdef PNG_FIXED_POINT_SUPPORTED
  180254. png_uint_32 PNGAPI
  180255. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  180256. int *unit, png_charpp width, png_charpp height)
  180257. {
  180258. if (png_ptr != NULL && info_ptr != NULL &&
  180259. (info_ptr->valid & PNG_INFO_sCAL))
  180260. {
  180261. *unit = info_ptr->scal_unit;
  180262. *width = info_ptr->scal_s_width;
  180263. *height = info_ptr->scal_s_height;
  180264. return (PNG_INFO_sCAL);
  180265. }
  180266. return(0);
  180267. }
  180268. #endif
  180269. #endif
  180270. #endif
  180271. #if defined(PNG_pHYs_SUPPORTED)
  180272. png_uint_32 PNGAPI
  180273. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  180274. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  180275. {
  180276. png_uint_32 retval = 0;
  180277. if (png_ptr != NULL && info_ptr != NULL &&
  180278. (info_ptr->valid & PNG_INFO_pHYs))
  180279. {
  180280. png_debug1(1, "in %s retrieval function\n", "pHYs");
  180281. if (res_x != NULL)
  180282. {
  180283. *res_x = info_ptr->x_pixels_per_unit;
  180284. retval |= PNG_INFO_pHYs;
  180285. }
  180286. if (res_y != NULL)
  180287. {
  180288. *res_y = info_ptr->y_pixels_per_unit;
  180289. retval |= PNG_INFO_pHYs;
  180290. }
  180291. if (unit_type != NULL)
  180292. {
  180293. *unit_type = (int)info_ptr->phys_unit_type;
  180294. retval |= PNG_INFO_pHYs;
  180295. }
  180296. }
  180297. return (retval);
  180298. }
  180299. #endif
  180300. png_uint_32 PNGAPI
  180301. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  180302. int *num_palette)
  180303. {
  180304. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  180305. && palette != NULL)
  180306. {
  180307. png_debug1(1, "in %s retrieval function\n", "PLTE");
  180308. *palette = info_ptr->palette;
  180309. *num_palette = info_ptr->num_palette;
  180310. png_debug1(3, "num_palette = %d\n", *num_palette);
  180311. return (PNG_INFO_PLTE);
  180312. }
  180313. return (0);
  180314. }
  180315. #if defined(PNG_sBIT_SUPPORTED)
  180316. png_uint_32 PNGAPI
  180317. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  180318. {
  180319. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  180320. && sig_bit != NULL)
  180321. {
  180322. png_debug1(1, "in %s retrieval function\n", "sBIT");
  180323. *sig_bit = &(info_ptr->sig_bit);
  180324. return (PNG_INFO_sBIT);
  180325. }
  180326. return (0);
  180327. }
  180328. #endif
  180329. #if defined(PNG_TEXT_SUPPORTED)
  180330. png_uint_32 PNGAPI
  180331. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  180332. int *num_text)
  180333. {
  180334. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  180335. {
  180336. png_debug1(1, "in %s retrieval function\n",
  180337. (png_ptr->chunk_name[0] == '\0' ? "text"
  180338. : (png_const_charp)png_ptr->chunk_name));
  180339. if (text_ptr != NULL)
  180340. *text_ptr = info_ptr->text;
  180341. if (num_text != NULL)
  180342. *num_text = info_ptr->num_text;
  180343. return ((png_uint_32)info_ptr->num_text);
  180344. }
  180345. if (num_text != NULL)
  180346. *num_text = 0;
  180347. return(0);
  180348. }
  180349. #endif
  180350. #if defined(PNG_tIME_SUPPORTED)
  180351. png_uint_32 PNGAPI
  180352. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  180353. {
  180354. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  180355. && mod_time != NULL)
  180356. {
  180357. png_debug1(1, "in %s retrieval function\n", "tIME");
  180358. *mod_time = &(info_ptr->mod_time);
  180359. return (PNG_INFO_tIME);
  180360. }
  180361. return (0);
  180362. }
  180363. #endif
  180364. #if defined(PNG_tRNS_SUPPORTED)
  180365. png_uint_32 PNGAPI
  180366. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  180367. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  180368. {
  180369. png_uint_32 retval = 0;
  180370. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  180371. {
  180372. png_debug1(1, "in %s retrieval function\n", "tRNS");
  180373. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  180374. {
  180375. if (trans != NULL)
  180376. {
  180377. *trans = info_ptr->trans;
  180378. retval |= PNG_INFO_tRNS;
  180379. }
  180380. if (trans_values != NULL)
  180381. *trans_values = &(info_ptr->trans_values);
  180382. }
  180383. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  180384. {
  180385. if (trans_values != NULL)
  180386. {
  180387. *trans_values = &(info_ptr->trans_values);
  180388. retval |= PNG_INFO_tRNS;
  180389. }
  180390. if(trans != NULL)
  180391. *trans = NULL;
  180392. }
  180393. if(num_trans != NULL)
  180394. {
  180395. *num_trans = info_ptr->num_trans;
  180396. retval |= PNG_INFO_tRNS;
  180397. }
  180398. }
  180399. return (retval);
  180400. }
  180401. #endif
  180402. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  180403. png_uint_32 PNGAPI
  180404. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  180405. png_unknown_chunkpp unknowns)
  180406. {
  180407. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  180408. {
  180409. *unknowns = info_ptr->unknown_chunks;
  180410. return ((png_uint_32)info_ptr->unknown_chunks_num);
  180411. }
  180412. return (0);
  180413. }
  180414. #endif
  180415. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  180416. png_byte PNGAPI
  180417. png_get_rgb_to_gray_status (png_structp png_ptr)
  180418. {
  180419. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  180420. }
  180421. #endif
  180422. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  180423. png_voidp PNGAPI
  180424. png_get_user_chunk_ptr(png_structp png_ptr)
  180425. {
  180426. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  180427. }
  180428. #endif
  180429. #ifdef PNG_WRITE_SUPPORTED
  180430. png_uint_32 PNGAPI
  180431. png_get_compression_buffer_size(png_structp png_ptr)
  180432. {
  180433. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  180434. }
  180435. #endif
  180436. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  180437. #ifndef PNG_1_0_X
  180438. /* this function was added to libpng 1.2.0 and should exist by default */
  180439. png_uint_32 PNGAPI
  180440. png_get_asm_flags (png_structp png_ptr)
  180441. {
  180442. /* obsolete, to be removed from libpng-1.4.0 */
  180443. return (png_ptr? 0L: 0L);
  180444. }
  180445. /* this function was added to libpng 1.2.0 and should exist by default */
  180446. png_uint_32 PNGAPI
  180447. png_get_asm_flagmask (int flag_select)
  180448. {
  180449. /* obsolete, to be removed from libpng-1.4.0 */
  180450. flag_select=flag_select;
  180451. return 0L;
  180452. }
  180453. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  180454. /* this function was added to libpng 1.2.0 */
  180455. png_uint_32 PNGAPI
  180456. png_get_mmx_flagmask (int flag_select, int *compilerID)
  180457. {
  180458. /* obsolete, to be removed from libpng-1.4.0 */
  180459. flag_select=flag_select;
  180460. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  180461. return 0L;
  180462. }
  180463. /* this function was added to libpng 1.2.0 */
  180464. png_byte PNGAPI
  180465. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  180466. {
  180467. /* obsolete, to be removed from libpng-1.4.0 */
  180468. return (png_ptr? 0: 0);
  180469. }
  180470. /* this function was added to libpng 1.2.0 */
  180471. png_uint_32 PNGAPI
  180472. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  180473. {
  180474. /* obsolete, to be removed from libpng-1.4.0 */
  180475. return (png_ptr? 0L: 0L);
  180476. }
  180477. #endif /* ?PNG_1_0_X */
  180478. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  180479. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  180480. /* these functions were added to libpng 1.2.6 */
  180481. png_uint_32 PNGAPI
  180482. png_get_user_width_max (png_structp png_ptr)
  180483. {
  180484. return (png_ptr? png_ptr->user_width_max : 0);
  180485. }
  180486. png_uint_32 PNGAPI
  180487. png_get_user_height_max (png_structp png_ptr)
  180488. {
  180489. return (png_ptr? png_ptr->user_height_max : 0);
  180490. }
  180491. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  180492. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  180493. /********* End of inlined file: pngget.c *********/
  180494. /********* Start of inlined file: pngmem.c *********/
  180495. /* pngmem.c - stub functions for memory allocation
  180496. *
  180497. * Last changed in libpng 1.2.13 November 13, 2006
  180498. * For conditions of distribution and use, see copyright notice in png.h
  180499. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  180500. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180501. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180502. *
  180503. * This file provides a location for all memory allocation. Users who
  180504. * need special memory handling are expected to supply replacement
  180505. * functions for png_malloc() and png_free(), and to use
  180506. * png_create_read_struct_2() and png_create_write_struct_2() to
  180507. * identify the replacement functions.
  180508. */
  180509. #define PNG_INTERNAL
  180510. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180511. /* Borland DOS special memory handler */
  180512. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  180513. /* if you change this, be sure to change the one in png.h also */
  180514. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  180515. by a single call to calloc() if this is thought to improve performance. */
  180516. png_voidp /* PRIVATE */
  180517. png_create_struct(int type)
  180518. {
  180519. #ifdef PNG_USER_MEM_SUPPORTED
  180520. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  180521. }
  180522. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  180523. png_voidp /* PRIVATE */
  180524. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  180525. {
  180526. #endif /* PNG_USER_MEM_SUPPORTED */
  180527. png_size_t size;
  180528. png_voidp struct_ptr;
  180529. if (type == PNG_STRUCT_INFO)
  180530. size = png_sizeof(png_info);
  180531. else if (type == PNG_STRUCT_PNG)
  180532. size = png_sizeof(png_struct);
  180533. else
  180534. return (png_get_copyright(NULL));
  180535. #ifdef PNG_USER_MEM_SUPPORTED
  180536. if(malloc_fn != NULL)
  180537. {
  180538. png_struct dummy_struct;
  180539. png_structp png_ptr = &dummy_struct;
  180540. png_ptr->mem_ptr=mem_ptr;
  180541. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  180542. }
  180543. else
  180544. #endif /* PNG_USER_MEM_SUPPORTED */
  180545. struct_ptr = (png_voidp)farmalloc(size);
  180546. if (struct_ptr != NULL)
  180547. png_memset(struct_ptr, 0, size);
  180548. return (struct_ptr);
  180549. }
  180550. /* Free memory allocated by a png_create_struct() call */
  180551. void /* PRIVATE */
  180552. png_destroy_struct(png_voidp struct_ptr)
  180553. {
  180554. #ifdef PNG_USER_MEM_SUPPORTED
  180555. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  180556. }
  180557. /* Free memory allocated by a png_create_struct() call */
  180558. void /* PRIVATE */
  180559. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  180560. png_voidp mem_ptr)
  180561. {
  180562. #endif
  180563. if (struct_ptr != NULL)
  180564. {
  180565. #ifdef PNG_USER_MEM_SUPPORTED
  180566. if(free_fn != NULL)
  180567. {
  180568. png_struct dummy_struct;
  180569. png_structp png_ptr = &dummy_struct;
  180570. png_ptr->mem_ptr=mem_ptr;
  180571. (*(free_fn))(png_ptr, struct_ptr);
  180572. return;
  180573. }
  180574. #endif /* PNG_USER_MEM_SUPPORTED */
  180575. farfree (struct_ptr);
  180576. }
  180577. }
  180578. /* Allocate memory. For reasonable files, size should never exceed
  180579. * 64K. However, zlib may allocate more then 64K if you don't tell
  180580. * it not to. See zconf.h and png.h for more information. zlib does
  180581. * need to allocate exactly 64K, so whatever you call here must
  180582. * have the ability to do that.
  180583. *
  180584. * Borland seems to have a problem in DOS mode for exactly 64K.
  180585. * It gives you a segment with an offset of 8 (perhaps to store its
  180586. * memory stuff). zlib doesn't like this at all, so we have to
  180587. * detect and deal with it. This code should not be needed in
  180588. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  180589. * been updated by Alexander Lehmann for version 0.89 to waste less
  180590. * memory.
  180591. *
  180592. * Note that we can't use png_size_t for the "size" declaration,
  180593. * since on some systems a png_size_t is a 16-bit quantity, and as a
  180594. * result, we would be truncating potentially larger memory requests
  180595. * (which should cause a fatal error) and introducing major problems.
  180596. */
  180597. png_voidp PNGAPI
  180598. png_malloc(png_structp png_ptr, png_uint_32 size)
  180599. {
  180600. png_voidp ret;
  180601. if (png_ptr == NULL || size == 0)
  180602. return (NULL);
  180603. #ifdef PNG_USER_MEM_SUPPORTED
  180604. if(png_ptr->malloc_fn != NULL)
  180605. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  180606. else
  180607. ret = (png_malloc_default(png_ptr, size));
  180608. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180609. png_error(png_ptr, "Out of memory!");
  180610. return (ret);
  180611. }
  180612. png_voidp PNGAPI
  180613. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  180614. {
  180615. png_voidp ret;
  180616. #endif /* PNG_USER_MEM_SUPPORTED */
  180617. if (png_ptr == NULL || size == 0)
  180618. return (NULL);
  180619. #ifdef PNG_MAX_MALLOC_64K
  180620. if (size > (png_uint_32)65536L)
  180621. {
  180622. png_warning(png_ptr, "Cannot Allocate > 64K");
  180623. ret = NULL;
  180624. }
  180625. else
  180626. #endif
  180627. if (size != (size_t)size)
  180628. ret = NULL;
  180629. else if (size == (png_uint_32)65536L)
  180630. {
  180631. if (png_ptr->offset_table == NULL)
  180632. {
  180633. /* try to see if we need to do any of this fancy stuff */
  180634. ret = farmalloc(size);
  180635. if (ret == NULL || ((png_size_t)ret & 0xffff))
  180636. {
  180637. int num_blocks;
  180638. png_uint_32 total_size;
  180639. png_bytep table;
  180640. int i;
  180641. png_byte huge * hptr;
  180642. if (ret != NULL)
  180643. {
  180644. farfree(ret);
  180645. ret = NULL;
  180646. }
  180647. if(png_ptr->zlib_window_bits > 14)
  180648. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  180649. else
  180650. num_blocks = 1;
  180651. if (png_ptr->zlib_mem_level >= 7)
  180652. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  180653. else
  180654. num_blocks++;
  180655. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  180656. table = farmalloc(total_size);
  180657. if (table == NULL)
  180658. {
  180659. #ifndef PNG_USER_MEM_SUPPORTED
  180660. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180661. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  180662. else
  180663. png_warning(png_ptr, "Out Of Memory.");
  180664. #endif
  180665. return (NULL);
  180666. }
  180667. if ((png_size_t)table & 0xfff0)
  180668. {
  180669. #ifndef PNG_USER_MEM_SUPPORTED
  180670. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180671. png_error(png_ptr,
  180672. "Farmalloc didn't return normalized pointer");
  180673. else
  180674. png_warning(png_ptr,
  180675. "Farmalloc didn't return normalized pointer");
  180676. #endif
  180677. return (NULL);
  180678. }
  180679. png_ptr->offset_table = table;
  180680. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  180681. png_sizeof (png_bytep));
  180682. if (png_ptr->offset_table_ptr == NULL)
  180683. {
  180684. #ifndef PNG_USER_MEM_SUPPORTED
  180685. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180686. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  180687. else
  180688. png_warning(png_ptr, "Out Of memory.");
  180689. #endif
  180690. return (NULL);
  180691. }
  180692. hptr = (png_byte huge *)table;
  180693. if ((png_size_t)hptr & 0xf)
  180694. {
  180695. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  180696. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  180697. }
  180698. for (i = 0; i < num_blocks; i++)
  180699. {
  180700. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  180701. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  180702. }
  180703. png_ptr->offset_table_number = num_blocks;
  180704. png_ptr->offset_table_count = 0;
  180705. png_ptr->offset_table_count_free = 0;
  180706. }
  180707. }
  180708. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  180709. {
  180710. #ifndef PNG_USER_MEM_SUPPORTED
  180711. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180712. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  180713. else
  180714. png_warning(png_ptr, "Out of Memory.");
  180715. #endif
  180716. return (NULL);
  180717. }
  180718. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  180719. }
  180720. else
  180721. ret = farmalloc(size);
  180722. #ifndef PNG_USER_MEM_SUPPORTED
  180723. if (ret == NULL)
  180724. {
  180725. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180726. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  180727. else
  180728. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  180729. }
  180730. #endif
  180731. return (ret);
  180732. }
  180733. /* free a pointer allocated by png_malloc(). In the default
  180734. configuration, png_ptr is not used, but is passed in case it
  180735. is needed. If ptr is NULL, return without taking any action. */
  180736. void PNGAPI
  180737. png_free(png_structp png_ptr, png_voidp ptr)
  180738. {
  180739. if (png_ptr == NULL || ptr == NULL)
  180740. return;
  180741. #ifdef PNG_USER_MEM_SUPPORTED
  180742. if (png_ptr->free_fn != NULL)
  180743. {
  180744. (*(png_ptr->free_fn))(png_ptr, ptr);
  180745. return;
  180746. }
  180747. else png_free_default(png_ptr, ptr);
  180748. }
  180749. void PNGAPI
  180750. png_free_default(png_structp png_ptr, png_voidp ptr)
  180751. {
  180752. #endif /* PNG_USER_MEM_SUPPORTED */
  180753. if(png_ptr == NULL) return;
  180754. if (png_ptr->offset_table != NULL)
  180755. {
  180756. int i;
  180757. for (i = 0; i < png_ptr->offset_table_count; i++)
  180758. {
  180759. if (ptr == png_ptr->offset_table_ptr[i])
  180760. {
  180761. ptr = NULL;
  180762. png_ptr->offset_table_count_free++;
  180763. break;
  180764. }
  180765. }
  180766. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  180767. {
  180768. farfree(png_ptr->offset_table);
  180769. farfree(png_ptr->offset_table_ptr);
  180770. png_ptr->offset_table = NULL;
  180771. png_ptr->offset_table_ptr = NULL;
  180772. }
  180773. }
  180774. if (ptr != NULL)
  180775. {
  180776. farfree(ptr);
  180777. }
  180778. }
  180779. #else /* Not the Borland DOS special memory handler */
  180780. /* Allocate memory for a png_struct or a png_info. The malloc and
  180781. memset can be replaced by a single call to calloc() if this is thought
  180782. to improve performance noticably. */
  180783. png_voidp /* PRIVATE */
  180784. png_create_struct(int type)
  180785. {
  180786. #ifdef PNG_USER_MEM_SUPPORTED
  180787. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  180788. }
  180789. /* Allocate memory for a png_struct or a png_info. The malloc and
  180790. memset can be replaced by a single call to calloc() if this is thought
  180791. to improve performance noticably. */
  180792. png_voidp /* PRIVATE */
  180793. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  180794. {
  180795. #endif /* PNG_USER_MEM_SUPPORTED */
  180796. png_size_t size;
  180797. png_voidp struct_ptr;
  180798. if (type == PNG_STRUCT_INFO)
  180799. size = png_sizeof(png_info);
  180800. else if (type == PNG_STRUCT_PNG)
  180801. size = png_sizeof(png_struct);
  180802. else
  180803. return (NULL);
  180804. #ifdef PNG_USER_MEM_SUPPORTED
  180805. if(malloc_fn != NULL)
  180806. {
  180807. png_struct dummy_struct;
  180808. png_structp png_ptr = &dummy_struct;
  180809. png_ptr->mem_ptr=mem_ptr;
  180810. struct_ptr = (*(malloc_fn))(png_ptr, size);
  180811. if (struct_ptr != NULL)
  180812. png_memset(struct_ptr, 0, size);
  180813. return (struct_ptr);
  180814. }
  180815. #endif /* PNG_USER_MEM_SUPPORTED */
  180816. #if defined(__TURBOC__) && !defined(__FLAT__)
  180817. struct_ptr = (png_voidp)farmalloc(size);
  180818. #else
  180819. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  180820. struct_ptr = (png_voidp)halloc(size,1);
  180821. # else
  180822. struct_ptr = (png_voidp)malloc(size);
  180823. # endif
  180824. #endif
  180825. if (struct_ptr != NULL)
  180826. png_memset(struct_ptr, 0, size);
  180827. return (struct_ptr);
  180828. }
  180829. /* Free memory allocated by a png_create_struct() call */
  180830. void /* PRIVATE */
  180831. png_destroy_struct(png_voidp struct_ptr)
  180832. {
  180833. #ifdef PNG_USER_MEM_SUPPORTED
  180834. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  180835. }
  180836. /* Free memory allocated by a png_create_struct() call */
  180837. void /* PRIVATE */
  180838. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  180839. png_voidp mem_ptr)
  180840. {
  180841. #endif /* PNG_USER_MEM_SUPPORTED */
  180842. if (struct_ptr != NULL)
  180843. {
  180844. #ifdef PNG_USER_MEM_SUPPORTED
  180845. if(free_fn != NULL)
  180846. {
  180847. png_struct dummy_struct;
  180848. png_structp png_ptr = &dummy_struct;
  180849. png_ptr->mem_ptr=mem_ptr;
  180850. (*(free_fn))(png_ptr, struct_ptr);
  180851. return;
  180852. }
  180853. #endif /* PNG_USER_MEM_SUPPORTED */
  180854. #if defined(__TURBOC__) && !defined(__FLAT__)
  180855. farfree(struct_ptr);
  180856. #else
  180857. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  180858. hfree(struct_ptr);
  180859. # else
  180860. free(struct_ptr);
  180861. # endif
  180862. #endif
  180863. }
  180864. }
  180865. /* Allocate memory. For reasonable files, size should never exceed
  180866. 64K. However, zlib may allocate more then 64K if you don't tell
  180867. it not to. See zconf.h and png.h for more information. zlib does
  180868. need to allocate exactly 64K, so whatever you call here must
  180869. have the ability to do that. */
  180870. png_voidp PNGAPI
  180871. png_malloc(png_structp png_ptr, png_uint_32 size)
  180872. {
  180873. png_voidp ret;
  180874. #ifdef PNG_USER_MEM_SUPPORTED
  180875. if (png_ptr == NULL || size == 0)
  180876. return (NULL);
  180877. if(png_ptr->malloc_fn != NULL)
  180878. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  180879. else
  180880. ret = (png_malloc_default(png_ptr, size));
  180881. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180882. png_error(png_ptr, "Out of Memory!");
  180883. return (ret);
  180884. }
  180885. png_voidp PNGAPI
  180886. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  180887. {
  180888. png_voidp ret;
  180889. #endif /* PNG_USER_MEM_SUPPORTED */
  180890. if (png_ptr == NULL || size == 0)
  180891. return (NULL);
  180892. #ifdef PNG_MAX_MALLOC_64K
  180893. if (size > (png_uint_32)65536L)
  180894. {
  180895. #ifndef PNG_USER_MEM_SUPPORTED
  180896. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180897. png_error(png_ptr, "Cannot Allocate > 64K");
  180898. else
  180899. #endif
  180900. return NULL;
  180901. }
  180902. #endif
  180903. /* Check for overflow */
  180904. #if defined(__TURBOC__) && !defined(__FLAT__)
  180905. if (size != (unsigned long)size)
  180906. ret = NULL;
  180907. else
  180908. ret = farmalloc(size);
  180909. #else
  180910. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  180911. if (size != (unsigned long)size)
  180912. ret = NULL;
  180913. else
  180914. ret = halloc(size, 1);
  180915. # else
  180916. if (size != (size_t)size)
  180917. ret = NULL;
  180918. else
  180919. ret = malloc((size_t)size);
  180920. # endif
  180921. #endif
  180922. #ifndef PNG_USER_MEM_SUPPORTED
  180923. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180924. png_error(png_ptr, "Out of Memory");
  180925. #endif
  180926. return (ret);
  180927. }
  180928. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  180929. without taking any action. */
  180930. void PNGAPI
  180931. png_free(png_structp png_ptr, png_voidp ptr)
  180932. {
  180933. if (png_ptr == NULL || ptr == NULL)
  180934. return;
  180935. #ifdef PNG_USER_MEM_SUPPORTED
  180936. if (png_ptr->free_fn != NULL)
  180937. {
  180938. (*(png_ptr->free_fn))(png_ptr, ptr);
  180939. return;
  180940. }
  180941. else png_free_default(png_ptr, ptr);
  180942. }
  180943. void PNGAPI
  180944. png_free_default(png_structp png_ptr, png_voidp ptr)
  180945. {
  180946. if (png_ptr == NULL || ptr == NULL)
  180947. return;
  180948. #endif /* PNG_USER_MEM_SUPPORTED */
  180949. #if defined(__TURBOC__) && !defined(__FLAT__)
  180950. farfree(ptr);
  180951. #else
  180952. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  180953. hfree(ptr);
  180954. # else
  180955. free(ptr);
  180956. # endif
  180957. #endif
  180958. }
  180959. #endif /* Not Borland DOS special memory handler */
  180960. #if defined(PNG_1_0_X)
  180961. # define png_malloc_warn png_malloc
  180962. #else
  180963. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  180964. * function will set up png_malloc() to issue a png_warning and return NULL
  180965. * instead of issuing a png_error, if it fails to allocate the requested
  180966. * memory.
  180967. */
  180968. png_voidp PNGAPI
  180969. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  180970. {
  180971. png_voidp ptr;
  180972. png_uint_32 save_flags;
  180973. if(png_ptr == NULL) return (NULL);
  180974. save_flags=png_ptr->flags;
  180975. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  180976. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  180977. png_ptr->flags=save_flags;
  180978. return(ptr);
  180979. }
  180980. #endif
  180981. png_voidp PNGAPI
  180982. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  180983. png_uint_32 length)
  180984. {
  180985. png_size_t size;
  180986. size = (png_size_t)length;
  180987. if ((png_uint_32)size != length)
  180988. png_error(png_ptr,"Overflow in png_memcpy_check.");
  180989. return(png_memcpy (s1, s2, size));
  180990. }
  180991. png_voidp PNGAPI
  180992. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  180993. png_uint_32 length)
  180994. {
  180995. png_size_t size;
  180996. size = (png_size_t)length;
  180997. if ((png_uint_32)size != length)
  180998. png_error(png_ptr,"Overflow in png_memset_check.");
  180999. return (png_memset (s1, value, size));
  181000. }
  181001. #ifdef PNG_USER_MEM_SUPPORTED
  181002. /* This function is called when the application wants to use another method
  181003. * of allocating and freeing memory.
  181004. */
  181005. void PNGAPI
  181006. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  181007. malloc_fn, png_free_ptr free_fn)
  181008. {
  181009. if(png_ptr != NULL) {
  181010. png_ptr->mem_ptr = mem_ptr;
  181011. png_ptr->malloc_fn = malloc_fn;
  181012. png_ptr->free_fn = free_fn;
  181013. }
  181014. }
  181015. /* This function returns a pointer to the mem_ptr associated with the user
  181016. * functions. The application should free any memory associated with this
  181017. * pointer before png_write_destroy and png_read_destroy are called.
  181018. */
  181019. png_voidp PNGAPI
  181020. png_get_mem_ptr(png_structp png_ptr)
  181021. {
  181022. if(png_ptr == NULL) return (NULL);
  181023. return ((png_voidp)png_ptr->mem_ptr);
  181024. }
  181025. #endif /* PNG_USER_MEM_SUPPORTED */
  181026. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  181027. /********* End of inlined file: pngmem.c *********/
  181028. /********* Start of inlined file: pngread.c *********/
  181029. /* pngread.c - read a PNG file
  181030. *
  181031. * Last changed in libpng 1.2.20 September 7, 2007
  181032. * For conditions of distribution and use, see copyright notice in png.h
  181033. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181034. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181035. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181036. *
  181037. * This file contains routines that an application calls directly to
  181038. * read a PNG file or stream.
  181039. */
  181040. #define PNG_INTERNAL
  181041. #if defined(PNG_READ_SUPPORTED)
  181042. /* Create a PNG structure for reading, and allocate any memory needed. */
  181043. png_structp PNGAPI
  181044. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  181045. png_error_ptr error_fn, png_error_ptr warn_fn)
  181046. {
  181047. #ifdef PNG_USER_MEM_SUPPORTED
  181048. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  181049. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  181050. }
  181051. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  181052. png_structp PNGAPI
  181053. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  181054. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  181055. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  181056. {
  181057. #endif /* PNG_USER_MEM_SUPPORTED */
  181058. png_structp png_ptr;
  181059. #ifdef PNG_SETJMP_SUPPORTED
  181060. #ifdef USE_FAR_KEYWORD
  181061. jmp_buf jmpbuf;
  181062. #endif
  181063. #endif
  181064. int i;
  181065. png_debug(1, "in png_create_read_struct\n");
  181066. #ifdef PNG_USER_MEM_SUPPORTED
  181067. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  181068. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  181069. #else
  181070. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  181071. #endif
  181072. if (png_ptr == NULL)
  181073. return (NULL);
  181074. /* added at libpng-1.2.6 */
  181075. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  181076. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  181077. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  181078. #endif
  181079. #ifdef PNG_SETJMP_SUPPORTED
  181080. #ifdef USE_FAR_KEYWORD
  181081. if (setjmp(jmpbuf))
  181082. #else
  181083. if (setjmp(png_ptr->jmpbuf))
  181084. #endif
  181085. {
  181086. png_free(png_ptr, png_ptr->zbuf);
  181087. png_ptr->zbuf=NULL;
  181088. #ifdef PNG_USER_MEM_SUPPORTED
  181089. png_destroy_struct_2((png_voidp)png_ptr,
  181090. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  181091. #else
  181092. png_destroy_struct((png_voidp)png_ptr);
  181093. #endif
  181094. return (NULL);
  181095. }
  181096. #ifdef USE_FAR_KEYWORD
  181097. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  181098. #endif
  181099. #endif
  181100. #ifdef PNG_USER_MEM_SUPPORTED
  181101. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  181102. #endif
  181103. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  181104. i=0;
  181105. do
  181106. {
  181107. if(user_png_ver[i] != png_libpng_ver[i])
  181108. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  181109. } while (png_libpng_ver[i++]);
  181110. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  181111. {
  181112. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  181113. * we must recompile any applications that use any older library version.
  181114. * For versions after libpng 1.0, we will be compatible, so we need
  181115. * only check the first digit.
  181116. */
  181117. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  181118. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  181119. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  181120. {
  181121. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  181122. char msg[80];
  181123. if (user_png_ver)
  181124. {
  181125. png_snprintf(msg, 80,
  181126. "Application was compiled with png.h from libpng-%.20s",
  181127. user_png_ver);
  181128. png_warning(png_ptr, msg);
  181129. }
  181130. png_snprintf(msg, 80,
  181131. "Application is running with png.c from libpng-%.20s",
  181132. png_libpng_ver);
  181133. png_warning(png_ptr, msg);
  181134. #endif
  181135. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181136. png_ptr->flags=0;
  181137. #endif
  181138. png_error(png_ptr,
  181139. "Incompatible libpng version in application and library");
  181140. }
  181141. }
  181142. /* initialize zbuf - compression buffer */
  181143. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  181144. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  181145. (png_uint_32)png_ptr->zbuf_size);
  181146. png_ptr->zstream.zalloc = png_zalloc;
  181147. png_ptr->zstream.zfree = png_zfree;
  181148. png_ptr->zstream.opaque = (voidpf)png_ptr;
  181149. switch (inflateInit(&png_ptr->zstream))
  181150. {
  181151. case Z_OK: /* Do nothing */ break;
  181152. case Z_MEM_ERROR:
  181153. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  181154. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  181155. default: png_error(png_ptr, "Unknown zlib error");
  181156. }
  181157. png_ptr->zstream.next_out = png_ptr->zbuf;
  181158. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  181159. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  181160. #ifdef PNG_SETJMP_SUPPORTED
  181161. /* Applications that neglect to set up their own setjmp() and then encounter
  181162. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  181163. abort instead of returning. */
  181164. #ifdef USE_FAR_KEYWORD
  181165. if (setjmp(jmpbuf))
  181166. PNG_ABORT();
  181167. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  181168. #else
  181169. if (setjmp(png_ptr->jmpbuf))
  181170. PNG_ABORT();
  181171. #endif
  181172. #endif
  181173. return (png_ptr);
  181174. }
  181175. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  181176. /* Initialize PNG structure for reading, and allocate any memory needed.
  181177. This interface is deprecated in favour of the png_create_read_struct(),
  181178. and it will disappear as of libpng-1.3.0. */
  181179. #undef png_read_init
  181180. void PNGAPI
  181181. png_read_init(png_structp png_ptr)
  181182. {
  181183. /* We only come here via pre-1.0.7-compiled applications */
  181184. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  181185. }
  181186. void PNGAPI
  181187. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  181188. png_size_t png_struct_size, png_size_t png_info_size)
  181189. {
  181190. /* We only come here via pre-1.0.12-compiled applications */
  181191. if(png_ptr == NULL) return;
  181192. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  181193. if(png_sizeof(png_struct) > png_struct_size ||
  181194. png_sizeof(png_info) > png_info_size)
  181195. {
  181196. char msg[80];
  181197. png_ptr->warning_fn=NULL;
  181198. if (user_png_ver)
  181199. {
  181200. png_snprintf(msg, 80,
  181201. "Application was compiled with png.h from libpng-%.20s",
  181202. user_png_ver);
  181203. png_warning(png_ptr, msg);
  181204. }
  181205. png_snprintf(msg, 80,
  181206. "Application is running with png.c from libpng-%.20s",
  181207. png_libpng_ver);
  181208. png_warning(png_ptr, msg);
  181209. }
  181210. #endif
  181211. if(png_sizeof(png_struct) > png_struct_size)
  181212. {
  181213. png_ptr->error_fn=NULL;
  181214. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181215. png_ptr->flags=0;
  181216. #endif
  181217. png_error(png_ptr,
  181218. "The png struct allocated by the application for reading is too small.");
  181219. }
  181220. if(png_sizeof(png_info) > png_info_size)
  181221. {
  181222. png_ptr->error_fn=NULL;
  181223. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181224. png_ptr->flags=0;
  181225. #endif
  181226. png_error(png_ptr,
  181227. "The info struct allocated by application for reading is too small.");
  181228. }
  181229. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  181230. }
  181231. #endif /* PNG_1_0_X || PNG_1_2_X */
  181232. void PNGAPI
  181233. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  181234. png_size_t png_struct_size)
  181235. {
  181236. #ifdef PNG_SETJMP_SUPPORTED
  181237. jmp_buf tmp_jmp; /* to save current jump buffer */
  181238. #endif
  181239. int i=0;
  181240. png_structp png_ptr=*ptr_ptr;
  181241. if(png_ptr == NULL) return;
  181242. do
  181243. {
  181244. if(user_png_ver[i] != png_libpng_ver[i])
  181245. {
  181246. #ifdef PNG_LEGACY_SUPPORTED
  181247. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  181248. #else
  181249. png_ptr->warning_fn=NULL;
  181250. png_warning(png_ptr,
  181251. "Application uses deprecated png_read_init() and should be recompiled.");
  181252. break;
  181253. #endif
  181254. }
  181255. } while (png_libpng_ver[i++]);
  181256. png_debug(1, "in png_read_init_3\n");
  181257. #ifdef PNG_SETJMP_SUPPORTED
  181258. /* save jump buffer and error functions */
  181259. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  181260. #endif
  181261. if(png_sizeof(png_struct) > png_struct_size)
  181262. {
  181263. png_destroy_struct(png_ptr);
  181264. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  181265. png_ptr = *ptr_ptr;
  181266. }
  181267. /* reset all variables to 0 */
  181268. png_memset(png_ptr, 0, png_sizeof (png_struct));
  181269. #ifdef PNG_SETJMP_SUPPORTED
  181270. /* restore jump buffer */
  181271. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  181272. #endif
  181273. /* added at libpng-1.2.6 */
  181274. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  181275. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  181276. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  181277. #endif
  181278. /* initialize zbuf - compression buffer */
  181279. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  181280. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  181281. (png_uint_32)png_ptr->zbuf_size);
  181282. png_ptr->zstream.zalloc = png_zalloc;
  181283. png_ptr->zstream.zfree = png_zfree;
  181284. png_ptr->zstream.opaque = (voidpf)png_ptr;
  181285. switch (inflateInit(&png_ptr->zstream))
  181286. {
  181287. case Z_OK: /* Do nothing */ break;
  181288. case Z_MEM_ERROR:
  181289. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  181290. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  181291. default: png_error(png_ptr, "Unknown zlib error");
  181292. }
  181293. png_ptr->zstream.next_out = png_ptr->zbuf;
  181294. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  181295. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  181296. }
  181297. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181298. /* Read the information before the actual image data. This has been
  181299. * changed in v0.90 to allow reading a file that already has the magic
  181300. * bytes read from the stream. You can tell libpng how many bytes have
  181301. * been read from the beginning of the stream (up to the maximum of 8)
  181302. * via png_set_sig_bytes(), and we will only check the remaining bytes
  181303. * here. The application can then have access to the signature bytes we
  181304. * read if it is determined that this isn't a valid PNG file.
  181305. */
  181306. void PNGAPI
  181307. png_read_info(png_structp png_ptr, png_infop info_ptr)
  181308. {
  181309. if(png_ptr == NULL) return;
  181310. png_debug(1, "in png_read_info\n");
  181311. /* If we haven't checked all of the PNG signature bytes, do so now. */
  181312. if (png_ptr->sig_bytes < 8)
  181313. {
  181314. png_size_t num_checked = png_ptr->sig_bytes,
  181315. num_to_check = 8 - num_checked;
  181316. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  181317. png_ptr->sig_bytes = 8;
  181318. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  181319. {
  181320. if (num_checked < 4 &&
  181321. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  181322. png_error(png_ptr, "Not a PNG file");
  181323. else
  181324. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  181325. }
  181326. if (num_checked < 3)
  181327. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  181328. }
  181329. for(;;)
  181330. {
  181331. #ifdef PNG_USE_LOCAL_ARRAYS
  181332. PNG_CONST PNG_IHDR;
  181333. PNG_CONST PNG_IDAT;
  181334. PNG_CONST PNG_IEND;
  181335. PNG_CONST PNG_PLTE;
  181336. #if defined(PNG_READ_bKGD_SUPPORTED)
  181337. PNG_CONST PNG_bKGD;
  181338. #endif
  181339. #if defined(PNG_READ_cHRM_SUPPORTED)
  181340. PNG_CONST PNG_cHRM;
  181341. #endif
  181342. #if defined(PNG_READ_gAMA_SUPPORTED)
  181343. PNG_CONST PNG_gAMA;
  181344. #endif
  181345. #if defined(PNG_READ_hIST_SUPPORTED)
  181346. PNG_CONST PNG_hIST;
  181347. #endif
  181348. #if defined(PNG_READ_iCCP_SUPPORTED)
  181349. PNG_CONST PNG_iCCP;
  181350. #endif
  181351. #if defined(PNG_READ_iTXt_SUPPORTED)
  181352. PNG_CONST PNG_iTXt;
  181353. #endif
  181354. #if defined(PNG_READ_oFFs_SUPPORTED)
  181355. PNG_CONST PNG_oFFs;
  181356. #endif
  181357. #if defined(PNG_READ_pCAL_SUPPORTED)
  181358. PNG_CONST PNG_pCAL;
  181359. #endif
  181360. #if defined(PNG_READ_pHYs_SUPPORTED)
  181361. PNG_CONST PNG_pHYs;
  181362. #endif
  181363. #if defined(PNG_READ_sBIT_SUPPORTED)
  181364. PNG_CONST PNG_sBIT;
  181365. #endif
  181366. #if defined(PNG_READ_sCAL_SUPPORTED)
  181367. PNG_CONST PNG_sCAL;
  181368. #endif
  181369. #if defined(PNG_READ_sPLT_SUPPORTED)
  181370. PNG_CONST PNG_sPLT;
  181371. #endif
  181372. #if defined(PNG_READ_sRGB_SUPPORTED)
  181373. PNG_CONST PNG_sRGB;
  181374. #endif
  181375. #if defined(PNG_READ_tEXt_SUPPORTED)
  181376. PNG_CONST PNG_tEXt;
  181377. #endif
  181378. #if defined(PNG_READ_tIME_SUPPORTED)
  181379. PNG_CONST PNG_tIME;
  181380. #endif
  181381. #if defined(PNG_READ_tRNS_SUPPORTED)
  181382. PNG_CONST PNG_tRNS;
  181383. #endif
  181384. #if defined(PNG_READ_zTXt_SUPPORTED)
  181385. PNG_CONST PNG_zTXt;
  181386. #endif
  181387. #endif /* PNG_USE_LOCAL_ARRAYS */
  181388. png_byte chunk_length[4];
  181389. png_uint_32 length;
  181390. png_read_data(png_ptr, chunk_length, 4);
  181391. length = png_get_uint_31(png_ptr,chunk_length);
  181392. png_reset_crc(png_ptr);
  181393. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  181394. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  181395. length);
  181396. /* This should be a binary subdivision search or a hash for
  181397. * matching the chunk name rather than a linear search.
  181398. */
  181399. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181400. if(png_ptr->mode & PNG_AFTER_IDAT)
  181401. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  181402. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  181403. png_handle_IHDR(png_ptr, info_ptr, length);
  181404. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  181405. png_handle_IEND(png_ptr, info_ptr, length);
  181406. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181407. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  181408. {
  181409. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181410. png_ptr->mode |= PNG_HAVE_IDAT;
  181411. png_handle_unknown(png_ptr, info_ptr, length);
  181412. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  181413. png_ptr->mode |= PNG_HAVE_PLTE;
  181414. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181415. {
  181416. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  181417. png_error(png_ptr, "Missing IHDR before IDAT");
  181418. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  181419. !(png_ptr->mode & PNG_HAVE_PLTE))
  181420. png_error(png_ptr, "Missing PLTE before IDAT");
  181421. break;
  181422. }
  181423. }
  181424. #endif
  181425. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  181426. png_handle_PLTE(png_ptr, info_ptr, length);
  181427. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181428. {
  181429. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  181430. png_error(png_ptr, "Missing IHDR before IDAT");
  181431. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  181432. !(png_ptr->mode & PNG_HAVE_PLTE))
  181433. png_error(png_ptr, "Missing PLTE before IDAT");
  181434. png_ptr->idat_size = length;
  181435. png_ptr->mode |= PNG_HAVE_IDAT;
  181436. break;
  181437. }
  181438. #if defined(PNG_READ_bKGD_SUPPORTED)
  181439. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  181440. png_handle_bKGD(png_ptr, info_ptr, length);
  181441. #endif
  181442. #if defined(PNG_READ_cHRM_SUPPORTED)
  181443. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  181444. png_handle_cHRM(png_ptr, info_ptr, length);
  181445. #endif
  181446. #if defined(PNG_READ_gAMA_SUPPORTED)
  181447. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  181448. png_handle_gAMA(png_ptr, info_ptr, length);
  181449. #endif
  181450. #if defined(PNG_READ_hIST_SUPPORTED)
  181451. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  181452. png_handle_hIST(png_ptr, info_ptr, length);
  181453. #endif
  181454. #if defined(PNG_READ_oFFs_SUPPORTED)
  181455. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  181456. png_handle_oFFs(png_ptr, info_ptr, length);
  181457. #endif
  181458. #if defined(PNG_READ_pCAL_SUPPORTED)
  181459. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  181460. png_handle_pCAL(png_ptr, info_ptr, length);
  181461. #endif
  181462. #if defined(PNG_READ_sCAL_SUPPORTED)
  181463. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  181464. png_handle_sCAL(png_ptr, info_ptr, length);
  181465. #endif
  181466. #if defined(PNG_READ_pHYs_SUPPORTED)
  181467. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  181468. png_handle_pHYs(png_ptr, info_ptr, length);
  181469. #endif
  181470. #if defined(PNG_READ_sBIT_SUPPORTED)
  181471. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  181472. png_handle_sBIT(png_ptr, info_ptr, length);
  181473. #endif
  181474. #if defined(PNG_READ_sRGB_SUPPORTED)
  181475. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  181476. png_handle_sRGB(png_ptr, info_ptr, length);
  181477. #endif
  181478. #if defined(PNG_READ_iCCP_SUPPORTED)
  181479. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  181480. png_handle_iCCP(png_ptr, info_ptr, length);
  181481. #endif
  181482. #if defined(PNG_READ_sPLT_SUPPORTED)
  181483. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  181484. png_handle_sPLT(png_ptr, info_ptr, length);
  181485. #endif
  181486. #if defined(PNG_READ_tEXt_SUPPORTED)
  181487. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  181488. png_handle_tEXt(png_ptr, info_ptr, length);
  181489. #endif
  181490. #if defined(PNG_READ_tIME_SUPPORTED)
  181491. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  181492. png_handle_tIME(png_ptr, info_ptr, length);
  181493. #endif
  181494. #if defined(PNG_READ_tRNS_SUPPORTED)
  181495. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  181496. png_handle_tRNS(png_ptr, info_ptr, length);
  181497. #endif
  181498. #if defined(PNG_READ_zTXt_SUPPORTED)
  181499. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  181500. png_handle_zTXt(png_ptr, info_ptr, length);
  181501. #endif
  181502. #if defined(PNG_READ_iTXt_SUPPORTED)
  181503. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  181504. png_handle_iTXt(png_ptr, info_ptr, length);
  181505. #endif
  181506. else
  181507. png_handle_unknown(png_ptr, info_ptr, length);
  181508. }
  181509. }
  181510. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181511. /* optional call to update the users info_ptr structure */
  181512. void PNGAPI
  181513. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  181514. {
  181515. png_debug(1, "in png_read_update_info\n");
  181516. if(png_ptr == NULL) return;
  181517. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  181518. png_read_start_row(png_ptr);
  181519. else
  181520. png_warning(png_ptr,
  181521. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  181522. png_read_transform_info(png_ptr, info_ptr);
  181523. }
  181524. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181525. /* Initialize palette, background, etc, after transformations
  181526. * are set, but before any reading takes place. This allows
  181527. * the user to obtain a gamma-corrected palette, for example.
  181528. * If the user doesn't call this, we will do it ourselves.
  181529. */
  181530. void PNGAPI
  181531. png_start_read_image(png_structp png_ptr)
  181532. {
  181533. png_debug(1, "in png_start_read_image\n");
  181534. if(png_ptr == NULL) return;
  181535. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  181536. png_read_start_row(png_ptr);
  181537. }
  181538. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181539. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181540. void PNGAPI
  181541. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  181542. {
  181543. #ifdef PNG_USE_LOCAL_ARRAYS
  181544. PNG_CONST PNG_IDAT;
  181545. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  181546. 0xff};
  181547. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  181548. #endif
  181549. int ret;
  181550. if(png_ptr == NULL) return;
  181551. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  181552. png_ptr->row_number, png_ptr->pass);
  181553. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  181554. png_read_start_row(png_ptr);
  181555. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  181556. {
  181557. /* check for transforms that have been set but were defined out */
  181558. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  181559. if (png_ptr->transformations & PNG_INVERT_MONO)
  181560. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  181561. #endif
  181562. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  181563. if (png_ptr->transformations & PNG_FILLER)
  181564. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  181565. #endif
  181566. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  181567. if (png_ptr->transformations & PNG_PACKSWAP)
  181568. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  181569. #endif
  181570. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  181571. if (png_ptr->transformations & PNG_PACK)
  181572. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  181573. #endif
  181574. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  181575. if (png_ptr->transformations & PNG_SHIFT)
  181576. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  181577. #endif
  181578. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  181579. if (png_ptr->transformations & PNG_BGR)
  181580. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  181581. #endif
  181582. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  181583. if (png_ptr->transformations & PNG_SWAP_BYTES)
  181584. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  181585. #endif
  181586. }
  181587. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  181588. /* if interlaced and we do not need a new row, combine row and return */
  181589. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  181590. {
  181591. switch (png_ptr->pass)
  181592. {
  181593. case 0:
  181594. if (png_ptr->row_number & 0x07)
  181595. {
  181596. if (dsp_row != NULL)
  181597. png_combine_row(png_ptr, dsp_row,
  181598. png_pass_dsp_mask[png_ptr->pass]);
  181599. png_read_finish_row(png_ptr);
  181600. return;
  181601. }
  181602. break;
  181603. case 1:
  181604. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  181605. {
  181606. if (dsp_row != NULL)
  181607. png_combine_row(png_ptr, dsp_row,
  181608. png_pass_dsp_mask[png_ptr->pass]);
  181609. png_read_finish_row(png_ptr);
  181610. return;
  181611. }
  181612. break;
  181613. case 2:
  181614. if ((png_ptr->row_number & 0x07) != 4)
  181615. {
  181616. if (dsp_row != NULL && (png_ptr->row_number & 4))
  181617. png_combine_row(png_ptr, dsp_row,
  181618. png_pass_dsp_mask[png_ptr->pass]);
  181619. png_read_finish_row(png_ptr);
  181620. return;
  181621. }
  181622. break;
  181623. case 3:
  181624. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  181625. {
  181626. if (dsp_row != NULL)
  181627. png_combine_row(png_ptr, dsp_row,
  181628. png_pass_dsp_mask[png_ptr->pass]);
  181629. png_read_finish_row(png_ptr);
  181630. return;
  181631. }
  181632. break;
  181633. case 4:
  181634. if ((png_ptr->row_number & 3) != 2)
  181635. {
  181636. if (dsp_row != NULL && (png_ptr->row_number & 2))
  181637. png_combine_row(png_ptr, dsp_row,
  181638. png_pass_dsp_mask[png_ptr->pass]);
  181639. png_read_finish_row(png_ptr);
  181640. return;
  181641. }
  181642. break;
  181643. case 5:
  181644. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  181645. {
  181646. if (dsp_row != NULL)
  181647. png_combine_row(png_ptr, dsp_row,
  181648. png_pass_dsp_mask[png_ptr->pass]);
  181649. png_read_finish_row(png_ptr);
  181650. return;
  181651. }
  181652. break;
  181653. case 6:
  181654. if (!(png_ptr->row_number & 1))
  181655. {
  181656. png_read_finish_row(png_ptr);
  181657. return;
  181658. }
  181659. break;
  181660. }
  181661. }
  181662. #endif
  181663. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  181664. png_error(png_ptr, "Invalid attempt to read row data");
  181665. png_ptr->zstream.next_out = png_ptr->row_buf;
  181666. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  181667. do
  181668. {
  181669. if (!(png_ptr->zstream.avail_in))
  181670. {
  181671. while (!png_ptr->idat_size)
  181672. {
  181673. png_byte chunk_length[4];
  181674. png_crc_finish(png_ptr, 0);
  181675. png_read_data(png_ptr, chunk_length, 4);
  181676. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  181677. png_reset_crc(png_ptr);
  181678. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  181679. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181680. png_error(png_ptr, "Not enough image data");
  181681. }
  181682. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  181683. png_ptr->zstream.next_in = png_ptr->zbuf;
  181684. if (png_ptr->zbuf_size > png_ptr->idat_size)
  181685. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  181686. png_crc_read(png_ptr, png_ptr->zbuf,
  181687. (png_size_t)png_ptr->zstream.avail_in);
  181688. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  181689. }
  181690. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  181691. if (ret == Z_STREAM_END)
  181692. {
  181693. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  181694. png_ptr->idat_size)
  181695. png_error(png_ptr, "Extra compressed data");
  181696. png_ptr->mode |= PNG_AFTER_IDAT;
  181697. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  181698. break;
  181699. }
  181700. if (ret != Z_OK)
  181701. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  181702. "Decompression error");
  181703. } while (png_ptr->zstream.avail_out);
  181704. png_ptr->row_info.color_type = png_ptr->color_type;
  181705. png_ptr->row_info.width = png_ptr->iwidth;
  181706. png_ptr->row_info.channels = png_ptr->channels;
  181707. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  181708. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  181709. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  181710. png_ptr->row_info.width);
  181711. if(png_ptr->row_buf[0])
  181712. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  181713. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  181714. (int)(png_ptr->row_buf[0]));
  181715. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  181716. png_ptr->rowbytes + 1);
  181717. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  181718. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  181719. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  181720. {
  181721. /* Intrapixel differencing */
  181722. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  181723. }
  181724. #endif
  181725. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  181726. png_do_read_transformations(png_ptr);
  181727. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  181728. /* blow up interlaced rows to full size */
  181729. if (png_ptr->interlaced &&
  181730. (png_ptr->transformations & PNG_INTERLACE))
  181731. {
  181732. if (png_ptr->pass < 6)
  181733. /* old interface (pre-1.0.9):
  181734. png_do_read_interlace(&(png_ptr->row_info),
  181735. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  181736. */
  181737. png_do_read_interlace(png_ptr);
  181738. if (dsp_row != NULL)
  181739. png_combine_row(png_ptr, dsp_row,
  181740. png_pass_dsp_mask[png_ptr->pass]);
  181741. if (row != NULL)
  181742. png_combine_row(png_ptr, row,
  181743. png_pass_mask[png_ptr->pass]);
  181744. }
  181745. else
  181746. #endif
  181747. {
  181748. if (row != NULL)
  181749. png_combine_row(png_ptr, row, 0xff);
  181750. if (dsp_row != NULL)
  181751. png_combine_row(png_ptr, dsp_row, 0xff);
  181752. }
  181753. png_read_finish_row(png_ptr);
  181754. if (png_ptr->read_row_fn != NULL)
  181755. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  181756. }
  181757. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181758. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181759. /* Read one or more rows of image data. If the image is interlaced,
  181760. * and png_set_interlace_handling() has been called, the rows need to
  181761. * contain the contents of the rows from the previous pass. If the
  181762. * image has alpha or transparency, and png_handle_alpha()[*] has been
  181763. * called, the rows contents must be initialized to the contents of the
  181764. * screen.
  181765. *
  181766. * "row" holds the actual image, and pixels are placed in it
  181767. * as they arrive. If the image is displayed after each pass, it will
  181768. * appear to "sparkle" in. "display_row" can be used to display a
  181769. * "chunky" progressive image, with finer detail added as it becomes
  181770. * available. If you do not want this "chunky" display, you may pass
  181771. * NULL for display_row. If you do not want the sparkle display, and
  181772. * you have not called png_handle_alpha(), you may pass NULL for rows.
  181773. * If you have called png_handle_alpha(), and the image has either an
  181774. * alpha channel or a transparency chunk, you must provide a buffer for
  181775. * rows. In this case, you do not have to provide a display_row buffer
  181776. * also, but you may. If the image is not interlaced, or if you have
  181777. * not called png_set_interlace_handling(), the display_row buffer will
  181778. * be ignored, so pass NULL to it.
  181779. *
  181780. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  181781. */
  181782. void PNGAPI
  181783. png_read_rows(png_structp png_ptr, png_bytepp row,
  181784. png_bytepp display_row, png_uint_32 num_rows)
  181785. {
  181786. png_uint_32 i;
  181787. png_bytepp rp;
  181788. png_bytepp dp;
  181789. png_debug(1, "in png_read_rows\n");
  181790. if(png_ptr == NULL) return;
  181791. rp = row;
  181792. dp = display_row;
  181793. if (rp != NULL && dp != NULL)
  181794. for (i = 0; i < num_rows; i++)
  181795. {
  181796. png_bytep rptr = *rp++;
  181797. png_bytep dptr = *dp++;
  181798. png_read_row(png_ptr, rptr, dptr);
  181799. }
  181800. else if(rp != NULL)
  181801. for (i = 0; i < num_rows; i++)
  181802. {
  181803. png_bytep rptr = *rp;
  181804. png_read_row(png_ptr, rptr, png_bytep_NULL);
  181805. rp++;
  181806. }
  181807. else if(dp != NULL)
  181808. for (i = 0; i < num_rows; i++)
  181809. {
  181810. png_bytep dptr = *dp;
  181811. png_read_row(png_ptr, png_bytep_NULL, dptr);
  181812. dp++;
  181813. }
  181814. }
  181815. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181816. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181817. /* Read the entire image. If the image has an alpha channel or a tRNS
  181818. * chunk, and you have called png_handle_alpha()[*], you will need to
  181819. * initialize the image to the current image that PNG will be overlaying.
  181820. * We set the num_rows again here, in case it was incorrectly set in
  181821. * png_read_start_row() by a call to png_read_update_info() or
  181822. * png_start_read_image() if png_set_interlace_handling() wasn't called
  181823. * prior to either of these functions like it should have been. You can
  181824. * only call this function once. If you desire to have an image for
  181825. * each pass of a interlaced image, use png_read_rows() instead.
  181826. *
  181827. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  181828. */
  181829. void PNGAPI
  181830. png_read_image(png_structp png_ptr, png_bytepp image)
  181831. {
  181832. png_uint_32 i,image_height;
  181833. int pass, j;
  181834. png_bytepp rp;
  181835. png_debug(1, "in png_read_image\n");
  181836. if(png_ptr == NULL) return;
  181837. #ifdef PNG_READ_INTERLACING_SUPPORTED
  181838. pass = png_set_interlace_handling(png_ptr);
  181839. #else
  181840. if (png_ptr->interlaced)
  181841. png_error(png_ptr,
  181842. "Cannot read interlaced image -- interlace handler disabled.");
  181843. pass = 1;
  181844. #endif
  181845. image_height=png_ptr->height;
  181846. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  181847. for (j = 0; j < pass; j++)
  181848. {
  181849. rp = image;
  181850. for (i = 0; i < image_height; i++)
  181851. {
  181852. png_read_row(png_ptr, *rp, png_bytep_NULL);
  181853. rp++;
  181854. }
  181855. }
  181856. }
  181857. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181858. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181859. /* Read the end of the PNG file. Will not read past the end of the
  181860. * file, will verify the end is accurate, and will read any comments
  181861. * or time information at the end of the file, if info is not NULL.
  181862. */
  181863. void PNGAPI
  181864. png_read_end(png_structp png_ptr, png_infop info_ptr)
  181865. {
  181866. png_byte chunk_length[4];
  181867. png_uint_32 length;
  181868. png_debug(1, "in png_read_end\n");
  181869. if(png_ptr == NULL) return;
  181870. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  181871. do
  181872. {
  181873. #ifdef PNG_USE_LOCAL_ARRAYS
  181874. PNG_CONST PNG_IHDR;
  181875. PNG_CONST PNG_IDAT;
  181876. PNG_CONST PNG_IEND;
  181877. PNG_CONST PNG_PLTE;
  181878. #if defined(PNG_READ_bKGD_SUPPORTED)
  181879. PNG_CONST PNG_bKGD;
  181880. #endif
  181881. #if defined(PNG_READ_cHRM_SUPPORTED)
  181882. PNG_CONST PNG_cHRM;
  181883. #endif
  181884. #if defined(PNG_READ_gAMA_SUPPORTED)
  181885. PNG_CONST PNG_gAMA;
  181886. #endif
  181887. #if defined(PNG_READ_hIST_SUPPORTED)
  181888. PNG_CONST PNG_hIST;
  181889. #endif
  181890. #if defined(PNG_READ_iCCP_SUPPORTED)
  181891. PNG_CONST PNG_iCCP;
  181892. #endif
  181893. #if defined(PNG_READ_iTXt_SUPPORTED)
  181894. PNG_CONST PNG_iTXt;
  181895. #endif
  181896. #if defined(PNG_READ_oFFs_SUPPORTED)
  181897. PNG_CONST PNG_oFFs;
  181898. #endif
  181899. #if defined(PNG_READ_pCAL_SUPPORTED)
  181900. PNG_CONST PNG_pCAL;
  181901. #endif
  181902. #if defined(PNG_READ_pHYs_SUPPORTED)
  181903. PNG_CONST PNG_pHYs;
  181904. #endif
  181905. #if defined(PNG_READ_sBIT_SUPPORTED)
  181906. PNG_CONST PNG_sBIT;
  181907. #endif
  181908. #if defined(PNG_READ_sCAL_SUPPORTED)
  181909. PNG_CONST PNG_sCAL;
  181910. #endif
  181911. #if defined(PNG_READ_sPLT_SUPPORTED)
  181912. PNG_CONST PNG_sPLT;
  181913. #endif
  181914. #if defined(PNG_READ_sRGB_SUPPORTED)
  181915. PNG_CONST PNG_sRGB;
  181916. #endif
  181917. #if defined(PNG_READ_tEXt_SUPPORTED)
  181918. PNG_CONST PNG_tEXt;
  181919. #endif
  181920. #if defined(PNG_READ_tIME_SUPPORTED)
  181921. PNG_CONST PNG_tIME;
  181922. #endif
  181923. #if defined(PNG_READ_tRNS_SUPPORTED)
  181924. PNG_CONST PNG_tRNS;
  181925. #endif
  181926. #if defined(PNG_READ_zTXt_SUPPORTED)
  181927. PNG_CONST PNG_zTXt;
  181928. #endif
  181929. #endif /* PNG_USE_LOCAL_ARRAYS */
  181930. png_read_data(png_ptr, chunk_length, 4);
  181931. length = png_get_uint_31(png_ptr,chunk_length);
  181932. png_reset_crc(png_ptr);
  181933. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  181934. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  181935. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  181936. png_handle_IHDR(png_ptr, info_ptr, length);
  181937. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  181938. png_handle_IEND(png_ptr, info_ptr, length);
  181939. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181940. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  181941. {
  181942. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181943. {
  181944. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  181945. png_error(png_ptr, "Too many IDAT's found");
  181946. }
  181947. png_handle_unknown(png_ptr, info_ptr, length);
  181948. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  181949. png_ptr->mode |= PNG_HAVE_PLTE;
  181950. }
  181951. #endif
  181952. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181953. {
  181954. /* Zero length IDATs are legal after the last IDAT has been
  181955. * read, but not after other chunks have been read.
  181956. */
  181957. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  181958. png_error(png_ptr, "Too many IDAT's found");
  181959. png_crc_finish(png_ptr, length);
  181960. }
  181961. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  181962. png_handle_PLTE(png_ptr, info_ptr, length);
  181963. #if defined(PNG_READ_bKGD_SUPPORTED)
  181964. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  181965. png_handle_bKGD(png_ptr, info_ptr, length);
  181966. #endif
  181967. #if defined(PNG_READ_cHRM_SUPPORTED)
  181968. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  181969. png_handle_cHRM(png_ptr, info_ptr, length);
  181970. #endif
  181971. #if defined(PNG_READ_gAMA_SUPPORTED)
  181972. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  181973. png_handle_gAMA(png_ptr, info_ptr, length);
  181974. #endif
  181975. #if defined(PNG_READ_hIST_SUPPORTED)
  181976. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  181977. png_handle_hIST(png_ptr, info_ptr, length);
  181978. #endif
  181979. #if defined(PNG_READ_oFFs_SUPPORTED)
  181980. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  181981. png_handle_oFFs(png_ptr, info_ptr, length);
  181982. #endif
  181983. #if defined(PNG_READ_pCAL_SUPPORTED)
  181984. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  181985. png_handle_pCAL(png_ptr, info_ptr, length);
  181986. #endif
  181987. #if defined(PNG_READ_sCAL_SUPPORTED)
  181988. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  181989. png_handle_sCAL(png_ptr, info_ptr, length);
  181990. #endif
  181991. #if defined(PNG_READ_pHYs_SUPPORTED)
  181992. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  181993. png_handle_pHYs(png_ptr, info_ptr, length);
  181994. #endif
  181995. #if defined(PNG_READ_sBIT_SUPPORTED)
  181996. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  181997. png_handle_sBIT(png_ptr, info_ptr, length);
  181998. #endif
  181999. #if defined(PNG_READ_sRGB_SUPPORTED)
  182000. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  182001. png_handle_sRGB(png_ptr, info_ptr, length);
  182002. #endif
  182003. #if defined(PNG_READ_iCCP_SUPPORTED)
  182004. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  182005. png_handle_iCCP(png_ptr, info_ptr, length);
  182006. #endif
  182007. #if defined(PNG_READ_sPLT_SUPPORTED)
  182008. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  182009. png_handle_sPLT(png_ptr, info_ptr, length);
  182010. #endif
  182011. #if defined(PNG_READ_tEXt_SUPPORTED)
  182012. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  182013. png_handle_tEXt(png_ptr, info_ptr, length);
  182014. #endif
  182015. #if defined(PNG_READ_tIME_SUPPORTED)
  182016. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  182017. png_handle_tIME(png_ptr, info_ptr, length);
  182018. #endif
  182019. #if defined(PNG_READ_tRNS_SUPPORTED)
  182020. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  182021. png_handle_tRNS(png_ptr, info_ptr, length);
  182022. #endif
  182023. #if defined(PNG_READ_zTXt_SUPPORTED)
  182024. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  182025. png_handle_zTXt(png_ptr, info_ptr, length);
  182026. #endif
  182027. #if defined(PNG_READ_iTXt_SUPPORTED)
  182028. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  182029. png_handle_iTXt(png_ptr, info_ptr, length);
  182030. #endif
  182031. else
  182032. png_handle_unknown(png_ptr, info_ptr, length);
  182033. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  182034. }
  182035. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  182036. /* free all memory used by the read */
  182037. void PNGAPI
  182038. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  182039. png_infopp end_info_ptr_ptr)
  182040. {
  182041. png_structp png_ptr = NULL;
  182042. png_infop info_ptr = NULL, end_info_ptr = NULL;
  182043. #ifdef PNG_USER_MEM_SUPPORTED
  182044. png_free_ptr free_fn;
  182045. png_voidp mem_ptr;
  182046. #endif
  182047. png_debug(1, "in png_destroy_read_struct\n");
  182048. if (png_ptr_ptr != NULL)
  182049. png_ptr = *png_ptr_ptr;
  182050. if (info_ptr_ptr != NULL)
  182051. info_ptr = *info_ptr_ptr;
  182052. if (end_info_ptr_ptr != NULL)
  182053. end_info_ptr = *end_info_ptr_ptr;
  182054. #ifdef PNG_USER_MEM_SUPPORTED
  182055. free_fn = png_ptr->free_fn;
  182056. mem_ptr = png_ptr->mem_ptr;
  182057. #endif
  182058. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  182059. if (info_ptr != NULL)
  182060. {
  182061. #if defined(PNG_TEXT_SUPPORTED)
  182062. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  182063. #endif
  182064. #ifdef PNG_USER_MEM_SUPPORTED
  182065. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  182066. (png_voidp)mem_ptr);
  182067. #else
  182068. png_destroy_struct((png_voidp)info_ptr);
  182069. #endif
  182070. *info_ptr_ptr = NULL;
  182071. }
  182072. if (end_info_ptr != NULL)
  182073. {
  182074. #if defined(PNG_READ_TEXT_SUPPORTED)
  182075. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  182076. #endif
  182077. #ifdef PNG_USER_MEM_SUPPORTED
  182078. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  182079. (png_voidp)mem_ptr);
  182080. #else
  182081. png_destroy_struct((png_voidp)end_info_ptr);
  182082. #endif
  182083. *end_info_ptr_ptr = NULL;
  182084. }
  182085. if (png_ptr != NULL)
  182086. {
  182087. #ifdef PNG_USER_MEM_SUPPORTED
  182088. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  182089. (png_voidp)mem_ptr);
  182090. #else
  182091. png_destroy_struct((png_voidp)png_ptr);
  182092. #endif
  182093. *png_ptr_ptr = NULL;
  182094. }
  182095. }
  182096. /* free all memory used by the read (old method) */
  182097. void /* PRIVATE */
  182098. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  182099. {
  182100. #ifdef PNG_SETJMP_SUPPORTED
  182101. jmp_buf tmp_jmp;
  182102. #endif
  182103. png_error_ptr error_fn;
  182104. png_error_ptr warning_fn;
  182105. png_voidp error_ptr;
  182106. #ifdef PNG_USER_MEM_SUPPORTED
  182107. png_free_ptr free_fn;
  182108. #endif
  182109. png_debug(1, "in png_read_destroy\n");
  182110. if (info_ptr != NULL)
  182111. png_info_destroy(png_ptr, info_ptr);
  182112. if (end_info_ptr != NULL)
  182113. png_info_destroy(png_ptr, end_info_ptr);
  182114. png_free(png_ptr, png_ptr->zbuf);
  182115. png_free(png_ptr, png_ptr->big_row_buf);
  182116. png_free(png_ptr, png_ptr->prev_row);
  182117. #if defined(PNG_READ_DITHER_SUPPORTED)
  182118. png_free(png_ptr, png_ptr->palette_lookup);
  182119. png_free(png_ptr, png_ptr->dither_index);
  182120. #endif
  182121. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182122. png_free(png_ptr, png_ptr->gamma_table);
  182123. #endif
  182124. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182125. png_free(png_ptr, png_ptr->gamma_from_1);
  182126. png_free(png_ptr, png_ptr->gamma_to_1);
  182127. #endif
  182128. #ifdef PNG_FREE_ME_SUPPORTED
  182129. if (png_ptr->free_me & PNG_FREE_PLTE)
  182130. png_zfree(png_ptr, png_ptr->palette);
  182131. png_ptr->free_me &= ~PNG_FREE_PLTE;
  182132. #else
  182133. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  182134. png_zfree(png_ptr, png_ptr->palette);
  182135. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  182136. #endif
  182137. #if defined(PNG_tRNS_SUPPORTED) || \
  182138. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182139. #ifdef PNG_FREE_ME_SUPPORTED
  182140. if (png_ptr->free_me & PNG_FREE_TRNS)
  182141. png_free(png_ptr, png_ptr->trans);
  182142. png_ptr->free_me &= ~PNG_FREE_TRNS;
  182143. #else
  182144. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  182145. png_free(png_ptr, png_ptr->trans);
  182146. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  182147. #endif
  182148. #endif
  182149. #if defined(PNG_READ_hIST_SUPPORTED)
  182150. #ifdef PNG_FREE_ME_SUPPORTED
  182151. if (png_ptr->free_me & PNG_FREE_HIST)
  182152. png_free(png_ptr, png_ptr->hist);
  182153. png_ptr->free_me &= ~PNG_FREE_HIST;
  182154. #else
  182155. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  182156. png_free(png_ptr, png_ptr->hist);
  182157. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  182158. #endif
  182159. #endif
  182160. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182161. if (png_ptr->gamma_16_table != NULL)
  182162. {
  182163. int i;
  182164. int istop = (1 << (8 - png_ptr->gamma_shift));
  182165. for (i = 0; i < istop; i++)
  182166. {
  182167. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  182168. }
  182169. png_free(png_ptr, png_ptr->gamma_16_table);
  182170. }
  182171. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182172. if (png_ptr->gamma_16_from_1 != NULL)
  182173. {
  182174. int i;
  182175. int istop = (1 << (8 - png_ptr->gamma_shift));
  182176. for (i = 0; i < istop; i++)
  182177. {
  182178. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  182179. }
  182180. png_free(png_ptr, png_ptr->gamma_16_from_1);
  182181. }
  182182. if (png_ptr->gamma_16_to_1 != NULL)
  182183. {
  182184. int i;
  182185. int istop = (1 << (8 - png_ptr->gamma_shift));
  182186. for (i = 0; i < istop; i++)
  182187. {
  182188. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  182189. }
  182190. png_free(png_ptr, png_ptr->gamma_16_to_1);
  182191. }
  182192. #endif
  182193. #endif
  182194. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182195. png_free(png_ptr, png_ptr->time_buffer);
  182196. #endif
  182197. inflateEnd(&png_ptr->zstream);
  182198. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182199. png_free(png_ptr, png_ptr->save_buffer);
  182200. #endif
  182201. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182202. #ifdef PNG_TEXT_SUPPORTED
  182203. png_free(png_ptr, png_ptr->current_text);
  182204. #endif /* PNG_TEXT_SUPPORTED */
  182205. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182206. /* Save the important info out of the png_struct, in case it is
  182207. * being used again.
  182208. */
  182209. #ifdef PNG_SETJMP_SUPPORTED
  182210. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  182211. #endif
  182212. error_fn = png_ptr->error_fn;
  182213. warning_fn = png_ptr->warning_fn;
  182214. error_ptr = png_ptr->error_ptr;
  182215. #ifdef PNG_USER_MEM_SUPPORTED
  182216. free_fn = png_ptr->free_fn;
  182217. #endif
  182218. png_memset(png_ptr, 0, png_sizeof (png_struct));
  182219. png_ptr->error_fn = error_fn;
  182220. png_ptr->warning_fn = warning_fn;
  182221. png_ptr->error_ptr = error_ptr;
  182222. #ifdef PNG_USER_MEM_SUPPORTED
  182223. png_ptr->free_fn = free_fn;
  182224. #endif
  182225. #ifdef PNG_SETJMP_SUPPORTED
  182226. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  182227. #endif
  182228. }
  182229. void PNGAPI
  182230. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  182231. {
  182232. if(png_ptr == NULL) return;
  182233. png_ptr->read_row_fn = read_row_fn;
  182234. }
  182235. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182236. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182237. void PNGAPI
  182238. png_read_png(png_structp png_ptr, png_infop info_ptr,
  182239. int transforms,
  182240. voidp params)
  182241. {
  182242. int row;
  182243. if(png_ptr == NULL) return;
  182244. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  182245. /* invert the alpha channel from opacity to transparency
  182246. */
  182247. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  182248. png_set_invert_alpha(png_ptr);
  182249. #endif
  182250. /* png_read_info() gives us all of the information from the
  182251. * PNG file before the first IDAT (image data chunk).
  182252. */
  182253. png_read_info(png_ptr, info_ptr);
  182254. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  182255. png_error(png_ptr,"Image is too high to process with png_read_png()");
  182256. /* -------------- image transformations start here ------------------- */
  182257. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  182258. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  182259. */
  182260. if (transforms & PNG_TRANSFORM_STRIP_16)
  182261. png_set_strip_16(png_ptr);
  182262. #endif
  182263. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182264. /* Strip alpha bytes from the input data without combining with
  182265. * the background (not recommended).
  182266. */
  182267. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  182268. png_set_strip_alpha(png_ptr);
  182269. #endif
  182270. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  182271. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  182272. * byte into separate bytes (useful for paletted and grayscale images).
  182273. */
  182274. if (transforms & PNG_TRANSFORM_PACKING)
  182275. png_set_packing(png_ptr);
  182276. #endif
  182277. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  182278. /* Change the order of packed pixels to least significant bit first
  182279. * (not useful if you are using png_set_packing).
  182280. */
  182281. if (transforms & PNG_TRANSFORM_PACKSWAP)
  182282. png_set_packswap(png_ptr);
  182283. #endif
  182284. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182285. /* Expand paletted colors into true RGB triplets
  182286. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  182287. * Expand paletted or RGB images with transparency to full alpha
  182288. * channels so the data will be available as RGBA quartets.
  182289. */
  182290. if (transforms & PNG_TRANSFORM_EXPAND)
  182291. if ((png_ptr->bit_depth < 8) ||
  182292. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  182293. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  182294. png_set_expand(png_ptr);
  182295. #endif
  182296. /* We don't handle background color or gamma transformation or dithering.
  182297. */
  182298. #if defined(PNG_READ_INVERT_SUPPORTED)
  182299. /* invert monochrome files to have 0 as white and 1 as black
  182300. */
  182301. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  182302. png_set_invert_mono(png_ptr);
  182303. #endif
  182304. #if defined(PNG_READ_SHIFT_SUPPORTED)
  182305. /* If you want to shift the pixel values from the range [0,255] or
  182306. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  182307. * colors were originally in:
  182308. */
  182309. if ((transforms & PNG_TRANSFORM_SHIFT)
  182310. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  182311. {
  182312. png_color_8p sig_bit;
  182313. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  182314. png_set_shift(png_ptr, sig_bit);
  182315. }
  182316. #endif
  182317. #if defined(PNG_READ_BGR_SUPPORTED)
  182318. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  182319. */
  182320. if (transforms & PNG_TRANSFORM_BGR)
  182321. png_set_bgr(png_ptr);
  182322. #endif
  182323. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  182324. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  182325. */
  182326. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  182327. png_set_swap_alpha(png_ptr);
  182328. #endif
  182329. #if defined(PNG_READ_SWAP_SUPPORTED)
  182330. /* swap bytes of 16 bit files to least significant byte first
  182331. */
  182332. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  182333. png_set_swap(png_ptr);
  182334. #endif
  182335. /* We don't handle adding filler bytes */
  182336. /* Optional call to gamma correct and add the background to the palette
  182337. * and update info structure. REQUIRED if you are expecting libpng to
  182338. * update the palette for you (i.e., you selected such a transform above).
  182339. */
  182340. png_read_update_info(png_ptr, info_ptr);
  182341. /* -------------- image transformations end here ------------------- */
  182342. #ifdef PNG_FREE_ME_SUPPORTED
  182343. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  182344. #endif
  182345. if(info_ptr->row_pointers == NULL)
  182346. {
  182347. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  182348. info_ptr->height * png_sizeof(png_bytep));
  182349. #ifdef PNG_FREE_ME_SUPPORTED
  182350. info_ptr->free_me |= PNG_FREE_ROWS;
  182351. #endif
  182352. for (row = 0; row < (int)info_ptr->height; row++)
  182353. {
  182354. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  182355. png_get_rowbytes(png_ptr, info_ptr));
  182356. }
  182357. }
  182358. png_read_image(png_ptr, info_ptr->row_pointers);
  182359. info_ptr->valid |= PNG_INFO_IDAT;
  182360. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  182361. png_read_end(png_ptr, info_ptr);
  182362. transforms = transforms; /* quiet compiler warnings */
  182363. params = params;
  182364. }
  182365. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  182366. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  182367. #endif /* PNG_READ_SUPPORTED */
  182368. /********* End of inlined file: pngread.c *********/
  182369. /********* Start of inlined file: pngpread.c *********/
  182370. /* pngpread.c - read a png file in push mode
  182371. *
  182372. * Last changed in libpng 1.2.21 October 4, 2007
  182373. * For conditions of distribution and use, see copyright notice in png.h
  182374. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  182375. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182376. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182377. */
  182378. #define PNG_INTERNAL
  182379. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182380. /* push model modes */
  182381. #define PNG_READ_SIG_MODE 0
  182382. #define PNG_READ_CHUNK_MODE 1
  182383. #define PNG_READ_IDAT_MODE 2
  182384. #define PNG_SKIP_MODE 3
  182385. #define PNG_READ_tEXt_MODE 4
  182386. #define PNG_READ_zTXt_MODE 5
  182387. #define PNG_READ_DONE_MODE 6
  182388. #define PNG_READ_iTXt_MODE 7
  182389. #define PNG_ERROR_MODE 8
  182390. void PNGAPI
  182391. png_process_data(png_structp png_ptr, png_infop info_ptr,
  182392. png_bytep buffer, png_size_t buffer_size)
  182393. {
  182394. if(png_ptr == NULL) return;
  182395. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  182396. while (png_ptr->buffer_size)
  182397. {
  182398. png_process_some_data(png_ptr, info_ptr);
  182399. }
  182400. }
  182401. /* What we do with the incoming data depends on what we were previously
  182402. * doing before we ran out of data...
  182403. */
  182404. void /* PRIVATE */
  182405. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  182406. {
  182407. if(png_ptr == NULL) return;
  182408. switch (png_ptr->process_mode)
  182409. {
  182410. case PNG_READ_SIG_MODE:
  182411. {
  182412. png_push_read_sig(png_ptr, info_ptr);
  182413. break;
  182414. }
  182415. case PNG_READ_CHUNK_MODE:
  182416. {
  182417. png_push_read_chunk(png_ptr, info_ptr);
  182418. break;
  182419. }
  182420. case PNG_READ_IDAT_MODE:
  182421. {
  182422. png_push_read_IDAT(png_ptr);
  182423. break;
  182424. }
  182425. #if defined(PNG_READ_tEXt_SUPPORTED)
  182426. case PNG_READ_tEXt_MODE:
  182427. {
  182428. png_push_read_tEXt(png_ptr, info_ptr);
  182429. break;
  182430. }
  182431. #endif
  182432. #if defined(PNG_READ_zTXt_SUPPORTED)
  182433. case PNG_READ_zTXt_MODE:
  182434. {
  182435. png_push_read_zTXt(png_ptr, info_ptr);
  182436. break;
  182437. }
  182438. #endif
  182439. #if defined(PNG_READ_iTXt_SUPPORTED)
  182440. case PNG_READ_iTXt_MODE:
  182441. {
  182442. png_push_read_iTXt(png_ptr, info_ptr);
  182443. break;
  182444. }
  182445. #endif
  182446. case PNG_SKIP_MODE:
  182447. {
  182448. png_push_crc_finish(png_ptr);
  182449. break;
  182450. }
  182451. default:
  182452. {
  182453. png_ptr->buffer_size = 0;
  182454. break;
  182455. }
  182456. }
  182457. }
  182458. /* Read any remaining signature bytes from the stream and compare them with
  182459. * the correct PNG signature. It is possible that this routine is called
  182460. * with bytes already read from the signature, either because they have been
  182461. * checked by the calling application, or because of multiple calls to this
  182462. * routine.
  182463. */
  182464. void /* PRIVATE */
  182465. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  182466. {
  182467. png_size_t num_checked = png_ptr->sig_bytes,
  182468. num_to_check = 8 - num_checked;
  182469. if (png_ptr->buffer_size < num_to_check)
  182470. {
  182471. num_to_check = png_ptr->buffer_size;
  182472. }
  182473. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  182474. num_to_check);
  182475. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  182476. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  182477. {
  182478. if (num_checked < 4 &&
  182479. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  182480. png_error(png_ptr, "Not a PNG file");
  182481. else
  182482. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  182483. }
  182484. else
  182485. {
  182486. if (png_ptr->sig_bytes >= 8)
  182487. {
  182488. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  182489. }
  182490. }
  182491. }
  182492. void /* PRIVATE */
  182493. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  182494. {
  182495. #ifdef PNG_USE_LOCAL_ARRAYS
  182496. PNG_CONST PNG_IHDR;
  182497. PNG_CONST PNG_IDAT;
  182498. PNG_CONST PNG_IEND;
  182499. PNG_CONST PNG_PLTE;
  182500. #if defined(PNG_READ_bKGD_SUPPORTED)
  182501. PNG_CONST PNG_bKGD;
  182502. #endif
  182503. #if defined(PNG_READ_cHRM_SUPPORTED)
  182504. PNG_CONST PNG_cHRM;
  182505. #endif
  182506. #if defined(PNG_READ_gAMA_SUPPORTED)
  182507. PNG_CONST PNG_gAMA;
  182508. #endif
  182509. #if defined(PNG_READ_hIST_SUPPORTED)
  182510. PNG_CONST PNG_hIST;
  182511. #endif
  182512. #if defined(PNG_READ_iCCP_SUPPORTED)
  182513. PNG_CONST PNG_iCCP;
  182514. #endif
  182515. #if defined(PNG_READ_iTXt_SUPPORTED)
  182516. PNG_CONST PNG_iTXt;
  182517. #endif
  182518. #if defined(PNG_READ_oFFs_SUPPORTED)
  182519. PNG_CONST PNG_oFFs;
  182520. #endif
  182521. #if defined(PNG_READ_pCAL_SUPPORTED)
  182522. PNG_CONST PNG_pCAL;
  182523. #endif
  182524. #if defined(PNG_READ_pHYs_SUPPORTED)
  182525. PNG_CONST PNG_pHYs;
  182526. #endif
  182527. #if defined(PNG_READ_sBIT_SUPPORTED)
  182528. PNG_CONST PNG_sBIT;
  182529. #endif
  182530. #if defined(PNG_READ_sCAL_SUPPORTED)
  182531. PNG_CONST PNG_sCAL;
  182532. #endif
  182533. #if defined(PNG_READ_sRGB_SUPPORTED)
  182534. PNG_CONST PNG_sRGB;
  182535. #endif
  182536. #if defined(PNG_READ_sPLT_SUPPORTED)
  182537. PNG_CONST PNG_sPLT;
  182538. #endif
  182539. #if defined(PNG_READ_tEXt_SUPPORTED)
  182540. PNG_CONST PNG_tEXt;
  182541. #endif
  182542. #if defined(PNG_READ_tIME_SUPPORTED)
  182543. PNG_CONST PNG_tIME;
  182544. #endif
  182545. #if defined(PNG_READ_tRNS_SUPPORTED)
  182546. PNG_CONST PNG_tRNS;
  182547. #endif
  182548. #if defined(PNG_READ_zTXt_SUPPORTED)
  182549. PNG_CONST PNG_zTXt;
  182550. #endif
  182551. #endif /* PNG_USE_LOCAL_ARRAYS */
  182552. /* First we make sure we have enough data for the 4 byte chunk name
  182553. * and the 4 byte chunk length before proceeding with decoding the
  182554. * chunk data. To fully decode each of these chunks, we also make
  182555. * sure we have enough data in the buffer for the 4 byte CRC at the
  182556. * end of every chunk (except IDAT, which is handled separately).
  182557. */
  182558. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  182559. {
  182560. png_byte chunk_length[4];
  182561. if (png_ptr->buffer_size < 8)
  182562. {
  182563. png_push_save_buffer(png_ptr);
  182564. return;
  182565. }
  182566. png_push_fill_buffer(png_ptr, chunk_length, 4);
  182567. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  182568. png_reset_crc(png_ptr);
  182569. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  182570. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  182571. }
  182572. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182573. if(png_ptr->mode & PNG_AFTER_IDAT)
  182574. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  182575. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  182576. {
  182577. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182578. {
  182579. png_push_save_buffer(png_ptr);
  182580. return;
  182581. }
  182582. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  182583. }
  182584. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  182585. {
  182586. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182587. {
  182588. png_push_save_buffer(png_ptr);
  182589. return;
  182590. }
  182591. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  182592. png_ptr->process_mode = PNG_READ_DONE_MODE;
  182593. png_push_have_end(png_ptr, info_ptr);
  182594. }
  182595. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182596. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  182597. {
  182598. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182599. {
  182600. png_push_save_buffer(png_ptr);
  182601. return;
  182602. }
  182603. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182604. png_ptr->mode |= PNG_HAVE_IDAT;
  182605. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  182606. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182607. png_ptr->mode |= PNG_HAVE_PLTE;
  182608. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182609. {
  182610. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  182611. png_error(png_ptr, "Missing IHDR before IDAT");
  182612. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  182613. !(png_ptr->mode & PNG_HAVE_PLTE))
  182614. png_error(png_ptr, "Missing PLTE before IDAT");
  182615. }
  182616. }
  182617. #endif
  182618. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182619. {
  182620. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182621. {
  182622. png_push_save_buffer(png_ptr);
  182623. return;
  182624. }
  182625. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  182626. }
  182627. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182628. {
  182629. /* If we reach an IDAT chunk, this means we have read all of the
  182630. * header chunks, and we can start reading the image (or if this
  182631. * is called after the image has been read - we have an error).
  182632. */
  182633. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  182634. png_error(png_ptr, "Missing IHDR before IDAT");
  182635. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  182636. !(png_ptr->mode & PNG_HAVE_PLTE))
  182637. png_error(png_ptr, "Missing PLTE before IDAT");
  182638. if (png_ptr->mode & PNG_HAVE_IDAT)
  182639. {
  182640. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  182641. if (png_ptr->push_length == 0)
  182642. return;
  182643. if (png_ptr->mode & PNG_AFTER_IDAT)
  182644. png_error(png_ptr, "Too many IDAT's found");
  182645. }
  182646. png_ptr->idat_size = png_ptr->push_length;
  182647. png_ptr->mode |= PNG_HAVE_IDAT;
  182648. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  182649. png_push_have_info(png_ptr, info_ptr);
  182650. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  182651. png_ptr->zstream.next_out = png_ptr->row_buf;
  182652. return;
  182653. }
  182654. #if defined(PNG_READ_gAMA_SUPPORTED)
  182655. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  182656. {
  182657. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182658. {
  182659. png_push_save_buffer(png_ptr);
  182660. return;
  182661. }
  182662. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  182663. }
  182664. #endif
  182665. #if defined(PNG_READ_sBIT_SUPPORTED)
  182666. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  182667. {
  182668. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182669. {
  182670. png_push_save_buffer(png_ptr);
  182671. return;
  182672. }
  182673. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  182674. }
  182675. #endif
  182676. #if defined(PNG_READ_cHRM_SUPPORTED)
  182677. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  182678. {
  182679. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182680. {
  182681. png_push_save_buffer(png_ptr);
  182682. return;
  182683. }
  182684. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  182685. }
  182686. #endif
  182687. #if defined(PNG_READ_sRGB_SUPPORTED)
  182688. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  182689. {
  182690. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182691. {
  182692. png_push_save_buffer(png_ptr);
  182693. return;
  182694. }
  182695. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  182696. }
  182697. #endif
  182698. #if defined(PNG_READ_iCCP_SUPPORTED)
  182699. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  182700. {
  182701. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182702. {
  182703. png_push_save_buffer(png_ptr);
  182704. return;
  182705. }
  182706. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  182707. }
  182708. #endif
  182709. #if defined(PNG_READ_sPLT_SUPPORTED)
  182710. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  182711. {
  182712. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182713. {
  182714. png_push_save_buffer(png_ptr);
  182715. return;
  182716. }
  182717. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  182718. }
  182719. #endif
  182720. #if defined(PNG_READ_tRNS_SUPPORTED)
  182721. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  182722. {
  182723. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182724. {
  182725. png_push_save_buffer(png_ptr);
  182726. return;
  182727. }
  182728. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  182729. }
  182730. #endif
  182731. #if defined(PNG_READ_bKGD_SUPPORTED)
  182732. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  182733. {
  182734. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182735. {
  182736. png_push_save_buffer(png_ptr);
  182737. return;
  182738. }
  182739. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  182740. }
  182741. #endif
  182742. #if defined(PNG_READ_hIST_SUPPORTED)
  182743. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  182744. {
  182745. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182746. {
  182747. png_push_save_buffer(png_ptr);
  182748. return;
  182749. }
  182750. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  182751. }
  182752. #endif
  182753. #if defined(PNG_READ_pHYs_SUPPORTED)
  182754. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  182755. {
  182756. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182757. {
  182758. png_push_save_buffer(png_ptr);
  182759. return;
  182760. }
  182761. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  182762. }
  182763. #endif
  182764. #if defined(PNG_READ_oFFs_SUPPORTED)
  182765. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  182766. {
  182767. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182768. {
  182769. png_push_save_buffer(png_ptr);
  182770. return;
  182771. }
  182772. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  182773. }
  182774. #endif
  182775. #if defined(PNG_READ_pCAL_SUPPORTED)
  182776. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  182777. {
  182778. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182779. {
  182780. png_push_save_buffer(png_ptr);
  182781. return;
  182782. }
  182783. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  182784. }
  182785. #endif
  182786. #if defined(PNG_READ_sCAL_SUPPORTED)
  182787. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  182788. {
  182789. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182790. {
  182791. png_push_save_buffer(png_ptr);
  182792. return;
  182793. }
  182794. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  182795. }
  182796. #endif
  182797. #if defined(PNG_READ_tIME_SUPPORTED)
  182798. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  182799. {
  182800. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182801. {
  182802. png_push_save_buffer(png_ptr);
  182803. return;
  182804. }
  182805. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  182806. }
  182807. #endif
  182808. #if defined(PNG_READ_tEXt_SUPPORTED)
  182809. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  182810. {
  182811. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182812. {
  182813. png_push_save_buffer(png_ptr);
  182814. return;
  182815. }
  182816. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  182817. }
  182818. #endif
  182819. #if defined(PNG_READ_zTXt_SUPPORTED)
  182820. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  182821. {
  182822. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182823. {
  182824. png_push_save_buffer(png_ptr);
  182825. return;
  182826. }
  182827. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  182828. }
  182829. #endif
  182830. #if defined(PNG_READ_iTXt_SUPPORTED)
  182831. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  182832. {
  182833. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182834. {
  182835. png_push_save_buffer(png_ptr);
  182836. return;
  182837. }
  182838. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  182839. }
  182840. #endif
  182841. else
  182842. {
  182843. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182844. {
  182845. png_push_save_buffer(png_ptr);
  182846. return;
  182847. }
  182848. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  182849. }
  182850. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  182851. }
  182852. void /* PRIVATE */
  182853. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  182854. {
  182855. png_ptr->process_mode = PNG_SKIP_MODE;
  182856. png_ptr->skip_length = skip;
  182857. }
  182858. void /* PRIVATE */
  182859. png_push_crc_finish(png_structp png_ptr)
  182860. {
  182861. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  182862. {
  182863. png_size_t save_size;
  182864. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  182865. save_size = (png_size_t)png_ptr->skip_length;
  182866. else
  182867. save_size = png_ptr->save_buffer_size;
  182868. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  182869. png_ptr->skip_length -= save_size;
  182870. png_ptr->buffer_size -= save_size;
  182871. png_ptr->save_buffer_size -= save_size;
  182872. png_ptr->save_buffer_ptr += save_size;
  182873. }
  182874. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  182875. {
  182876. png_size_t save_size;
  182877. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  182878. save_size = (png_size_t)png_ptr->skip_length;
  182879. else
  182880. save_size = png_ptr->current_buffer_size;
  182881. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  182882. png_ptr->skip_length -= save_size;
  182883. png_ptr->buffer_size -= save_size;
  182884. png_ptr->current_buffer_size -= save_size;
  182885. png_ptr->current_buffer_ptr += save_size;
  182886. }
  182887. if (!png_ptr->skip_length)
  182888. {
  182889. if (png_ptr->buffer_size < 4)
  182890. {
  182891. png_push_save_buffer(png_ptr);
  182892. return;
  182893. }
  182894. png_crc_finish(png_ptr, 0);
  182895. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  182896. }
  182897. }
  182898. void PNGAPI
  182899. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  182900. {
  182901. png_bytep ptr;
  182902. if(png_ptr == NULL) return;
  182903. ptr = buffer;
  182904. if (png_ptr->save_buffer_size)
  182905. {
  182906. png_size_t save_size;
  182907. if (length < png_ptr->save_buffer_size)
  182908. save_size = length;
  182909. else
  182910. save_size = png_ptr->save_buffer_size;
  182911. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  182912. length -= save_size;
  182913. ptr += save_size;
  182914. png_ptr->buffer_size -= save_size;
  182915. png_ptr->save_buffer_size -= save_size;
  182916. png_ptr->save_buffer_ptr += save_size;
  182917. }
  182918. if (length && png_ptr->current_buffer_size)
  182919. {
  182920. png_size_t save_size;
  182921. if (length < png_ptr->current_buffer_size)
  182922. save_size = length;
  182923. else
  182924. save_size = png_ptr->current_buffer_size;
  182925. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  182926. png_ptr->buffer_size -= save_size;
  182927. png_ptr->current_buffer_size -= save_size;
  182928. png_ptr->current_buffer_ptr += save_size;
  182929. }
  182930. }
  182931. void /* PRIVATE */
  182932. png_push_save_buffer(png_structp png_ptr)
  182933. {
  182934. if (png_ptr->save_buffer_size)
  182935. {
  182936. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  182937. {
  182938. png_size_t i,istop;
  182939. png_bytep sp;
  182940. png_bytep dp;
  182941. istop = png_ptr->save_buffer_size;
  182942. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  182943. i < istop; i++, sp++, dp++)
  182944. {
  182945. *dp = *sp;
  182946. }
  182947. }
  182948. }
  182949. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  182950. png_ptr->save_buffer_max)
  182951. {
  182952. png_size_t new_max;
  182953. png_bytep old_buffer;
  182954. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  182955. (png_ptr->current_buffer_size + 256))
  182956. {
  182957. png_error(png_ptr, "Potential overflow of save_buffer");
  182958. }
  182959. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  182960. old_buffer = png_ptr->save_buffer;
  182961. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  182962. (png_uint_32)new_max);
  182963. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  182964. png_free(png_ptr, old_buffer);
  182965. png_ptr->save_buffer_max = new_max;
  182966. }
  182967. if (png_ptr->current_buffer_size)
  182968. {
  182969. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  182970. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  182971. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  182972. png_ptr->current_buffer_size = 0;
  182973. }
  182974. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  182975. png_ptr->buffer_size = 0;
  182976. }
  182977. void /* PRIVATE */
  182978. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  182979. png_size_t buffer_length)
  182980. {
  182981. png_ptr->current_buffer = buffer;
  182982. png_ptr->current_buffer_size = buffer_length;
  182983. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  182984. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  182985. }
  182986. void /* PRIVATE */
  182987. png_push_read_IDAT(png_structp png_ptr)
  182988. {
  182989. #ifdef PNG_USE_LOCAL_ARRAYS
  182990. PNG_CONST PNG_IDAT;
  182991. #endif
  182992. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  182993. {
  182994. png_byte chunk_length[4];
  182995. if (png_ptr->buffer_size < 8)
  182996. {
  182997. png_push_save_buffer(png_ptr);
  182998. return;
  182999. }
  183000. png_push_fill_buffer(png_ptr, chunk_length, 4);
  183001. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  183002. png_reset_crc(png_ptr);
  183003. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  183004. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  183005. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183006. {
  183007. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  183008. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  183009. png_error(png_ptr, "Not enough compressed data");
  183010. return;
  183011. }
  183012. png_ptr->idat_size = png_ptr->push_length;
  183013. }
  183014. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  183015. {
  183016. png_size_t save_size;
  183017. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  183018. {
  183019. save_size = (png_size_t)png_ptr->idat_size;
  183020. /* check for overflow */
  183021. if((png_uint_32)save_size != png_ptr->idat_size)
  183022. png_error(png_ptr, "save_size overflowed in pngpread");
  183023. }
  183024. else
  183025. save_size = png_ptr->save_buffer_size;
  183026. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  183027. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  183028. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  183029. png_ptr->idat_size -= save_size;
  183030. png_ptr->buffer_size -= save_size;
  183031. png_ptr->save_buffer_size -= save_size;
  183032. png_ptr->save_buffer_ptr += save_size;
  183033. }
  183034. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  183035. {
  183036. png_size_t save_size;
  183037. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  183038. {
  183039. save_size = (png_size_t)png_ptr->idat_size;
  183040. /* check for overflow */
  183041. if((png_uint_32)save_size != png_ptr->idat_size)
  183042. png_error(png_ptr, "save_size overflowed in pngpread");
  183043. }
  183044. else
  183045. save_size = png_ptr->current_buffer_size;
  183046. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  183047. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  183048. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  183049. png_ptr->idat_size -= save_size;
  183050. png_ptr->buffer_size -= save_size;
  183051. png_ptr->current_buffer_size -= save_size;
  183052. png_ptr->current_buffer_ptr += save_size;
  183053. }
  183054. if (!png_ptr->idat_size)
  183055. {
  183056. if (png_ptr->buffer_size < 4)
  183057. {
  183058. png_push_save_buffer(png_ptr);
  183059. return;
  183060. }
  183061. png_crc_finish(png_ptr, 0);
  183062. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  183063. png_ptr->mode |= PNG_AFTER_IDAT;
  183064. }
  183065. }
  183066. void /* PRIVATE */
  183067. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  183068. png_size_t buffer_length)
  183069. {
  183070. int ret;
  183071. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  183072. png_error(png_ptr, "Extra compression data");
  183073. png_ptr->zstream.next_in = buffer;
  183074. png_ptr->zstream.avail_in = (uInt)buffer_length;
  183075. for(;;)
  183076. {
  183077. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  183078. if (ret != Z_OK)
  183079. {
  183080. if (ret == Z_STREAM_END)
  183081. {
  183082. if (png_ptr->zstream.avail_in)
  183083. png_error(png_ptr, "Extra compressed data");
  183084. if (!(png_ptr->zstream.avail_out))
  183085. {
  183086. png_push_process_row(png_ptr);
  183087. }
  183088. png_ptr->mode |= PNG_AFTER_IDAT;
  183089. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  183090. break;
  183091. }
  183092. else if (ret == Z_BUF_ERROR)
  183093. break;
  183094. else
  183095. png_error(png_ptr, "Decompression Error");
  183096. }
  183097. if (!(png_ptr->zstream.avail_out))
  183098. {
  183099. if ((
  183100. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183101. png_ptr->interlaced && png_ptr->pass > 6) ||
  183102. (!png_ptr->interlaced &&
  183103. #endif
  183104. png_ptr->row_number == png_ptr->num_rows))
  183105. {
  183106. if (png_ptr->zstream.avail_in)
  183107. {
  183108. png_warning(png_ptr, "Too much data in IDAT chunks");
  183109. }
  183110. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  183111. break;
  183112. }
  183113. png_push_process_row(png_ptr);
  183114. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  183115. png_ptr->zstream.next_out = png_ptr->row_buf;
  183116. }
  183117. else
  183118. break;
  183119. }
  183120. }
  183121. void /* PRIVATE */
  183122. png_push_process_row(png_structp png_ptr)
  183123. {
  183124. png_ptr->row_info.color_type = png_ptr->color_type;
  183125. png_ptr->row_info.width = png_ptr->iwidth;
  183126. png_ptr->row_info.channels = png_ptr->channels;
  183127. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  183128. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  183129. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  183130. png_ptr->row_info.width);
  183131. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  183132. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  183133. (int)(png_ptr->row_buf[0]));
  183134. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  183135. png_ptr->rowbytes + 1);
  183136. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  183137. png_do_read_transformations(png_ptr);
  183138. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183139. /* blow up interlaced rows to full size */
  183140. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  183141. {
  183142. if (png_ptr->pass < 6)
  183143. /* old interface (pre-1.0.9):
  183144. png_do_read_interlace(&(png_ptr->row_info),
  183145. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  183146. */
  183147. png_do_read_interlace(png_ptr);
  183148. switch (png_ptr->pass)
  183149. {
  183150. case 0:
  183151. {
  183152. int i;
  183153. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  183154. {
  183155. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183156. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  183157. }
  183158. if (png_ptr->pass == 2) /* pass 1 might be empty */
  183159. {
  183160. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  183161. {
  183162. png_push_have_row(png_ptr, png_bytep_NULL);
  183163. png_read_push_finish_row(png_ptr);
  183164. }
  183165. }
  183166. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  183167. {
  183168. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  183169. {
  183170. png_push_have_row(png_ptr, png_bytep_NULL);
  183171. png_read_push_finish_row(png_ptr);
  183172. }
  183173. }
  183174. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  183175. {
  183176. png_push_have_row(png_ptr, png_bytep_NULL);
  183177. png_read_push_finish_row(png_ptr);
  183178. }
  183179. break;
  183180. }
  183181. case 1:
  183182. {
  183183. int i;
  183184. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  183185. {
  183186. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183187. png_read_push_finish_row(png_ptr);
  183188. }
  183189. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  183190. {
  183191. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  183192. {
  183193. png_push_have_row(png_ptr, png_bytep_NULL);
  183194. png_read_push_finish_row(png_ptr);
  183195. }
  183196. }
  183197. break;
  183198. }
  183199. case 2:
  183200. {
  183201. int i;
  183202. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  183203. {
  183204. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183205. png_read_push_finish_row(png_ptr);
  183206. }
  183207. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  183208. {
  183209. png_push_have_row(png_ptr, png_bytep_NULL);
  183210. png_read_push_finish_row(png_ptr);
  183211. }
  183212. if (png_ptr->pass == 4) /* pass 3 might be empty */
  183213. {
  183214. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  183215. {
  183216. png_push_have_row(png_ptr, png_bytep_NULL);
  183217. png_read_push_finish_row(png_ptr);
  183218. }
  183219. }
  183220. break;
  183221. }
  183222. case 3:
  183223. {
  183224. int i;
  183225. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  183226. {
  183227. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183228. png_read_push_finish_row(png_ptr);
  183229. }
  183230. if (png_ptr->pass == 4) /* skip top two generated rows */
  183231. {
  183232. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  183233. {
  183234. png_push_have_row(png_ptr, png_bytep_NULL);
  183235. png_read_push_finish_row(png_ptr);
  183236. }
  183237. }
  183238. break;
  183239. }
  183240. case 4:
  183241. {
  183242. int i;
  183243. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  183244. {
  183245. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183246. png_read_push_finish_row(png_ptr);
  183247. }
  183248. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  183249. {
  183250. png_push_have_row(png_ptr, png_bytep_NULL);
  183251. png_read_push_finish_row(png_ptr);
  183252. }
  183253. if (png_ptr->pass == 6) /* pass 5 might be empty */
  183254. {
  183255. png_push_have_row(png_ptr, png_bytep_NULL);
  183256. png_read_push_finish_row(png_ptr);
  183257. }
  183258. break;
  183259. }
  183260. case 5:
  183261. {
  183262. int i;
  183263. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  183264. {
  183265. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183266. png_read_push_finish_row(png_ptr);
  183267. }
  183268. if (png_ptr->pass == 6) /* skip top generated row */
  183269. {
  183270. png_push_have_row(png_ptr, png_bytep_NULL);
  183271. png_read_push_finish_row(png_ptr);
  183272. }
  183273. break;
  183274. }
  183275. case 6:
  183276. {
  183277. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183278. png_read_push_finish_row(png_ptr);
  183279. if (png_ptr->pass != 6)
  183280. break;
  183281. png_push_have_row(png_ptr, png_bytep_NULL);
  183282. png_read_push_finish_row(png_ptr);
  183283. }
  183284. }
  183285. }
  183286. else
  183287. #endif
  183288. {
  183289. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183290. png_read_push_finish_row(png_ptr);
  183291. }
  183292. }
  183293. void /* PRIVATE */
  183294. png_read_push_finish_row(png_structp png_ptr)
  183295. {
  183296. #ifdef PNG_USE_LOCAL_ARRAYS
  183297. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  183298. /* start of interlace block */
  183299. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  183300. /* offset to next interlace block */
  183301. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  183302. /* start of interlace block in the y direction */
  183303. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  183304. /* offset to next interlace block in the y direction */
  183305. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  183306. /* Height of interlace block. This is not currently used - if you need
  183307. * it, uncomment it here and in png.h
  183308. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  183309. */
  183310. #endif
  183311. png_ptr->row_number++;
  183312. if (png_ptr->row_number < png_ptr->num_rows)
  183313. return;
  183314. if (png_ptr->interlaced)
  183315. {
  183316. png_ptr->row_number = 0;
  183317. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  183318. png_ptr->rowbytes + 1);
  183319. do
  183320. {
  183321. png_ptr->pass++;
  183322. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  183323. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  183324. (png_ptr->pass == 5 && png_ptr->width < 2))
  183325. png_ptr->pass++;
  183326. if (png_ptr->pass > 7)
  183327. png_ptr->pass--;
  183328. if (png_ptr->pass >= 7)
  183329. break;
  183330. png_ptr->iwidth = (png_ptr->width +
  183331. png_pass_inc[png_ptr->pass] - 1 -
  183332. png_pass_start[png_ptr->pass]) /
  183333. png_pass_inc[png_ptr->pass];
  183334. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  183335. png_ptr->iwidth) + 1;
  183336. if (png_ptr->transformations & PNG_INTERLACE)
  183337. break;
  183338. png_ptr->num_rows = (png_ptr->height +
  183339. png_pass_yinc[png_ptr->pass] - 1 -
  183340. png_pass_ystart[png_ptr->pass]) /
  183341. png_pass_yinc[png_ptr->pass];
  183342. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  183343. }
  183344. }
  183345. #if defined(PNG_READ_tEXt_SUPPORTED)
  183346. void /* PRIVATE */
  183347. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  183348. length)
  183349. {
  183350. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  183351. {
  183352. png_error(png_ptr, "Out of place tEXt");
  183353. info_ptr = info_ptr; /* to quiet some compiler warnings */
  183354. }
  183355. #ifdef PNG_MAX_MALLOC_64K
  183356. png_ptr->skip_length = 0; /* This may not be necessary */
  183357. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  183358. {
  183359. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  183360. png_ptr->skip_length = length - (png_uint_32)65535L;
  183361. length = (png_uint_32)65535L;
  183362. }
  183363. #endif
  183364. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  183365. (png_uint_32)(length+1));
  183366. png_ptr->current_text[length] = '\0';
  183367. png_ptr->current_text_ptr = png_ptr->current_text;
  183368. png_ptr->current_text_size = (png_size_t)length;
  183369. png_ptr->current_text_left = (png_size_t)length;
  183370. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  183371. }
  183372. void /* PRIVATE */
  183373. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  183374. {
  183375. if (png_ptr->buffer_size && png_ptr->current_text_left)
  183376. {
  183377. png_size_t text_size;
  183378. if (png_ptr->buffer_size < png_ptr->current_text_left)
  183379. text_size = png_ptr->buffer_size;
  183380. else
  183381. text_size = png_ptr->current_text_left;
  183382. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  183383. png_ptr->current_text_left -= text_size;
  183384. png_ptr->current_text_ptr += text_size;
  183385. }
  183386. if (!(png_ptr->current_text_left))
  183387. {
  183388. png_textp text_ptr;
  183389. png_charp text;
  183390. png_charp key;
  183391. int ret;
  183392. if (png_ptr->buffer_size < 4)
  183393. {
  183394. png_push_save_buffer(png_ptr);
  183395. return;
  183396. }
  183397. png_push_crc_finish(png_ptr);
  183398. #if defined(PNG_MAX_MALLOC_64K)
  183399. if (png_ptr->skip_length)
  183400. return;
  183401. #endif
  183402. key = png_ptr->current_text;
  183403. for (text = key; *text; text++)
  183404. /* empty loop */ ;
  183405. if (text < key + png_ptr->current_text_size)
  183406. text++;
  183407. text_ptr = (png_textp)png_malloc(png_ptr,
  183408. (png_uint_32)png_sizeof(png_text));
  183409. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  183410. text_ptr->key = key;
  183411. #ifdef PNG_iTXt_SUPPORTED
  183412. text_ptr->lang = NULL;
  183413. text_ptr->lang_key = NULL;
  183414. #endif
  183415. text_ptr->text = text;
  183416. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  183417. png_free(png_ptr, key);
  183418. png_free(png_ptr, text_ptr);
  183419. png_ptr->current_text = NULL;
  183420. if (ret)
  183421. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  183422. }
  183423. }
  183424. #endif
  183425. #if defined(PNG_READ_zTXt_SUPPORTED)
  183426. void /* PRIVATE */
  183427. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  183428. length)
  183429. {
  183430. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  183431. {
  183432. png_error(png_ptr, "Out of place zTXt");
  183433. info_ptr = info_ptr; /* to quiet some compiler warnings */
  183434. }
  183435. #ifdef PNG_MAX_MALLOC_64K
  183436. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  183437. * to be able to store the uncompressed data. Actually, the threshold
  183438. * is probably around 32K, but it isn't as definite as 64K is.
  183439. */
  183440. if (length > (png_uint_32)65535L)
  183441. {
  183442. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  183443. png_push_crc_skip(png_ptr, length);
  183444. return;
  183445. }
  183446. #endif
  183447. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  183448. (png_uint_32)(length+1));
  183449. png_ptr->current_text[length] = '\0';
  183450. png_ptr->current_text_ptr = png_ptr->current_text;
  183451. png_ptr->current_text_size = (png_size_t)length;
  183452. png_ptr->current_text_left = (png_size_t)length;
  183453. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  183454. }
  183455. void /* PRIVATE */
  183456. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  183457. {
  183458. if (png_ptr->buffer_size && png_ptr->current_text_left)
  183459. {
  183460. png_size_t text_size;
  183461. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  183462. text_size = png_ptr->buffer_size;
  183463. else
  183464. text_size = png_ptr->current_text_left;
  183465. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  183466. png_ptr->current_text_left -= text_size;
  183467. png_ptr->current_text_ptr += text_size;
  183468. }
  183469. if (!(png_ptr->current_text_left))
  183470. {
  183471. png_textp text_ptr;
  183472. png_charp text;
  183473. png_charp key;
  183474. int ret;
  183475. png_size_t text_size, key_size;
  183476. if (png_ptr->buffer_size < 4)
  183477. {
  183478. png_push_save_buffer(png_ptr);
  183479. return;
  183480. }
  183481. png_push_crc_finish(png_ptr);
  183482. key = png_ptr->current_text;
  183483. for (text = key; *text; text++)
  183484. /* empty loop */ ;
  183485. /* zTXt can't have zero text */
  183486. if (text >= key + png_ptr->current_text_size)
  183487. {
  183488. png_ptr->current_text = NULL;
  183489. png_free(png_ptr, key);
  183490. return;
  183491. }
  183492. text++;
  183493. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  183494. {
  183495. png_ptr->current_text = NULL;
  183496. png_free(png_ptr, key);
  183497. return;
  183498. }
  183499. text++;
  183500. png_ptr->zstream.next_in = (png_bytep )text;
  183501. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  183502. (text - key));
  183503. png_ptr->zstream.next_out = png_ptr->zbuf;
  183504. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  183505. key_size = text - key;
  183506. text_size = 0;
  183507. text = NULL;
  183508. ret = Z_STREAM_END;
  183509. while (png_ptr->zstream.avail_in)
  183510. {
  183511. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  183512. if (ret != Z_OK && ret != Z_STREAM_END)
  183513. {
  183514. inflateReset(&png_ptr->zstream);
  183515. png_ptr->zstream.avail_in = 0;
  183516. png_ptr->current_text = NULL;
  183517. png_free(png_ptr, key);
  183518. png_free(png_ptr, text);
  183519. return;
  183520. }
  183521. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  183522. {
  183523. if (text == NULL)
  183524. {
  183525. text = (png_charp)png_malloc(png_ptr,
  183526. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  183527. + key_size + 1));
  183528. png_memcpy(text + key_size, png_ptr->zbuf,
  183529. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  183530. png_memcpy(text, key, key_size);
  183531. text_size = key_size + png_ptr->zbuf_size -
  183532. png_ptr->zstream.avail_out;
  183533. *(text + text_size) = '\0';
  183534. }
  183535. else
  183536. {
  183537. png_charp tmp;
  183538. tmp = text;
  183539. text = (png_charp)png_malloc(png_ptr, text_size +
  183540. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  183541. + 1));
  183542. png_memcpy(text, tmp, text_size);
  183543. png_free(png_ptr, tmp);
  183544. png_memcpy(text + text_size, png_ptr->zbuf,
  183545. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  183546. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  183547. *(text + text_size) = '\0';
  183548. }
  183549. if (ret != Z_STREAM_END)
  183550. {
  183551. png_ptr->zstream.next_out = png_ptr->zbuf;
  183552. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  183553. }
  183554. }
  183555. else
  183556. {
  183557. break;
  183558. }
  183559. if (ret == Z_STREAM_END)
  183560. break;
  183561. }
  183562. inflateReset(&png_ptr->zstream);
  183563. png_ptr->zstream.avail_in = 0;
  183564. if (ret != Z_STREAM_END)
  183565. {
  183566. png_ptr->current_text = NULL;
  183567. png_free(png_ptr, key);
  183568. png_free(png_ptr, text);
  183569. return;
  183570. }
  183571. png_ptr->current_text = NULL;
  183572. png_free(png_ptr, key);
  183573. key = text;
  183574. text += key_size;
  183575. text_ptr = (png_textp)png_malloc(png_ptr,
  183576. (png_uint_32)png_sizeof(png_text));
  183577. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  183578. text_ptr->key = key;
  183579. #ifdef PNG_iTXt_SUPPORTED
  183580. text_ptr->lang = NULL;
  183581. text_ptr->lang_key = NULL;
  183582. #endif
  183583. text_ptr->text = text;
  183584. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  183585. png_free(png_ptr, key);
  183586. png_free(png_ptr, text_ptr);
  183587. if (ret)
  183588. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  183589. }
  183590. }
  183591. #endif
  183592. #if defined(PNG_READ_iTXt_SUPPORTED)
  183593. void /* PRIVATE */
  183594. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  183595. length)
  183596. {
  183597. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  183598. {
  183599. png_error(png_ptr, "Out of place iTXt");
  183600. info_ptr = info_ptr; /* to quiet some compiler warnings */
  183601. }
  183602. #ifdef PNG_MAX_MALLOC_64K
  183603. png_ptr->skip_length = 0; /* This may not be necessary */
  183604. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  183605. {
  183606. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  183607. png_ptr->skip_length = length - (png_uint_32)65535L;
  183608. length = (png_uint_32)65535L;
  183609. }
  183610. #endif
  183611. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  183612. (png_uint_32)(length+1));
  183613. png_ptr->current_text[length] = '\0';
  183614. png_ptr->current_text_ptr = png_ptr->current_text;
  183615. png_ptr->current_text_size = (png_size_t)length;
  183616. png_ptr->current_text_left = (png_size_t)length;
  183617. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  183618. }
  183619. void /* PRIVATE */
  183620. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  183621. {
  183622. if (png_ptr->buffer_size && png_ptr->current_text_left)
  183623. {
  183624. png_size_t text_size;
  183625. if (png_ptr->buffer_size < png_ptr->current_text_left)
  183626. text_size = png_ptr->buffer_size;
  183627. else
  183628. text_size = png_ptr->current_text_left;
  183629. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  183630. png_ptr->current_text_left -= text_size;
  183631. png_ptr->current_text_ptr += text_size;
  183632. }
  183633. if (!(png_ptr->current_text_left))
  183634. {
  183635. png_textp text_ptr;
  183636. png_charp key;
  183637. int comp_flag;
  183638. png_charp lang;
  183639. png_charp lang_key;
  183640. png_charp text;
  183641. int ret;
  183642. if (png_ptr->buffer_size < 4)
  183643. {
  183644. png_push_save_buffer(png_ptr);
  183645. return;
  183646. }
  183647. png_push_crc_finish(png_ptr);
  183648. #if defined(PNG_MAX_MALLOC_64K)
  183649. if (png_ptr->skip_length)
  183650. return;
  183651. #endif
  183652. key = png_ptr->current_text;
  183653. for (lang = key; *lang; lang++)
  183654. /* empty loop */ ;
  183655. if (lang < key + png_ptr->current_text_size - 3)
  183656. lang++;
  183657. comp_flag = *lang++;
  183658. lang++; /* skip comp_type, always zero */
  183659. for (lang_key = lang; *lang_key; lang_key++)
  183660. /* empty loop */ ;
  183661. lang_key++; /* skip NUL separator */
  183662. text=lang_key;
  183663. if (lang_key < key + png_ptr->current_text_size - 1)
  183664. {
  183665. for (; *text; text++)
  183666. /* empty loop */ ;
  183667. }
  183668. if (text < key + png_ptr->current_text_size)
  183669. text++;
  183670. text_ptr = (png_textp)png_malloc(png_ptr,
  183671. (png_uint_32)png_sizeof(png_text));
  183672. text_ptr->compression = comp_flag + 2;
  183673. text_ptr->key = key;
  183674. text_ptr->lang = lang;
  183675. text_ptr->lang_key = lang_key;
  183676. text_ptr->text = text;
  183677. text_ptr->text_length = 0;
  183678. text_ptr->itxt_length = png_strlen(text);
  183679. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  183680. png_ptr->current_text = NULL;
  183681. png_free(png_ptr, text_ptr);
  183682. if (ret)
  183683. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  183684. }
  183685. }
  183686. #endif
  183687. /* This function is called when we haven't found a handler for this
  183688. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  183689. * name or a critical chunk), the chunk is (currently) silently ignored.
  183690. */
  183691. void /* PRIVATE */
  183692. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  183693. length)
  183694. {
  183695. png_uint_32 skip=0;
  183696. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  183697. if (!(png_ptr->chunk_name[0] & 0x20))
  183698. {
  183699. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  183700. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  183701. PNG_HANDLE_CHUNK_ALWAYS
  183702. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  183703. && png_ptr->read_user_chunk_fn == NULL
  183704. #endif
  183705. )
  183706. #endif
  183707. png_chunk_error(png_ptr, "unknown critical chunk");
  183708. info_ptr = info_ptr; /* to quiet some compiler warnings */
  183709. }
  183710. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  183711. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  183712. {
  183713. #ifdef PNG_MAX_MALLOC_64K
  183714. if (length > (png_uint_32)65535L)
  183715. {
  183716. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  183717. skip = length - (png_uint_32)65535L;
  183718. length = (png_uint_32)65535L;
  183719. }
  183720. #endif
  183721. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  183722. (png_charp)png_ptr->chunk_name, 5);
  183723. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  183724. png_ptr->unknown_chunk.size = (png_size_t)length;
  183725. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  183726. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  183727. if(png_ptr->read_user_chunk_fn != NULL)
  183728. {
  183729. /* callback to user unknown chunk handler */
  183730. int ret;
  183731. ret = (*(png_ptr->read_user_chunk_fn))
  183732. (png_ptr, &png_ptr->unknown_chunk);
  183733. if (ret < 0)
  183734. png_chunk_error(png_ptr, "error in user chunk");
  183735. if (ret == 0)
  183736. {
  183737. if (!(png_ptr->chunk_name[0] & 0x20))
  183738. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  183739. PNG_HANDLE_CHUNK_ALWAYS)
  183740. png_chunk_error(png_ptr, "unknown critical chunk");
  183741. png_set_unknown_chunks(png_ptr, info_ptr,
  183742. &png_ptr->unknown_chunk, 1);
  183743. }
  183744. }
  183745. #else
  183746. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  183747. #endif
  183748. png_free(png_ptr, png_ptr->unknown_chunk.data);
  183749. png_ptr->unknown_chunk.data = NULL;
  183750. }
  183751. else
  183752. #endif
  183753. skip=length;
  183754. png_push_crc_skip(png_ptr, skip);
  183755. }
  183756. void /* PRIVATE */
  183757. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  183758. {
  183759. if (png_ptr->info_fn != NULL)
  183760. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  183761. }
  183762. void /* PRIVATE */
  183763. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  183764. {
  183765. if (png_ptr->end_fn != NULL)
  183766. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  183767. }
  183768. void /* PRIVATE */
  183769. png_push_have_row(png_structp png_ptr, png_bytep row)
  183770. {
  183771. if (png_ptr->row_fn != NULL)
  183772. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  183773. (int)png_ptr->pass);
  183774. }
  183775. void PNGAPI
  183776. png_progressive_combine_row (png_structp png_ptr,
  183777. png_bytep old_row, png_bytep new_row)
  183778. {
  183779. #ifdef PNG_USE_LOCAL_ARRAYS
  183780. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  183781. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  183782. #endif
  183783. if(png_ptr == NULL) return;
  183784. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  183785. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  183786. }
  183787. void PNGAPI
  183788. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  183789. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183790. png_progressive_end_ptr end_fn)
  183791. {
  183792. if(png_ptr == NULL) return;
  183793. png_ptr->info_fn = info_fn;
  183794. png_ptr->row_fn = row_fn;
  183795. png_ptr->end_fn = end_fn;
  183796. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  183797. }
  183798. png_voidp PNGAPI
  183799. png_get_progressive_ptr(png_structp png_ptr)
  183800. {
  183801. if(png_ptr == NULL) return (NULL);
  183802. return png_ptr->io_ptr;
  183803. }
  183804. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183805. /********* End of inlined file: pngpread.c *********/
  183806. /********* Start of inlined file: pngrio.c *********/
  183807. /* pngrio.c - functions for data input
  183808. *
  183809. * Last changed in libpng 1.2.13 November 13, 2006
  183810. * For conditions of distribution and use, see copyright notice in png.h
  183811. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  183812. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183813. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183814. *
  183815. * This file provides a location for all input. Users who need
  183816. * special handling are expected to write a function that has the same
  183817. * arguments as this and performs a similar function, but that possibly
  183818. * has a different input method. Note that you shouldn't change this
  183819. * function, but rather write a replacement function and then make
  183820. * libpng use it at run time with png_set_read_fn(...).
  183821. */
  183822. #define PNG_INTERNAL
  183823. #if defined(PNG_READ_SUPPORTED)
  183824. /* Read the data from whatever input you are using. The default routine
  183825. reads from a file pointer. Note that this routine sometimes gets called
  183826. with very small lengths, so you should implement some kind of simple
  183827. buffering if you are using unbuffered reads. This should never be asked
  183828. to read more then 64K on a 16 bit machine. */
  183829. void /* PRIVATE */
  183830. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  183831. {
  183832. png_debug1(4,"reading %d bytes\n", (int)length);
  183833. if (png_ptr->read_data_fn != NULL)
  183834. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  183835. else
  183836. png_error(png_ptr, "Call to NULL read function");
  183837. }
  183838. #if !defined(PNG_NO_STDIO)
  183839. /* This is the function that does the actual reading of data. If you are
  183840. not reading from a standard C stream, you should create a replacement
  183841. read_data function and use it at run time with png_set_read_fn(), rather
  183842. than changing the library. */
  183843. #ifndef USE_FAR_KEYWORD
  183844. void PNGAPI
  183845. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  183846. {
  183847. png_size_t check;
  183848. if(png_ptr == NULL) return;
  183849. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  183850. * instead of an int, which is what fread() actually returns.
  183851. */
  183852. #if defined(_WIN32_WCE)
  183853. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  183854. check = 0;
  183855. #else
  183856. check = (png_size_t)fread(data, (png_size_t)1, length,
  183857. (png_FILE_p)png_ptr->io_ptr);
  183858. #endif
  183859. if (check != length)
  183860. png_error(png_ptr, "Read Error");
  183861. }
  183862. #else
  183863. /* this is the model-independent version. Since the standard I/O library
  183864. can't handle far buffers in the medium and small models, we have to copy
  183865. the data.
  183866. */
  183867. #define NEAR_BUF_SIZE 1024
  183868. #define MIN(a,b) (a <= b ? a : b)
  183869. static void PNGAPI
  183870. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  183871. {
  183872. int check;
  183873. png_byte *n_data;
  183874. png_FILE_p io_ptr;
  183875. if(png_ptr == NULL) return;
  183876. /* Check if data really is near. If so, use usual code. */
  183877. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  183878. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  183879. if ((png_bytep)n_data == data)
  183880. {
  183881. #if defined(_WIN32_WCE)
  183882. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  183883. check = 0;
  183884. #else
  183885. check = fread(n_data, 1, length, io_ptr);
  183886. #endif
  183887. }
  183888. else
  183889. {
  183890. png_byte buf[NEAR_BUF_SIZE];
  183891. png_size_t read, remaining, err;
  183892. check = 0;
  183893. remaining = length;
  183894. do
  183895. {
  183896. read = MIN(NEAR_BUF_SIZE, remaining);
  183897. #if defined(_WIN32_WCE)
  183898. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  183899. err = 0;
  183900. #else
  183901. err = fread(buf, (png_size_t)1, read, io_ptr);
  183902. #endif
  183903. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  183904. if(err != read)
  183905. break;
  183906. else
  183907. check += err;
  183908. data += read;
  183909. remaining -= read;
  183910. }
  183911. while (remaining != 0);
  183912. }
  183913. if ((png_uint_32)check != (png_uint_32)length)
  183914. png_error(png_ptr, "read Error");
  183915. }
  183916. #endif
  183917. #endif
  183918. /* This function allows the application to supply a new input function
  183919. for libpng if standard C streams aren't being used.
  183920. This function takes as its arguments:
  183921. png_ptr - pointer to a png input data structure
  183922. io_ptr - pointer to user supplied structure containing info about
  183923. the input functions. May be NULL.
  183924. read_data_fn - pointer to a new input function that takes as its
  183925. arguments a pointer to a png_struct, a pointer to
  183926. a location where input data can be stored, and a 32-bit
  183927. unsigned int that is the number of bytes to be read.
  183928. To exit and output any fatal error messages the new write
  183929. function should call png_error(png_ptr, "Error msg"). */
  183930. void PNGAPI
  183931. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  183932. png_rw_ptr read_data_fn)
  183933. {
  183934. if(png_ptr == NULL) return;
  183935. png_ptr->io_ptr = io_ptr;
  183936. #if !defined(PNG_NO_STDIO)
  183937. if (read_data_fn != NULL)
  183938. png_ptr->read_data_fn = read_data_fn;
  183939. else
  183940. png_ptr->read_data_fn = png_default_read_data;
  183941. #else
  183942. png_ptr->read_data_fn = read_data_fn;
  183943. #endif
  183944. /* It is an error to write to a read device */
  183945. if (png_ptr->write_data_fn != NULL)
  183946. {
  183947. png_ptr->write_data_fn = NULL;
  183948. png_warning(png_ptr,
  183949. "It's an error to set both read_data_fn and write_data_fn in the ");
  183950. png_warning(png_ptr,
  183951. "same structure. Resetting write_data_fn to NULL.");
  183952. }
  183953. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183954. png_ptr->output_flush_fn = NULL;
  183955. #endif
  183956. }
  183957. #endif /* PNG_READ_SUPPORTED */
  183958. /********* End of inlined file: pngrio.c *********/
  183959. /********* Start of inlined file: pngrtran.c *********/
  183960. /* pngrtran.c - transforms the data in a row for PNG readers
  183961. *
  183962. * Last changed in libpng 1.2.21 [October 4, 2007]
  183963. * For conditions of distribution and use, see copyright notice in png.h
  183964. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  183965. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183966. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183967. *
  183968. * This file contains functions optionally called by an application
  183969. * in order to tell libpng how to handle data when reading a PNG.
  183970. * Transformations that are used in both reading and writing are
  183971. * in pngtrans.c.
  183972. */
  183973. #define PNG_INTERNAL
  183974. #if defined(PNG_READ_SUPPORTED)
  183975. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  183976. void PNGAPI
  183977. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  183978. {
  183979. png_debug(1, "in png_set_crc_action\n");
  183980. /* Tell libpng how we react to CRC errors in critical chunks */
  183981. if(png_ptr == NULL) return;
  183982. switch (crit_action)
  183983. {
  183984. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  183985. break;
  183986. case PNG_CRC_WARN_USE: /* warn/use data */
  183987. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  183988. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  183989. break;
  183990. case PNG_CRC_QUIET_USE: /* quiet/use data */
  183991. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  183992. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  183993. PNG_FLAG_CRC_CRITICAL_IGNORE;
  183994. break;
  183995. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  183996. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  183997. case PNG_CRC_ERROR_QUIT: /* error/quit */
  183998. case PNG_CRC_DEFAULT:
  183999. default:
  184000. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  184001. break;
  184002. }
  184003. switch (ancil_action)
  184004. {
  184005. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  184006. break;
  184007. case PNG_CRC_WARN_USE: /* warn/use data */
  184008. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  184009. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  184010. break;
  184011. case PNG_CRC_QUIET_USE: /* quiet/use data */
  184012. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  184013. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  184014. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  184015. break;
  184016. case PNG_CRC_ERROR_QUIT: /* error/quit */
  184017. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  184018. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  184019. break;
  184020. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  184021. case PNG_CRC_DEFAULT:
  184022. default:
  184023. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  184024. break;
  184025. }
  184026. }
  184027. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  184028. defined(PNG_FLOATING_POINT_SUPPORTED)
  184029. /* handle alpha and tRNS via a background color */
  184030. void PNGAPI
  184031. png_set_background(png_structp png_ptr,
  184032. png_color_16p background_color, int background_gamma_code,
  184033. int need_expand, double background_gamma)
  184034. {
  184035. png_debug(1, "in png_set_background\n");
  184036. if(png_ptr == NULL) return;
  184037. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  184038. {
  184039. png_warning(png_ptr, "Application must supply a known background gamma");
  184040. return;
  184041. }
  184042. png_ptr->transformations |= PNG_BACKGROUND;
  184043. png_memcpy(&(png_ptr->background), background_color,
  184044. png_sizeof(png_color_16));
  184045. png_ptr->background_gamma = (float)background_gamma;
  184046. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  184047. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  184048. }
  184049. #endif
  184050. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184051. /* strip 16 bit depth files to 8 bit depth */
  184052. void PNGAPI
  184053. png_set_strip_16(png_structp png_ptr)
  184054. {
  184055. png_debug(1, "in png_set_strip_16\n");
  184056. if(png_ptr == NULL) return;
  184057. png_ptr->transformations |= PNG_16_TO_8;
  184058. }
  184059. #endif
  184060. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184061. void PNGAPI
  184062. png_set_strip_alpha(png_structp png_ptr)
  184063. {
  184064. png_debug(1, "in png_set_strip_alpha\n");
  184065. if(png_ptr == NULL) return;
  184066. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  184067. }
  184068. #endif
  184069. #if defined(PNG_READ_DITHER_SUPPORTED)
  184070. /* Dither file to 8 bit. Supply a palette, the current number
  184071. * of elements in the palette, the maximum number of elements
  184072. * allowed, and a histogram if possible. If the current number
  184073. * of colors is greater then the maximum number, the palette will be
  184074. * modified to fit in the maximum number. "full_dither" indicates
  184075. * whether we need a dithering cube set up for RGB images, or if we
  184076. * simply are reducing the number of colors in a paletted image.
  184077. */
  184078. typedef struct png_dsort_struct
  184079. {
  184080. struct png_dsort_struct FAR * next;
  184081. png_byte left;
  184082. png_byte right;
  184083. } png_dsort;
  184084. typedef png_dsort FAR * png_dsortp;
  184085. typedef png_dsort FAR * FAR * png_dsortpp;
  184086. void PNGAPI
  184087. png_set_dither(png_structp png_ptr, png_colorp palette,
  184088. int num_palette, int maximum_colors, png_uint_16p histogram,
  184089. int full_dither)
  184090. {
  184091. png_debug(1, "in png_set_dither\n");
  184092. if(png_ptr == NULL) return;
  184093. png_ptr->transformations |= PNG_DITHER;
  184094. if (!full_dither)
  184095. {
  184096. int i;
  184097. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  184098. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  184099. for (i = 0; i < num_palette; i++)
  184100. png_ptr->dither_index[i] = (png_byte)i;
  184101. }
  184102. if (num_palette > maximum_colors)
  184103. {
  184104. if (histogram != NULL)
  184105. {
  184106. /* This is easy enough, just throw out the least used colors.
  184107. Perhaps not the best solution, but good enough. */
  184108. int i;
  184109. /* initialize an array to sort colors */
  184110. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  184111. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  184112. /* initialize the dither_sort array */
  184113. for (i = 0; i < num_palette; i++)
  184114. png_ptr->dither_sort[i] = (png_byte)i;
  184115. /* Find the least used palette entries by starting a
  184116. bubble sort, and running it until we have sorted
  184117. out enough colors. Note that we don't care about
  184118. sorting all the colors, just finding which are
  184119. least used. */
  184120. for (i = num_palette - 1; i >= maximum_colors; i--)
  184121. {
  184122. int done; /* to stop early if the list is pre-sorted */
  184123. int j;
  184124. done = 1;
  184125. for (j = 0; j < i; j++)
  184126. {
  184127. if (histogram[png_ptr->dither_sort[j]]
  184128. < histogram[png_ptr->dither_sort[j + 1]])
  184129. {
  184130. png_byte t;
  184131. t = png_ptr->dither_sort[j];
  184132. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  184133. png_ptr->dither_sort[j + 1] = t;
  184134. done = 0;
  184135. }
  184136. }
  184137. if (done)
  184138. break;
  184139. }
  184140. /* swap the palette around, and set up a table, if necessary */
  184141. if (full_dither)
  184142. {
  184143. int j = num_palette;
  184144. /* put all the useful colors within the max, but don't
  184145. move the others */
  184146. for (i = 0; i < maximum_colors; i++)
  184147. {
  184148. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  184149. {
  184150. do
  184151. j--;
  184152. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  184153. palette[i] = palette[j];
  184154. }
  184155. }
  184156. }
  184157. else
  184158. {
  184159. int j = num_palette;
  184160. /* move all the used colors inside the max limit, and
  184161. develop a translation table */
  184162. for (i = 0; i < maximum_colors; i++)
  184163. {
  184164. /* only move the colors we need to */
  184165. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  184166. {
  184167. png_color tmp_color;
  184168. do
  184169. j--;
  184170. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  184171. tmp_color = palette[j];
  184172. palette[j] = palette[i];
  184173. palette[i] = tmp_color;
  184174. /* indicate where the color went */
  184175. png_ptr->dither_index[j] = (png_byte)i;
  184176. png_ptr->dither_index[i] = (png_byte)j;
  184177. }
  184178. }
  184179. /* find closest color for those colors we are not using */
  184180. for (i = 0; i < num_palette; i++)
  184181. {
  184182. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  184183. {
  184184. int min_d, k, min_k, d_index;
  184185. /* find the closest color to one we threw out */
  184186. d_index = png_ptr->dither_index[i];
  184187. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  184188. for (k = 1, min_k = 0; k < maximum_colors; k++)
  184189. {
  184190. int d;
  184191. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  184192. if (d < min_d)
  184193. {
  184194. min_d = d;
  184195. min_k = k;
  184196. }
  184197. }
  184198. /* point to closest color */
  184199. png_ptr->dither_index[i] = (png_byte)min_k;
  184200. }
  184201. }
  184202. }
  184203. png_free(png_ptr, png_ptr->dither_sort);
  184204. png_ptr->dither_sort=NULL;
  184205. }
  184206. else
  184207. {
  184208. /* This is much harder to do simply (and quickly). Perhaps
  184209. we need to go through a median cut routine, but those
  184210. don't always behave themselves with only a few colors
  184211. as input. So we will just find the closest two colors,
  184212. and throw out one of them (chosen somewhat randomly).
  184213. [We don't understand this at all, so if someone wants to
  184214. work on improving it, be our guest - AED, GRP]
  184215. */
  184216. int i;
  184217. int max_d;
  184218. int num_new_palette;
  184219. png_dsortp t;
  184220. png_dsortpp hash;
  184221. t=NULL;
  184222. /* initialize palette index arrays */
  184223. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  184224. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  184225. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  184226. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  184227. /* initialize the sort array */
  184228. for (i = 0; i < num_palette; i++)
  184229. {
  184230. png_ptr->index_to_palette[i] = (png_byte)i;
  184231. png_ptr->palette_to_index[i] = (png_byte)i;
  184232. }
  184233. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  184234. png_sizeof (png_dsortp)));
  184235. for (i = 0; i < 769; i++)
  184236. hash[i] = NULL;
  184237. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  184238. num_new_palette = num_palette;
  184239. /* initial wild guess at how far apart the farthest pixel
  184240. pair we will be eliminating will be. Larger
  184241. numbers mean more areas will be allocated, Smaller
  184242. numbers run the risk of not saving enough data, and
  184243. having to do this all over again.
  184244. I have not done extensive checking on this number.
  184245. */
  184246. max_d = 96;
  184247. while (num_new_palette > maximum_colors)
  184248. {
  184249. for (i = 0; i < num_new_palette - 1; i++)
  184250. {
  184251. int j;
  184252. for (j = i + 1; j < num_new_palette; j++)
  184253. {
  184254. int d;
  184255. d = PNG_COLOR_DIST(palette[i], palette[j]);
  184256. if (d <= max_d)
  184257. {
  184258. t = (png_dsortp)png_malloc_warn(png_ptr,
  184259. (png_uint_32)(png_sizeof(png_dsort)));
  184260. if (t == NULL)
  184261. break;
  184262. t->next = hash[d];
  184263. t->left = (png_byte)i;
  184264. t->right = (png_byte)j;
  184265. hash[d] = t;
  184266. }
  184267. }
  184268. if (t == NULL)
  184269. break;
  184270. }
  184271. if (t != NULL)
  184272. for (i = 0; i <= max_d; i++)
  184273. {
  184274. if (hash[i] != NULL)
  184275. {
  184276. png_dsortp p;
  184277. for (p = hash[i]; p; p = p->next)
  184278. {
  184279. if ((int)png_ptr->index_to_palette[p->left]
  184280. < num_new_palette &&
  184281. (int)png_ptr->index_to_palette[p->right]
  184282. < num_new_palette)
  184283. {
  184284. int j, next_j;
  184285. if (num_new_palette & 0x01)
  184286. {
  184287. j = p->left;
  184288. next_j = p->right;
  184289. }
  184290. else
  184291. {
  184292. j = p->right;
  184293. next_j = p->left;
  184294. }
  184295. num_new_palette--;
  184296. palette[png_ptr->index_to_palette[j]]
  184297. = palette[num_new_palette];
  184298. if (!full_dither)
  184299. {
  184300. int k;
  184301. for (k = 0; k < num_palette; k++)
  184302. {
  184303. if (png_ptr->dither_index[k] ==
  184304. png_ptr->index_to_palette[j])
  184305. png_ptr->dither_index[k] =
  184306. png_ptr->index_to_palette[next_j];
  184307. if ((int)png_ptr->dither_index[k] ==
  184308. num_new_palette)
  184309. png_ptr->dither_index[k] =
  184310. png_ptr->index_to_palette[j];
  184311. }
  184312. }
  184313. png_ptr->index_to_palette[png_ptr->palette_to_index
  184314. [num_new_palette]] = png_ptr->index_to_palette[j];
  184315. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  184316. = png_ptr->palette_to_index[num_new_palette];
  184317. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  184318. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  184319. }
  184320. if (num_new_palette <= maximum_colors)
  184321. break;
  184322. }
  184323. if (num_new_palette <= maximum_colors)
  184324. break;
  184325. }
  184326. }
  184327. for (i = 0; i < 769; i++)
  184328. {
  184329. if (hash[i] != NULL)
  184330. {
  184331. png_dsortp p = hash[i];
  184332. while (p)
  184333. {
  184334. t = p->next;
  184335. png_free(png_ptr, p);
  184336. p = t;
  184337. }
  184338. }
  184339. hash[i] = 0;
  184340. }
  184341. max_d += 96;
  184342. }
  184343. png_free(png_ptr, hash);
  184344. png_free(png_ptr, png_ptr->palette_to_index);
  184345. png_free(png_ptr, png_ptr->index_to_palette);
  184346. png_ptr->palette_to_index=NULL;
  184347. png_ptr->index_to_palette=NULL;
  184348. }
  184349. num_palette = maximum_colors;
  184350. }
  184351. if (png_ptr->palette == NULL)
  184352. {
  184353. png_ptr->palette = palette;
  184354. }
  184355. png_ptr->num_palette = (png_uint_16)num_palette;
  184356. if (full_dither)
  184357. {
  184358. int i;
  184359. png_bytep distance;
  184360. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  184361. PNG_DITHER_BLUE_BITS;
  184362. int num_red = (1 << PNG_DITHER_RED_BITS);
  184363. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  184364. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  184365. png_size_t num_entries = ((png_size_t)1 << total_bits);
  184366. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  184367. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  184368. png_memset(png_ptr->palette_lookup, 0, num_entries *
  184369. png_sizeof (png_byte));
  184370. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  184371. png_sizeof(png_byte)));
  184372. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  184373. for (i = 0; i < num_palette; i++)
  184374. {
  184375. int ir, ig, ib;
  184376. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  184377. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  184378. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  184379. for (ir = 0; ir < num_red; ir++)
  184380. {
  184381. /* int dr = abs(ir - r); */
  184382. int dr = ((ir > r) ? ir - r : r - ir);
  184383. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  184384. for (ig = 0; ig < num_green; ig++)
  184385. {
  184386. /* int dg = abs(ig - g); */
  184387. int dg = ((ig > g) ? ig - g : g - ig);
  184388. int dt = dr + dg;
  184389. int dm = ((dr > dg) ? dr : dg);
  184390. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  184391. for (ib = 0; ib < num_blue; ib++)
  184392. {
  184393. int d_index = index_g | ib;
  184394. /* int db = abs(ib - b); */
  184395. int db = ((ib > b) ? ib - b : b - ib);
  184396. int dmax = ((dm > db) ? dm : db);
  184397. int d = dmax + dt + db;
  184398. if (d < (int)distance[d_index])
  184399. {
  184400. distance[d_index] = (png_byte)d;
  184401. png_ptr->palette_lookup[d_index] = (png_byte)i;
  184402. }
  184403. }
  184404. }
  184405. }
  184406. }
  184407. png_free(png_ptr, distance);
  184408. }
  184409. }
  184410. #endif
  184411. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184412. /* Transform the image from the file_gamma to the screen_gamma. We
  184413. * only do transformations on images where the file_gamma and screen_gamma
  184414. * are not close reciprocals, otherwise it slows things down slightly, and
  184415. * also needlessly introduces small errors.
  184416. *
  184417. * We will turn off gamma transformation later if no semitransparent entries
  184418. * are present in the tRNS array for palette images. We can't do it here
  184419. * because we don't necessarily have the tRNS chunk yet.
  184420. */
  184421. void PNGAPI
  184422. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  184423. {
  184424. png_debug(1, "in png_set_gamma\n");
  184425. if(png_ptr == NULL) return;
  184426. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  184427. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  184428. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  184429. png_ptr->transformations |= PNG_GAMMA;
  184430. png_ptr->gamma = (float)file_gamma;
  184431. png_ptr->screen_gamma = (float)scrn_gamma;
  184432. }
  184433. #endif
  184434. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184435. /* Expand paletted images to RGB, expand grayscale images of
  184436. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  184437. * to alpha channels.
  184438. */
  184439. void PNGAPI
  184440. png_set_expand(png_structp png_ptr)
  184441. {
  184442. png_debug(1, "in png_set_expand\n");
  184443. if(png_ptr == NULL) return;
  184444. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  184445. #ifdef PNG_WARN_UNINITIALIZED_ROW
  184446. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  184447. #endif
  184448. }
  184449. /* GRR 19990627: the following three functions currently are identical
  184450. * to png_set_expand(). However, it is entirely reasonable that someone
  184451. * might wish to expand an indexed image to RGB but *not* expand a single,
  184452. * fully transparent palette entry to a full alpha channel--perhaps instead
  184453. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  184454. * the transparent color with a particular RGB value, or drop tRNS entirely.
  184455. * IOW, a future version of the library may make the transformations flag
  184456. * a bit more fine-grained, with separate bits for each of these three
  184457. * functions.
  184458. *
  184459. * More to the point, these functions make it obvious what libpng will be
  184460. * doing, whereas "expand" can (and does) mean any number of things.
  184461. *
  184462. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  184463. * to expand only the sample depth but not to expand the tRNS to alpha.
  184464. */
  184465. /* Expand paletted images to RGB. */
  184466. void PNGAPI
  184467. png_set_palette_to_rgb(png_structp png_ptr)
  184468. {
  184469. png_debug(1, "in png_set_palette_to_rgb\n");
  184470. if(png_ptr == NULL) return;
  184471. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  184472. #ifdef PNG_WARN_UNINITIALIZED_ROW
  184473. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  184474. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  184475. #endif
  184476. }
  184477. #if !defined(PNG_1_0_X)
  184478. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  184479. void PNGAPI
  184480. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  184481. {
  184482. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  184483. if(png_ptr == NULL) return;
  184484. png_ptr->transformations |= PNG_EXPAND;
  184485. #ifdef PNG_WARN_UNINITIALIZED_ROW
  184486. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  184487. #endif
  184488. }
  184489. #endif
  184490. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184491. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  184492. /* Deprecated as of libpng-1.2.9 */
  184493. void PNGAPI
  184494. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  184495. {
  184496. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  184497. if(png_ptr == NULL) return;
  184498. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  184499. }
  184500. #endif
  184501. /* Expand tRNS chunks to alpha channels. */
  184502. void PNGAPI
  184503. png_set_tRNS_to_alpha(png_structp png_ptr)
  184504. {
  184505. png_debug(1, "in png_set_tRNS_to_alpha\n");
  184506. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  184507. #ifdef PNG_WARN_UNINITIALIZED_ROW
  184508. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  184509. #endif
  184510. }
  184511. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  184512. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184513. void PNGAPI
  184514. png_set_gray_to_rgb(png_structp png_ptr)
  184515. {
  184516. png_debug(1, "in png_set_gray_to_rgb\n");
  184517. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  184518. #ifdef PNG_WARN_UNINITIALIZED_ROW
  184519. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  184520. #endif
  184521. }
  184522. #endif
  184523. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184524. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  184525. /* Convert a RGB image to a grayscale of the same width. This allows us,
  184526. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  184527. */
  184528. void PNGAPI
  184529. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  184530. double green)
  184531. {
  184532. int red_fixed = (int)((float)red*100000.0 + 0.5);
  184533. int green_fixed = (int)((float)green*100000.0 + 0.5);
  184534. if(png_ptr == NULL) return;
  184535. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  184536. }
  184537. #endif
  184538. void PNGAPI
  184539. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  184540. png_fixed_point red, png_fixed_point green)
  184541. {
  184542. png_debug(1, "in png_set_rgb_to_gray\n");
  184543. if(png_ptr == NULL) return;
  184544. switch(error_action)
  184545. {
  184546. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  184547. break;
  184548. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  184549. break;
  184550. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  184551. }
  184552. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  184553. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184554. png_ptr->transformations |= PNG_EXPAND;
  184555. #else
  184556. {
  184557. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  184558. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  184559. }
  184560. #endif
  184561. {
  184562. png_uint_16 red_int, green_int;
  184563. if(red < 0 || green < 0)
  184564. {
  184565. red_int = 6968; /* .212671 * 32768 + .5 */
  184566. green_int = 23434; /* .715160 * 32768 + .5 */
  184567. }
  184568. else if(red + green < 100000L)
  184569. {
  184570. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  184571. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  184572. }
  184573. else
  184574. {
  184575. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  184576. red_int = 6968;
  184577. green_int = 23434;
  184578. }
  184579. png_ptr->rgb_to_gray_red_coeff = red_int;
  184580. png_ptr->rgb_to_gray_green_coeff = green_int;
  184581. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  184582. }
  184583. }
  184584. #endif
  184585. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  184586. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  184587. defined(PNG_LEGACY_SUPPORTED)
  184588. void PNGAPI
  184589. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  184590. read_user_transform_fn)
  184591. {
  184592. png_debug(1, "in png_set_read_user_transform_fn\n");
  184593. if(png_ptr == NULL) return;
  184594. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  184595. png_ptr->transformations |= PNG_USER_TRANSFORM;
  184596. png_ptr->read_user_transform_fn = read_user_transform_fn;
  184597. #endif
  184598. #ifdef PNG_LEGACY_SUPPORTED
  184599. if(read_user_transform_fn)
  184600. png_warning(png_ptr,
  184601. "This version of libpng does not support user transforms");
  184602. #endif
  184603. }
  184604. #endif
  184605. /* Initialize everything needed for the read. This includes modifying
  184606. * the palette.
  184607. */
  184608. void /* PRIVATE */
  184609. png_init_read_transformations(png_structp png_ptr)
  184610. {
  184611. png_debug(1, "in png_init_read_transformations\n");
  184612. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  184613. if(png_ptr != NULL)
  184614. #endif
  184615. {
  184616. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  184617. || defined(PNG_READ_GAMMA_SUPPORTED)
  184618. int color_type = png_ptr->color_type;
  184619. #endif
  184620. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  184621. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184622. /* Detect gray background and attempt to enable optimization
  184623. * for gray --> RGB case */
  184624. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  184625. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  184626. * background color might actually be gray yet not be flagged as such.
  184627. * This is not a problem for the current code, which uses
  184628. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  184629. * png_do_gray_to_rgb() transformation.
  184630. */
  184631. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  184632. !(color_type & PNG_COLOR_MASK_COLOR))
  184633. {
  184634. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  184635. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  184636. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  184637. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  184638. png_ptr->background.red == png_ptr->background.green &&
  184639. png_ptr->background.red == png_ptr->background.blue)
  184640. {
  184641. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  184642. png_ptr->background.gray = png_ptr->background.red;
  184643. }
  184644. #endif
  184645. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  184646. (png_ptr->transformations & PNG_EXPAND))
  184647. {
  184648. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  184649. {
  184650. /* expand background and tRNS chunks */
  184651. switch (png_ptr->bit_depth)
  184652. {
  184653. case 1:
  184654. png_ptr->background.gray *= (png_uint_16)0xff;
  184655. png_ptr->background.red = png_ptr->background.green
  184656. = png_ptr->background.blue = png_ptr->background.gray;
  184657. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  184658. {
  184659. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  184660. png_ptr->trans_values.red = png_ptr->trans_values.green
  184661. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  184662. }
  184663. break;
  184664. case 2:
  184665. png_ptr->background.gray *= (png_uint_16)0x55;
  184666. png_ptr->background.red = png_ptr->background.green
  184667. = png_ptr->background.blue = png_ptr->background.gray;
  184668. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  184669. {
  184670. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  184671. png_ptr->trans_values.red = png_ptr->trans_values.green
  184672. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  184673. }
  184674. break;
  184675. case 4:
  184676. png_ptr->background.gray *= (png_uint_16)0x11;
  184677. png_ptr->background.red = png_ptr->background.green
  184678. = png_ptr->background.blue = png_ptr->background.gray;
  184679. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  184680. {
  184681. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  184682. png_ptr->trans_values.red = png_ptr->trans_values.green
  184683. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  184684. }
  184685. break;
  184686. case 8:
  184687. case 16:
  184688. png_ptr->background.red = png_ptr->background.green
  184689. = png_ptr->background.blue = png_ptr->background.gray;
  184690. break;
  184691. }
  184692. }
  184693. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  184694. {
  184695. png_ptr->background.red =
  184696. png_ptr->palette[png_ptr->background.index].red;
  184697. png_ptr->background.green =
  184698. png_ptr->palette[png_ptr->background.index].green;
  184699. png_ptr->background.blue =
  184700. png_ptr->palette[png_ptr->background.index].blue;
  184701. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184702. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  184703. {
  184704. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184705. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  184706. #endif
  184707. {
  184708. /* invert the alpha channel (in tRNS) unless the pixels are
  184709. going to be expanded, in which case leave it for later */
  184710. int i,istop;
  184711. istop=(int)png_ptr->num_trans;
  184712. for (i=0; i<istop; i++)
  184713. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  184714. }
  184715. }
  184716. #endif
  184717. }
  184718. }
  184719. #endif
  184720. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  184721. png_ptr->background_1 = png_ptr->background;
  184722. #endif
  184723. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184724. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  184725. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  184726. < PNG_GAMMA_THRESHOLD))
  184727. {
  184728. int i,k;
  184729. k=0;
  184730. for (i=0; i<png_ptr->num_trans; i++)
  184731. {
  184732. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  184733. k=1; /* partial transparency is present */
  184734. }
  184735. if (k == 0)
  184736. png_ptr->transformations &= (~PNG_GAMMA);
  184737. }
  184738. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  184739. png_ptr->gamma != 0.0)
  184740. {
  184741. png_build_gamma_table(png_ptr);
  184742. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184743. if (png_ptr->transformations & PNG_BACKGROUND)
  184744. {
  184745. if (color_type == PNG_COLOR_TYPE_PALETTE)
  184746. {
  184747. /* could skip if no transparency and
  184748. */
  184749. png_color back, back_1;
  184750. png_colorp palette = png_ptr->palette;
  184751. int num_palette = png_ptr->num_palette;
  184752. int i;
  184753. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  184754. {
  184755. back.red = png_ptr->gamma_table[png_ptr->background.red];
  184756. back.green = png_ptr->gamma_table[png_ptr->background.green];
  184757. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  184758. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  184759. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  184760. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  184761. }
  184762. else
  184763. {
  184764. double g, gs;
  184765. switch (png_ptr->background_gamma_type)
  184766. {
  184767. case PNG_BACKGROUND_GAMMA_SCREEN:
  184768. g = (png_ptr->screen_gamma);
  184769. gs = 1.0;
  184770. break;
  184771. case PNG_BACKGROUND_GAMMA_FILE:
  184772. g = 1.0 / (png_ptr->gamma);
  184773. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  184774. break;
  184775. case PNG_BACKGROUND_GAMMA_UNIQUE:
  184776. g = 1.0 / (png_ptr->background_gamma);
  184777. gs = 1.0 / (png_ptr->background_gamma *
  184778. png_ptr->screen_gamma);
  184779. break;
  184780. default:
  184781. g = 1.0; /* back_1 */
  184782. gs = 1.0; /* back */
  184783. }
  184784. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  184785. {
  184786. back.red = (png_byte)png_ptr->background.red;
  184787. back.green = (png_byte)png_ptr->background.green;
  184788. back.blue = (png_byte)png_ptr->background.blue;
  184789. }
  184790. else
  184791. {
  184792. back.red = (png_byte)(pow(
  184793. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  184794. back.green = (png_byte)(pow(
  184795. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  184796. back.blue = (png_byte)(pow(
  184797. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  184798. }
  184799. back_1.red = (png_byte)(pow(
  184800. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  184801. back_1.green = (png_byte)(pow(
  184802. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  184803. back_1.blue = (png_byte)(pow(
  184804. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  184805. }
  184806. for (i = 0; i < num_palette; i++)
  184807. {
  184808. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  184809. {
  184810. if (png_ptr->trans[i] == 0)
  184811. {
  184812. palette[i] = back;
  184813. }
  184814. else /* if (png_ptr->trans[i] != 0xff) */
  184815. {
  184816. png_byte v, w;
  184817. v = png_ptr->gamma_to_1[palette[i].red];
  184818. png_composite(w, v, png_ptr->trans[i], back_1.red);
  184819. palette[i].red = png_ptr->gamma_from_1[w];
  184820. v = png_ptr->gamma_to_1[palette[i].green];
  184821. png_composite(w, v, png_ptr->trans[i], back_1.green);
  184822. palette[i].green = png_ptr->gamma_from_1[w];
  184823. v = png_ptr->gamma_to_1[palette[i].blue];
  184824. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  184825. palette[i].blue = png_ptr->gamma_from_1[w];
  184826. }
  184827. }
  184828. else
  184829. {
  184830. palette[i].red = png_ptr->gamma_table[palette[i].red];
  184831. palette[i].green = png_ptr->gamma_table[palette[i].green];
  184832. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  184833. }
  184834. }
  184835. }
  184836. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  184837. else
  184838. /* color_type != PNG_COLOR_TYPE_PALETTE */
  184839. {
  184840. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  184841. double g = 1.0;
  184842. double gs = 1.0;
  184843. switch (png_ptr->background_gamma_type)
  184844. {
  184845. case PNG_BACKGROUND_GAMMA_SCREEN:
  184846. g = (png_ptr->screen_gamma);
  184847. gs = 1.0;
  184848. break;
  184849. case PNG_BACKGROUND_GAMMA_FILE:
  184850. g = 1.0 / (png_ptr->gamma);
  184851. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  184852. break;
  184853. case PNG_BACKGROUND_GAMMA_UNIQUE:
  184854. g = 1.0 / (png_ptr->background_gamma);
  184855. gs = 1.0 / (png_ptr->background_gamma *
  184856. png_ptr->screen_gamma);
  184857. break;
  184858. }
  184859. png_ptr->background_1.gray = (png_uint_16)(pow(
  184860. (double)png_ptr->background.gray / m, g) * m + .5);
  184861. png_ptr->background.gray = (png_uint_16)(pow(
  184862. (double)png_ptr->background.gray / m, gs) * m + .5);
  184863. if ((png_ptr->background.red != png_ptr->background.green) ||
  184864. (png_ptr->background.red != png_ptr->background.blue) ||
  184865. (png_ptr->background.red != png_ptr->background.gray))
  184866. {
  184867. /* RGB or RGBA with color background */
  184868. png_ptr->background_1.red = (png_uint_16)(pow(
  184869. (double)png_ptr->background.red / m, g) * m + .5);
  184870. png_ptr->background_1.green = (png_uint_16)(pow(
  184871. (double)png_ptr->background.green / m, g) * m + .5);
  184872. png_ptr->background_1.blue = (png_uint_16)(pow(
  184873. (double)png_ptr->background.blue / m, g) * m + .5);
  184874. png_ptr->background.red = (png_uint_16)(pow(
  184875. (double)png_ptr->background.red / m, gs) * m + .5);
  184876. png_ptr->background.green = (png_uint_16)(pow(
  184877. (double)png_ptr->background.green / m, gs) * m + .5);
  184878. png_ptr->background.blue = (png_uint_16)(pow(
  184879. (double)png_ptr->background.blue / m, gs) * m + .5);
  184880. }
  184881. else
  184882. {
  184883. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  184884. png_ptr->background_1.red = png_ptr->background_1.green
  184885. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  184886. png_ptr->background.red = png_ptr->background.green
  184887. = png_ptr->background.blue = png_ptr->background.gray;
  184888. }
  184889. }
  184890. }
  184891. else
  184892. /* transformation does not include PNG_BACKGROUND */
  184893. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  184894. if (color_type == PNG_COLOR_TYPE_PALETTE)
  184895. {
  184896. png_colorp palette = png_ptr->palette;
  184897. int num_palette = png_ptr->num_palette;
  184898. int i;
  184899. for (i = 0; i < num_palette; i++)
  184900. {
  184901. palette[i].red = png_ptr->gamma_table[palette[i].red];
  184902. palette[i].green = png_ptr->gamma_table[palette[i].green];
  184903. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  184904. }
  184905. }
  184906. }
  184907. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184908. else
  184909. #endif
  184910. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  184911. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184912. /* No GAMMA transformation */
  184913. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  184914. (color_type == PNG_COLOR_TYPE_PALETTE))
  184915. {
  184916. int i;
  184917. int istop = (int)png_ptr->num_trans;
  184918. png_color back;
  184919. png_colorp palette = png_ptr->palette;
  184920. back.red = (png_byte)png_ptr->background.red;
  184921. back.green = (png_byte)png_ptr->background.green;
  184922. back.blue = (png_byte)png_ptr->background.blue;
  184923. for (i = 0; i < istop; i++)
  184924. {
  184925. if (png_ptr->trans[i] == 0)
  184926. {
  184927. palette[i] = back;
  184928. }
  184929. else if (png_ptr->trans[i] != 0xff)
  184930. {
  184931. /* The png_composite() macro is defined in png.h */
  184932. png_composite(palette[i].red, palette[i].red,
  184933. png_ptr->trans[i], back.red);
  184934. png_composite(palette[i].green, palette[i].green,
  184935. png_ptr->trans[i], back.green);
  184936. png_composite(palette[i].blue, palette[i].blue,
  184937. png_ptr->trans[i], back.blue);
  184938. }
  184939. }
  184940. }
  184941. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  184942. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184943. if ((png_ptr->transformations & PNG_SHIFT) &&
  184944. (color_type == PNG_COLOR_TYPE_PALETTE))
  184945. {
  184946. png_uint_16 i;
  184947. png_uint_16 istop = png_ptr->num_palette;
  184948. int sr = 8 - png_ptr->sig_bit.red;
  184949. int sg = 8 - png_ptr->sig_bit.green;
  184950. int sb = 8 - png_ptr->sig_bit.blue;
  184951. if (sr < 0 || sr > 8)
  184952. sr = 0;
  184953. if (sg < 0 || sg > 8)
  184954. sg = 0;
  184955. if (sb < 0 || sb > 8)
  184956. sb = 0;
  184957. for (i = 0; i < istop; i++)
  184958. {
  184959. png_ptr->palette[i].red >>= sr;
  184960. png_ptr->palette[i].green >>= sg;
  184961. png_ptr->palette[i].blue >>= sb;
  184962. }
  184963. }
  184964. #endif /* PNG_READ_SHIFT_SUPPORTED */
  184965. }
  184966. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  184967. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  184968. if(png_ptr)
  184969. return;
  184970. #endif
  184971. }
  184972. /* Modify the info structure to reflect the transformations. The
  184973. * info should be updated so a PNG file could be written with it,
  184974. * assuming the transformations result in valid PNG data.
  184975. */
  184976. void /* PRIVATE */
  184977. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  184978. {
  184979. png_debug(1, "in png_read_transform_info\n");
  184980. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184981. if (png_ptr->transformations & PNG_EXPAND)
  184982. {
  184983. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  184984. {
  184985. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  184986. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  184987. else
  184988. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  184989. info_ptr->bit_depth = 8;
  184990. info_ptr->num_trans = 0;
  184991. }
  184992. else
  184993. {
  184994. if (png_ptr->num_trans)
  184995. {
  184996. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  184997. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  184998. else
  184999. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  185000. }
  185001. if (info_ptr->bit_depth < 8)
  185002. info_ptr->bit_depth = 8;
  185003. info_ptr->num_trans = 0;
  185004. }
  185005. }
  185006. #endif
  185007. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185008. if (png_ptr->transformations & PNG_BACKGROUND)
  185009. {
  185010. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  185011. info_ptr->num_trans = 0;
  185012. info_ptr->background = png_ptr->background;
  185013. }
  185014. #endif
  185015. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185016. if (png_ptr->transformations & PNG_GAMMA)
  185017. {
  185018. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185019. info_ptr->gamma = png_ptr->gamma;
  185020. #endif
  185021. #ifdef PNG_FIXED_POINT_SUPPORTED
  185022. info_ptr->int_gamma = png_ptr->int_gamma;
  185023. #endif
  185024. }
  185025. #endif
  185026. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  185027. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  185028. info_ptr->bit_depth = 8;
  185029. #endif
  185030. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185031. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  185032. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  185033. #endif
  185034. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185035. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  185036. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  185037. #endif
  185038. #if defined(PNG_READ_DITHER_SUPPORTED)
  185039. if (png_ptr->transformations & PNG_DITHER)
  185040. {
  185041. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  185042. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  185043. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  185044. {
  185045. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  185046. }
  185047. }
  185048. #endif
  185049. #if defined(PNG_READ_PACK_SUPPORTED)
  185050. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  185051. info_ptr->bit_depth = 8;
  185052. #endif
  185053. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185054. info_ptr->channels = 1;
  185055. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  185056. info_ptr->channels = 3;
  185057. else
  185058. info_ptr->channels = 1;
  185059. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  185060. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  185061. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  185062. #endif
  185063. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  185064. info_ptr->channels++;
  185065. #if defined(PNG_READ_FILLER_SUPPORTED)
  185066. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  185067. if ((png_ptr->transformations & PNG_FILLER) &&
  185068. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  185069. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  185070. {
  185071. info_ptr->channels++;
  185072. /* if adding a true alpha channel not just filler */
  185073. #if !defined(PNG_1_0_X)
  185074. if (png_ptr->transformations & PNG_ADD_ALPHA)
  185075. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  185076. #endif
  185077. }
  185078. #endif
  185079. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  185080. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  185081. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  185082. {
  185083. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  185084. info_ptr->bit_depth = png_ptr->user_transform_depth;
  185085. if(info_ptr->channels < png_ptr->user_transform_channels)
  185086. info_ptr->channels = png_ptr->user_transform_channels;
  185087. }
  185088. #endif
  185089. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  185090. info_ptr->bit_depth);
  185091. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  185092. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  185093. if(png_ptr)
  185094. return;
  185095. #endif
  185096. }
  185097. /* Transform the row. The order of transformations is significant,
  185098. * and is very touchy. If you add a transformation, take care to
  185099. * decide how it fits in with the other transformations here.
  185100. */
  185101. void /* PRIVATE */
  185102. png_do_read_transformations(png_structp png_ptr)
  185103. {
  185104. png_debug(1, "in png_do_read_transformations\n");
  185105. if (png_ptr->row_buf == NULL)
  185106. {
  185107. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  185108. char msg[50];
  185109. png_snprintf2(msg, 50,
  185110. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  185111. png_ptr->pass);
  185112. png_error(png_ptr, msg);
  185113. #else
  185114. png_error(png_ptr, "NULL row buffer");
  185115. #endif
  185116. }
  185117. #ifdef PNG_WARN_UNINITIALIZED_ROW
  185118. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  185119. /* Application has failed to call either png_read_start_image()
  185120. * or png_read_update_info() after setting transforms that expand
  185121. * pixels. This check added to libpng-1.2.19 */
  185122. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  185123. png_error(png_ptr, "Uninitialized row");
  185124. #else
  185125. png_warning(png_ptr, "Uninitialized row");
  185126. #endif
  185127. #endif
  185128. #if defined(PNG_READ_EXPAND_SUPPORTED)
  185129. if (png_ptr->transformations & PNG_EXPAND)
  185130. {
  185131. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  185132. {
  185133. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185134. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  185135. }
  185136. else
  185137. {
  185138. if (png_ptr->num_trans &&
  185139. (png_ptr->transformations & PNG_EXPAND_tRNS))
  185140. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185141. &(png_ptr->trans_values));
  185142. else
  185143. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185144. NULL);
  185145. }
  185146. }
  185147. #endif
  185148. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  185149. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  185150. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185151. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  185152. #endif
  185153. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185154. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  185155. {
  185156. int rgb_error =
  185157. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  185158. if(rgb_error)
  185159. {
  185160. png_ptr->rgb_to_gray_status=1;
  185161. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  185162. PNG_RGB_TO_GRAY_WARN)
  185163. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  185164. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  185165. PNG_RGB_TO_GRAY_ERR)
  185166. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  185167. }
  185168. }
  185169. #endif
  185170. /*
  185171. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  185172. In most cases, the "simple transparency" should be done prior to doing
  185173. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  185174. pixel is transparent. You would also need to make sure that the
  185175. transparency information is upgraded to RGB.
  185176. To summarize, the current flow is:
  185177. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  185178. with background "in place" if transparent,
  185179. convert to RGB if necessary
  185180. - Gray + alpha -> composite with gray background and remove alpha bytes,
  185181. convert to RGB if necessary
  185182. To support RGB backgrounds for gray images we need:
  185183. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  185184. 3 or 6 bytes and composite with background
  185185. "in place" if transparent (3x compare/pixel
  185186. compared to doing composite with gray bkgrnd)
  185187. - Gray + alpha -> convert to RGB + alpha, composite with background and
  185188. remove alpha bytes (3x float operations/pixel
  185189. compared with composite on gray background)
  185190. Greg's change will do this. The reason it wasn't done before is for
  185191. performance, as this increases the per-pixel operations. If we would check
  185192. in advance if the background was gray or RGB, and position the gray-to-RGB
  185193. transform appropriately, then it would save a lot of work/time.
  185194. */
  185195. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185196. /* if gray -> RGB, do so now only if background is non-gray; else do later
  185197. * for performance reasons */
  185198. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  185199. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  185200. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185201. #endif
  185202. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185203. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  185204. ((png_ptr->num_trans != 0 ) ||
  185205. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  185206. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185207. &(png_ptr->trans_values), &(png_ptr->background)
  185208. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185209. , &(png_ptr->background_1),
  185210. png_ptr->gamma_table, png_ptr->gamma_from_1,
  185211. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  185212. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  185213. png_ptr->gamma_shift
  185214. #endif
  185215. );
  185216. #endif
  185217. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185218. if ((png_ptr->transformations & PNG_GAMMA) &&
  185219. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185220. !((png_ptr->transformations & PNG_BACKGROUND) &&
  185221. ((png_ptr->num_trans != 0) ||
  185222. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  185223. #endif
  185224. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  185225. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185226. png_ptr->gamma_table, png_ptr->gamma_16_table,
  185227. png_ptr->gamma_shift);
  185228. #endif
  185229. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  185230. if (png_ptr->transformations & PNG_16_TO_8)
  185231. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185232. #endif
  185233. #if defined(PNG_READ_DITHER_SUPPORTED)
  185234. if (png_ptr->transformations & PNG_DITHER)
  185235. {
  185236. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  185237. png_ptr->palette_lookup, png_ptr->dither_index);
  185238. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  185239. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  185240. }
  185241. #endif
  185242. #if defined(PNG_READ_INVERT_SUPPORTED)
  185243. if (png_ptr->transformations & PNG_INVERT_MONO)
  185244. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185245. #endif
  185246. #if defined(PNG_READ_SHIFT_SUPPORTED)
  185247. if (png_ptr->transformations & PNG_SHIFT)
  185248. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185249. &(png_ptr->shift));
  185250. #endif
  185251. #if defined(PNG_READ_PACK_SUPPORTED)
  185252. if (png_ptr->transformations & PNG_PACK)
  185253. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185254. #endif
  185255. #if defined(PNG_READ_BGR_SUPPORTED)
  185256. if (png_ptr->transformations & PNG_BGR)
  185257. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185258. #endif
  185259. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  185260. if (png_ptr->transformations & PNG_PACKSWAP)
  185261. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185262. #endif
  185263. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185264. /* if gray -> RGB, do so now only if we did not do so above */
  185265. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  185266. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  185267. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185268. #endif
  185269. #if defined(PNG_READ_FILLER_SUPPORTED)
  185270. if (png_ptr->transformations & PNG_FILLER)
  185271. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185272. (png_uint_32)png_ptr->filler, png_ptr->flags);
  185273. #endif
  185274. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  185275. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  185276. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185277. #endif
  185278. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  185279. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  185280. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185281. #endif
  185282. #if defined(PNG_READ_SWAP_SUPPORTED)
  185283. if (png_ptr->transformations & PNG_SWAP_BYTES)
  185284. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185285. #endif
  185286. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  185287. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  185288. {
  185289. if(png_ptr->read_user_transform_fn != NULL)
  185290. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  185291. (png_ptr, /* png_ptr */
  185292. &(png_ptr->row_info), /* row_info: */
  185293. /* png_uint_32 width; width of row */
  185294. /* png_uint_32 rowbytes; number of bytes in row */
  185295. /* png_byte color_type; color type of pixels */
  185296. /* png_byte bit_depth; bit depth of samples */
  185297. /* png_byte channels; number of channels (1-4) */
  185298. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  185299. png_ptr->row_buf + 1); /* start of pixel data for row */
  185300. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  185301. if(png_ptr->user_transform_depth)
  185302. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  185303. if(png_ptr->user_transform_channels)
  185304. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  185305. #endif
  185306. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  185307. png_ptr->row_info.channels);
  185308. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  185309. png_ptr->row_info.width);
  185310. }
  185311. #endif
  185312. }
  185313. #if defined(PNG_READ_PACK_SUPPORTED)
  185314. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  185315. * without changing the actual values. Thus, if you had a row with
  185316. * a bit depth of 1, you would end up with bytes that only contained
  185317. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  185318. * png_do_shift() after this.
  185319. */
  185320. void /* PRIVATE */
  185321. png_do_unpack(png_row_infop row_info, png_bytep row)
  185322. {
  185323. png_debug(1, "in png_do_unpack\n");
  185324. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185325. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  185326. #else
  185327. if (row_info->bit_depth < 8)
  185328. #endif
  185329. {
  185330. png_uint_32 i;
  185331. png_uint_32 row_width=row_info->width;
  185332. switch (row_info->bit_depth)
  185333. {
  185334. case 1:
  185335. {
  185336. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  185337. png_bytep dp = row + (png_size_t)row_width - 1;
  185338. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  185339. for (i = 0; i < row_width; i++)
  185340. {
  185341. *dp = (png_byte)((*sp >> shift) & 0x01);
  185342. if (shift == 7)
  185343. {
  185344. shift = 0;
  185345. sp--;
  185346. }
  185347. else
  185348. shift++;
  185349. dp--;
  185350. }
  185351. break;
  185352. }
  185353. case 2:
  185354. {
  185355. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  185356. png_bytep dp = row + (png_size_t)row_width - 1;
  185357. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  185358. for (i = 0; i < row_width; i++)
  185359. {
  185360. *dp = (png_byte)((*sp >> shift) & 0x03);
  185361. if (shift == 6)
  185362. {
  185363. shift = 0;
  185364. sp--;
  185365. }
  185366. else
  185367. shift += 2;
  185368. dp--;
  185369. }
  185370. break;
  185371. }
  185372. case 4:
  185373. {
  185374. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  185375. png_bytep dp = row + (png_size_t)row_width - 1;
  185376. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  185377. for (i = 0; i < row_width; i++)
  185378. {
  185379. *dp = (png_byte)((*sp >> shift) & 0x0f);
  185380. if (shift == 4)
  185381. {
  185382. shift = 0;
  185383. sp--;
  185384. }
  185385. else
  185386. shift = 4;
  185387. dp--;
  185388. }
  185389. break;
  185390. }
  185391. }
  185392. row_info->bit_depth = 8;
  185393. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  185394. row_info->rowbytes = row_width * row_info->channels;
  185395. }
  185396. }
  185397. #endif
  185398. #if defined(PNG_READ_SHIFT_SUPPORTED)
  185399. /* Reverse the effects of png_do_shift. This routine merely shifts the
  185400. * pixels back to their significant bits values. Thus, if you have
  185401. * a row of bit depth 8, but only 5 are significant, this will shift
  185402. * the values back to 0 through 31.
  185403. */
  185404. void /* PRIVATE */
  185405. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  185406. {
  185407. png_debug(1, "in png_do_unshift\n");
  185408. if (
  185409. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185410. row != NULL && row_info != NULL && sig_bits != NULL &&
  185411. #endif
  185412. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  185413. {
  185414. int shift[4];
  185415. int channels = 0;
  185416. int c;
  185417. png_uint_16 value = 0;
  185418. png_uint_32 row_width = row_info->width;
  185419. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  185420. {
  185421. shift[channels++] = row_info->bit_depth - sig_bits->red;
  185422. shift[channels++] = row_info->bit_depth - sig_bits->green;
  185423. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  185424. }
  185425. else
  185426. {
  185427. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  185428. }
  185429. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  185430. {
  185431. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  185432. }
  185433. for (c = 0; c < channels; c++)
  185434. {
  185435. if (shift[c] <= 0)
  185436. shift[c] = 0;
  185437. else
  185438. value = 1;
  185439. }
  185440. if (!value)
  185441. return;
  185442. switch (row_info->bit_depth)
  185443. {
  185444. case 2:
  185445. {
  185446. png_bytep bp;
  185447. png_uint_32 i;
  185448. png_uint_32 istop = row_info->rowbytes;
  185449. for (bp = row, i = 0; i < istop; i++)
  185450. {
  185451. *bp >>= 1;
  185452. *bp++ &= 0x55;
  185453. }
  185454. break;
  185455. }
  185456. case 4:
  185457. {
  185458. png_bytep bp = row;
  185459. png_uint_32 i;
  185460. png_uint_32 istop = row_info->rowbytes;
  185461. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  185462. (png_byte)((int)0xf >> shift[0]));
  185463. for (i = 0; i < istop; i++)
  185464. {
  185465. *bp >>= shift[0];
  185466. *bp++ &= mask;
  185467. }
  185468. break;
  185469. }
  185470. case 8:
  185471. {
  185472. png_bytep bp = row;
  185473. png_uint_32 i;
  185474. png_uint_32 istop = row_width * channels;
  185475. for (i = 0; i < istop; i++)
  185476. {
  185477. *bp++ >>= shift[i%channels];
  185478. }
  185479. break;
  185480. }
  185481. case 16:
  185482. {
  185483. png_bytep bp = row;
  185484. png_uint_32 i;
  185485. png_uint_32 istop = channels * row_width;
  185486. for (i = 0; i < istop; i++)
  185487. {
  185488. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  185489. value >>= shift[i%channels];
  185490. *bp++ = (png_byte)(value >> 8);
  185491. *bp++ = (png_byte)(value & 0xff);
  185492. }
  185493. break;
  185494. }
  185495. }
  185496. }
  185497. }
  185498. #endif
  185499. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  185500. /* chop rows of bit depth 16 down to 8 */
  185501. void /* PRIVATE */
  185502. png_do_chop(png_row_infop row_info, png_bytep row)
  185503. {
  185504. png_debug(1, "in png_do_chop\n");
  185505. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185506. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  185507. #else
  185508. if (row_info->bit_depth == 16)
  185509. #endif
  185510. {
  185511. png_bytep sp = row;
  185512. png_bytep dp = row;
  185513. png_uint_32 i;
  185514. png_uint_32 istop = row_info->width * row_info->channels;
  185515. for (i = 0; i<istop; i++, sp += 2, dp++)
  185516. {
  185517. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  185518. /* This does a more accurate scaling of the 16-bit color
  185519. * value, rather than a simple low-byte truncation.
  185520. *
  185521. * What the ideal calculation should be:
  185522. * *dp = (((((png_uint_32)(*sp) << 8) |
  185523. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  185524. *
  185525. * GRR: no, I think this is what it really should be:
  185526. * *dp = (((((png_uint_32)(*sp) << 8) |
  185527. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  185528. *
  185529. * GRR: here's the exact calculation with shifts:
  185530. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  185531. * *dp = (temp - (temp >> 8)) >> 8;
  185532. *
  185533. * Approximate calculation with shift/add instead of multiply/divide:
  185534. * *dp = ((((png_uint_32)(*sp) << 8) |
  185535. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  185536. *
  185537. * What we actually do to avoid extra shifting and conversion:
  185538. */
  185539. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  185540. #else
  185541. /* Simply discard the low order byte */
  185542. *dp = *sp;
  185543. #endif
  185544. }
  185545. row_info->bit_depth = 8;
  185546. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  185547. row_info->rowbytes = row_info->width * row_info->channels;
  185548. }
  185549. }
  185550. #endif
  185551. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  185552. void /* PRIVATE */
  185553. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  185554. {
  185555. png_debug(1, "in png_do_read_swap_alpha\n");
  185556. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185557. if (row != NULL && row_info != NULL)
  185558. #endif
  185559. {
  185560. png_uint_32 row_width = row_info->width;
  185561. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  185562. {
  185563. /* This converts from RGBA to ARGB */
  185564. if (row_info->bit_depth == 8)
  185565. {
  185566. png_bytep sp = row + row_info->rowbytes;
  185567. png_bytep dp = sp;
  185568. png_byte save;
  185569. png_uint_32 i;
  185570. for (i = 0; i < row_width; i++)
  185571. {
  185572. save = *(--sp);
  185573. *(--dp) = *(--sp);
  185574. *(--dp) = *(--sp);
  185575. *(--dp) = *(--sp);
  185576. *(--dp) = save;
  185577. }
  185578. }
  185579. /* This converts from RRGGBBAA to AARRGGBB */
  185580. else
  185581. {
  185582. png_bytep sp = row + row_info->rowbytes;
  185583. png_bytep dp = sp;
  185584. png_byte save[2];
  185585. png_uint_32 i;
  185586. for (i = 0; i < row_width; i++)
  185587. {
  185588. save[0] = *(--sp);
  185589. save[1] = *(--sp);
  185590. *(--dp) = *(--sp);
  185591. *(--dp) = *(--sp);
  185592. *(--dp) = *(--sp);
  185593. *(--dp) = *(--sp);
  185594. *(--dp) = *(--sp);
  185595. *(--dp) = *(--sp);
  185596. *(--dp) = save[0];
  185597. *(--dp) = save[1];
  185598. }
  185599. }
  185600. }
  185601. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  185602. {
  185603. /* This converts from GA to AG */
  185604. if (row_info->bit_depth == 8)
  185605. {
  185606. png_bytep sp = row + row_info->rowbytes;
  185607. png_bytep dp = sp;
  185608. png_byte save;
  185609. png_uint_32 i;
  185610. for (i = 0; i < row_width; i++)
  185611. {
  185612. save = *(--sp);
  185613. *(--dp) = *(--sp);
  185614. *(--dp) = save;
  185615. }
  185616. }
  185617. /* This converts from GGAA to AAGG */
  185618. else
  185619. {
  185620. png_bytep sp = row + row_info->rowbytes;
  185621. png_bytep dp = sp;
  185622. png_byte save[2];
  185623. png_uint_32 i;
  185624. for (i = 0; i < row_width; i++)
  185625. {
  185626. save[0] = *(--sp);
  185627. save[1] = *(--sp);
  185628. *(--dp) = *(--sp);
  185629. *(--dp) = *(--sp);
  185630. *(--dp) = save[0];
  185631. *(--dp) = save[1];
  185632. }
  185633. }
  185634. }
  185635. }
  185636. }
  185637. #endif
  185638. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  185639. void /* PRIVATE */
  185640. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  185641. {
  185642. png_debug(1, "in png_do_read_invert_alpha\n");
  185643. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185644. if (row != NULL && row_info != NULL)
  185645. #endif
  185646. {
  185647. png_uint_32 row_width = row_info->width;
  185648. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  185649. {
  185650. /* This inverts the alpha channel in RGBA */
  185651. if (row_info->bit_depth == 8)
  185652. {
  185653. png_bytep sp = row + row_info->rowbytes;
  185654. png_bytep dp = sp;
  185655. png_uint_32 i;
  185656. for (i = 0; i < row_width; i++)
  185657. {
  185658. *(--dp) = (png_byte)(255 - *(--sp));
  185659. /* This does nothing:
  185660. *(--dp) = *(--sp);
  185661. *(--dp) = *(--sp);
  185662. *(--dp) = *(--sp);
  185663. We can replace it with:
  185664. */
  185665. sp-=3;
  185666. dp=sp;
  185667. }
  185668. }
  185669. /* This inverts the alpha channel in RRGGBBAA */
  185670. else
  185671. {
  185672. png_bytep sp = row + row_info->rowbytes;
  185673. png_bytep dp = sp;
  185674. png_uint_32 i;
  185675. for (i = 0; i < row_width; i++)
  185676. {
  185677. *(--dp) = (png_byte)(255 - *(--sp));
  185678. *(--dp) = (png_byte)(255 - *(--sp));
  185679. /* This does nothing:
  185680. *(--dp) = *(--sp);
  185681. *(--dp) = *(--sp);
  185682. *(--dp) = *(--sp);
  185683. *(--dp) = *(--sp);
  185684. *(--dp) = *(--sp);
  185685. *(--dp) = *(--sp);
  185686. We can replace it with:
  185687. */
  185688. sp-=6;
  185689. dp=sp;
  185690. }
  185691. }
  185692. }
  185693. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  185694. {
  185695. /* This inverts the alpha channel in GA */
  185696. if (row_info->bit_depth == 8)
  185697. {
  185698. png_bytep sp = row + row_info->rowbytes;
  185699. png_bytep dp = sp;
  185700. png_uint_32 i;
  185701. for (i = 0; i < row_width; i++)
  185702. {
  185703. *(--dp) = (png_byte)(255 - *(--sp));
  185704. *(--dp) = *(--sp);
  185705. }
  185706. }
  185707. /* This inverts the alpha channel in GGAA */
  185708. else
  185709. {
  185710. png_bytep sp = row + row_info->rowbytes;
  185711. png_bytep dp = sp;
  185712. png_uint_32 i;
  185713. for (i = 0; i < row_width; i++)
  185714. {
  185715. *(--dp) = (png_byte)(255 - *(--sp));
  185716. *(--dp) = (png_byte)(255 - *(--sp));
  185717. /*
  185718. *(--dp) = *(--sp);
  185719. *(--dp) = *(--sp);
  185720. */
  185721. sp-=2;
  185722. dp=sp;
  185723. }
  185724. }
  185725. }
  185726. }
  185727. }
  185728. #endif
  185729. #if defined(PNG_READ_FILLER_SUPPORTED)
  185730. /* Add filler channel if we have RGB color */
  185731. void /* PRIVATE */
  185732. png_do_read_filler(png_row_infop row_info, png_bytep row,
  185733. png_uint_32 filler, png_uint_32 flags)
  185734. {
  185735. png_uint_32 i;
  185736. png_uint_32 row_width = row_info->width;
  185737. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  185738. png_byte lo_filler = (png_byte)(filler & 0xff);
  185739. png_debug(1, "in png_do_read_filler\n");
  185740. if (
  185741. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185742. row != NULL && row_info != NULL &&
  185743. #endif
  185744. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  185745. {
  185746. if(row_info->bit_depth == 8)
  185747. {
  185748. /* This changes the data from G to GX */
  185749. if (flags & PNG_FLAG_FILLER_AFTER)
  185750. {
  185751. png_bytep sp = row + (png_size_t)row_width;
  185752. png_bytep dp = sp + (png_size_t)row_width;
  185753. for (i = 1; i < row_width; i++)
  185754. {
  185755. *(--dp) = lo_filler;
  185756. *(--dp) = *(--sp);
  185757. }
  185758. *(--dp) = lo_filler;
  185759. row_info->channels = 2;
  185760. row_info->pixel_depth = 16;
  185761. row_info->rowbytes = row_width * 2;
  185762. }
  185763. /* This changes the data from G to XG */
  185764. else
  185765. {
  185766. png_bytep sp = row + (png_size_t)row_width;
  185767. png_bytep dp = sp + (png_size_t)row_width;
  185768. for (i = 0; i < row_width; i++)
  185769. {
  185770. *(--dp) = *(--sp);
  185771. *(--dp) = lo_filler;
  185772. }
  185773. row_info->channels = 2;
  185774. row_info->pixel_depth = 16;
  185775. row_info->rowbytes = row_width * 2;
  185776. }
  185777. }
  185778. else if(row_info->bit_depth == 16)
  185779. {
  185780. /* This changes the data from GG to GGXX */
  185781. if (flags & PNG_FLAG_FILLER_AFTER)
  185782. {
  185783. png_bytep sp = row + (png_size_t)row_width * 2;
  185784. png_bytep dp = sp + (png_size_t)row_width * 2;
  185785. for (i = 1; i < row_width; i++)
  185786. {
  185787. *(--dp) = hi_filler;
  185788. *(--dp) = lo_filler;
  185789. *(--dp) = *(--sp);
  185790. *(--dp) = *(--sp);
  185791. }
  185792. *(--dp) = hi_filler;
  185793. *(--dp) = lo_filler;
  185794. row_info->channels = 2;
  185795. row_info->pixel_depth = 32;
  185796. row_info->rowbytes = row_width * 4;
  185797. }
  185798. /* This changes the data from GG to XXGG */
  185799. else
  185800. {
  185801. png_bytep sp = row + (png_size_t)row_width * 2;
  185802. png_bytep dp = sp + (png_size_t)row_width * 2;
  185803. for (i = 0; i < row_width; i++)
  185804. {
  185805. *(--dp) = *(--sp);
  185806. *(--dp) = *(--sp);
  185807. *(--dp) = hi_filler;
  185808. *(--dp) = lo_filler;
  185809. }
  185810. row_info->channels = 2;
  185811. row_info->pixel_depth = 32;
  185812. row_info->rowbytes = row_width * 4;
  185813. }
  185814. }
  185815. } /* COLOR_TYPE == GRAY */
  185816. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  185817. {
  185818. if(row_info->bit_depth == 8)
  185819. {
  185820. /* This changes the data from RGB to RGBX */
  185821. if (flags & PNG_FLAG_FILLER_AFTER)
  185822. {
  185823. png_bytep sp = row + (png_size_t)row_width * 3;
  185824. png_bytep dp = sp + (png_size_t)row_width;
  185825. for (i = 1; i < row_width; i++)
  185826. {
  185827. *(--dp) = lo_filler;
  185828. *(--dp) = *(--sp);
  185829. *(--dp) = *(--sp);
  185830. *(--dp) = *(--sp);
  185831. }
  185832. *(--dp) = lo_filler;
  185833. row_info->channels = 4;
  185834. row_info->pixel_depth = 32;
  185835. row_info->rowbytes = row_width * 4;
  185836. }
  185837. /* This changes the data from RGB to XRGB */
  185838. else
  185839. {
  185840. png_bytep sp = row + (png_size_t)row_width * 3;
  185841. png_bytep dp = sp + (png_size_t)row_width;
  185842. for (i = 0; i < row_width; i++)
  185843. {
  185844. *(--dp) = *(--sp);
  185845. *(--dp) = *(--sp);
  185846. *(--dp) = *(--sp);
  185847. *(--dp) = lo_filler;
  185848. }
  185849. row_info->channels = 4;
  185850. row_info->pixel_depth = 32;
  185851. row_info->rowbytes = row_width * 4;
  185852. }
  185853. }
  185854. else if(row_info->bit_depth == 16)
  185855. {
  185856. /* This changes the data from RRGGBB to RRGGBBXX */
  185857. if (flags & PNG_FLAG_FILLER_AFTER)
  185858. {
  185859. png_bytep sp = row + (png_size_t)row_width * 6;
  185860. png_bytep dp = sp + (png_size_t)row_width * 2;
  185861. for (i = 1; i < row_width; i++)
  185862. {
  185863. *(--dp) = hi_filler;
  185864. *(--dp) = lo_filler;
  185865. *(--dp) = *(--sp);
  185866. *(--dp) = *(--sp);
  185867. *(--dp) = *(--sp);
  185868. *(--dp) = *(--sp);
  185869. *(--dp) = *(--sp);
  185870. *(--dp) = *(--sp);
  185871. }
  185872. *(--dp) = hi_filler;
  185873. *(--dp) = lo_filler;
  185874. row_info->channels = 4;
  185875. row_info->pixel_depth = 64;
  185876. row_info->rowbytes = row_width * 8;
  185877. }
  185878. /* This changes the data from RRGGBB to XXRRGGBB */
  185879. else
  185880. {
  185881. png_bytep sp = row + (png_size_t)row_width * 6;
  185882. png_bytep dp = sp + (png_size_t)row_width * 2;
  185883. for (i = 0; i < row_width; i++)
  185884. {
  185885. *(--dp) = *(--sp);
  185886. *(--dp) = *(--sp);
  185887. *(--dp) = *(--sp);
  185888. *(--dp) = *(--sp);
  185889. *(--dp) = *(--sp);
  185890. *(--dp) = *(--sp);
  185891. *(--dp) = hi_filler;
  185892. *(--dp) = lo_filler;
  185893. }
  185894. row_info->channels = 4;
  185895. row_info->pixel_depth = 64;
  185896. row_info->rowbytes = row_width * 8;
  185897. }
  185898. }
  185899. } /* COLOR_TYPE == RGB */
  185900. }
  185901. #endif
  185902. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185903. /* expand grayscale files to RGB, with or without alpha */
  185904. void /* PRIVATE */
  185905. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  185906. {
  185907. png_uint_32 i;
  185908. png_uint_32 row_width = row_info->width;
  185909. png_debug(1, "in png_do_gray_to_rgb\n");
  185910. if (row_info->bit_depth >= 8 &&
  185911. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185912. row != NULL && row_info != NULL &&
  185913. #endif
  185914. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  185915. {
  185916. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  185917. {
  185918. if (row_info->bit_depth == 8)
  185919. {
  185920. png_bytep sp = row + (png_size_t)row_width - 1;
  185921. png_bytep dp = sp + (png_size_t)row_width * 2;
  185922. for (i = 0; i < row_width; i++)
  185923. {
  185924. *(dp--) = *sp;
  185925. *(dp--) = *sp;
  185926. *(dp--) = *(sp--);
  185927. }
  185928. }
  185929. else
  185930. {
  185931. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  185932. png_bytep dp = sp + (png_size_t)row_width * 4;
  185933. for (i = 0; i < row_width; i++)
  185934. {
  185935. *(dp--) = *sp;
  185936. *(dp--) = *(sp - 1);
  185937. *(dp--) = *sp;
  185938. *(dp--) = *(sp - 1);
  185939. *(dp--) = *(sp--);
  185940. *(dp--) = *(sp--);
  185941. }
  185942. }
  185943. }
  185944. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  185945. {
  185946. if (row_info->bit_depth == 8)
  185947. {
  185948. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  185949. png_bytep dp = sp + (png_size_t)row_width * 2;
  185950. for (i = 0; i < row_width; i++)
  185951. {
  185952. *(dp--) = *(sp--);
  185953. *(dp--) = *sp;
  185954. *(dp--) = *sp;
  185955. *(dp--) = *(sp--);
  185956. }
  185957. }
  185958. else
  185959. {
  185960. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  185961. png_bytep dp = sp + (png_size_t)row_width * 4;
  185962. for (i = 0; i < row_width; i++)
  185963. {
  185964. *(dp--) = *(sp--);
  185965. *(dp--) = *(sp--);
  185966. *(dp--) = *sp;
  185967. *(dp--) = *(sp - 1);
  185968. *(dp--) = *sp;
  185969. *(dp--) = *(sp - 1);
  185970. *(dp--) = *(sp--);
  185971. *(dp--) = *(sp--);
  185972. }
  185973. }
  185974. }
  185975. row_info->channels += (png_byte)2;
  185976. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  185977. row_info->pixel_depth = (png_byte)(row_info->channels *
  185978. row_info->bit_depth);
  185979. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  185980. }
  185981. }
  185982. #endif
  185983. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185984. /* reduce RGB files to grayscale, with or without alpha
  185985. * using the equation given in Poynton's ColorFAQ at
  185986. * <http://www.inforamp.net/~poynton/>
  185987. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  185988. *
  185989. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  185990. *
  185991. * We approximate this with
  185992. *
  185993. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  185994. *
  185995. * which can be expressed with integers as
  185996. *
  185997. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  185998. *
  185999. * The calculation is to be done in a linear colorspace.
  186000. *
  186001. * Other integer coefficents can be used via png_set_rgb_to_gray().
  186002. */
  186003. int /* PRIVATE */
  186004. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  186005. {
  186006. png_uint_32 i;
  186007. png_uint_32 row_width = row_info->width;
  186008. int rgb_error = 0;
  186009. png_debug(1, "in png_do_rgb_to_gray\n");
  186010. if (
  186011. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186012. row != NULL && row_info != NULL &&
  186013. #endif
  186014. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  186015. {
  186016. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  186017. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  186018. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  186019. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  186020. {
  186021. if (row_info->bit_depth == 8)
  186022. {
  186023. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  186024. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  186025. {
  186026. png_bytep sp = row;
  186027. png_bytep dp = row;
  186028. for (i = 0; i < row_width; i++)
  186029. {
  186030. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  186031. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  186032. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  186033. if(red != green || red != blue)
  186034. {
  186035. rgb_error |= 1;
  186036. *(dp++) = png_ptr->gamma_from_1[
  186037. (rc*red+gc*green+bc*blue)>>15];
  186038. }
  186039. else
  186040. *(dp++) = *(sp-1);
  186041. }
  186042. }
  186043. else
  186044. #endif
  186045. {
  186046. png_bytep sp = row;
  186047. png_bytep dp = row;
  186048. for (i = 0; i < row_width; i++)
  186049. {
  186050. png_byte red = *(sp++);
  186051. png_byte green = *(sp++);
  186052. png_byte blue = *(sp++);
  186053. if(red != green || red != blue)
  186054. {
  186055. rgb_error |= 1;
  186056. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  186057. }
  186058. else
  186059. *(dp++) = *(sp-1);
  186060. }
  186061. }
  186062. }
  186063. else /* RGB bit_depth == 16 */
  186064. {
  186065. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  186066. if (png_ptr->gamma_16_to_1 != NULL &&
  186067. png_ptr->gamma_16_from_1 != NULL)
  186068. {
  186069. png_bytep sp = row;
  186070. png_bytep dp = row;
  186071. for (i = 0; i < row_width; i++)
  186072. {
  186073. png_uint_16 red, green, blue, w;
  186074. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186075. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186076. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186077. if(red == green && red == blue)
  186078. w = red;
  186079. else
  186080. {
  186081. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  186082. png_ptr->gamma_shift][red>>8];
  186083. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  186084. png_ptr->gamma_shift][green>>8];
  186085. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  186086. png_ptr->gamma_shift][blue>>8];
  186087. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  186088. + bc*blue_1)>>15);
  186089. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  186090. png_ptr->gamma_shift][gray16 >> 8];
  186091. rgb_error |= 1;
  186092. }
  186093. *(dp++) = (png_byte)((w>>8) & 0xff);
  186094. *(dp++) = (png_byte)(w & 0xff);
  186095. }
  186096. }
  186097. else
  186098. #endif
  186099. {
  186100. png_bytep sp = row;
  186101. png_bytep dp = row;
  186102. for (i = 0; i < row_width; i++)
  186103. {
  186104. png_uint_16 red, green, blue, gray16;
  186105. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186106. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186107. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186108. if(red != green || red != blue)
  186109. rgb_error |= 1;
  186110. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  186111. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  186112. *(dp++) = (png_byte)(gray16 & 0xff);
  186113. }
  186114. }
  186115. }
  186116. }
  186117. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  186118. {
  186119. if (row_info->bit_depth == 8)
  186120. {
  186121. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  186122. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  186123. {
  186124. png_bytep sp = row;
  186125. png_bytep dp = row;
  186126. for (i = 0; i < row_width; i++)
  186127. {
  186128. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  186129. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  186130. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  186131. if(red != green || red != blue)
  186132. rgb_error |= 1;
  186133. *(dp++) = png_ptr->gamma_from_1
  186134. [(rc*red + gc*green + bc*blue)>>15];
  186135. *(dp++) = *(sp++); /* alpha */
  186136. }
  186137. }
  186138. else
  186139. #endif
  186140. {
  186141. png_bytep sp = row;
  186142. png_bytep dp = row;
  186143. for (i = 0; i < row_width; i++)
  186144. {
  186145. png_byte red = *(sp++);
  186146. png_byte green = *(sp++);
  186147. png_byte blue = *(sp++);
  186148. if(red != green || red != blue)
  186149. rgb_error |= 1;
  186150. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  186151. *(dp++) = *(sp++); /* alpha */
  186152. }
  186153. }
  186154. }
  186155. else /* RGBA bit_depth == 16 */
  186156. {
  186157. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  186158. if (png_ptr->gamma_16_to_1 != NULL &&
  186159. png_ptr->gamma_16_from_1 != NULL)
  186160. {
  186161. png_bytep sp = row;
  186162. png_bytep dp = row;
  186163. for (i = 0; i < row_width; i++)
  186164. {
  186165. png_uint_16 red, green, blue, w;
  186166. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186167. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186168. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186169. if(red == green && red == blue)
  186170. w = red;
  186171. else
  186172. {
  186173. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  186174. png_ptr->gamma_shift][red>>8];
  186175. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  186176. png_ptr->gamma_shift][green>>8];
  186177. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  186178. png_ptr->gamma_shift][blue>>8];
  186179. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  186180. + gc * green_1 + bc * blue_1)>>15);
  186181. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  186182. png_ptr->gamma_shift][gray16 >> 8];
  186183. rgb_error |= 1;
  186184. }
  186185. *(dp++) = (png_byte)((w>>8) & 0xff);
  186186. *(dp++) = (png_byte)(w & 0xff);
  186187. *(dp++) = *(sp++); /* alpha */
  186188. *(dp++) = *(sp++);
  186189. }
  186190. }
  186191. else
  186192. #endif
  186193. {
  186194. png_bytep sp = row;
  186195. png_bytep dp = row;
  186196. for (i = 0; i < row_width; i++)
  186197. {
  186198. png_uint_16 red, green, blue, gray16;
  186199. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  186200. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  186201. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  186202. if(red != green || red != blue)
  186203. rgb_error |= 1;
  186204. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  186205. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  186206. *(dp++) = (png_byte)(gray16 & 0xff);
  186207. *(dp++) = *(sp++); /* alpha */
  186208. *(dp++) = *(sp++);
  186209. }
  186210. }
  186211. }
  186212. }
  186213. row_info->channels -= (png_byte)2;
  186214. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  186215. row_info->pixel_depth = (png_byte)(row_info->channels *
  186216. row_info->bit_depth);
  186217. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  186218. }
  186219. return rgb_error;
  186220. }
  186221. #endif
  186222. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  186223. * large of png_color. This lets grayscale images be treated as
  186224. * paletted. Most useful for gamma correction and simplification
  186225. * of code.
  186226. */
  186227. void PNGAPI
  186228. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  186229. {
  186230. int num_palette;
  186231. int color_inc;
  186232. int i;
  186233. int v;
  186234. png_debug(1, "in png_do_build_grayscale_palette\n");
  186235. if (palette == NULL)
  186236. return;
  186237. switch (bit_depth)
  186238. {
  186239. case 1:
  186240. num_palette = 2;
  186241. color_inc = 0xff;
  186242. break;
  186243. case 2:
  186244. num_palette = 4;
  186245. color_inc = 0x55;
  186246. break;
  186247. case 4:
  186248. num_palette = 16;
  186249. color_inc = 0x11;
  186250. break;
  186251. case 8:
  186252. num_palette = 256;
  186253. color_inc = 1;
  186254. break;
  186255. default:
  186256. num_palette = 0;
  186257. color_inc = 0;
  186258. break;
  186259. }
  186260. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  186261. {
  186262. palette[i].red = (png_byte)v;
  186263. palette[i].green = (png_byte)v;
  186264. palette[i].blue = (png_byte)v;
  186265. }
  186266. }
  186267. /* This function is currently unused. Do we really need it? */
  186268. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  186269. void /* PRIVATE */
  186270. png_correct_palette(png_structp png_ptr, png_colorp palette,
  186271. int num_palette)
  186272. {
  186273. png_debug(1, "in png_correct_palette\n");
  186274. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  186275. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186276. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  186277. {
  186278. png_color back, back_1;
  186279. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  186280. {
  186281. back.red = png_ptr->gamma_table[png_ptr->background.red];
  186282. back.green = png_ptr->gamma_table[png_ptr->background.green];
  186283. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  186284. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  186285. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  186286. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  186287. }
  186288. else
  186289. {
  186290. double g;
  186291. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  186292. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  186293. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  186294. {
  186295. back.red = png_ptr->background.red;
  186296. back.green = png_ptr->background.green;
  186297. back.blue = png_ptr->background.blue;
  186298. }
  186299. else
  186300. {
  186301. back.red =
  186302. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  186303. 255.0 + 0.5);
  186304. back.green =
  186305. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  186306. 255.0 + 0.5);
  186307. back.blue =
  186308. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  186309. 255.0 + 0.5);
  186310. }
  186311. g = 1.0 / png_ptr->background_gamma;
  186312. back_1.red =
  186313. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  186314. 255.0 + 0.5);
  186315. back_1.green =
  186316. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  186317. 255.0 + 0.5);
  186318. back_1.blue =
  186319. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  186320. 255.0 + 0.5);
  186321. }
  186322. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186323. {
  186324. png_uint_32 i;
  186325. for (i = 0; i < (png_uint_32)num_palette; i++)
  186326. {
  186327. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  186328. {
  186329. palette[i] = back;
  186330. }
  186331. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  186332. {
  186333. png_byte v, w;
  186334. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  186335. png_composite(w, v, png_ptr->trans[i], back_1.red);
  186336. palette[i].red = png_ptr->gamma_from_1[w];
  186337. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  186338. png_composite(w, v, png_ptr->trans[i], back_1.green);
  186339. palette[i].green = png_ptr->gamma_from_1[w];
  186340. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  186341. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  186342. palette[i].blue = png_ptr->gamma_from_1[w];
  186343. }
  186344. else
  186345. {
  186346. palette[i].red = png_ptr->gamma_table[palette[i].red];
  186347. palette[i].green = png_ptr->gamma_table[palette[i].green];
  186348. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  186349. }
  186350. }
  186351. }
  186352. else
  186353. {
  186354. int i;
  186355. for (i = 0; i < num_palette; i++)
  186356. {
  186357. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  186358. {
  186359. palette[i] = back;
  186360. }
  186361. else
  186362. {
  186363. palette[i].red = png_ptr->gamma_table[palette[i].red];
  186364. palette[i].green = png_ptr->gamma_table[palette[i].green];
  186365. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  186366. }
  186367. }
  186368. }
  186369. }
  186370. else
  186371. #endif
  186372. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186373. if (png_ptr->transformations & PNG_GAMMA)
  186374. {
  186375. int i;
  186376. for (i = 0; i < num_palette; i++)
  186377. {
  186378. palette[i].red = png_ptr->gamma_table[palette[i].red];
  186379. palette[i].green = png_ptr->gamma_table[palette[i].green];
  186380. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  186381. }
  186382. }
  186383. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186384. else
  186385. #endif
  186386. #endif
  186387. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186388. if (png_ptr->transformations & PNG_BACKGROUND)
  186389. {
  186390. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186391. {
  186392. png_color back;
  186393. back.red = (png_byte)png_ptr->background.red;
  186394. back.green = (png_byte)png_ptr->background.green;
  186395. back.blue = (png_byte)png_ptr->background.blue;
  186396. for (i = 0; i < (int)png_ptr->num_trans; i++)
  186397. {
  186398. if (png_ptr->trans[i] == 0)
  186399. {
  186400. palette[i].red = back.red;
  186401. palette[i].green = back.green;
  186402. palette[i].blue = back.blue;
  186403. }
  186404. else if (png_ptr->trans[i] != 0xff)
  186405. {
  186406. png_composite(palette[i].red, png_ptr->palette[i].red,
  186407. png_ptr->trans[i], back.red);
  186408. png_composite(palette[i].green, png_ptr->palette[i].green,
  186409. png_ptr->trans[i], back.green);
  186410. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  186411. png_ptr->trans[i], back.blue);
  186412. }
  186413. }
  186414. }
  186415. else /* assume grayscale palette (what else could it be?) */
  186416. {
  186417. int i;
  186418. for (i = 0; i < num_palette; i++)
  186419. {
  186420. if (i == (png_byte)png_ptr->trans_values.gray)
  186421. {
  186422. palette[i].red = (png_byte)png_ptr->background.red;
  186423. palette[i].green = (png_byte)png_ptr->background.green;
  186424. palette[i].blue = (png_byte)png_ptr->background.blue;
  186425. }
  186426. }
  186427. }
  186428. }
  186429. #endif
  186430. }
  186431. #endif
  186432. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186433. /* Replace any alpha or transparency with the supplied background color.
  186434. * "background" is already in the screen gamma, while "background_1" is
  186435. * at a gamma of 1.0. Paletted files have already been taken care of.
  186436. */
  186437. void /* PRIVATE */
  186438. png_do_background(png_row_infop row_info, png_bytep row,
  186439. png_color_16p trans_values, png_color_16p background
  186440. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186441. , png_color_16p background_1,
  186442. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  186443. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  186444. png_uint_16pp gamma_16_to_1, int gamma_shift
  186445. #endif
  186446. )
  186447. {
  186448. png_bytep sp, dp;
  186449. png_uint_32 i;
  186450. png_uint_32 row_width=row_info->width;
  186451. int shift;
  186452. png_debug(1, "in png_do_background\n");
  186453. if (background != NULL &&
  186454. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186455. row != NULL && row_info != NULL &&
  186456. #endif
  186457. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  186458. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  186459. {
  186460. switch (row_info->color_type)
  186461. {
  186462. case PNG_COLOR_TYPE_GRAY:
  186463. {
  186464. switch (row_info->bit_depth)
  186465. {
  186466. case 1:
  186467. {
  186468. sp = row;
  186469. shift = 7;
  186470. for (i = 0; i < row_width; i++)
  186471. {
  186472. if ((png_uint_16)((*sp >> shift) & 0x01)
  186473. == trans_values->gray)
  186474. {
  186475. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  186476. *sp |= (png_byte)(background->gray << shift);
  186477. }
  186478. if (!shift)
  186479. {
  186480. shift = 7;
  186481. sp++;
  186482. }
  186483. else
  186484. shift--;
  186485. }
  186486. break;
  186487. }
  186488. case 2:
  186489. {
  186490. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186491. if (gamma_table != NULL)
  186492. {
  186493. sp = row;
  186494. shift = 6;
  186495. for (i = 0; i < row_width; i++)
  186496. {
  186497. if ((png_uint_16)((*sp >> shift) & 0x03)
  186498. == trans_values->gray)
  186499. {
  186500. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  186501. *sp |= (png_byte)(background->gray << shift);
  186502. }
  186503. else
  186504. {
  186505. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  186506. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  186507. (p << 4) | (p << 6)] >> 6) & 0x03);
  186508. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  186509. *sp |= (png_byte)(g << shift);
  186510. }
  186511. if (!shift)
  186512. {
  186513. shift = 6;
  186514. sp++;
  186515. }
  186516. else
  186517. shift -= 2;
  186518. }
  186519. }
  186520. else
  186521. #endif
  186522. {
  186523. sp = row;
  186524. shift = 6;
  186525. for (i = 0; i < row_width; i++)
  186526. {
  186527. if ((png_uint_16)((*sp >> shift) & 0x03)
  186528. == trans_values->gray)
  186529. {
  186530. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  186531. *sp |= (png_byte)(background->gray << shift);
  186532. }
  186533. if (!shift)
  186534. {
  186535. shift = 6;
  186536. sp++;
  186537. }
  186538. else
  186539. shift -= 2;
  186540. }
  186541. }
  186542. break;
  186543. }
  186544. case 4:
  186545. {
  186546. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186547. if (gamma_table != NULL)
  186548. {
  186549. sp = row;
  186550. shift = 4;
  186551. for (i = 0; i < row_width; i++)
  186552. {
  186553. if ((png_uint_16)((*sp >> shift) & 0x0f)
  186554. == trans_values->gray)
  186555. {
  186556. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  186557. *sp |= (png_byte)(background->gray << shift);
  186558. }
  186559. else
  186560. {
  186561. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  186562. png_byte g = (png_byte)((gamma_table[p |
  186563. (p << 4)] >> 4) & 0x0f);
  186564. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  186565. *sp |= (png_byte)(g << shift);
  186566. }
  186567. if (!shift)
  186568. {
  186569. shift = 4;
  186570. sp++;
  186571. }
  186572. else
  186573. shift -= 4;
  186574. }
  186575. }
  186576. else
  186577. #endif
  186578. {
  186579. sp = row;
  186580. shift = 4;
  186581. for (i = 0; i < row_width; i++)
  186582. {
  186583. if ((png_uint_16)((*sp >> shift) & 0x0f)
  186584. == trans_values->gray)
  186585. {
  186586. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  186587. *sp |= (png_byte)(background->gray << shift);
  186588. }
  186589. if (!shift)
  186590. {
  186591. shift = 4;
  186592. sp++;
  186593. }
  186594. else
  186595. shift -= 4;
  186596. }
  186597. }
  186598. break;
  186599. }
  186600. case 8:
  186601. {
  186602. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186603. if (gamma_table != NULL)
  186604. {
  186605. sp = row;
  186606. for (i = 0; i < row_width; i++, sp++)
  186607. {
  186608. if (*sp == trans_values->gray)
  186609. {
  186610. *sp = (png_byte)background->gray;
  186611. }
  186612. else
  186613. {
  186614. *sp = gamma_table[*sp];
  186615. }
  186616. }
  186617. }
  186618. else
  186619. #endif
  186620. {
  186621. sp = row;
  186622. for (i = 0; i < row_width; i++, sp++)
  186623. {
  186624. if (*sp == trans_values->gray)
  186625. {
  186626. *sp = (png_byte)background->gray;
  186627. }
  186628. }
  186629. }
  186630. break;
  186631. }
  186632. case 16:
  186633. {
  186634. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186635. if (gamma_16 != NULL)
  186636. {
  186637. sp = row;
  186638. for (i = 0; i < row_width; i++, sp += 2)
  186639. {
  186640. png_uint_16 v;
  186641. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  186642. if (v == trans_values->gray)
  186643. {
  186644. /* background is already in screen gamma */
  186645. *sp = (png_byte)((background->gray >> 8) & 0xff);
  186646. *(sp + 1) = (png_byte)(background->gray & 0xff);
  186647. }
  186648. else
  186649. {
  186650. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  186651. *sp = (png_byte)((v >> 8) & 0xff);
  186652. *(sp + 1) = (png_byte)(v & 0xff);
  186653. }
  186654. }
  186655. }
  186656. else
  186657. #endif
  186658. {
  186659. sp = row;
  186660. for (i = 0; i < row_width; i++, sp += 2)
  186661. {
  186662. png_uint_16 v;
  186663. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  186664. if (v == trans_values->gray)
  186665. {
  186666. *sp = (png_byte)((background->gray >> 8) & 0xff);
  186667. *(sp + 1) = (png_byte)(background->gray & 0xff);
  186668. }
  186669. }
  186670. }
  186671. break;
  186672. }
  186673. }
  186674. break;
  186675. }
  186676. case PNG_COLOR_TYPE_RGB:
  186677. {
  186678. if (row_info->bit_depth == 8)
  186679. {
  186680. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186681. if (gamma_table != NULL)
  186682. {
  186683. sp = row;
  186684. for (i = 0; i < row_width; i++, sp += 3)
  186685. {
  186686. if (*sp == trans_values->red &&
  186687. *(sp + 1) == trans_values->green &&
  186688. *(sp + 2) == trans_values->blue)
  186689. {
  186690. *sp = (png_byte)background->red;
  186691. *(sp + 1) = (png_byte)background->green;
  186692. *(sp + 2) = (png_byte)background->blue;
  186693. }
  186694. else
  186695. {
  186696. *sp = gamma_table[*sp];
  186697. *(sp + 1) = gamma_table[*(sp + 1)];
  186698. *(sp + 2) = gamma_table[*(sp + 2)];
  186699. }
  186700. }
  186701. }
  186702. else
  186703. #endif
  186704. {
  186705. sp = row;
  186706. for (i = 0; i < row_width; i++, sp += 3)
  186707. {
  186708. if (*sp == trans_values->red &&
  186709. *(sp + 1) == trans_values->green &&
  186710. *(sp + 2) == trans_values->blue)
  186711. {
  186712. *sp = (png_byte)background->red;
  186713. *(sp + 1) = (png_byte)background->green;
  186714. *(sp + 2) = (png_byte)background->blue;
  186715. }
  186716. }
  186717. }
  186718. }
  186719. else /* if (row_info->bit_depth == 16) */
  186720. {
  186721. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186722. if (gamma_16 != NULL)
  186723. {
  186724. sp = row;
  186725. for (i = 0; i < row_width; i++, sp += 6)
  186726. {
  186727. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  186728. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186729. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  186730. if (r == trans_values->red && g == trans_values->green &&
  186731. b == trans_values->blue)
  186732. {
  186733. /* background is already in screen gamma */
  186734. *sp = (png_byte)((background->red >> 8) & 0xff);
  186735. *(sp + 1) = (png_byte)(background->red & 0xff);
  186736. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  186737. *(sp + 3) = (png_byte)(background->green & 0xff);
  186738. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  186739. *(sp + 5) = (png_byte)(background->blue & 0xff);
  186740. }
  186741. else
  186742. {
  186743. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  186744. *sp = (png_byte)((v >> 8) & 0xff);
  186745. *(sp + 1) = (png_byte)(v & 0xff);
  186746. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  186747. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  186748. *(sp + 3) = (png_byte)(v & 0xff);
  186749. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  186750. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  186751. *(sp + 5) = (png_byte)(v & 0xff);
  186752. }
  186753. }
  186754. }
  186755. else
  186756. #endif
  186757. {
  186758. sp = row;
  186759. for (i = 0; i < row_width; i++, sp += 6)
  186760. {
  186761. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  186762. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186763. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  186764. if (r == trans_values->red && g == trans_values->green &&
  186765. b == trans_values->blue)
  186766. {
  186767. *sp = (png_byte)((background->red >> 8) & 0xff);
  186768. *(sp + 1) = (png_byte)(background->red & 0xff);
  186769. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  186770. *(sp + 3) = (png_byte)(background->green & 0xff);
  186771. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  186772. *(sp + 5) = (png_byte)(background->blue & 0xff);
  186773. }
  186774. }
  186775. }
  186776. }
  186777. break;
  186778. }
  186779. case PNG_COLOR_TYPE_GRAY_ALPHA:
  186780. {
  186781. if (row_info->bit_depth == 8)
  186782. {
  186783. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186784. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  186785. gamma_table != NULL)
  186786. {
  186787. sp = row;
  186788. dp = row;
  186789. for (i = 0; i < row_width; i++, sp += 2, dp++)
  186790. {
  186791. png_uint_16 a = *(sp + 1);
  186792. if (a == 0xff)
  186793. {
  186794. *dp = gamma_table[*sp];
  186795. }
  186796. else if (a == 0)
  186797. {
  186798. /* background is already in screen gamma */
  186799. *dp = (png_byte)background->gray;
  186800. }
  186801. else
  186802. {
  186803. png_byte v, w;
  186804. v = gamma_to_1[*sp];
  186805. png_composite(w, v, a, background_1->gray);
  186806. *dp = gamma_from_1[w];
  186807. }
  186808. }
  186809. }
  186810. else
  186811. #endif
  186812. {
  186813. sp = row;
  186814. dp = row;
  186815. for (i = 0; i < row_width; i++, sp += 2, dp++)
  186816. {
  186817. png_byte a = *(sp + 1);
  186818. if (a == 0xff)
  186819. {
  186820. *dp = *sp;
  186821. }
  186822. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186823. else if (a == 0)
  186824. {
  186825. *dp = (png_byte)background->gray;
  186826. }
  186827. else
  186828. {
  186829. png_composite(*dp, *sp, a, background_1->gray);
  186830. }
  186831. #else
  186832. *dp = (png_byte)background->gray;
  186833. #endif
  186834. }
  186835. }
  186836. }
  186837. else /* if (png_ptr->bit_depth == 16) */
  186838. {
  186839. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186840. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  186841. gamma_16_to_1 != NULL)
  186842. {
  186843. sp = row;
  186844. dp = row;
  186845. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  186846. {
  186847. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186848. if (a == (png_uint_16)0xffff)
  186849. {
  186850. png_uint_16 v;
  186851. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  186852. *dp = (png_byte)((v >> 8) & 0xff);
  186853. *(dp + 1) = (png_byte)(v & 0xff);
  186854. }
  186855. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186856. else if (a == 0)
  186857. #else
  186858. else
  186859. #endif
  186860. {
  186861. /* background is already in screen gamma */
  186862. *dp = (png_byte)((background->gray >> 8) & 0xff);
  186863. *(dp + 1) = (png_byte)(background->gray & 0xff);
  186864. }
  186865. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186866. else
  186867. {
  186868. png_uint_16 g, v, w;
  186869. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  186870. png_composite_16(v, g, a, background_1->gray);
  186871. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  186872. *dp = (png_byte)((w >> 8) & 0xff);
  186873. *(dp + 1) = (png_byte)(w & 0xff);
  186874. }
  186875. #endif
  186876. }
  186877. }
  186878. else
  186879. #endif
  186880. {
  186881. sp = row;
  186882. dp = row;
  186883. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  186884. {
  186885. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186886. if (a == (png_uint_16)0xffff)
  186887. {
  186888. png_memcpy(dp, sp, 2);
  186889. }
  186890. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186891. else if (a == 0)
  186892. #else
  186893. else
  186894. #endif
  186895. {
  186896. *dp = (png_byte)((background->gray >> 8) & 0xff);
  186897. *(dp + 1) = (png_byte)(background->gray & 0xff);
  186898. }
  186899. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186900. else
  186901. {
  186902. png_uint_16 g, v;
  186903. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  186904. png_composite_16(v, g, a, background_1->gray);
  186905. *dp = (png_byte)((v >> 8) & 0xff);
  186906. *(dp + 1) = (png_byte)(v & 0xff);
  186907. }
  186908. #endif
  186909. }
  186910. }
  186911. }
  186912. break;
  186913. }
  186914. case PNG_COLOR_TYPE_RGB_ALPHA:
  186915. {
  186916. if (row_info->bit_depth == 8)
  186917. {
  186918. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186919. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  186920. gamma_table != NULL)
  186921. {
  186922. sp = row;
  186923. dp = row;
  186924. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  186925. {
  186926. png_byte a = *(sp + 3);
  186927. if (a == 0xff)
  186928. {
  186929. *dp = gamma_table[*sp];
  186930. *(dp + 1) = gamma_table[*(sp + 1)];
  186931. *(dp + 2) = gamma_table[*(sp + 2)];
  186932. }
  186933. else if (a == 0)
  186934. {
  186935. /* background is already in screen gamma */
  186936. *dp = (png_byte)background->red;
  186937. *(dp + 1) = (png_byte)background->green;
  186938. *(dp + 2) = (png_byte)background->blue;
  186939. }
  186940. else
  186941. {
  186942. png_byte v, w;
  186943. v = gamma_to_1[*sp];
  186944. png_composite(w, v, a, background_1->red);
  186945. *dp = gamma_from_1[w];
  186946. v = gamma_to_1[*(sp + 1)];
  186947. png_composite(w, v, a, background_1->green);
  186948. *(dp + 1) = gamma_from_1[w];
  186949. v = gamma_to_1[*(sp + 2)];
  186950. png_composite(w, v, a, background_1->blue);
  186951. *(dp + 2) = gamma_from_1[w];
  186952. }
  186953. }
  186954. }
  186955. else
  186956. #endif
  186957. {
  186958. sp = row;
  186959. dp = row;
  186960. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  186961. {
  186962. png_byte a = *(sp + 3);
  186963. if (a == 0xff)
  186964. {
  186965. *dp = *sp;
  186966. *(dp + 1) = *(sp + 1);
  186967. *(dp + 2) = *(sp + 2);
  186968. }
  186969. else if (a == 0)
  186970. {
  186971. *dp = (png_byte)background->red;
  186972. *(dp + 1) = (png_byte)background->green;
  186973. *(dp + 2) = (png_byte)background->blue;
  186974. }
  186975. else
  186976. {
  186977. png_composite(*dp, *sp, a, background->red);
  186978. png_composite(*(dp + 1), *(sp + 1), a,
  186979. background->green);
  186980. png_composite(*(dp + 2), *(sp + 2), a,
  186981. background->blue);
  186982. }
  186983. }
  186984. }
  186985. }
  186986. else /* if (row_info->bit_depth == 16) */
  186987. {
  186988. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186989. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  186990. gamma_16_to_1 != NULL)
  186991. {
  186992. sp = row;
  186993. dp = row;
  186994. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  186995. {
  186996. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  186997. << 8) + (png_uint_16)(*(sp + 7)));
  186998. if (a == (png_uint_16)0xffff)
  186999. {
  187000. png_uint_16 v;
  187001. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  187002. *dp = (png_byte)((v >> 8) & 0xff);
  187003. *(dp + 1) = (png_byte)(v & 0xff);
  187004. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  187005. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  187006. *(dp + 3) = (png_byte)(v & 0xff);
  187007. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  187008. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  187009. *(dp + 5) = (png_byte)(v & 0xff);
  187010. }
  187011. else if (a == 0)
  187012. {
  187013. /* background is already in screen gamma */
  187014. *dp = (png_byte)((background->red >> 8) & 0xff);
  187015. *(dp + 1) = (png_byte)(background->red & 0xff);
  187016. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  187017. *(dp + 3) = (png_byte)(background->green & 0xff);
  187018. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  187019. *(dp + 5) = (png_byte)(background->blue & 0xff);
  187020. }
  187021. else
  187022. {
  187023. png_uint_16 v, w, x;
  187024. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  187025. png_composite_16(w, v, a, background_1->red);
  187026. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  187027. *dp = (png_byte)((x >> 8) & 0xff);
  187028. *(dp + 1) = (png_byte)(x & 0xff);
  187029. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  187030. png_composite_16(w, v, a, background_1->green);
  187031. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  187032. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  187033. *(dp + 3) = (png_byte)(x & 0xff);
  187034. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  187035. png_composite_16(w, v, a, background_1->blue);
  187036. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  187037. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  187038. *(dp + 5) = (png_byte)(x & 0xff);
  187039. }
  187040. }
  187041. }
  187042. else
  187043. #endif
  187044. {
  187045. sp = row;
  187046. dp = row;
  187047. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  187048. {
  187049. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  187050. << 8) + (png_uint_16)(*(sp + 7)));
  187051. if (a == (png_uint_16)0xffff)
  187052. {
  187053. png_memcpy(dp, sp, 6);
  187054. }
  187055. else if (a == 0)
  187056. {
  187057. *dp = (png_byte)((background->red >> 8) & 0xff);
  187058. *(dp + 1) = (png_byte)(background->red & 0xff);
  187059. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  187060. *(dp + 3) = (png_byte)(background->green & 0xff);
  187061. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  187062. *(dp + 5) = (png_byte)(background->blue & 0xff);
  187063. }
  187064. else
  187065. {
  187066. png_uint_16 v;
  187067. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  187068. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  187069. + *(sp + 3));
  187070. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  187071. + *(sp + 5));
  187072. png_composite_16(v, r, a, background->red);
  187073. *dp = (png_byte)((v >> 8) & 0xff);
  187074. *(dp + 1) = (png_byte)(v & 0xff);
  187075. png_composite_16(v, g, a, background->green);
  187076. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  187077. *(dp + 3) = (png_byte)(v & 0xff);
  187078. png_composite_16(v, b, a, background->blue);
  187079. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  187080. *(dp + 5) = (png_byte)(v & 0xff);
  187081. }
  187082. }
  187083. }
  187084. }
  187085. break;
  187086. }
  187087. }
  187088. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  187089. {
  187090. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  187091. row_info->channels--;
  187092. row_info->pixel_depth = (png_byte)(row_info->channels *
  187093. row_info->bit_depth);
  187094. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187095. }
  187096. }
  187097. }
  187098. #endif
  187099. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187100. /* Gamma correct the image, avoiding the alpha channel. Make sure
  187101. * you do this after you deal with the transparency issue on grayscale
  187102. * or RGB images. If your bit depth is 8, use gamma_table, if it
  187103. * is 16, use gamma_16_table and gamma_shift. Build these with
  187104. * build_gamma_table().
  187105. */
  187106. void /* PRIVATE */
  187107. png_do_gamma(png_row_infop row_info, png_bytep row,
  187108. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  187109. int gamma_shift)
  187110. {
  187111. png_bytep sp;
  187112. png_uint_32 i;
  187113. png_uint_32 row_width=row_info->width;
  187114. png_debug(1, "in png_do_gamma\n");
  187115. if (
  187116. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187117. row != NULL && row_info != NULL &&
  187118. #endif
  187119. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  187120. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  187121. {
  187122. switch (row_info->color_type)
  187123. {
  187124. case PNG_COLOR_TYPE_RGB:
  187125. {
  187126. if (row_info->bit_depth == 8)
  187127. {
  187128. sp = row;
  187129. for (i = 0; i < row_width; i++)
  187130. {
  187131. *sp = gamma_table[*sp];
  187132. sp++;
  187133. *sp = gamma_table[*sp];
  187134. sp++;
  187135. *sp = gamma_table[*sp];
  187136. sp++;
  187137. }
  187138. }
  187139. else /* if (row_info->bit_depth == 16) */
  187140. {
  187141. sp = row;
  187142. for (i = 0; i < row_width; i++)
  187143. {
  187144. png_uint_16 v;
  187145. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187146. *sp = (png_byte)((v >> 8) & 0xff);
  187147. *(sp + 1) = (png_byte)(v & 0xff);
  187148. sp += 2;
  187149. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187150. *sp = (png_byte)((v >> 8) & 0xff);
  187151. *(sp + 1) = (png_byte)(v & 0xff);
  187152. sp += 2;
  187153. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187154. *sp = (png_byte)((v >> 8) & 0xff);
  187155. *(sp + 1) = (png_byte)(v & 0xff);
  187156. sp += 2;
  187157. }
  187158. }
  187159. break;
  187160. }
  187161. case PNG_COLOR_TYPE_RGB_ALPHA:
  187162. {
  187163. if (row_info->bit_depth == 8)
  187164. {
  187165. sp = row;
  187166. for (i = 0; i < row_width; i++)
  187167. {
  187168. *sp = gamma_table[*sp];
  187169. sp++;
  187170. *sp = gamma_table[*sp];
  187171. sp++;
  187172. *sp = gamma_table[*sp];
  187173. sp++;
  187174. sp++;
  187175. }
  187176. }
  187177. else /* if (row_info->bit_depth == 16) */
  187178. {
  187179. sp = row;
  187180. for (i = 0; i < row_width; i++)
  187181. {
  187182. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187183. *sp = (png_byte)((v >> 8) & 0xff);
  187184. *(sp + 1) = (png_byte)(v & 0xff);
  187185. sp += 2;
  187186. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187187. *sp = (png_byte)((v >> 8) & 0xff);
  187188. *(sp + 1) = (png_byte)(v & 0xff);
  187189. sp += 2;
  187190. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187191. *sp = (png_byte)((v >> 8) & 0xff);
  187192. *(sp + 1) = (png_byte)(v & 0xff);
  187193. sp += 4;
  187194. }
  187195. }
  187196. break;
  187197. }
  187198. case PNG_COLOR_TYPE_GRAY_ALPHA:
  187199. {
  187200. if (row_info->bit_depth == 8)
  187201. {
  187202. sp = row;
  187203. for (i = 0; i < row_width; i++)
  187204. {
  187205. *sp = gamma_table[*sp];
  187206. sp += 2;
  187207. }
  187208. }
  187209. else /* if (row_info->bit_depth == 16) */
  187210. {
  187211. sp = row;
  187212. for (i = 0; i < row_width; i++)
  187213. {
  187214. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187215. *sp = (png_byte)((v >> 8) & 0xff);
  187216. *(sp + 1) = (png_byte)(v & 0xff);
  187217. sp += 4;
  187218. }
  187219. }
  187220. break;
  187221. }
  187222. case PNG_COLOR_TYPE_GRAY:
  187223. {
  187224. if (row_info->bit_depth == 2)
  187225. {
  187226. sp = row;
  187227. for (i = 0; i < row_width; i += 4)
  187228. {
  187229. int a = *sp & 0xc0;
  187230. int b = *sp & 0x30;
  187231. int c = *sp & 0x0c;
  187232. int d = *sp & 0x03;
  187233. *sp = (png_byte)(
  187234. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  187235. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  187236. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  187237. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  187238. sp++;
  187239. }
  187240. }
  187241. if (row_info->bit_depth == 4)
  187242. {
  187243. sp = row;
  187244. for (i = 0; i < row_width; i += 2)
  187245. {
  187246. int msb = *sp & 0xf0;
  187247. int lsb = *sp & 0x0f;
  187248. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  187249. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  187250. sp++;
  187251. }
  187252. }
  187253. else if (row_info->bit_depth == 8)
  187254. {
  187255. sp = row;
  187256. for (i = 0; i < row_width; i++)
  187257. {
  187258. *sp = gamma_table[*sp];
  187259. sp++;
  187260. }
  187261. }
  187262. else if (row_info->bit_depth == 16)
  187263. {
  187264. sp = row;
  187265. for (i = 0; i < row_width; i++)
  187266. {
  187267. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187268. *sp = (png_byte)((v >> 8) & 0xff);
  187269. *(sp + 1) = (png_byte)(v & 0xff);
  187270. sp += 2;
  187271. }
  187272. }
  187273. break;
  187274. }
  187275. }
  187276. }
  187277. }
  187278. #endif
  187279. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187280. /* Expands a palette row to an RGB or RGBA row depending
  187281. * upon whether you supply trans and num_trans.
  187282. */
  187283. void /* PRIVATE */
  187284. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  187285. png_colorp palette, png_bytep trans, int num_trans)
  187286. {
  187287. int shift, value;
  187288. png_bytep sp, dp;
  187289. png_uint_32 i;
  187290. png_uint_32 row_width=row_info->width;
  187291. png_debug(1, "in png_do_expand_palette\n");
  187292. if (
  187293. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187294. row != NULL && row_info != NULL &&
  187295. #endif
  187296. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  187297. {
  187298. if (row_info->bit_depth < 8)
  187299. {
  187300. switch (row_info->bit_depth)
  187301. {
  187302. case 1:
  187303. {
  187304. sp = row + (png_size_t)((row_width - 1) >> 3);
  187305. dp = row + (png_size_t)row_width - 1;
  187306. shift = 7 - (int)((row_width + 7) & 0x07);
  187307. for (i = 0; i < row_width; i++)
  187308. {
  187309. if ((*sp >> shift) & 0x01)
  187310. *dp = 1;
  187311. else
  187312. *dp = 0;
  187313. if (shift == 7)
  187314. {
  187315. shift = 0;
  187316. sp--;
  187317. }
  187318. else
  187319. shift++;
  187320. dp--;
  187321. }
  187322. break;
  187323. }
  187324. case 2:
  187325. {
  187326. sp = row + (png_size_t)((row_width - 1) >> 2);
  187327. dp = row + (png_size_t)row_width - 1;
  187328. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  187329. for (i = 0; i < row_width; i++)
  187330. {
  187331. value = (*sp >> shift) & 0x03;
  187332. *dp = (png_byte)value;
  187333. if (shift == 6)
  187334. {
  187335. shift = 0;
  187336. sp--;
  187337. }
  187338. else
  187339. shift += 2;
  187340. dp--;
  187341. }
  187342. break;
  187343. }
  187344. case 4:
  187345. {
  187346. sp = row + (png_size_t)((row_width - 1) >> 1);
  187347. dp = row + (png_size_t)row_width - 1;
  187348. shift = (int)((row_width & 0x01) << 2);
  187349. for (i = 0; i < row_width; i++)
  187350. {
  187351. value = (*sp >> shift) & 0x0f;
  187352. *dp = (png_byte)value;
  187353. if (shift == 4)
  187354. {
  187355. shift = 0;
  187356. sp--;
  187357. }
  187358. else
  187359. shift += 4;
  187360. dp--;
  187361. }
  187362. break;
  187363. }
  187364. }
  187365. row_info->bit_depth = 8;
  187366. row_info->pixel_depth = 8;
  187367. row_info->rowbytes = row_width;
  187368. }
  187369. switch (row_info->bit_depth)
  187370. {
  187371. case 8:
  187372. {
  187373. if (trans != NULL)
  187374. {
  187375. sp = row + (png_size_t)row_width - 1;
  187376. dp = row + (png_size_t)(row_width << 2) - 1;
  187377. for (i = 0; i < row_width; i++)
  187378. {
  187379. if ((int)(*sp) >= num_trans)
  187380. *dp-- = 0xff;
  187381. else
  187382. *dp-- = trans[*sp];
  187383. *dp-- = palette[*sp].blue;
  187384. *dp-- = palette[*sp].green;
  187385. *dp-- = palette[*sp].red;
  187386. sp--;
  187387. }
  187388. row_info->bit_depth = 8;
  187389. row_info->pixel_depth = 32;
  187390. row_info->rowbytes = row_width * 4;
  187391. row_info->color_type = 6;
  187392. row_info->channels = 4;
  187393. }
  187394. else
  187395. {
  187396. sp = row + (png_size_t)row_width - 1;
  187397. dp = row + (png_size_t)(row_width * 3) - 1;
  187398. for (i = 0; i < row_width; i++)
  187399. {
  187400. *dp-- = palette[*sp].blue;
  187401. *dp-- = palette[*sp].green;
  187402. *dp-- = palette[*sp].red;
  187403. sp--;
  187404. }
  187405. row_info->bit_depth = 8;
  187406. row_info->pixel_depth = 24;
  187407. row_info->rowbytes = row_width * 3;
  187408. row_info->color_type = 2;
  187409. row_info->channels = 3;
  187410. }
  187411. break;
  187412. }
  187413. }
  187414. }
  187415. }
  187416. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  187417. * expanded transparency value is supplied, an alpha channel is built.
  187418. */
  187419. void /* PRIVATE */
  187420. png_do_expand(png_row_infop row_info, png_bytep row,
  187421. png_color_16p trans_value)
  187422. {
  187423. int shift, value;
  187424. png_bytep sp, dp;
  187425. png_uint_32 i;
  187426. png_uint_32 row_width=row_info->width;
  187427. png_debug(1, "in png_do_expand\n");
  187428. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187429. if (row != NULL && row_info != NULL)
  187430. #endif
  187431. {
  187432. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  187433. {
  187434. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  187435. if (row_info->bit_depth < 8)
  187436. {
  187437. switch (row_info->bit_depth)
  187438. {
  187439. case 1:
  187440. {
  187441. gray = (png_uint_16)((gray&0x01)*0xff);
  187442. sp = row + (png_size_t)((row_width - 1) >> 3);
  187443. dp = row + (png_size_t)row_width - 1;
  187444. shift = 7 - (int)((row_width + 7) & 0x07);
  187445. for (i = 0; i < row_width; i++)
  187446. {
  187447. if ((*sp >> shift) & 0x01)
  187448. *dp = 0xff;
  187449. else
  187450. *dp = 0;
  187451. if (shift == 7)
  187452. {
  187453. shift = 0;
  187454. sp--;
  187455. }
  187456. else
  187457. shift++;
  187458. dp--;
  187459. }
  187460. break;
  187461. }
  187462. case 2:
  187463. {
  187464. gray = (png_uint_16)((gray&0x03)*0x55);
  187465. sp = row + (png_size_t)((row_width - 1) >> 2);
  187466. dp = row + (png_size_t)row_width - 1;
  187467. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  187468. for (i = 0; i < row_width; i++)
  187469. {
  187470. value = (*sp >> shift) & 0x03;
  187471. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  187472. (value << 6));
  187473. if (shift == 6)
  187474. {
  187475. shift = 0;
  187476. sp--;
  187477. }
  187478. else
  187479. shift += 2;
  187480. dp--;
  187481. }
  187482. break;
  187483. }
  187484. case 4:
  187485. {
  187486. gray = (png_uint_16)((gray&0x0f)*0x11);
  187487. sp = row + (png_size_t)((row_width - 1) >> 1);
  187488. dp = row + (png_size_t)row_width - 1;
  187489. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  187490. for (i = 0; i < row_width; i++)
  187491. {
  187492. value = (*sp >> shift) & 0x0f;
  187493. *dp = (png_byte)(value | (value << 4));
  187494. if (shift == 4)
  187495. {
  187496. shift = 0;
  187497. sp--;
  187498. }
  187499. else
  187500. shift = 4;
  187501. dp--;
  187502. }
  187503. break;
  187504. }
  187505. }
  187506. row_info->bit_depth = 8;
  187507. row_info->pixel_depth = 8;
  187508. row_info->rowbytes = row_width;
  187509. }
  187510. if (trans_value != NULL)
  187511. {
  187512. if (row_info->bit_depth == 8)
  187513. {
  187514. gray = gray & 0xff;
  187515. sp = row + (png_size_t)row_width - 1;
  187516. dp = row + (png_size_t)(row_width << 1) - 1;
  187517. for (i = 0; i < row_width; i++)
  187518. {
  187519. if (*sp == gray)
  187520. *dp-- = 0;
  187521. else
  187522. *dp-- = 0xff;
  187523. *dp-- = *sp--;
  187524. }
  187525. }
  187526. else if (row_info->bit_depth == 16)
  187527. {
  187528. png_byte gray_high = (gray >> 8) & 0xff;
  187529. png_byte gray_low = gray & 0xff;
  187530. sp = row + row_info->rowbytes - 1;
  187531. dp = row + (row_info->rowbytes << 1) - 1;
  187532. for (i = 0; i < row_width; i++)
  187533. {
  187534. if (*(sp-1) == gray_high && *(sp) == gray_low)
  187535. {
  187536. *dp-- = 0;
  187537. *dp-- = 0;
  187538. }
  187539. else
  187540. {
  187541. *dp-- = 0xff;
  187542. *dp-- = 0xff;
  187543. }
  187544. *dp-- = *sp--;
  187545. *dp-- = *sp--;
  187546. }
  187547. }
  187548. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  187549. row_info->channels = 2;
  187550. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  187551. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  187552. row_width);
  187553. }
  187554. }
  187555. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  187556. {
  187557. if (row_info->bit_depth == 8)
  187558. {
  187559. png_byte red = trans_value->red & 0xff;
  187560. png_byte green = trans_value->green & 0xff;
  187561. png_byte blue = trans_value->blue & 0xff;
  187562. sp = row + (png_size_t)row_info->rowbytes - 1;
  187563. dp = row + (png_size_t)(row_width << 2) - 1;
  187564. for (i = 0; i < row_width; i++)
  187565. {
  187566. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  187567. *dp-- = 0;
  187568. else
  187569. *dp-- = 0xff;
  187570. *dp-- = *sp--;
  187571. *dp-- = *sp--;
  187572. *dp-- = *sp--;
  187573. }
  187574. }
  187575. else if (row_info->bit_depth == 16)
  187576. {
  187577. png_byte red_high = (trans_value->red >> 8) & 0xff;
  187578. png_byte green_high = (trans_value->green >> 8) & 0xff;
  187579. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  187580. png_byte red_low = trans_value->red & 0xff;
  187581. png_byte green_low = trans_value->green & 0xff;
  187582. png_byte blue_low = trans_value->blue & 0xff;
  187583. sp = row + row_info->rowbytes - 1;
  187584. dp = row + (png_size_t)(row_width << 3) - 1;
  187585. for (i = 0; i < row_width; i++)
  187586. {
  187587. if (*(sp - 5) == red_high &&
  187588. *(sp - 4) == red_low &&
  187589. *(sp - 3) == green_high &&
  187590. *(sp - 2) == green_low &&
  187591. *(sp - 1) == blue_high &&
  187592. *(sp ) == blue_low)
  187593. {
  187594. *dp-- = 0;
  187595. *dp-- = 0;
  187596. }
  187597. else
  187598. {
  187599. *dp-- = 0xff;
  187600. *dp-- = 0xff;
  187601. }
  187602. *dp-- = *sp--;
  187603. *dp-- = *sp--;
  187604. *dp-- = *sp--;
  187605. *dp-- = *sp--;
  187606. *dp-- = *sp--;
  187607. *dp-- = *sp--;
  187608. }
  187609. }
  187610. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  187611. row_info->channels = 4;
  187612. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  187613. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187614. }
  187615. }
  187616. }
  187617. #endif
  187618. #if defined(PNG_READ_DITHER_SUPPORTED)
  187619. void /* PRIVATE */
  187620. png_do_dither(png_row_infop row_info, png_bytep row,
  187621. png_bytep palette_lookup, png_bytep dither_lookup)
  187622. {
  187623. png_bytep sp, dp;
  187624. png_uint_32 i;
  187625. png_uint_32 row_width=row_info->width;
  187626. png_debug(1, "in png_do_dither\n");
  187627. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187628. if (row != NULL && row_info != NULL)
  187629. #endif
  187630. {
  187631. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  187632. palette_lookup && row_info->bit_depth == 8)
  187633. {
  187634. int r, g, b, p;
  187635. sp = row;
  187636. dp = row;
  187637. for (i = 0; i < row_width; i++)
  187638. {
  187639. r = *sp++;
  187640. g = *sp++;
  187641. b = *sp++;
  187642. /* this looks real messy, but the compiler will reduce
  187643. it down to a reasonable formula. For example, with
  187644. 5 bits per color, we get:
  187645. p = (((r >> 3) & 0x1f) << 10) |
  187646. (((g >> 3) & 0x1f) << 5) |
  187647. ((b >> 3) & 0x1f);
  187648. */
  187649. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  187650. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  187651. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  187652. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  187653. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  187654. (PNG_DITHER_BLUE_BITS)) |
  187655. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  187656. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  187657. *dp++ = palette_lookup[p];
  187658. }
  187659. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  187660. row_info->channels = 1;
  187661. row_info->pixel_depth = row_info->bit_depth;
  187662. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187663. }
  187664. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  187665. palette_lookup != NULL && row_info->bit_depth == 8)
  187666. {
  187667. int r, g, b, p;
  187668. sp = row;
  187669. dp = row;
  187670. for (i = 0; i < row_width; i++)
  187671. {
  187672. r = *sp++;
  187673. g = *sp++;
  187674. b = *sp++;
  187675. sp++;
  187676. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  187677. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  187678. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  187679. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  187680. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  187681. (PNG_DITHER_BLUE_BITS)) |
  187682. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  187683. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  187684. *dp++ = palette_lookup[p];
  187685. }
  187686. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  187687. row_info->channels = 1;
  187688. row_info->pixel_depth = row_info->bit_depth;
  187689. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187690. }
  187691. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  187692. dither_lookup && row_info->bit_depth == 8)
  187693. {
  187694. sp = row;
  187695. for (i = 0; i < row_width; i++, sp++)
  187696. {
  187697. *sp = dither_lookup[*sp];
  187698. }
  187699. }
  187700. }
  187701. }
  187702. #endif
  187703. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187704. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187705. static PNG_CONST int png_gamma_shift[] =
  187706. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  187707. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  187708. * tables, we don't make a full table if we are reducing to 8-bit in
  187709. * the future. Note also how the gamma_16 tables are segmented so that
  187710. * we don't need to allocate > 64K chunks for a full 16-bit table.
  187711. */
  187712. void /* PRIVATE */
  187713. png_build_gamma_table(png_structp png_ptr)
  187714. {
  187715. png_debug(1, "in png_build_gamma_table\n");
  187716. if (png_ptr->bit_depth <= 8)
  187717. {
  187718. int i;
  187719. double g;
  187720. if (png_ptr->screen_gamma > .000001)
  187721. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  187722. else
  187723. g = 1.0;
  187724. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  187725. (png_uint_32)256);
  187726. for (i = 0; i < 256; i++)
  187727. {
  187728. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  187729. g) * 255.0 + .5);
  187730. }
  187731. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  187732. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187733. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  187734. {
  187735. g = 1.0 / (png_ptr->gamma);
  187736. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  187737. (png_uint_32)256);
  187738. for (i = 0; i < 256; i++)
  187739. {
  187740. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  187741. g) * 255.0 + .5);
  187742. }
  187743. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  187744. (png_uint_32)256);
  187745. if(png_ptr->screen_gamma > 0.000001)
  187746. g = 1.0 / png_ptr->screen_gamma;
  187747. else
  187748. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  187749. for (i = 0; i < 256; i++)
  187750. {
  187751. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  187752. g) * 255.0 + .5);
  187753. }
  187754. }
  187755. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  187756. }
  187757. else
  187758. {
  187759. double g;
  187760. int i, j, shift, num;
  187761. int sig_bit;
  187762. png_uint_32 ig;
  187763. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  187764. {
  187765. sig_bit = (int)png_ptr->sig_bit.red;
  187766. if ((int)png_ptr->sig_bit.green > sig_bit)
  187767. sig_bit = png_ptr->sig_bit.green;
  187768. if ((int)png_ptr->sig_bit.blue > sig_bit)
  187769. sig_bit = png_ptr->sig_bit.blue;
  187770. }
  187771. else
  187772. {
  187773. sig_bit = (int)png_ptr->sig_bit.gray;
  187774. }
  187775. if (sig_bit > 0)
  187776. shift = 16 - sig_bit;
  187777. else
  187778. shift = 0;
  187779. if (png_ptr->transformations & PNG_16_TO_8)
  187780. {
  187781. if (shift < (16 - PNG_MAX_GAMMA_8))
  187782. shift = (16 - PNG_MAX_GAMMA_8);
  187783. }
  187784. if (shift > 8)
  187785. shift = 8;
  187786. if (shift < 0)
  187787. shift = 0;
  187788. png_ptr->gamma_shift = (png_byte)shift;
  187789. num = (1 << (8 - shift));
  187790. if (png_ptr->screen_gamma > .000001)
  187791. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  187792. else
  187793. g = 1.0;
  187794. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  187795. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  187796. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  187797. {
  187798. double fin, fout;
  187799. png_uint_32 last, max;
  187800. for (i = 0; i < num; i++)
  187801. {
  187802. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  187803. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187804. }
  187805. g = 1.0 / g;
  187806. last = 0;
  187807. for (i = 0; i < 256; i++)
  187808. {
  187809. fout = ((double)i + 0.5) / 256.0;
  187810. fin = pow(fout, g);
  187811. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  187812. while (last <= max)
  187813. {
  187814. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  187815. [(int)(last >> (8 - shift))] = (png_uint_16)(
  187816. (png_uint_16)i | ((png_uint_16)i << 8));
  187817. last++;
  187818. }
  187819. }
  187820. while (last < ((png_uint_32)num << 8))
  187821. {
  187822. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  187823. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  187824. last++;
  187825. }
  187826. }
  187827. else
  187828. {
  187829. for (i = 0; i < num; i++)
  187830. {
  187831. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  187832. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187833. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  187834. for (j = 0; j < 256; j++)
  187835. {
  187836. png_ptr->gamma_16_table[i][j] =
  187837. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  187838. 65535.0, g) * 65535.0 + .5);
  187839. }
  187840. }
  187841. }
  187842. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  187843. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187844. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  187845. {
  187846. g = 1.0 / (png_ptr->gamma);
  187847. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  187848. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  187849. for (i = 0; i < num; i++)
  187850. {
  187851. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  187852. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187853. ig = (((png_uint_32)i *
  187854. (png_uint_32)png_gamma_shift[shift]) >> 4);
  187855. for (j = 0; j < 256; j++)
  187856. {
  187857. png_ptr->gamma_16_to_1[i][j] =
  187858. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  187859. 65535.0, g) * 65535.0 + .5);
  187860. }
  187861. }
  187862. if(png_ptr->screen_gamma > 0.000001)
  187863. g = 1.0 / png_ptr->screen_gamma;
  187864. else
  187865. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  187866. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  187867. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  187868. for (i = 0; i < num; i++)
  187869. {
  187870. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  187871. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187872. ig = (((png_uint_32)i *
  187873. (png_uint_32)png_gamma_shift[shift]) >> 4);
  187874. for (j = 0; j < 256; j++)
  187875. {
  187876. png_ptr->gamma_16_from_1[i][j] =
  187877. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  187878. 65535.0, g) * 65535.0 + .5);
  187879. }
  187880. }
  187881. }
  187882. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  187883. }
  187884. }
  187885. #endif
  187886. /* To do: install integer version of png_build_gamma_table here */
  187887. #endif
  187888. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187889. /* undoes intrapixel differencing */
  187890. void /* PRIVATE */
  187891. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  187892. {
  187893. png_debug(1, "in png_do_read_intrapixel\n");
  187894. if (
  187895. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187896. row != NULL && row_info != NULL &&
  187897. #endif
  187898. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  187899. {
  187900. int bytes_per_pixel;
  187901. png_uint_32 row_width = row_info->width;
  187902. if (row_info->bit_depth == 8)
  187903. {
  187904. png_bytep rp;
  187905. png_uint_32 i;
  187906. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  187907. bytes_per_pixel = 3;
  187908. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187909. bytes_per_pixel = 4;
  187910. else
  187911. return;
  187912. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  187913. {
  187914. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  187915. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  187916. }
  187917. }
  187918. else if (row_info->bit_depth == 16)
  187919. {
  187920. png_bytep rp;
  187921. png_uint_32 i;
  187922. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  187923. bytes_per_pixel = 6;
  187924. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187925. bytes_per_pixel = 8;
  187926. else
  187927. return;
  187928. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  187929. {
  187930. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  187931. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  187932. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  187933. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  187934. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  187935. *(rp ) = (png_byte)((red >> 8) & 0xff);
  187936. *(rp+1) = (png_byte)(red & 0xff);
  187937. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  187938. *(rp+5) = (png_byte)(blue & 0xff);
  187939. }
  187940. }
  187941. }
  187942. }
  187943. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  187944. #endif /* PNG_READ_SUPPORTED */
  187945. /********* End of inlined file: pngrtran.c *********/
  187946. /********* Start of inlined file: pngrutil.c *********/
  187947. /* pngrutil.c - utilities to read a PNG file
  187948. *
  187949. * Last changed in libpng 1.2.21 [October 4, 2007]
  187950. * For conditions of distribution and use, see copyright notice in png.h
  187951. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187952. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187953. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187954. *
  187955. * This file contains routines that are only called from within
  187956. * libpng itself during the course of reading an image.
  187957. */
  187958. #define PNG_INTERNAL
  187959. #if defined(PNG_READ_SUPPORTED)
  187960. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  187961. # define WIN32_WCE_OLD
  187962. #endif
  187963. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187964. # if defined(WIN32_WCE_OLD)
  187965. /* strtod() function is not supported on WindowsCE */
  187966. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  187967. {
  187968. double result = 0;
  187969. int len;
  187970. wchar_t *str, *end;
  187971. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  187972. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  187973. if ( NULL != str )
  187974. {
  187975. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  187976. result = wcstod(str, &end);
  187977. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  187978. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  187979. png_free(png_ptr, str);
  187980. }
  187981. return result;
  187982. }
  187983. # else
  187984. # define png_strtod(p,a,b) strtod(a,b)
  187985. # endif
  187986. #endif
  187987. png_uint_32 PNGAPI
  187988. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  187989. {
  187990. png_uint_32 i = png_get_uint_32(buf);
  187991. if (i > PNG_UINT_31_MAX)
  187992. png_error(png_ptr, "PNG unsigned integer out of range.");
  187993. return (i);
  187994. }
  187995. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  187996. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  187997. png_uint_32 PNGAPI
  187998. png_get_uint_32(png_bytep buf)
  187999. {
  188000. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  188001. ((png_uint_32)(*(buf + 1)) << 16) +
  188002. ((png_uint_32)(*(buf + 2)) << 8) +
  188003. (png_uint_32)(*(buf + 3));
  188004. return (i);
  188005. }
  188006. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  188007. * data is stored in the PNG file in two's complement format, and it is
  188008. * assumed that the machine format for signed integers is the same. */
  188009. png_int_32 PNGAPI
  188010. png_get_int_32(png_bytep buf)
  188011. {
  188012. png_int_32 i = ((png_int_32)(*buf) << 24) +
  188013. ((png_int_32)(*(buf + 1)) << 16) +
  188014. ((png_int_32)(*(buf + 2)) << 8) +
  188015. (png_int_32)(*(buf + 3));
  188016. return (i);
  188017. }
  188018. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  188019. png_uint_16 PNGAPI
  188020. png_get_uint_16(png_bytep buf)
  188021. {
  188022. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  188023. (png_uint_16)(*(buf + 1)));
  188024. return (i);
  188025. }
  188026. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  188027. /* Read data, and (optionally) run it through the CRC. */
  188028. void /* PRIVATE */
  188029. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  188030. {
  188031. if(png_ptr == NULL) return;
  188032. png_read_data(png_ptr, buf, length);
  188033. png_calculate_crc(png_ptr, buf, length);
  188034. }
  188035. /* Optionally skip data and then check the CRC. Depending on whether we
  188036. are reading a ancillary or critical chunk, and how the program has set
  188037. things up, we may calculate the CRC on the data and print a message.
  188038. Returns '1' if there was a CRC error, '0' otherwise. */
  188039. int /* PRIVATE */
  188040. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  188041. {
  188042. png_size_t i;
  188043. png_size_t istop = png_ptr->zbuf_size;
  188044. for (i = (png_size_t)skip; i > istop; i -= istop)
  188045. {
  188046. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  188047. }
  188048. if (i)
  188049. {
  188050. png_crc_read(png_ptr, png_ptr->zbuf, i);
  188051. }
  188052. if (png_crc_error(png_ptr))
  188053. {
  188054. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  188055. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  188056. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  188057. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  188058. {
  188059. png_chunk_warning(png_ptr, "CRC error");
  188060. }
  188061. else
  188062. {
  188063. png_chunk_error(png_ptr, "CRC error");
  188064. }
  188065. return (1);
  188066. }
  188067. return (0);
  188068. }
  188069. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  188070. the data it has read thus far. */
  188071. int /* PRIVATE */
  188072. png_crc_error(png_structp png_ptr)
  188073. {
  188074. png_byte crc_bytes[4];
  188075. png_uint_32 crc;
  188076. int need_crc = 1;
  188077. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  188078. {
  188079. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  188080. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  188081. need_crc = 0;
  188082. }
  188083. else /* critical */
  188084. {
  188085. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  188086. need_crc = 0;
  188087. }
  188088. png_read_data(png_ptr, crc_bytes, 4);
  188089. if (need_crc)
  188090. {
  188091. crc = png_get_uint_32(crc_bytes);
  188092. return ((int)(crc != png_ptr->crc));
  188093. }
  188094. else
  188095. return (0);
  188096. }
  188097. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  188098. defined(PNG_READ_iCCP_SUPPORTED)
  188099. /*
  188100. * Decompress trailing data in a chunk. The assumption is that chunkdata
  188101. * points at an allocated area holding the contents of a chunk with a
  188102. * trailing compressed part. What we get back is an allocated area
  188103. * holding the original prefix part and an uncompressed version of the
  188104. * trailing part (the malloc area passed in is freed).
  188105. */
  188106. png_charp /* PRIVATE */
  188107. png_decompress_chunk(png_structp png_ptr, int comp_type,
  188108. png_charp chunkdata, png_size_t chunklength,
  188109. png_size_t prefix_size, png_size_t *newlength)
  188110. {
  188111. static PNG_CONST char msg[] = "Error decoding compressed text";
  188112. png_charp text;
  188113. png_size_t text_size;
  188114. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  188115. {
  188116. int ret = Z_OK;
  188117. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  188118. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  188119. png_ptr->zstream.next_out = png_ptr->zbuf;
  188120. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188121. text_size = 0;
  188122. text = NULL;
  188123. while (png_ptr->zstream.avail_in)
  188124. {
  188125. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188126. if (ret != Z_OK && ret != Z_STREAM_END)
  188127. {
  188128. if (png_ptr->zstream.msg != NULL)
  188129. png_warning(png_ptr, png_ptr->zstream.msg);
  188130. else
  188131. png_warning(png_ptr, msg);
  188132. inflateReset(&png_ptr->zstream);
  188133. png_ptr->zstream.avail_in = 0;
  188134. if (text == NULL)
  188135. {
  188136. text_size = prefix_size + png_sizeof(msg) + 1;
  188137. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  188138. if (text == NULL)
  188139. {
  188140. png_free(png_ptr,chunkdata);
  188141. png_error(png_ptr,"Not enough memory to decompress chunk");
  188142. }
  188143. png_memcpy(text, chunkdata, prefix_size);
  188144. }
  188145. text[text_size - 1] = 0x00;
  188146. /* Copy what we can of the error message into the text chunk */
  188147. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  188148. text_size = png_sizeof(msg) > text_size ? text_size :
  188149. png_sizeof(msg);
  188150. png_memcpy(text + prefix_size, msg, text_size + 1);
  188151. break;
  188152. }
  188153. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  188154. {
  188155. if (text == NULL)
  188156. {
  188157. text_size = prefix_size +
  188158. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  188159. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  188160. if (text == NULL)
  188161. {
  188162. png_free(png_ptr,chunkdata);
  188163. png_error(png_ptr,"Not enough memory to decompress chunk.");
  188164. }
  188165. png_memcpy(text + prefix_size, png_ptr->zbuf,
  188166. text_size - prefix_size);
  188167. png_memcpy(text, chunkdata, prefix_size);
  188168. *(text + text_size) = 0x00;
  188169. }
  188170. else
  188171. {
  188172. png_charp tmp;
  188173. tmp = text;
  188174. text = (png_charp)png_malloc_warn(png_ptr,
  188175. (png_uint_32)(text_size +
  188176. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  188177. if (text == NULL)
  188178. {
  188179. png_free(png_ptr, tmp);
  188180. png_free(png_ptr, chunkdata);
  188181. png_error(png_ptr,"Not enough memory to decompress chunk..");
  188182. }
  188183. png_memcpy(text, tmp, text_size);
  188184. png_free(png_ptr, tmp);
  188185. png_memcpy(text + text_size, png_ptr->zbuf,
  188186. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  188187. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  188188. *(text + text_size) = 0x00;
  188189. }
  188190. if (ret == Z_STREAM_END)
  188191. break;
  188192. else
  188193. {
  188194. png_ptr->zstream.next_out = png_ptr->zbuf;
  188195. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188196. }
  188197. }
  188198. }
  188199. if (ret != Z_STREAM_END)
  188200. {
  188201. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  188202. char umsg[52];
  188203. if (ret == Z_BUF_ERROR)
  188204. png_snprintf(umsg, 52,
  188205. "Buffer error in compressed datastream in %s chunk",
  188206. png_ptr->chunk_name);
  188207. else if (ret == Z_DATA_ERROR)
  188208. png_snprintf(umsg, 52,
  188209. "Data error in compressed datastream in %s chunk",
  188210. png_ptr->chunk_name);
  188211. else
  188212. png_snprintf(umsg, 52,
  188213. "Incomplete compressed datastream in %s chunk",
  188214. png_ptr->chunk_name);
  188215. png_warning(png_ptr, umsg);
  188216. #else
  188217. png_warning(png_ptr,
  188218. "Incomplete compressed datastream in chunk other than IDAT");
  188219. #endif
  188220. text_size=prefix_size;
  188221. if (text == NULL)
  188222. {
  188223. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  188224. if (text == NULL)
  188225. {
  188226. png_free(png_ptr, chunkdata);
  188227. png_error(png_ptr,"Not enough memory for text.");
  188228. }
  188229. png_memcpy(text, chunkdata, prefix_size);
  188230. }
  188231. *(text + text_size) = 0x00;
  188232. }
  188233. inflateReset(&png_ptr->zstream);
  188234. png_ptr->zstream.avail_in = 0;
  188235. png_free(png_ptr, chunkdata);
  188236. chunkdata = text;
  188237. *newlength=text_size;
  188238. }
  188239. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  188240. {
  188241. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  188242. char umsg[50];
  188243. png_snprintf(umsg, 50,
  188244. "Unknown zTXt compression type %d", comp_type);
  188245. png_warning(png_ptr, umsg);
  188246. #else
  188247. png_warning(png_ptr, "Unknown zTXt compression type");
  188248. #endif
  188249. *(chunkdata + prefix_size) = 0x00;
  188250. *newlength=prefix_size;
  188251. }
  188252. return chunkdata;
  188253. }
  188254. #endif
  188255. /* read and check the IDHR chunk */
  188256. void /* PRIVATE */
  188257. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188258. {
  188259. png_byte buf[13];
  188260. png_uint_32 width, height;
  188261. int bit_depth, color_type, compression_type, filter_type;
  188262. int interlace_type;
  188263. png_debug(1, "in png_handle_IHDR\n");
  188264. if (png_ptr->mode & PNG_HAVE_IHDR)
  188265. png_error(png_ptr, "Out of place IHDR");
  188266. /* check the length */
  188267. if (length != 13)
  188268. png_error(png_ptr, "Invalid IHDR chunk");
  188269. png_ptr->mode |= PNG_HAVE_IHDR;
  188270. png_crc_read(png_ptr, buf, 13);
  188271. png_crc_finish(png_ptr, 0);
  188272. width = png_get_uint_31(png_ptr, buf);
  188273. height = png_get_uint_31(png_ptr, buf + 4);
  188274. bit_depth = buf[8];
  188275. color_type = buf[9];
  188276. compression_type = buf[10];
  188277. filter_type = buf[11];
  188278. interlace_type = buf[12];
  188279. /* set internal variables */
  188280. png_ptr->width = width;
  188281. png_ptr->height = height;
  188282. png_ptr->bit_depth = (png_byte)bit_depth;
  188283. png_ptr->interlaced = (png_byte)interlace_type;
  188284. png_ptr->color_type = (png_byte)color_type;
  188285. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  188286. png_ptr->filter_type = (png_byte)filter_type;
  188287. #endif
  188288. png_ptr->compression_type = (png_byte)compression_type;
  188289. /* find number of channels */
  188290. switch (png_ptr->color_type)
  188291. {
  188292. case PNG_COLOR_TYPE_GRAY:
  188293. case PNG_COLOR_TYPE_PALETTE:
  188294. png_ptr->channels = 1;
  188295. break;
  188296. case PNG_COLOR_TYPE_RGB:
  188297. png_ptr->channels = 3;
  188298. break;
  188299. case PNG_COLOR_TYPE_GRAY_ALPHA:
  188300. png_ptr->channels = 2;
  188301. break;
  188302. case PNG_COLOR_TYPE_RGB_ALPHA:
  188303. png_ptr->channels = 4;
  188304. break;
  188305. }
  188306. /* set up other useful info */
  188307. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  188308. png_ptr->channels);
  188309. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  188310. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  188311. png_debug1(3,"channels = %d\n", png_ptr->channels);
  188312. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  188313. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  188314. color_type, interlace_type, compression_type, filter_type);
  188315. }
  188316. /* read and check the palette */
  188317. void /* PRIVATE */
  188318. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188319. {
  188320. png_color palette[PNG_MAX_PALETTE_LENGTH];
  188321. int num, i;
  188322. #ifndef PNG_NO_POINTER_INDEXING
  188323. png_colorp pal_ptr;
  188324. #endif
  188325. png_debug(1, "in png_handle_PLTE\n");
  188326. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188327. png_error(png_ptr, "Missing IHDR before PLTE");
  188328. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188329. {
  188330. png_warning(png_ptr, "Invalid PLTE after IDAT");
  188331. png_crc_finish(png_ptr, length);
  188332. return;
  188333. }
  188334. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188335. png_error(png_ptr, "Duplicate PLTE chunk");
  188336. png_ptr->mode |= PNG_HAVE_PLTE;
  188337. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  188338. {
  188339. png_warning(png_ptr,
  188340. "Ignoring PLTE chunk in grayscale PNG");
  188341. png_crc_finish(png_ptr, length);
  188342. return;
  188343. }
  188344. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  188345. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  188346. {
  188347. png_crc_finish(png_ptr, length);
  188348. return;
  188349. }
  188350. #endif
  188351. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  188352. {
  188353. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  188354. {
  188355. png_warning(png_ptr, "Invalid palette chunk");
  188356. png_crc_finish(png_ptr, length);
  188357. return;
  188358. }
  188359. else
  188360. {
  188361. png_error(png_ptr, "Invalid palette chunk");
  188362. }
  188363. }
  188364. num = (int)length / 3;
  188365. #ifndef PNG_NO_POINTER_INDEXING
  188366. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  188367. {
  188368. png_byte buf[3];
  188369. png_crc_read(png_ptr, buf, 3);
  188370. pal_ptr->red = buf[0];
  188371. pal_ptr->green = buf[1];
  188372. pal_ptr->blue = buf[2];
  188373. }
  188374. #else
  188375. for (i = 0; i < num; i++)
  188376. {
  188377. png_byte buf[3];
  188378. png_crc_read(png_ptr, buf, 3);
  188379. /* don't depend upon png_color being any order */
  188380. palette[i].red = buf[0];
  188381. palette[i].green = buf[1];
  188382. palette[i].blue = buf[2];
  188383. }
  188384. #endif
  188385. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  188386. whatever the normal CRC configuration tells us. However, if we
  188387. have an RGB image, the PLTE can be considered ancillary, so
  188388. we will act as though it is. */
  188389. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  188390. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188391. #endif
  188392. {
  188393. png_crc_finish(png_ptr, 0);
  188394. }
  188395. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  188396. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  188397. {
  188398. /* If we don't want to use the data from an ancillary chunk,
  188399. we have two options: an error abort, or a warning and we
  188400. ignore the data in this chunk (which should be OK, since
  188401. it's considered ancillary for a RGB or RGBA image). */
  188402. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  188403. {
  188404. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  188405. {
  188406. png_chunk_error(png_ptr, "CRC error");
  188407. }
  188408. else
  188409. {
  188410. png_chunk_warning(png_ptr, "CRC error");
  188411. return;
  188412. }
  188413. }
  188414. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  188415. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  188416. {
  188417. png_chunk_warning(png_ptr, "CRC error");
  188418. }
  188419. }
  188420. #endif
  188421. png_set_PLTE(png_ptr, info_ptr, palette, num);
  188422. #if defined(PNG_READ_tRNS_SUPPORTED)
  188423. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188424. {
  188425. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  188426. {
  188427. if (png_ptr->num_trans > (png_uint_16)num)
  188428. {
  188429. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  188430. png_ptr->num_trans = (png_uint_16)num;
  188431. }
  188432. if (info_ptr->num_trans > (png_uint_16)num)
  188433. {
  188434. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  188435. info_ptr->num_trans = (png_uint_16)num;
  188436. }
  188437. }
  188438. }
  188439. #endif
  188440. }
  188441. void /* PRIVATE */
  188442. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188443. {
  188444. png_debug(1, "in png_handle_IEND\n");
  188445. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  188446. {
  188447. png_error(png_ptr, "No image in file");
  188448. }
  188449. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  188450. if (length != 0)
  188451. {
  188452. png_warning(png_ptr, "Incorrect IEND chunk length");
  188453. }
  188454. png_crc_finish(png_ptr, length);
  188455. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  188456. }
  188457. #if defined(PNG_READ_gAMA_SUPPORTED)
  188458. void /* PRIVATE */
  188459. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188460. {
  188461. png_fixed_point igamma;
  188462. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188463. float file_gamma;
  188464. #endif
  188465. png_byte buf[4];
  188466. png_debug(1, "in png_handle_gAMA\n");
  188467. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188468. png_error(png_ptr, "Missing IHDR before gAMA");
  188469. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188470. {
  188471. png_warning(png_ptr, "Invalid gAMA after IDAT");
  188472. png_crc_finish(png_ptr, length);
  188473. return;
  188474. }
  188475. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188476. /* Should be an error, but we can cope with it */
  188477. png_warning(png_ptr, "Out of place gAMA chunk");
  188478. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  188479. #if defined(PNG_READ_sRGB_SUPPORTED)
  188480. && !(info_ptr->valid & PNG_INFO_sRGB)
  188481. #endif
  188482. )
  188483. {
  188484. png_warning(png_ptr, "Duplicate gAMA chunk");
  188485. png_crc_finish(png_ptr, length);
  188486. return;
  188487. }
  188488. if (length != 4)
  188489. {
  188490. png_warning(png_ptr, "Incorrect gAMA chunk length");
  188491. png_crc_finish(png_ptr, length);
  188492. return;
  188493. }
  188494. png_crc_read(png_ptr, buf, 4);
  188495. if (png_crc_finish(png_ptr, 0))
  188496. return;
  188497. igamma = (png_fixed_point)png_get_uint_32(buf);
  188498. /* check for zero gamma */
  188499. if (igamma == 0)
  188500. {
  188501. png_warning(png_ptr,
  188502. "Ignoring gAMA chunk with gamma=0");
  188503. return;
  188504. }
  188505. #if defined(PNG_READ_sRGB_SUPPORTED)
  188506. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  188507. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  188508. {
  188509. png_warning(png_ptr,
  188510. "Ignoring incorrect gAMA value when sRGB is also present");
  188511. #ifndef PNG_NO_CONSOLE_IO
  188512. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  188513. #endif
  188514. return;
  188515. }
  188516. #endif /* PNG_READ_sRGB_SUPPORTED */
  188517. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188518. file_gamma = (float)igamma / (float)100000.0;
  188519. # ifdef PNG_READ_GAMMA_SUPPORTED
  188520. png_ptr->gamma = file_gamma;
  188521. # endif
  188522. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  188523. #endif
  188524. #ifdef PNG_FIXED_POINT_SUPPORTED
  188525. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  188526. #endif
  188527. }
  188528. #endif
  188529. #if defined(PNG_READ_sBIT_SUPPORTED)
  188530. void /* PRIVATE */
  188531. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188532. {
  188533. png_size_t truelen;
  188534. png_byte buf[4];
  188535. png_debug(1, "in png_handle_sBIT\n");
  188536. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  188537. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188538. png_error(png_ptr, "Missing IHDR before sBIT");
  188539. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188540. {
  188541. png_warning(png_ptr, "Invalid sBIT after IDAT");
  188542. png_crc_finish(png_ptr, length);
  188543. return;
  188544. }
  188545. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188546. {
  188547. /* Should be an error, but we can cope with it */
  188548. png_warning(png_ptr, "Out of place sBIT chunk");
  188549. }
  188550. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  188551. {
  188552. png_warning(png_ptr, "Duplicate sBIT chunk");
  188553. png_crc_finish(png_ptr, length);
  188554. return;
  188555. }
  188556. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188557. truelen = 3;
  188558. else
  188559. truelen = (png_size_t)png_ptr->channels;
  188560. if (length != truelen || length > 4)
  188561. {
  188562. png_warning(png_ptr, "Incorrect sBIT chunk length");
  188563. png_crc_finish(png_ptr, length);
  188564. return;
  188565. }
  188566. png_crc_read(png_ptr, buf, truelen);
  188567. if (png_crc_finish(png_ptr, 0))
  188568. return;
  188569. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  188570. {
  188571. png_ptr->sig_bit.red = buf[0];
  188572. png_ptr->sig_bit.green = buf[1];
  188573. png_ptr->sig_bit.blue = buf[2];
  188574. png_ptr->sig_bit.alpha = buf[3];
  188575. }
  188576. else
  188577. {
  188578. png_ptr->sig_bit.gray = buf[0];
  188579. png_ptr->sig_bit.red = buf[0];
  188580. png_ptr->sig_bit.green = buf[0];
  188581. png_ptr->sig_bit.blue = buf[0];
  188582. png_ptr->sig_bit.alpha = buf[1];
  188583. }
  188584. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  188585. }
  188586. #endif
  188587. #if defined(PNG_READ_cHRM_SUPPORTED)
  188588. void /* PRIVATE */
  188589. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188590. {
  188591. png_byte buf[4];
  188592. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188593. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  188594. #endif
  188595. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  188596. int_y_green, int_x_blue, int_y_blue;
  188597. png_uint_32 uint_x, uint_y;
  188598. png_debug(1, "in png_handle_cHRM\n");
  188599. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188600. png_error(png_ptr, "Missing IHDR before cHRM");
  188601. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188602. {
  188603. png_warning(png_ptr, "Invalid cHRM after IDAT");
  188604. png_crc_finish(png_ptr, length);
  188605. return;
  188606. }
  188607. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188608. /* Should be an error, but we can cope with it */
  188609. png_warning(png_ptr, "Missing PLTE before cHRM");
  188610. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  188611. #if defined(PNG_READ_sRGB_SUPPORTED)
  188612. && !(info_ptr->valid & PNG_INFO_sRGB)
  188613. #endif
  188614. )
  188615. {
  188616. png_warning(png_ptr, "Duplicate cHRM chunk");
  188617. png_crc_finish(png_ptr, length);
  188618. return;
  188619. }
  188620. if (length != 32)
  188621. {
  188622. png_warning(png_ptr, "Incorrect cHRM chunk length");
  188623. png_crc_finish(png_ptr, length);
  188624. return;
  188625. }
  188626. png_crc_read(png_ptr, buf, 4);
  188627. uint_x = png_get_uint_32(buf);
  188628. png_crc_read(png_ptr, buf, 4);
  188629. uint_y = png_get_uint_32(buf);
  188630. if (uint_x > 80000L || uint_y > 80000L ||
  188631. uint_x + uint_y > 100000L)
  188632. {
  188633. png_warning(png_ptr, "Invalid cHRM white point");
  188634. png_crc_finish(png_ptr, 24);
  188635. return;
  188636. }
  188637. int_x_white = (png_fixed_point)uint_x;
  188638. int_y_white = (png_fixed_point)uint_y;
  188639. png_crc_read(png_ptr, buf, 4);
  188640. uint_x = png_get_uint_32(buf);
  188641. png_crc_read(png_ptr, buf, 4);
  188642. uint_y = png_get_uint_32(buf);
  188643. if (uint_x + uint_y > 100000L)
  188644. {
  188645. png_warning(png_ptr, "Invalid cHRM red point");
  188646. png_crc_finish(png_ptr, 16);
  188647. return;
  188648. }
  188649. int_x_red = (png_fixed_point)uint_x;
  188650. int_y_red = (png_fixed_point)uint_y;
  188651. png_crc_read(png_ptr, buf, 4);
  188652. uint_x = png_get_uint_32(buf);
  188653. png_crc_read(png_ptr, buf, 4);
  188654. uint_y = png_get_uint_32(buf);
  188655. if (uint_x + uint_y > 100000L)
  188656. {
  188657. png_warning(png_ptr, "Invalid cHRM green point");
  188658. png_crc_finish(png_ptr, 8);
  188659. return;
  188660. }
  188661. int_x_green = (png_fixed_point)uint_x;
  188662. int_y_green = (png_fixed_point)uint_y;
  188663. png_crc_read(png_ptr, buf, 4);
  188664. uint_x = png_get_uint_32(buf);
  188665. png_crc_read(png_ptr, buf, 4);
  188666. uint_y = png_get_uint_32(buf);
  188667. if (uint_x + uint_y > 100000L)
  188668. {
  188669. png_warning(png_ptr, "Invalid cHRM blue point");
  188670. png_crc_finish(png_ptr, 0);
  188671. return;
  188672. }
  188673. int_x_blue = (png_fixed_point)uint_x;
  188674. int_y_blue = (png_fixed_point)uint_y;
  188675. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188676. white_x = (float)int_x_white / (float)100000.0;
  188677. white_y = (float)int_y_white / (float)100000.0;
  188678. red_x = (float)int_x_red / (float)100000.0;
  188679. red_y = (float)int_y_red / (float)100000.0;
  188680. green_x = (float)int_x_green / (float)100000.0;
  188681. green_y = (float)int_y_green / (float)100000.0;
  188682. blue_x = (float)int_x_blue / (float)100000.0;
  188683. blue_y = (float)int_y_blue / (float)100000.0;
  188684. #endif
  188685. #if defined(PNG_READ_sRGB_SUPPORTED)
  188686. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  188687. {
  188688. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  188689. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  188690. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  188691. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  188692. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  188693. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  188694. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  188695. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  188696. {
  188697. png_warning(png_ptr,
  188698. "Ignoring incorrect cHRM value when sRGB is also present");
  188699. #ifndef PNG_NO_CONSOLE_IO
  188700. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188701. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  188702. white_x, white_y, red_x, red_y);
  188703. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  188704. green_x, green_y, blue_x, blue_y);
  188705. #else
  188706. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  188707. int_x_white, int_y_white, int_x_red, int_y_red);
  188708. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  188709. int_x_green, int_y_green, int_x_blue, int_y_blue);
  188710. #endif
  188711. #endif /* PNG_NO_CONSOLE_IO */
  188712. }
  188713. png_crc_finish(png_ptr, 0);
  188714. return;
  188715. }
  188716. #endif /* PNG_READ_sRGB_SUPPORTED */
  188717. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188718. png_set_cHRM(png_ptr, info_ptr,
  188719. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  188720. #endif
  188721. #ifdef PNG_FIXED_POINT_SUPPORTED
  188722. png_set_cHRM_fixed(png_ptr, info_ptr,
  188723. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  188724. int_y_green, int_x_blue, int_y_blue);
  188725. #endif
  188726. if (png_crc_finish(png_ptr, 0))
  188727. return;
  188728. }
  188729. #endif
  188730. #if defined(PNG_READ_sRGB_SUPPORTED)
  188731. void /* PRIVATE */
  188732. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188733. {
  188734. int intent;
  188735. png_byte buf[1];
  188736. png_debug(1, "in png_handle_sRGB\n");
  188737. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188738. png_error(png_ptr, "Missing IHDR before sRGB");
  188739. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188740. {
  188741. png_warning(png_ptr, "Invalid sRGB after IDAT");
  188742. png_crc_finish(png_ptr, length);
  188743. return;
  188744. }
  188745. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188746. /* Should be an error, but we can cope with it */
  188747. png_warning(png_ptr, "Out of place sRGB chunk");
  188748. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  188749. {
  188750. png_warning(png_ptr, "Duplicate sRGB chunk");
  188751. png_crc_finish(png_ptr, length);
  188752. return;
  188753. }
  188754. if (length != 1)
  188755. {
  188756. png_warning(png_ptr, "Incorrect sRGB chunk length");
  188757. png_crc_finish(png_ptr, length);
  188758. return;
  188759. }
  188760. png_crc_read(png_ptr, buf, 1);
  188761. if (png_crc_finish(png_ptr, 0))
  188762. return;
  188763. intent = buf[0];
  188764. /* check for bad intent */
  188765. if (intent >= PNG_sRGB_INTENT_LAST)
  188766. {
  188767. png_warning(png_ptr, "Unknown sRGB intent");
  188768. return;
  188769. }
  188770. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  188771. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  188772. {
  188773. png_fixed_point igamma;
  188774. #ifdef PNG_FIXED_POINT_SUPPORTED
  188775. igamma=info_ptr->int_gamma;
  188776. #else
  188777. # ifdef PNG_FLOATING_POINT_SUPPORTED
  188778. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  188779. # endif
  188780. #endif
  188781. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  188782. {
  188783. png_warning(png_ptr,
  188784. "Ignoring incorrect gAMA value when sRGB is also present");
  188785. #ifndef PNG_NO_CONSOLE_IO
  188786. # ifdef PNG_FIXED_POINT_SUPPORTED
  188787. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  188788. # else
  188789. # ifdef PNG_FLOATING_POINT_SUPPORTED
  188790. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  188791. # endif
  188792. # endif
  188793. #endif
  188794. }
  188795. }
  188796. #endif /* PNG_READ_gAMA_SUPPORTED */
  188797. #ifdef PNG_READ_cHRM_SUPPORTED
  188798. #ifdef PNG_FIXED_POINT_SUPPORTED
  188799. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  188800. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  188801. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  188802. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  188803. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  188804. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  188805. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  188806. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  188807. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  188808. {
  188809. png_warning(png_ptr,
  188810. "Ignoring incorrect cHRM value when sRGB is also present");
  188811. }
  188812. #endif /* PNG_FIXED_POINT_SUPPORTED */
  188813. #endif /* PNG_READ_cHRM_SUPPORTED */
  188814. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  188815. }
  188816. #endif /* PNG_READ_sRGB_SUPPORTED */
  188817. #if defined(PNG_READ_iCCP_SUPPORTED)
  188818. void /* PRIVATE */
  188819. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188820. /* Note: this does not properly handle chunks that are > 64K under DOS */
  188821. {
  188822. png_charp chunkdata;
  188823. png_byte compression_type;
  188824. png_bytep pC;
  188825. png_charp profile;
  188826. png_uint_32 skip = 0;
  188827. png_uint_32 profile_size, profile_length;
  188828. png_size_t slength, prefix_length, data_length;
  188829. png_debug(1, "in png_handle_iCCP\n");
  188830. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188831. png_error(png_ptr, "Missing IHDR before iCCP");
  188832. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188833. {
  188834. png_warning(png_ptr, "Invalid iCCP after IDAT");
  188835. png_crc_finish(png_ptr, length);
  188836. return;
  188837. }
  188838. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188839. /* Should be an error, but we can cope with it */
  188840. png_warning(png_ptr, "Out of place iCCP chunk");
  188841. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  188842. {
  188843. png_warning(png_ptr, "Duplicate iCCP chunk");
  188844. png_crc_finish(png_ptr, length);
  188845. return;
  188846. }
  188847. #ifdef PNG_MAX_MALLOC_64K
  188848. if (length > (png_uint_32)65535L)
  188849. {
  188850. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  188851. skip = length - (png_uint_32)65535L;
  188852. length = (png_uint_32)65535L;
  188853. }
  188854. #endif
  188855. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  188856. slength = (png_size_t)length;
  188857. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  188858. if (png_crc_finish(png_ptr, skip))
  188859. {
  188860. png_free(png_ptr, chunkdata);
  188861. return;
  188862. }
  188863. chunkdata[slength] = 0x00;
  188864. for (profile = chunkdata; *profile; profile++)
  188865. /* empty loop to find end of name */ ;
  188866. ++profile;
  188867. /* there should be at least one zero (the compression type byte)
  188868. following the separator, and we should be on it */
  188869. if ( profile >= chunkdata + slength - 1)
  188870. {
  188871. png_free(png_ptr, chunkdata);
  188872. png_warning(png_ptr, "Malformed iCCP chunk");
  188873. return;
  188874. }
  188875. /* compression_type should always be zero */
  188876. compression_type = *profile++;
  188877. if (compression_type)
  188878. {
  188879. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  188880. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  188881. wrote nonzero) */
  188882. }
  188883. prefix_length = profile - chunkdata;
  188884. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  188885. slength, prefix_length, &data_length);
  188886. profile_length = data_length - prefix_length;
  188887. if ( prefix_length > data_length || profile_length < 4)
  188888. {
  188889. png_free(png_ptr, chunkdata);
  188890. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  188891. return;
  188892. }
  188893. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  188894. pC = (png_bytep)(chunkdata+prefix_length);
  188895. profile_size = ((*(pC ))<<24) |
  188896. ((*(pC+1))<<16) |
  188897. ((*(pC+2))<< 8) |
  188898. ((*(pC+3)) );
  188899. if(profile_size < profile_length)
  188900. profile_length = profile_size;
  188901. if(profile_size > profile_length)
  188902. {
  188903. png_free(png_ptr, chunkdata);
  188904. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  188905. return;
  188906. }
  188907. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  188908. chunkdata + prefix_length, profile_length);
  188909. png_free(png_ptr, chunkdata);
  188910. }
  188911. #endif /* PNG_READ_iCCP_SUPPORTED */
  188912. #if defined(PNG_READ_sPLT_SUPPORTED)
  188913. void /* PRIVATE */
  188914. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188915. /* Note: this does not properly handle chunks that are > 64K under DOS */
  188916. {
  188917. png_bytep chunkdata;
  188918. png_bytep entry_start;
  188919. png_sPLT_t new_palette;
  188920. #ifdef PNG_NO_POINTER_INDEXING
  188921. png_sPLT_entryp pp;
  188922. #endif
  188923. int data_length, entry_size, i;
  188924. png_uint_32 skip = 0;
  188925. png_size_t slength;
  188926. png_debug(1, "in png_handle_sPLT\n");
  188927. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188928. png_error(png_ptr, "Missing IHDR before sPLT");
  188929. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188930. {
  188931. png_warning(png_ptr, "Invalid sPLT after IDAT");
  188932. png_crc_finish(png_ptr, length);
  188933. return;
  188934. }
  188935. #ifdef PNG_MAX_MALLOC_64K
  188936. if (length > (png_uint_32)65535L)
  188937. {
  188938. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  188939. skip = length - (png_uint_32)65535L;
  188940. length = (png_uint_32)65535L;
  188941. }
  188942. #endif
  188943. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  188944. slength = (png_size_t)length;
  188945. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  188946. if (png_crc_finish(png_ptr, skip))
  188947. {
  188948. png_free(png_ptr, chunkdata);
  188949. return;
  188950. }
  188951. chunkdata[slength] = 0x00;
  188952. for (entry_start = chunkdata; *entry_start; entry_start++)
  188953. /* empty loop to find end of name */ ;
  188954. ++entry_start;
  188955. /* a sample depth should follow the separator, and we should be on it */
  188956. if (entry_start > chunkdata + slength - 2)
  188957. {
  188958. png_free(png_ptr, chunkdata);
  188959. png_warning(png_ptr, "malformed sPLT chunk");
  188960. return;
  188961. }
  188962. new_palette.depth = *entry_start++;
  188963. entry_size = (new_palette.depth == 8 ? 6 : 10);
  188964. data_length = (slength - (entry_start - chunkdata));
  188965. /* integrity-check the data length */
  188966. if (data_length % entry_size)
  188967. {
  188968. png_free(png_ptr, chunkdata);
  188969. png_warning(png_ptr, "sPLT chunk has bad length");
  188970. return;
  188971. }
  188972. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  188973. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  188974. png_sizeof(png_sPLT_entry)))
  188975. {
  188976. png_warning(png_ptr, "sPLT chunk too long");
  188977. return;
  188978. }
  188979. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  188980. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  188981. if (new_palette.entries == NULL)
  188982. {
  188983. png_warning(png_ptr, "sPLT chunk requires too much memory");
  188984. return;
  188985. }
  188986. #ifndef PNG_NO_POINTER_INDEXING
  188987. for (i = 0; i < new_palette.nentries; i++)
  188988. {
  188989. png_sPLT_entryp pp = new_palette.entries + i;
  188990. if (new_palette.depth == 8)
  188991. {
  188992. pp->red = *entry_start++;
  188993. pp->green = *entry_start++;
  188994. pp->blue = *entry_start++;
  188995. pp->alpha = *entry_start++;
  188996. }
  188997. else
  188998. {
  188999. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  189000. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  189001. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  189002. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  189003. }
  189004. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  189005. }
  189006. #else
  189007. pp = new_palette.entries;
  189008. for (i = 0; i < new_palette.nentries; i++)
  189009. {
  189010. if (new_palette.depth == 8)
  189011. {
  189012. pp[i].red = *entry_start++;
  189013. pp[i].green = *entry_start++;
  189014. pp[i].blue = *entry_start++;
  189015. pp[i].alpha = *entry_start++;
  189016. }
  189017. else
  189018. {
  189019. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  189020. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  189021. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  189022. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  189023. }
  189024. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  189025. }
  189026. #endif
  189027. /* discard all chunk data except the name and stash that */
  189028. new_palette.name = (png_charp)chunkdata;
  189029. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  189030. png_free(png_ptr, chunkdata);
  189031. png_free(png_ptr, new_palette.entries);
  189032. }
  189033. #endif /* PNG_READ_sPLT_SUPPORTED */
  189034. #if defined(PNG_READ_tRNS_SUPPORTED)
  189035. void /* PRIVATE */
  189036. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189037. {
  189038. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  189039. int bit_mask;
  189040. png_debug(1, "in png_handle_tRNS\n");
  189041. /* For non-indexed color, mask off any bits in the tRNS value that
  189042. * exceed the bit depth. Some creators were writing extra bits there.
  189043. * This is not needed for indexed color. */
  189044. bit_mask = (1 << png_ptr->bit_depth) - 1;
  189045. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189046. png_error(png_ptr, "Missing IHDR before tRNS");
  189047. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189048. {
  189049. png_warning(png_ptr, "Invalid tRNS after IDAT");
  189050. png_crc_finish(png_ptr, length);
  189051. return;
  189052. }
  189053. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  189054. {
  189055. png_warning(png_ptr, "Duplicate tRNS chunk");
  189056. png_crc_finish(png_ptr, length);
  189057. return;
  189058. }
  189059. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  189060. {
  189061. png_byte buf[2];
  189062. if (length != 2)
  189063. {
  189064. png_warning(png_ptr, "Incorrect tRNS chunk length");
  189065. png_crc_finish(png_ptr, length);
  189066. return;
  189067. }
  189068. png_crc_read(png_ptr, buf, 2);
  189069. png_ptr->num_trans = 1;
  189070. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  189071. }
  189072. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  189073. {
  189074. png_byte buf[6];
  189075. if (length != 6)
  189076. {
  189077. png_warning(png_ptr, "Incorrect tRNS chunk length");
  189078. png_crc_finish(png_ptr, length);
  189079. return;
  189080. }
  189081. png_crc_read(png_ptr, buf, (png_size_t)length);
  189082. png_ptr->num_trans = 1;
  189083. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  189084. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  189085. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  189086. }
  189087. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189088. {
  189089. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  189090. {
  189091. /* Should be an error, but we can cope with it. */
  189092. png_warning(png_ptr, "Missing PLTE before tRNS");
  189093. }
  189094. if (length > (png_uint_32)png_ptr->num_palette ||
  189095. length > PNG_MAX_PALETTE_LENGTH)
  189096. {
  189097. png_warning(png_ptr, "Incorrect tRNS chunk length");
  189098. png_crc_finish(png_ptr, length);
  189099. return;
  189100. }
  189101. if (length == 0)
  189102. {
  189103. png_warning(png_ptr, "Zero length tRNS chunk");
  189104. png_crc_finish(png_ptr, length);
  189105. return;
  189106. }
  189107. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  189108. png_ptr->num_trans = (png_uint_16)length;
  189109. }
  189110. else
  189111. {
  189112. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  189113. png_crc_finish(png_ptr, length);
  189114. return;
  189115. }
  189116. if (png_crc_finish(png_ptr, 0))
  189117. {
  189118. png_ptr->num_trans = 0;
  189119. return;
  189120. }
  189121. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  189122. &(png_ptr->trans_values));
  189123. }
  189124. #endif
  189125. #if defined(PNG_READ_bKGD_SUPPORTED)
  189126. void /* PRIVATE */
  189127. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189128. {
  189129. png_size_t truelen;
  189130. png_byte buf[6];
  189131. png_debug(1, "in png_handle_bKGD\n");
  189132. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189133. png_error(png_ptr, "Missing IHDR before bKGD");
  189134. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189135. {
  189136. png_warning(png_ptr, "Invalid bKGD after IDAT");
  189137. png_crc_finish(png_ptr, length);
  189138. return;
  189139. }
  189140. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  189141. !(png_ptr->mode & PNG_HAVE_PLTE))
  189142. {
  189143. png_warning(png_ptr, "Missing PLTE before bKGD");
  189144. png_crc_finish(png_ptr, length);
  189145. return;
  189146. }
  189147. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  189148. {
  189149. png_warning(png_ptr, "Duplicate bKGD chunk");
  189150. png_crc_finish(png_ptr, length);
  189151. return;
  189152. }
  189153. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189154. truelen = 1;
  189155. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  189156. truelen = 6;
  189157. else
  189158. truelen = 2;
  189159. if (length != truelen)
  189160. {
  189161. png_warning(png_ptr, "Incorrect bKGD chunk length");
  189162. png_crc_finish(png_ptr, length);
  189163. return;
  189164. }
  189165. png_crc_read(png_ptr, buf, truelen);
  189166. if (png_crc_finish(png_ptr, 0))
  189167. return;
  189168. /* We convert the index value into RGB components so that we can allow
  189169. * arbitrary RGB values for background when we have transparency, and
  189170. * so it is easy to determine the RGB values of the background color
  189171. * from the info_ptr struct. */
  189172. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189173. {
  189174. png_ptr->background.index = buf[0];
  189175. if(info_ptr->num_palette)
  189176. {
  189177. if(buf[0] > info_ptr->num_palette)
  189178. {
  189179. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  189180. return;
  189181. }
  189182. png_ptr->background.red =
  189183. (png_uint_16)png_ptr->palette[buf[0]].red;
  189184. png_ptr->background.green =
  189185. (png_uint_16)png_ptr->palette[buf[0]].green;
  189186. png_ptr->background.blue =
  189187. (png_uint_16)png_ptr->palette[buf[0]].blue;
  189188. }
  189189. }
  189190. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  189191. {
  189192. png_ptr->background.red =
  189193. png_ptr->background.green =
  189194. png_ptr->background.blue =
  189195. png_ptr->background.gray = png_get_uint_16(buf);
  189196. }
  189197. else
  189198. {
  189199. png_ptr->background.red = png_get_uint_16(buf);
  189200. png_ptr->background.green = png_get_uint_16(buf + 2);
  189201. png_ptr->background.blue = png_get_uint_16(buf + 4);
  189202. }
  189203. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  189204. }
  189205. #endif
  189206. #if defined(PNG_READ_hIST_SUPPORTED)
  189207. void /* PRIVATE */
  189208. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189209. {
  189210. unsigned int num, i;
  189211. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  189212. png_debug(1, "in png_handle_hIST\n");
  189213. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189214. png_error(png_ptr, "Missing IHDR before hIST");
  189215. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189216. {
  189217. png_warning(png_ptr, "Invalid hIST after IDAT");
  189218. png_crc_finish(png_ptr, length);
  189219. return;
  189220. }
  189221. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  189222. {
  189223. png_warning(png_ptr, "Missing PLTE before hIST");
  189224. png_crc_finish(png_ptr, length);
  189225. return;
  189226. }
  189227. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  189228. {
  189229. png_warning(png_ptr, "Duplicate hIST chunk");
  189230. png_crc_finish(png_ptr, length);
  189231. return;
  189232. }
  189233. num = length / 2 ;
  189234. if (num != (unsigned int) png_ptr->num_palette || num >
  189235. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  189236. {
  189237. png_warning(png_ptr, "Incorrect hIST chunk length");
  189238. png_crc_finish(png_ptr, length);
  189239. return;
  189240. }
  189241. for (i = 0; i < num; i++)
  189242. {
  189243. png_byte buf[2];
  189244. png_crc_read(png_ptr, buf, 2);
  189245. readbuf[i] = png_get_uint_16(buf);
  189246. }
  189247. if (png_crc_finish(png_ptr, 0))
  189248. return;
  189249. png_set_hIST(png_ptr, info_ptr, readbuf);
  189250. }
  189251. #endif
  189252. #if defined(PNG_READ_pHYs_SUPPORTED)
  189253. void /* PRIVATE */
  189254. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189255. {
  189256. png_byte buf[9];
  189257. png_uint_32 res_x, res_y;
  189258. int unit_type;
  189259. png_debug(1, "in png_handle_pHYs\n");
  189260. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189261. png_error(png_ptr, "Missing IHDR before pHYs");
  189262. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189263. {
  189264. png_warning(png_ptr, "Invalid pHYs after IDAT");
  189265. png_crc_finish(png_ptr, length);
  189266. return;
  189267. }
  189268. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  189269. {
  189270. png_warning(png_ptr, "Duplicate pHYs chunk");
  189271. png_crc_finish(png_ptr, length);
  189272. return;
  189273. }
  189274. if (length != 9)
  189275. {
  189276. png_warning(png_ptr, "Incorrect pHYs chunk length");
  189277. png_crc_finish(png_ptr, length);
  189278. return;
  189279. }
  189280. png_crc_read(png_ptr, buf, 9);
  189281. if (png_crc_finish(png_ptr, 0))
  189282. return;
  189283. res_x = png_get_uint_32(buf);
  189284. res_y = png_get_uint_32(buf + 4);
  189285. unit_type = buf[8];
  189286. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  189287. }
  189288. #endif
  189289. #if defined(PNG_READ_oFFs_SUPPORTED)
  189290. void /* PRIVATE */
  189291. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189292. {
  189293. png_byte buf[9];
  189294. png_int_32 offset_x, offset_y;
  189295. int unit_type;
  189296. png_debug(1, "in png_handle_oFFs\n");
  189297. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189298. png_error(png_ptr, "Missing IHDR before oFFs");
  189299. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189300. {
  189301. png_warning(png_ptr, "Invalid oFFs after IDAT");
  189302. png_crc_finish(png_ptr, length);
  189303. return;
  189304. }
  189305. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  189306. {
  189307. png_warning(png_ptr, "Duplicate oFFs chunk");
  189308. png_crc_finish(png_ptr, length);
  189309. return;
  189310. }
  189311. if (length != 9)
  189312. {
  189313. png_warning(png_ptr, "Incorrect oFFs chunk length");
  189314. png_crc_finish(png_ptr, length);
  189315. return;
  189316. }
  189317. png_crc_read(png_ptr, buf, 9);
  189318. if (png_crc_finish(png_ptr, 0))
  189319. return;
  189320. offset_x = png_get_int_32(buf);
  189321. offset_y = png_get_int_32(buf + 4);
  189322. unit_type = buf[8];
  189323. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  189324. }
  189325. #endif
  189326. #if defined(PNG_READ_pCAL_SUPPORTED)
  189327. /* read the pCAL chunk (described in the PNG Extensions document) */
  189328. void /* PRIVATE */
  189329. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189330. {
  189331. png_charp purpose;
  189332. png_int_32 X0, X1;
  189333. png_byte type, nparams;
  189334. png_charp buf, units, endptr;
  189335. png_charpp params;
  189336. png_size_t slength;
  189337. int i;
  189338. png_debug(1, "in png_handle_pCAL\n");
  189339. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189340. png_error(png_ptr, "Missing IHDR before pCAL");
  189341. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189342. {
  189343. png_warning(png_ptr, "Invalid pCAL after IDAT");
  189344. png_crc_finish(png_ptr, length);
  189345. return;
  189346. }
  189347. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  189348. {
  189349. png_warning(png_ptr, "Duplicate pCAL chunk");
  189350. png_crc_finish(png_ptr, length);
  189351. return;
  189352. }
  189353. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  189354. length + 1);
  189355. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  189356. if (purpose == NULL)
  189357. {
  189358. png_warning(png_ptr, "No memory for pCAL purpose.");
  189359. return;
  189360. }
  189361. slength = (png_size_t)length;
  189362. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  189363. if (png_crc_finish(png_ptr, 0))
  189364. {
  189365. png_free(png_ptr, purpose);
  189366. return;
  189367. }
  189368. purpose[slength] = 0x00; /* null terminate the last string */
  189369. png_debug(3, "Finding end of pCAL purpose string\n");
  189370. for (buf = purpose; *buf; buf++)
  189371. /* empty loop */ ;
  189372. endptr = purpose + slength;
  189373. /* We need to have at least 12 bytes after the purpose string
  189374. in order to get the parameter information. */
  189375. if (endptr <= buf + 12)
  189376. {
  189377. png_warning(png_ptr, "Invalid pCAL data");
  189378. png_free(png_ptr, purpose);
  189379. return;
  189380. }
  189381. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  189382. X0 = png_get_int_32((png_bytep)buf+1);
  189383. X1 = png_get_int_32((png_bytep)buf+5);
  189384. type = buf[9];
  189385. nparams = buf[10];
  189386. units = buf + 11;
  189387. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  189388. /* Check that we have the right number of parameters for known
  189389. equation types. */
  189390. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  189391. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  189392. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  189393. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  189394. {
  189395. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  189396. png_free(png_ptr, purpose);
  189397. return;
  189398. }
  189399. else if (type >= PNG_EQUATION_LAST)
  189400. {
  189401. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  189402. }
  189403. for (buf = units; *buf; buf++)
  189404. /* Empty loop to move past the units string. */ ;
  189405. png_debug(3, "Allocating pCAL parameters array\n");
  189406. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  189407. *png_sizeof(png_charp))) ;
  189408. if (params == NULL)
  189409. {
  189410. png_free(png_ptr, purpose);
  189411. png_warning(png_ptr, "No memory for pCAL params.");
  189412. return;
  189413. }
  189414. /* Get pointers to the start of each parameter string. */
  189415. for (i = 0; i < (int)nparams; i++)
  189416. {
  189417. buf++; /* Skip the null string terminator from previous parameter. */
  189418. png_debug1(3, "Reading pCAL parameter %d\n", i);
  189419. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  189420. /* Empty loop to move past each parameter string */ ;
  189421. /* Make sure we haven't run out of data yet */
  189422. if (buf > endptr)
  189423. {
  189424. png_warning(png_ptr, "Invalid pCAL data");
  189425. png_free(png_ptr, purpose);
  189426. png_free(png_ptr, params);
  189427. return;
  189428. }
  189429. }
  189430. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  189431. units, params);
  189432. png_free(png_ptr, purpose);
  189433. png_free(png_ptr, params);
  189434. }
  189435. #endif
  189436. #if defined(PNG_READ_sCAL_SUPPORTED)
  189437. /* read the sCAL chunk */
  189438. void /* PRIVATE */
  189439. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189440. {
  189441. png_charp buffer, ep;
  189442. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189443. double width, height;
  189444. png_charp vp;
  189445. #else
  189446. #ifdef PNG_FIXED_POINT_SUPPORTED
  189447. png_charp swidth, sheight;
  189448. #endif
  189449. #endif
  189450. png_size_t slength;
  189451. png_debug(1, "in png_handle_sCAL\n");
  189452. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189453. png_error(png_ptr, "Missing IHDR before sCAL");
  189454. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189455. {
  189456. png_warning(png_ptr, "Invalid sCAL after IDAT");
  189457. png_crc_finish(png_ptr, length);
  189458. return;
  189459. }
  189460. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  189461. {
  189462. png_warning(png_ptr, "Duplicate sCAL chunk");
  189463. png_crc_finish(png_ptr, length);
  189464. return;
  189465. }
  189466. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  189467. length + 1);
  189468. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  189469. if (buffer == NULL)
  189470. {
  189471. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  189472. return;
  189473. }
  189474. slength = (png_size_t)length;
  189475. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  189476. if (png_crc_finish(png_ptr, 0))
  189477. {
  189478. png_free(png_ptr, buffer);
  189479. return;
  189480. }
  189481. buffer[slength] = 0x00; /* null terminate the last string */
  189482. ep = buffer + 1; /* skip unit byte */
  189483. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189484. width = png_strtod(png_ptr, ep, &vp);
  189485. if (*vp)
  189486. {
  189487. png_warning(png_ptr, "malformed width string in sCAL chunk");
  189488. return;
  189489. }
  189490. #else
  189491. #ifdef PNG_FIXED_POINT_SUPPORTED
  189492. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  189493. if (swidth == NULL)
  189494. {
  189495. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  189496. return;
  189497. }
  189498. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  189499. #endif
  189500. #endif
  189501. for (ep = buffer; *ep; ep++)
  189502. /* empty loop */ ;
  189503. ep++;
  189504. if (buffer + slength < ep)
  189505. {
  189506. png_warning(png_ptr, "Truncated sCAL chunk");
  189507. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  189508. !defined(PNG_FLOATING_POINT_SUPPORTED)
  189509. png_free(png_ptr, swidth);
  189510. #endif
  189511. png_free(png_ptr, buffer);
  189512. return;
  189513. }
  189514. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189515. height = png_strtod(png_ptr, ep, &vp);
  189516. if (*vp)
  189517. {
  189518. png_warning(png_ptr, "malformed height string in sCAL chunk");
  189519. return;
  189520. }
  189521. #else
  189522. #ifdef PNG_FIXED_POINT_SUPPORTED
  189523. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  189524. if (swidth == NULL)
  189525. {
  189526. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  189527. return;
  189528. }
  189529. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  189530. #endif
  189531. #endif
  189532. if (buffer + slength < ep
  189533. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189534. || width <= 0. || height <= 0.
  189535. #endif
  189536. )
  189537. {
  189538. png_warning(png_ptr, "Invalid sCAL data");
  189539. png_free(png_ptr, buffer);
  189540. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  189541. png_free(png_ptr, swidth);
  189542. png_free(png_ptr, sheight);
  189543. #endif
  189544. return;
  189545. }
  189546. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189547. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  189548. #else
  189549. #ifdef PNG_FIXED_POINT_SUPPORTED
  189550. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  189551. #endif
  189552. #endif
  189553. png_free(png_ptr, buffer);
  189554. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  189555. png_free(png_ptr, swidth);
  189556. png_free(png_ptr, sheight);
  189557. #endif
  189558. }
  189559. #endif
  189560. #if defined(PNG_READ_tIME_SUPPORTED)
  189561. void /* PRIVATE */
  189562. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189563. {
  189564. png_byte buf[7];
  189565. png_time mod_time;
  189566. png_debug(1, "in png_handle_tIME\n");
  189567. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189568. png_error(png_ptr, "Out of place tIME chunk");
  189569. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  189570. {
  189571. png_warning(png_ptr, "Duplicate tIME chunk");
  189572. png_crc_finish(png_ptr, length);
  189573. return;
  189574. }
  189575. if (png_ptr->mode & PNG_HAVE_IDAT)
  189576. png_ptr->mode |= PNG_AFTER_IDAT;
  189577. if (length != 7)
  189578. {
  189579. png_warning(png_ptr, "Incorrect tIME chunk length");
  189580. png_crc_finish(png_ptr, length);
  189581. return;
  189582. }
  189583. png_crc_read(png_ptr, buf, 7);
  189584. if (png_crc_finish(png_ptr, 0))
  189585. return;
  189586. mod_time.second = buf[6];
  189587. mod_time.minute = buf[5];
  189588. mod_time.hour = buf[4];
  189589. mod_time.day = buf[3];
  189590. mod_time.month = buf[2];
  189591. mod_time.year = png_get_uint_16(buf);
  189592. png_set_tIME(png_ptr, info_ptr, &mod_time);
  189593. }
  189594. #endif
  189595. #if defined(PNG_READ_tEXt_SUPPORTED)
  189596. /* Note: this does not properly handle chunks that are > 64K under DOS */
  189597. void /* PRIVATE */
  189598. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189599. {
  189600. png_textp text_ptr;
  189601. png_charp key;
  189602. png_charp text;
  189603. png_uint_32 skip = 0;
  189604. png_size_t slength;
  189605. int ret;
  189606. png_debug(1, "in png_handle_tEXt\n");
  189607. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189608. png_error(png_ptr, "Missing IHDR before tEXt");
  189609. if (png_ptr->mode & PNG_HAVE_IDAT)
  189610. png_ptr->mode |= PNG_AFTER_IDAT;
  189611. #ifdef PNG_MAX_MALLOC_64K
  189612. if (length > (png_uint_32)65535L)
  189613. {
  189614. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189615. skip = length - (png_uint_32)65535L;
  189616. length = (png_uint_32)65535L;
  189617. }
  189618. #endif
  189619. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  189620. if (key == NULL)
  189621. {
  189622. png_warning(png_ptr, "No memory to process text chunk.");
  189623. return;
  189624. }
  189625. slength = (png_size_t)length;
  189626. png_crc_read(png_ptr, (png_bytep)key, slength);
  189627. if (png_crc_finish(png_ptr, skip))
  189628. {
  189629. png_free(png_ptr, key);
  189630. return;
  189631. }
  189632. key[slength] = 0x00;
  189633. for (text = key; *text; text++)
  189634. /* empty loop to find end of key */ ;
  189635. if (text != key + slength)
  189636. text++;
  189637. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  189638. (png_uint_32)png_sizeof(png_text));
  189639. if (text_ptr == NULL)
  189640. {
  189641. png_warning(png_ptr, "Not enough memory to process text chunk.");
  189642. png_free(png_ptr, key);
  189643. return;
  189644. }
  189645. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189646. text_ptr->key = key;
  189647. #ifdef PNG_iTXt_SUPPORTED
  189648. text_ptr->lang = NULL;
  189649. text_ptr->lang_key = NULL;
  189650. text_ptr->itxt_length = 0;
  189651. #endif
  189652. text_ptr->text = text;
  189653. text_ptr->text_length = png_strlen(text);
  189654. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189655. png_free(png_ptr, key);
  189656. png_free(png_ptr, text_ptr);
  189657. if (ret)
  189658. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  189659. }
  189660. #endif
  189661. #if defined(PNG_READ_zTXt_SUPPORTED)
  189662. /* note: this does not correctly handle chunks that are > 64K under DOS */
  189663. void /* PRIVATE */
  189664. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189665. {
  189666. png_textp text_ptr;
  189667. png_charp chunkdata;
  189668. png_charp text;
  189669. int comp_type;
  189670. int ret;
  189671. png_size_t slength, prefix_len, data_len;
  189672. png_debug(1, "in png_handle_zTXt\n");
  189673. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189674. png_error(png_ptr, "Missing IHDR before zTXt");
  189675. if (png_ptr->mode & PNG_HAVE_IDAT)
  189676. png_ptr->mode |= PNG_AFTER_IDAT;
  189677. #ifdef PNG_MAX_MALLOC_64K
  189678. /* We will no doubt have problems with chunks even half this size, but
  189679. there is no hard and fast rule to tell us where to stop. */
  189680. if (length > (png_uint_32)65535L)
  189681. {
  189682. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  189683. png_crc_finish(png_ptr, length);
  189684. return;
  189685. }
  189686. #endif
  189687. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  189688. if (chunkdata == NULL)
  189689. {
  189690. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  189691. return;
  189692. }
  189693. slength = (png_size_t)length;
  189694. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  189695. if (png_crc_finish(png_ptr, 0))
  189696. {
  189697. png_free(png_ptr, chunkdata);
  189698. return;
  189699. }
  189700. chunkdata[slength] = 0x00;
  189701. for (text = chunkdata; *text; text++)
  189702. /* empty loop */ ;
  189703. /* zTXt must have some text after the chunkdataword */
  189704. if (text >= chunkdata + slength - 2)
  189705. {
  189706. png_warning(png_ptr, "Truncated zTXt chunk");
  189707. png_free(png_ptr, chunkdata);
  189708. return;
  189709. }
  189710. else
  189711. {
  189712. comp_type = *(++text);
  189713. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  189714. {
  189715. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  189716. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  189717. }
  189718. text++; /* skip the compression_method byte */
  189719. }
  189720. prefix_len = text - chunkdata;
  189721. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  189722. (png_size_t)length, prefix_len, &data_len);
  189723. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  189724. (png_uint_32)png_sizeof(png_text));
  189725. if (text_ptr == NULL)
  189726. {
  189727. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  189728. png_free(png_ptr, chunkdata);
  189729. return;
  189730. }
  189731. text_ptr->compression = comp_type;
  189732. text_ptr->key = chunkdata;
  189733. #ifdef PNG_iTXt_SUPPORTED
  189734. text_ptr->lang = NULL;
  189735. text_ptr->lang_key = NULL;
  189736. text_ptr->itxt_length = 0;
  189737. #endif
  189738. text_ptr->text = chunkdata + prefix_len;
  189739. text_ptr->text_length = data_len;
  189740. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189741. png_free(png_ptr, text_ptr);
  189742. png_free(png_ptr, chunkdata);
  189743. if (ret)
  189744. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  189745. }
  189746. #endif
  189747. #if defined(PNG_READ_iTXt_SUPPORTED)
  189748. /* note: this does not correctly handle chunks that are > 64K under DOS */
  189749. void /* PRIVATE */
  189750. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189751. {
  189752. png_textp text_ptr;
  189753. png_charp chunkdata;
  189754. png_charp key, lang, text, lang_key;
  189755. int comp_flag;
  189756. int comp_type = 0;
  189757. int ret;
  189758. png_size_t slength, prefix_len, data_len;
  189759. png_debug(1, "in png_handle_iTXt\n");
  189760. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189761. png_error(png_ptr, "Missing IHDR before iTXt");
  189762. if (png_ptr->mode & PNG_HAVE_IDAT)
  189763. png_ptr->mode |= PNG_AFTER_IDAT;
  189764. #ifdef PNG_MAX_MALLOC_64K
  189765. /* We will no doubt have problems with chunks even half this size, but
  189766. there is no hard and fast rule to tell us where to stop. */
  189767. if (length > (png_uint_32)65535L)
  189768. {
  189769. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  189770. png_crc_finish(png_ptr, length);
  189771. return;
  189772. }
  189773. #endif
  189774. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  189775. if (chunkdata == NULL)
  189776. {
  189777. png_warning(png_ptr, "No memory to process iTXt chunk.");
  189778. return;
  189779. }
  189780. slength = (png_size_t)length;
  189781. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  189782. if (png_crc_finish(png_ptr, 0))
  189783. {
  189784. png_free(png_ptr, chunkdata);
  189785. return;
  189786. }
  189787. chunkdata[slength] = 0x00;
  189788. for (lang = chunkdata; *lang; lang++)
  189789. /* empty loop */ ;
  189790. lang++; /* skip NUL separator */
  189791. /* iTXt must have a language tag (possibly empty), two compression bytes,
  189792. translated keyword (possibly empty), and possibly some text after the
  189793. keyword */
  189794. if (lang >= chunkdata + slength - 3)
  189795. {
  189796. png_warning(png_ptr, "Truncated iTXt chunk");
  189797. png_free(png_ptr, chunkdata);
  189798. return;
  189799. }
  189800. else
  189801. {
  189802. comp_flag = *lang++;
  189803. comp_type = *lang++;
  189804. }
  189805. for (lang_key = lang; *lang_key; lang_key++)
  189806. /* empty loop */ ;
  189807. lang_key++; /* skip NUL separator */
  189808. if (lang_key >= chunkdata + slength)
  189809. {
  189810. png_warning(png_ptr, "Truncated iTXt chunk");
  189811. png_free(png_ptr, chunkdata);
  189812. return;
  189813. }
  189814. for (text = lang_key; *text; text++)
  189815. /* empty loop */ ;
  189816. text++; /* skip NUL separator */
  189817. if (text >= chunkdata + slength)
  189818. {
  189819. png_warning(png_ptr, "Malformed iTXt chunk");
  189820. png_free(png_ptr, chunkdata);
  189821. return;
  189822. }
  189823. prefix_len = text - chunkdata;
  189824. key=chunkdata;
  189825. if (comp_flag)
  189826. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  189827. (size_t)length, prefix_len, &data_len);
  189828. else
  189829. data_len=png_strlen(chunkdata + prefix_len);
  189830. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  189831. (png_uint_32)png_sizeof(png_text));
  189832. if (text_ptr == NULL)
  189833. {
  189834. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  189835. png_free(png_ptr, chunkdata);
  189836. return;
  189837. }
  189838. text_ptr->compression = (int)comp_flag + 1;
  189839. text_ptr->lang_key = chunkdata+(lang_key-key);
  189840. text_ptr->lang = chunkdata+(lang-key);
  189841. text_ptr->itxt_length = data_len;
  189842. text_ptr->text_length = 0;
  189843. text_ptr->key = chunkdata;
  189844. text_ptr->text = chunkdata + prefix_len;
  189845. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189846. png_free(png_ptr, text_ptr);
  189847. png_free(png_ptr, chunkdata);
  189848. if (ret)
  189849. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  189850. }
  189851. #endif
  189852. /* This function is called when we haven't found a handler for a
  189853. chunk. If there isn't a problem with the chunk itself (ie bad
  189854. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  189855. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  189856. case it will be saved away to be written out later. */
  189857. void /* PRIVATE */
  189858. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189859. {
  189860. png_uint_32 skip = 0;
  189861. png_debug(1, "in png_handle_unknown\n");
  189862. if (png_ptr->mode & PNG_HAVE_IDAT)
  189863. {
  189864. #ifdef PNG_USE_LOCAL_ARRAYS
  189865. PNG_CONST PNG_IDAT;
  189866. #endif
  189867. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  189868. png_ptr->mode |= PNG_AFTER_IDAT;
  189869. }
  189870. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189871. if (!(png_ptr->chunk_name[0] & 0x20))
  189872. {
  189873. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189874. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189875. PNG_HANDLE_CHUNK_ALWAYS
  189876. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189877. && png_ptr->read_user_chunk_fn == NULL
  189878. #endif
  189879. )
  189880. #endif
  189881. png_chunk_error(png_ptr, "unknown critical chunk");
  189882. }
  189883. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189884. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  189885. (png_ptr->read_user_chunk_fn != NULL))
  189886. {
  189887. #ifdef PNG_MAX_MALLOC_64K
  189888. if (length > (png_uint_32)65535L)
  189889. {
  189890. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189891. skip = length - (png_uint_32)65535L;
  189892. length = (png_uint_32)65535L;
  189893. }
  189894. #endif
  189895. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189896. (png_charp)png_ptr->chunk_name, 5);
  189897. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189898. png_ptr->unknown_chunk.size = (png_size_t)length;
  189899. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189900. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189901. if(png_ptr->read_user_chunk_fn != NULL)
  189902. {
  189903. /* callback to user unknown chunk handler */
  189904. int ret;
  189905. ret = (*(png_ptr->read_user_chunk_fn))
  189906. (png_ptr, &png_ptr->unknown_chunk);
  189907. if (ret < 0)
  189908. png_chunk_error(png_ptr, "error in user chunk");
  189909. if (ret == 0)
  189910. {
  189911. if (!(png_ptr->chunk_name[0] & 0x20))
  189912. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189913. PNG_HANDLE_CHUNK_ALWAYS)
  189914. png_chunk_error(png_ptr, "unknown critical chunk");
  189915. png_set_unknown_chunks(png_ptr, info_ptr,
  189916. &png_ptr->unknown_chunk, 1);
  189917. }
  189918. }
  189919. #else
  189920. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189921. #endif
  189922. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189923. png_ptr->unknown_chunk.data = NULL;
  189924. }
  189925. else
  189926. #endif
  189927. skip = length;
  189928. png_crc_finish(png_ptr, skip);
  189929. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189930. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  189931. #endif
  189932. }
  189933. /* This function is called to verify that a chunk name is valid.
  189934. This function can't have the "critical chunk check" incorporated
  189935. into it, since in the future we will need to be able to call user
  189936. functions to handle unknown critical chunks after we check that
  189937. the chunk name itself is valid. */
  189938. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  189939. void /* PRIVATE */
  189940. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  189941. {
  189942. png_debug(1, "in png_check_chunk_name\n");
  189943. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  189944. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  189945. {
  189946. png_chunk_error(png_ptr, "invalid chunk type");
  189947. }
  189948. }
  189949. /* Combines the row recently read in with the existing pixels in the
  189950. row. This routine takes care of alpha and transparency if requested.
  189951. This routine also handles the two methods of progressive display
  189952. of interlaced images, depending on the mask value.
  189953. The mask value describes which pixels are to be combined with
  189954. the row. The pattern always repeats every 8 pixels, so just 8
  189955. bits are needed. A one indicates the pixel is to be combined,
  189956. a zero indicates the pixel is to be skipped. This is in addition
  189957. to any alpha or transparency value associated with the pixel. If
  189958. you want all pixels to be combined, pass 0xff (255) in mask. */
  189959. void /* PRIVATE */
  189960. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  189961. {
  189962. png_debug(1,"in png_combine_row\n");
  189963. if (mask == 0xff)
  189964. {
  189965. png_memcpy(row, png_ptr->row_buf + 1,
  189966. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  189967. }
  189968. else
  189969. {
  189970. switch (png_ptr->row_info.pixel_depth)
  189971. {
  189972. case 1:
  189973. {
  189974. png_bytep sp = png_ptr->row_buf + 1;
  189975. png_bytep dp = row;
  189976. int s_inc, s_start, s_end;
  189977. int m = 0x80;
  189978. int shift;
  189979. png_uint_32 i;
  189980. png_uint_32 row_width = png_ptr->width;
  189981. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  189982. if (png_ptr->transformations & PNG_PACKSWAP)
  189983. {
  189984. s_start = 0;
  189985. s_end = 7;
  189986. s_inc = 1;
  189987. }
  189988. else
  189989. #endif
  189990. {
  189991. s_start = 7;
  189992. s_end = 0;
  189993. s_inc = -1;
  189994. }
  189995. shift = s_start;
  189996. for (i = 0; i < row_width; i++)
  189997. {
  189998. if (m & mask)
  189999. {
  190000. int value;
  190001. value = (*sp >> shift) & 0x01;
  190002. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  190003. *dp |= (png_byte)(value << shift);
  190004. }
  190005. if (shift == s_end)
  190006. {
  190007. shift = s_start;
  190008. sp++;
  190009. dp++;
  190010. }
  190011. else
  190012. shift += s_inc;
  190013. if (m == 1)
  190014. m = 0x80;
  190015. else
  190016. m >>= 1;
  190017. }
  190018. break;
  190019. }
  190020. case 2:
  190021. {
  190022. png_bytep sp = png_ptr->row_buf + 1;
  190023. png_bytep dp = row;
  190024. int s_start, s_end, s_inc;
  190025. int m = 0x80;
  190026. int shift;
  190027. png_uint_32 i;
  190028. png_uint_32 row_width = png_ptr->width;
  190029. int value;
  190030. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190031. if (png_ptr->transformations & PNG_PACKSWAP)
  190032. {
  190033. s_start = 0;
  190034. s_end = 6;
  190035. s_inc = 2;
  190036. }
  190037. else
  190038. #endif
  190039. {
  190040. s_start = 6;
  190041. s_end = 0;
  190042. s_inc = -2;
  190043. }
  190044. shift = s_start;
  190045. for (i = 0; i < row_width; i++)
  190046. {
  190047. if (m & mask)
  190048. {
  190049. value = (*sp >> shift) & 0x03;
  190050. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  190051. *dp |= (png_byte)(value << shift);
  190052. }
  190053. if (shift == s_end)
  190054. {
  190055. shift = s_start;
  190056. sp++;
  190057. dp++;
  190058. }
  190059. else
  190060. shift += s_inc;
  190061. if (m == 1)
  190062. m = 0x80;
  190063. else
  190064. m >>= 1;
  190065. }
  190066. break;
  190067. }
  190068. case 4:
  190069. {
  190070. png_bytep sp = png_ptr->row_buf + 1;
  190071. png_bytep dp = row;
  190072. int s_start, s_end, s_inc;
  190073. int m = 0x80;
  190074. int shift;
  190075. png_uint_32 i;
  190076. png_uint_32 row_width = png_ptr->width;
  190077. int value;
  190078. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190079. if (png_ptr->transformations & PNG_PACKSWAP)
  190080. {
  190081. s_start = 0;
  190082. s_end = 4;
  190083. s_inc = 4;
  190084. }
  190085. else
  190086. #endif
  190087. {
  190088. s_start = 4;
  190089. s_end = 0;
  190090. s_inc = -4;
  190091. }
  190092. shift = s_start;
  190093. for (i = 0; i < row_width; i++)
  190094. {
  190095. if (m & mask)
  190096. {
  190097. value = (*sp >> shift) & 0xf;
  190098. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  190099. *dp |= (png_byte)(value << shift);
  190100. }
  190101. if (shift == s_end)
  190102. {
  190103. shift = s_start;
  190104. sp++;
  190105. dp++;
  190106. }
  190107. else
  190108. shift += s_inc;
  190109. if (m == 1)
  190110. m = 0x80;
  190111. else
  190112. m >>= 1;
  190113. }
  190114. break;
  190115. }
  190116. default:
  190117. {
  190118. png_bytep sp = png_ptr->row_buf + 1;
  190119. png_bytep dp = row;
  190120. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  190121. png_uint_32 i;
  190122. png_uint_32 row_width = png_ptr->width;
  190123. png_byte m = 0x80;
  190124. for (i = 0; i < row_width; i++)
  190125. {
  190126. if (m & mask)
  190127. {
  190128. png_memcpy(dp, sp, pixel_bytes);
  190129. }
  190130. sp += pixel_bytes;
  190131. dp += pixel_bytes;
  190132. if (m == 1)
  190133. m = 0x80;
  190134. else
  190135. m >>= 1;
  190136. }
  190137. break;
  190138. }
  190139. }
  190140. }
  190141. }
  190142. #ifdef PNG_READ_INTERLACING_SUPPORTED
  190143. /* OLD pre-1.0.9 interface:
  190144. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  190145. png_uint_32 transformations)
  190146. */
  190147. void /* PRIVATE */
  190148. png_do_read_interlace(png_structp png_ptr)
  190149. {
  190150. png_row_infop row_info = &(png_ptr->row_info);
  190151. png_bytep row = png_ptr->row_buf + 1;
  190152. int pass = png_ptr->pass;
  190153. png_uint_32 transformations = png_ptr->transformations;
  190154. #ifdef PNG_USE_LOCAL_ARRAYS
  190155. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  190156. /* offset to next interlace block */
  190157. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  190158. #endif
  190159. png_debug(1,"in png_do_read_interlace\n");
  190160. if (row != NULL && row_info != NULL)
  190161. {
  190162. png_uint_32 final_width;
  190163. final_width = row_info->width * png_pass_inc[pass];
  190164. switch (row_info->pixel_depth)
  190165. {
  190166. case 1:
  190167. {
  190168. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  190169. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  190170. int sshift, dshift;
  190171. int s_start, s_end, s_inc;
  190172. int jstop = png_pass_inc[pass];
  190173. png_byte v;
  190174. png_uint_32 i;
  190175. int j;
  190176. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190177. if (transformations & PNG_PACKSWAP)
  190178. {
  190179. sshift = (int)((row_info->width + 7) & 0x07);
  190180. dshift = (int)((final_width + 7) & 0x07);
  190181. s_start = 7;
  190182. s_end = 0;
  190183. s_inc = -1;
  190184. }
  190185. else
  190186. #endif
  190187. {
  190188. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  190189. dshift = 7 - (int)((final_width + 7) & 0x07);
  190190. s_start = 0;
  190191. s_end = 7;
  190192. s_inc = 1;
  190193. }
  190194. for (i = 0; i < row_info->width; i++)
  190195. {
  190196. v = (png_byte)((*sp >> sshift) & 0x01);
  190197. for (j = 0; j < jstop; j++)
  190198. {
  190199. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  190200. *dp |= (png_byte)(v << dshift);
  190201. if (dshift == s_end)
  190202. {
  190203. dshift = s_start;
  190204. dp--;
  190205. }
  190206. else
  190207. dshift += s_inc;
  190208. }
  190209. if (sshift == s_end)
  190210. {
  190211. sshift = s_start;
  190212. sp--;
  190213. }
  190214. else
  190215. sshift += s_inc;
  190216. }
  190217. break;
  190218. }
  190219. case 2:
  190220. {
  190221. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  190222. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  190223. int sshift, dshift;
  190224. int s_start, s_end, s_inc;
  190225. int jstop = png_pass_inc[pass];
  190226. png_uint_32 i;
  190227. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190228. if (transformations & PNG_PACKSWAP)
  190229. {
  190230. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  190231. dshift = (int)(((final_width + 3) & 0x03) << 1);
  190232. s_start = 6;
  190233. s_end = 0;
  190234. s_inc = -2;
  190235. }
  190236. else
  190237. #endif
  190238. {
  190239. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  190240. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  190241. s_start = 0;
  190242. s_end = 6;
  190243. s_inc = 2;
  190244. }
  190245. for (i = 0; i < row_info->width; i++)
  190246. {
  190247. png_byte v;
  190248. int j;
  190249. v = (png_byte)((*sp >> sshift) & 0x03);
  190250. for (j = 0; j < jstop; j++)
  190251. {
  190252. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  190253. *dp |= (png_byte)(v << dshift);
  190254. if (dshift == s_end)
  190255. {
  190256. dshift = s_start;
  190257. dp--;
  190258. }
  190259. else
  190260. dshift += s_inc;
  190261. }
  190262. if (sshift == s_end)
  190263. {
  190264. sshift = s_start;
  190265. sp--;
  190266. }
  190267. else
  190268. sshift += s_inc;
  190269. }
  190270. break;
  190271. }
  190272. case 4:
  190273. {
  190274. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  190275. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  190276. int sshift, dshift;
  190277. int s_start, s_end, s_inc;
  190278. png_uint_32 i;
  190279. int jstop = png_pass_inc[pass];
  190280. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190281. if (transformations & PNG_PACKSWAP)
  190282. {
  190283. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  190284. dshift = (int)(((final_width + 1) & 0x01) << 2);
  190285. s_start = 4;
  190286. s_end = 0;
  190287. s_inc = -4;
  190288. }
  190289. else
  190290. #endif
  190291. {
  190292. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  190293. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  190294. s_start = 0;
  190295. s_end = 4;
  190296. s_inc = 4;
  190297. }
  190298. for (i = 0; i < row_info->width; i++)
  190299. {
  190300. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  190301. int j;
  190302. for (j = 0; j < jstop; j++)
  190303. {
  190304. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  190305. *dp |= (png_byte)(v << dshift);
  190306. if (dshift == s_end)
  190307. {
  190308. dshift = s_start;
  190309. dp--;
  190310. }
  190311. else
  190312. dshift += s_inc;
  190313. }
  190314. if (sshift == s_end)
  190315. {
  190316. sshift = s_start;
  190317. sp--;
  190318. }
  190319. else
  190320. sshift += s_inc;
  190321. }
  190322. break;
  190323. }
  190324. default:
  190325. {
  190326. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  190327. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  190328. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  190329. int jstop = png_pass_inc[pass];
  190330. png_uint_32 i;
  190331. for (i = 0; i < row_info->width; i++)
  190332. {
  190333. png_byte v[8];
  190334. int j;
  190335. png_memcpy(v, sp, pixel_bytes);
  190336. for (j = 0; j < jstop; j++)
  190337. {
  190338. png_memcpy(dp, v, pixel_bytes);
  190339. dp -= pixel_bytes;
  190340. }
  190341. sp -= pixel_bytes;
  190342. }
  190343. break;
  190344. }
  190345. }
  190346. row_info->width = final_width;
  190347. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  190348. }
  190349. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  190350. transformations = transformations; /* silence compiler warning */
  190351. #endif
  190352. }
  190353. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  190354. void /* PRIVATE */
  190355. png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep row,
  190356. png_bytep prev_row, int filter)
  190357. {
  190358. png_debug(1, "in png_read_filter_row\n");
  190359. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  190360. switch (filter)
  190361. {
  190362. case PNG_FILTER_VALUE_NONE:
  190363. break;
  190364. case PNG_FILTER_VALUE_SUB:
  190365. {
  190366. png_uint_32 i;
  190367. png_uint_32 istop = row_info->rowbytes;
  190368. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  190369. png_bytep rp = row + bpp;
  190370. png_bytep lp = row;
  190371. for (i = bpp; i < istop; i++)
  190372. {
  190373. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  190374. rp++;
  190375. }
  190376. break;
  190377. }
  190378. case PNG_FILTER_VALUE_UP:
  190379. {
  190380. png_uint_32 i;
  190381. png_uint_32 istop = row_info->rowbytes;
  190382. png_bytep rp = row;
  190383. png_bytep pp = prev_row;
  190384. for (i = 0; i < istop; i++)
  190385. {
  190386. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  190387. rp++;
  190388. }
  190389. break;
  190390. }
  190391. case PNG_FILTER_VALUE_AVG:
  190392. {
  190393. png_uint_32 i;
  190394. png_bytep rp = row;
  190395. png_bytep pp = prev_row;
  190396. png_bytep lp = row;
  190397. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  190398. png_uint_32 istop = row_info->rowbytes - bpp;
  190399. for (i = 0; i < bpp; i++)
  190400. {
  190401. *rp = (png_byte)(((int)(*rp) +
  190402. ((int)(*pp++) / 2 )) & 0xff);
  190403. rp++;
  190404. }
  190405. for (i = 0; i < istop; i++)
  190406. {
  190407. *rp = (png_byte)(((int)(*rp) +
  190408. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  190409. rp++;
  190410. }
  190411. break;
  190412. }
  190413. case PNG_FILTER_VALUE_PAETH:
  190414. {
  190415. png_uint_32 i;
  190416. png_bytep rp = row;
  190417. png_bytep pp = prev_row;
  190418. png_bytep lp = row;
  190419. png_bytep cp = prev_row;
  190420. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  190421. png_uint_32 istop=row_info->rowbytes - bpp;
  190422. for (i = 0; i < bpp; i++)
  190423. {
  190424. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  190425. rp++;
  190426. }
  190427. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  190428. {
  190429. int a, b, c, pa, pb, pc, p;
  190430. a = *lp++;
  190431. b = *pp++;
  190432. c = *cp++;
  190433. p = b - c;
  190434. pc = a - c;
  190435. #ifdef PNG_USE_ABS
  190436. pa = abs(p);
  190437. pb = abs(pc);
  190438. pc = abs(p + pc);
  190439. #else
  190440. pa = p < 0 ? -p : p;
  190441. pb = pc < 0 ? -pc : pc;
  190442. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  190443. #endif
  190444. /*
  190445. if (pa <= pb && pa <= pc)
  190446. p = a;
  190447. else if (pb <= pc)
  190448. p = b;
  190449. else
  190450. p = c;
  190451. */
  190452. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  190453. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  190454. rp++;
  190455. }
  190456. break;
  190457. }
  190458. default:
  190459. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  190460. *row=0;
  190461. break;
  190462. }
  190463. }
  190464. void /* PRIVATE */
  190465. png_read_finish_row(png_structp png_ptr)
  190466. {
  190467. #ifdef PNG_USE_LOCAL_ARRAYS
  190468. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  190469. /* start of interlace block */
  190470. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  190471. /* offset to next interlace block */
  190472. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  190473. /* start of interlace block in the y direction */
  190474. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  190475. /* offset to next interlace block in the y direction */
  190476. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  190477. #endif
  190478. png_debug(1, "in png_read_finish_row\n");
  190479. png_ptr->row_number++;
  190480. if (png_ptr->row_number < png_ptr->num_rows)
  190481. return;
  190482. if (png_ptr->interlaced)
  190483. {
  190484. png_ptr->row_number = 0;
  190485. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  190486. png_ptr->rowbytes + 1);
  190487. do
  190488. {
  190489. png_ptr->pass++;
  190490. if (png_ptr->pass >= 7)
  190491. break;
  190492. png_ptr->iwidth = (png_ptr->width +
  190493. png_pass_inc[png_ptr->pass] - 1 -
  190494. png_pass_start[png_ptr->pass]) /
  190495. png_pass_inc[png_ptr->pass];
  190496. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  190497. png_ptr->iwidth) + 1;
  190498. if (!(png_ptr->transformations & PNG_INTERLACE))
  190499. {
  190500. png_ptr->num_rows = (png_ptr->height +
  190501. png_pass_yinc[png_ptr->pass] - 1 -
  190502. png_pass_ystart[png_ptr->pass]) /
  190503. png_pass_yinc[png_ptr->pass];
  190504. if (!(png_ptr->num_rows))
  190505. continue;
  190506. }
  190507. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  190508. break;
  190509. } while (png_ptr->iwidth == 0);
  190510. if (png_ptr->pass < 7)
  190511. return;
  190512. }
  190513. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  190514. {
  190515. #ifdef PNG_USE_LOCAL_ARRAYS
  190516. PNG_CONST PNG_IDAT;
  190517. #endif
  190518. char extra;
  190519. int ret;
  190520. png_ptr->zstream.next_out = (Byte *)&extra;
  190521. png_ptr->zstream.avail_out = (uInt)1;
  190522. for(;;)
  190523. {
  190524. if (!(png_ptr->zstream.avail_in))
  190525. {
  190526. while (!png_ptr->idat_size)
  190527. {
  190528. png_byte chunk_length[4];
  190529. png_crc_finish(png_ptr, 0);
  190530. png_read_data(png_ptr, chunk_length, 4);
  190531. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  190532. png_reset_crc(png_ptr);
  190533. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  190534. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  190535. png_error(png_ptr, "Not enough image data");
  190536. }
  190537. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  190538. png_ptr->zstream.next_in = png_ptr->zbuf;
  190539. if (png_ptr->zbuf_size > png_ptr->idat_size)
  190540. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  190541. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  190542. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  190543. }
  190544. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  190545. if (ret == Z_STREAM_END)
  190546. {
  190547. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  190548. png_ptr->idat_size)
  190549. png_warning(png_ptr, "Extra compressed data");
  190550. png_ptr->mode |= PNG_AFTER_IDAT;
  190551. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  190552. break;
  190553. }
  190554. if (ret != Z_OK)
  190555. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  190556. "Decompression Error");
  190557. if (!(png_ptr->zstream.avail_out))
  190558. {
  190559. png_warning(png_ptr, "Extra compressed data.");
  190560. png_ptr->mode |= PNG_AFTER_IDAT;
  190561. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  190562. break;
  190563. }
  190564. }
  190565. png_ptr->zstream.avail_out = 0;
  190566. }
  190567. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  190568. png_warning(png_ptr, "Extra compression data");
  190569. inflateReset(&png_ptr->zstream);
  190570. png_ptr->mode |= PNG_AFTER_IDAT;
  190571. }
  190572. void /* PRIVATE */
  190573. png_read_start_row(png_structp png_ptr)
  190574. {
  190575. #ifdef PNG_USE_LOCAL_ARRAYS
  190576. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  190577. /* start of interlace block */
  190578. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  190579. /* offset to next interlace block */
  190580. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  190581. /* start of interlace block in the y direction */
  190582. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  190583. /* offset to next interlace block in the y direction */
  190584. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  190585. #endif
  190586. int max_pixel_depth;
  190587. png_uint_32 row_bytes;
  190588. png_debug(1, "in png_read_start_row\n");
  190589. png_ptr->zstream.avail_in = 0;
  190590. png_init_read_transformations(png_ptr);
  190591. if (png_ptr->interlaced)
  190592. {
  190593. if (!(png_ptr->transformations & PNG_INTERLACE))
  190594. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  190595. png_pass_ystart[0]) / png_pass_yinc[0];
  190596. else
  190597. png_ptr->num_rows = png_ptr->height;
  190598. png_ptr->iwidth = (png_ptr->width +
  190599. png_pass_inc[png_ptr->pass] - 1 -
  190600. png_pass_start[png_ptr->pass]) /
  190601. png_pass_inc[png_ptr->pass];
  190602. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  190603. png_ptr->irowbytes = (png_size_t)row_bytes;
  190604. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  190605. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  190606. }
  190607. else
  190608. {
  190609. png_ptr->num_rows = png_ptr->height;
  190610. png_ptr->iwidth = png_ptr->width;
  190611. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  190612. }
  190613. max_pixel_depth = png_ptr->pixel_depth;
  190614. #if defined(PNG_READ_PACK_SUPPORTED)
  190615. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  190616. max_pixel_depth = 8;
  190617. #endif
  190618. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190619. if (png_ptr->transformations & PNG_EXPAND)
  190620. {
  190621. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190622. {
  190623. if (png_ptr->num_trans)
  190624. max_pixel_depth = 32;
  190625. else
  190626. max_pixel_depth = 24;
  190627. }
  190628. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  190629. {
  190630. if (max_pixel_depth < 8)
  190631. max_pixel_depth = 8;
  190632. if (png_ptr->num_trans)
  190633. max_pixel_depth *= 2;
  190634. }
  190635. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  190636. {
  190637. if (png_ptr->num_trans)
  190638. {
  190639. max_pixel_depth *= 4;
  190640. max_pixel_depth /= 3;
  190641. }
  190642. }
  190643. }
  190644. #endif
  190645. #if defined(PNG_READ_FILLER_SUPPORTED)
  190646. if (png_ptr->transformations & (PNG_FILLER))
  190647. {
  190648. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190649. max_pixel_depth = 32;
  190650. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  190651. {
  190652. if (max_pixel_depth <= 8)
  190653. max_pixel_depth = 16;
  190654. else
  190655. max_pixel_depth = 32;
  190656. }
  190657. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  190658. {
  190659. if (max_pixel_depth <= 32)
  190660. max_pixel_depth = 32;
  190661. else
  190662. max_pixel_depth = 64;
  190663. }
  190664. }
  190665. #endif
  190666. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190667. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  190668. {
  190669. if (
  190670. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190671. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  190672. #endif
  190673. #if defined(PNG_READ_FILLER_SUPPORTED)
  190674. (png_ptr->transformations & (PNG_FILLER)) ||
  190675. #endif
  190676. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  190677. {
  190678. if (max_pixel_depth <= 16)
  190679. max_pixel_depth = 32;
  190680. else
  190681. max_pixel_depth = 64;
  190682. }
  190683. else
  190684. {
  190685. if (max_pixel_depth <= 8)
  190686. {
  190687. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190688. max_pixel_depth = 32;
  190689. else
  190690. max_pixel_depth = 24;
  190691. }
  190692. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190693. max_pixel_depth = 64;
  190694. else
  190695. max_pixel_depth = 48;
  190696. }
  190697. }
  190698. #endif
  190699. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  190700. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  190701. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  190702. {
  190703. int user_pixel_depth=png_ptr->user_transform_depth*
  190704. png_ptr->user_transform_channels;
  190705. if(user_pixel_depth > max_pixel_depth)
  190706. max_pixel_depth=user_pixel_depth;
  190707. }
  190708. #endif
  190709. /* align the width on the next larger 8 pixels. Mainly used
  190710. for interlacing */
  190711. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  190712. /* calculate the maximum bytes needed, adding a byte and a pixel
  190713. for safety's sake */
  190714. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  190715. 1 + ((max_pixel_depth + 7) >> 3);
  190716. #ifdef PNG_MAX_MALLOC_64K
  190717. if (row_bytes > (png_uint_32)65536L)
  190718. png_error(png_ptr, "This image requires a row greater than 64KB");
  190719. #endif
  190720. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  190721. png_ptr->row_buf = png_ptr->big_row_buf+32;
  190722. #ifdef PNG_MAX_MALLOC_64K
  190723. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  190724. png_error(png_ptr, "This image requires a row greater than 64KB");
  190725. #endif
  190726. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  190727. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  190728. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  190729. png_ptr->rowbytes + 1));
  190730. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  190731. png_debug1(3, "width = %lu,\n", png_ptr->width);
  190732. png_debug1(3, "height = %lu,\n", png_ptr->height);
  190733. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  190734. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  190735. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  190736. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  190737. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  190738. }
  190739. #endif /* PNG_READ_SUPPORTED */
  190740. /********* End of inlined file: pngrutil.c *********/
  190741. /********* Start of inlined file: pngset.c *********/
  190742. /* pngset.c - storage of image information into info struct
  190743. *
  190744. * Last changed in libpng 1.2.21 [October 4, 2007]
  190745. * For conditions of distribution and use, see copyright notice in png.h
  190746. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190747. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190748. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190749. *
  190750. * The functions here are used during reads to store data from the file
  190751. * into the info struct, and during writes to store application data
  190752. * into the info struct for writing into the file. This abstracts the
  190753. * info struct and allows us to change the structure in the future.
  190754. */
  190755. #define PNG_INTERNAL
  190756. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  190757. #if defined(PNG_bKGD_SUPPORTED)
  190758. void PNGAPI
  190759. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  190760. {
  190761. png_debug1(1, "in %s storage function\n", "bKGD");
  190762. if (png_ptr == NULL || info_ptr == NULL)
  190763. return;
  190764. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  190765. info_ptr->valid |= PNG_INFO_bKGD;
  190766. }
  190767. #endif
  190768. #if defined(PNG_cHRM_SUPPORTED)
  190769. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190770. void PNGAPI
  190771. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  190772. double white_x, double white_y, double red_x, double red_y,
  190773. double green_x, double green_y, double blue_x, double blue_y)
  190774. {
  190775. png_debug1(1, "in %s storage function\n", "cHRM");
  190776. if (png_ptr == NULL || info_ptr == NULL)
  190777. return;
  190778. if (white_x < 0.0 || white_y < 0.0 ||
  190779. red_x < 0.0 || red_y < 0.0 ||
  190780. green_x < 0.0 || green_y < 0.0 ||
  190781. blue_x < 0.0 || blue_y < 0.0)
  190782. {
  190783. png_warning(png_ptr,
  190784. "Ignoring attempt to set negative chromaticity value");
  190785. return;
  190786. }
  190787. if (white_x > 21474.83 || white_y > 21474.83 ||
  190788. red_x > 21474.83 || red_y > 21474.83 ||
  190789. green_x > 21474.83 || green_y > 21474.83 ||
  190790. blue_x > 21474.83 || blue_y > 21474.83)
  190791. {
  190792. png_warning(png_ptr,
  190793. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  190794. return;
  190795. }
  190796. info_ptr->x_white = (float)white_x;
  190797. info_ptr->y_white = (float)white_y;
  190798. info_ptr->x_red = (float)red_x;
  190799. info_ptr->y_red = (float)red_y;
  190800. info_ptr->x_green = (float)green_x;
  190801. info_ptr->y_green = (float)green_y;
  190802. info_ptr->x_blue = (float)blue_x;
  190803. info_ptr->y_blue = (float)blue_y;
  190804. #ifdef PNG_FIXED_POINT_SUPPORTED
  190805. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  190806. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  190807. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  190808. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  190809. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  190810. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  190811. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  190812. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  190813. #endif
  190814. info_ptr->valid |= PNG_INFO_cHRM;
  190815. }
  190816. #endif
  190817. #ifdef PNG_FIXED_POINT_SUPPORTED
  190818. void PNGAPI
  190819. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  190820. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  190821. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  190822. png_fixed_point blue_x, png_fixed_point blue_y)
  190823. {
  190824. png_debug1(1, "in %s storage function\n", "cHRM");
  190825. if (png_ptr == NULL || info_ptr == NULL)
  190826. return;
  190827. if (white_x < 0 || white_y < 0 ||
  190828. red_x < 0 || red_y < 0 ||
  190829. green_x < 0 || green_y < 0 ||
  190830. blue_x < 0 || blue_y < 0)
  190831. {
  190832. png_warning(png_ptr,
  190833. "Ignoring attempt to set negative chromaticity value");
  190834. return;
  190835. }
  190836. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190837. if (white_x > (double) PNG_UINT_31_MAX ||
  190838. white_y > (double) PNG_UINT_31_MAX ||
  190839. red_x > (double) PNG_UINT_31_MAX ||
  190840. red_y > (double) PNG_UINT_31_MAX ||
  190841. green_x > (double) PNG_UINT_31_MAX ||
  190842. green_y > (double) PNG_UINT_31_MAX ||
  190843. blue_x > (double) PNG_UINT_31_MAX ||
  190844. blue_y > (double) PNG_UINT_31_MAX)
  190845. #else
  190846. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190847. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190848. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190849. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190850. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190851. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190852. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190853. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  190854. #endif
  190855. {
  190856. png_warning(png_ptr,
  190857. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  190858. return;
  190859. }
  190860. info_ptr->int_x_white = white_x;
  190861. info_ptr->int_y_white = white_y;
  190862. info_ptr->int_x_red = red_x;
  190863. info_ptr->int_y_red = red_y;
  190864. info_ptr->int_x_green = green_x;
  190865. info_ptr->int_y_green = green_y;
  190866. info_ptr->int_x_blue = blue_x;
  190867. info_ptr->int_y_blue = blue_y;
  190868. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190869. info_ptr->x_white = (float)(white_x/100000.);
  190870. info_ptr->y_white = (float)(white_y/100000.);
  190871. info_ptr->x_red = (float)( red_x/100000.);
  190872. info_ptr->y_red = (float)( red_y/100000.);
  190873. info_ptr->x_green = (float)(green_x/100000.);
  190874. info_ptr->y_green = (float)(green_y/100000.);
  190875. info_ptr->x_blue = (float)( blue_x/100000.);
  190876. info_ptr->y_blue = (float)( blue_y/100000.);
  190877. #endif
  190878. info_ptr->valid |= PNG_INFO_cHRM;
  190879. }
  190880. #endif
  190881. #endif
  190882. #if defined(PNG_gAMA_SUPPORTED)
  190883. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190884. void PNGAPI
  190885. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  190886. {
  190887. double gamma;
  190888. png_debug1(1, "in %s storage function\n", "gAMA");
  190889. if (png_ptr == NULL || info_ptr == NULL)
  190890. return;
  190891. /* Check for overflow */
  190892. if (file_gamma > 21474.83)
  190893. {
  190894. png_warning(png_ptr, "Limiting gamma to 21474.83");
  190895. gamma=21474.83;
  190896. }
  190897. else
  190898. gamma=file_gamma;
  190899. info_ptr->gamma = (float)gamma;
  190900. #ifdef PNG_FIXED_POINT_SUPPORTED
  190901. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  190902. #endif
  190903. info_ptr->valid |= PNG_INFO_gAMA;
  190904. if(gamma == 0.0)
  190905. png_warning(png_ptr, "Setting gamma=0");
  190906. }
  190907. #endif
  190908. void PNGAPI
  190909. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  190910. int_gamma)
  190911. {
  190912. png_fixed_point gamma;
  190913. png_debug1(1, "in %s storage function\n", "gAMA");
  190914. if (png_ptr == NULL || info_ptr == NULL)
  190915. return;
  190916. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  190917. {
  190918. png_warning(png_ptr, "Limiting gamma to 21474.83");
  190919. gamma=PNG_UINT_31_MAX;
  190920. }
  190921. else
  190922. {
  190923. if (int_gamma < 0)
  190924. {
  190925. png_warning(png_ptr, "Setting negative gamma to zero");
  190926. gamma=0;
  190927. }
  190928. else
  190929. gamma=int_gamma;
  190930. }
  190931. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190932. info_ptr->gamma = (float)(gamma/100000.);
  190933. #endif
  190934. #ifdef PNG_FIXED_POINT_SUPPORTED
  190935. info_ptr->int_gamma = gamma;
  190936. #endif
  190937. info_ptr->valid |= PNG_INFO_gAMA;
  190938. if(gamma == 0)
  190939. png_warning(png_ptr, "Setting gamma=0");
  190940. }
  190941. #endif
  190942. #if defined(PNG_hIST_SUPPORTED)
  190943. void PNGAPI
  190944. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  190945. {
  190946. int i;
  190947. png_debug1(1, "in %s storage function\n", "hIST");
  190948. if (png_ptr == NULL || info_ptr == NULL)
  190949. return;
  190950. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  190951. > PNG_MAX_PALETTE_LENGTH)
  190952. {
  190953. png_warning(png_ptr,
  190954. "Invalid palette size, hIST allocation skipped.");
  190955. return;
  190956. }
  190957. #ifdef PNG_FREE_ME_SUPPORTED
  190958. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  190959. #endif
  190960. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  190961. 1.2.1 */
  190962. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  190963. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  190964. if (png_ptr->hist == NULL)
  190965. {
  190966. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  190967. return;
  190968. }
  190969. for (i = 0; i < info_ptr->num_palette; i++)
  190970. png_ptr->hist[i] = hist[i];
  190971. info_ptr->hist = png_ptr->hist;
  190972. info_ptr->valid |= PNG_INFO_hIST;
  190973. #ifdef PNG_FREE_ME_SUPPORTED
  190974. info_ptr->free_me |= PNG_FREE_HIST;
  190975. #else
  190976. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  190977. #endif
  190978. }
  190979. #endif
  190980. void PNGAPI
  190981. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  190982. png_uint_32 width, png_uint_32 height, int bit_depth,
  190983. int color_type, int interlace_type, int compression_type,
  190984. int filter_type)
  190985. {
  190986. png_debug1(1, "in %s storage function\n", "IHDR");
  190987. if (png_ptr == NULL || info_ptr == NULL)
  190988. return;
  190989. /* check for width and height valid values */
  190990. if (width == 0 || height == 0)
  190991. png_error(png_ptr, "Image width or height is zero in IHDR");
  190992. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  190993. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  190994. png_error(png_ptr, "image size exceeds user limits in IHDR");
  190995. #else
  190996. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  190997. png_error(png_ptr, "image size exceeds user limits in IHDR");
  190998. #endif
  190999. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  191000. png_error(png_ptr, "Invalid image size in IHDR");
  191001. if ( width > (PNG_UINT_32_MAX
  191002. >> 3) /* 8-byte RGBA pixels */
  191003. - 64 /* bigrowbuf hack */
  191004. - 1 /* filter byte */
  191005. - 7*8 /* rounding of width to multiple of 8 pixels */
  191006. - 8) /* extra max_pixel_depth pad */
  191007. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  191008. /* check other values */
  191009. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  191010. bit_depth != 8 && bit_depth != 16)
  191011. png_error(png_ptr, "Invalid bit depth in IHDR");
  191012. if (color_type < 0 || color_type == 1 ||
  191013. color_type == 5 || color_type > 6)
  191014. png_error(png_ptr, "Invalid color type in IHDR");
  191015. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  191016. ((color_type == PNG_COLOR_TYPE_RGB ||
  191017. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  191018. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  191019. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  191020. if (interlace_type >= PNG_INTERLACE_LAST)
  191021. png_error(png_ptr, "Unknown interlace method in IHDR");
  191022. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  191023. png_error(png_ptr, "Unknown compression method in IHDR");
  191024. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  191025. /* Accept filter_method 64 (intrapixel differencing) only if
  191026. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  191027. * 2. Libpng did not read a PNG signature (this filter_method is only
  191028. * used in PNG datastreams that are embedded in MNG datastreams) and
  191029. * 3. The application called png_permit_mng_features with a mask that
  191030. * included PNG_FLAG_MNG_FILTER_64 and
  191031. * 4. The filter_method is 64 and
  191032. * 5. The color_type is RGB or RGBA
  191033. */
  191034. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  191035. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  191036. if(filter_type != PNG_FILTER_TYPE_BASE)
  191037. {
  191038. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  191039. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  191040. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  191041. (color_type == PNG_COLOR_TYPE_RGB ||
  191042. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  191043. png_error(png_ptr, "Unknown filter method in IHDR");
  191044. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  191045. png_warning(png_ptr, "Invalid filter method in IHDR");
  191046. }
  191047. #else
  191048. if(filter_type != PNG_FILTER_TYPE_BASE)
  191049. png_error(png_ptr, "Unknown filter method in IHDR");
  191050. #endif
  191051. info_ptr->width = width;
  191052. info_ptr->height = height;
  191053. info_ptr->bit_depth = (png_byte)bit_depth;
  191054. info_ptr->color_type =(png_byte) color_type;
  191055. info_ptr->compression_type = (png_byte)compression_type;
  191056. info_ptr->filter_type = (png_byte)filter_type;
  191057. info_ptr->interlace_type = (png_byte)interlace_type;
  191058. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191059. info_ptr->channels = 1;
  191060. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191061. info_ptr->channels = 3;
  191062. else
  191063. info_ptr->channels = 1;
  191064. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191065. info_ptr->channels++;
  191066. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  191067. /* check for potential overflow */
  191068. if (width > (PNG_UINT_32_MAX
  191069. >> 3) /* 8-byte RGBA pixels */
  191070. - 64 /* bigrowbuf hack */
  191071. - 1 /* filter byte */
  191072. - 7*8 /* rounding of width to multiple of 8 pixels */
  191073. - 8) /* extra max_pixel_depth pad */
  191074. info_ptr->rowbytes = (png_size_t)0;
  191075. else
  191076. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  191077. }
  191078. #if defined(PNG_oFFs_SUPPORTED)
  191079. void PNGAPI
  191080. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  191081. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  191082. {
  191083. png_debug1(1, "in %s storage function\n", "oFFs");
  191084. if (png_ptr == NULL || info_ptr == NULL)
  191085. return;
  191086. info_ptr->x_offset = offset_x;
  191087. info_ptr->y_offset = offset_y;
  191088. info_ptr->offset_unit_type = (png_byte)unit_type;
  191089. info_ptr->valid |= PNG_INFO_oFFs;
  191090. }
  191091. #endif
  191092. #if defined(PNG_pCAL_SUPPORTED)
  191093. void PNGAPI
  191094. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  191095. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  191096. png_charp units, png_charpp params)
  191097. {
  191098. png_uint_32 length;
  191099. int i;
  191100. png_debug1(1, "in %s storage function\n", "pCAL");
  191101. if (png_ptr == NULL || info_ptr == NULL)
  191102. return;
  191103. length = png_strlen(purpose) + 1;
  191104. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  191105. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  191106. if (info_ptr->pcal_purpose == NULL)
  191107. {
  191108. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  191109. return;
  191110. }
  191111. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  191112. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  191113. info_ptr->pcal_X0 = X0;
  191114. info_ptr->pcal_X1 = X1;
  191115. info_ptr->pcal_type = (png_byte)type;
  191116. info_ptr->pcal_nparams = (png_byte)nparams;
  191117. length = png_strlen(units) + 1;
  191118. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  191119. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  191120. if (info_ptr->pcal_units == NULL)
  191121. {
  191122. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  191123. return;
  191124. }
  191125. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  191126. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  191127. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  191128. if (info_ptr->pcal_params == NULL)
  191129. {
  191130. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  191131. return;
  191132. }
  191133. info_ptr->pcal_params[nparams] = NULL;
  191134. for (i = 0; i < nparams; i++)
  191135. {
  191136. length = png_strlen(params[i]) + 1;
  191137. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  191138. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  191139. if (info_ptr->pcal_params[i] == NULL)
  191140. {
  191141. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  191142. return;
  191143. }
  191144. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  191145. }
  191146. info_ptr->valid |= PNG_INFO_pCAL;
  191147. #ifdef PNG_FREE_ME_SUPPORTED
  191148. info_ptr->free_me |= PNG_FREE_PCAL;
  191149. #endif
  191150. }
  191151. #endif
  191152. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  191153. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191154. void PNGAPI
  191155. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  191156. int unit, double width, double height)
  191157. {
  191158. png_debug1(1, "in %s storage function\n", "sCAL");
  191159. if (png_ptr == NULL || info_ptr == NULL)
  191160. return;
  191161. info_ptr->scal_unit = (png_byte)unit;
  191162. info_ptr->scal_pixel_width = width;
  191163. info_ptr->scal_pixel_height = height;
  191164. info_ptr->valid |= PNG_INFO_sCAL;
  191165. }
  191166. #else
  191167. #ifdef PNG_FIXED_POINT_SUPPORTED
  191168. void PNGAPI
  191169. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  191170. int unit, png_charp swidth, png_charp sheight)
  191171. {
  191172. png_uint_32 length;
  191173. png_debug1(1, "in %s storage function\n", "sCAL");
  191174. if (png_ptr == NULL || info_ptr == NULL)
  191175. return;
  191176. info_ptr->scal_unit = (png_byte)unit;
  191177. length = png_strlen(swidth) + 1;
  191178. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  191179. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  191180. if (info_ptr->scal_s_width == NULL)
  191181. {
  191182. png_warning(png_ptr,
  191183. "Memory allocation failed while processing sCAL.");
  191184. }
  191185. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  191186. length = png_strlen(sheight) + 1;
  191187. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  191188. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  191189. if (info_ptr->scal_s_height == NULL)
  191190. {
  191191. png_free (png_ptr, info_ptr->scal_s_width);
  191192. png_warning(png_ptr,
  191193. "Memory allocation failed while processing sCAL.");
  191194. }
  191195. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  191196. info_ptr->valid |= PNG_INFO_sCAL;
  191197. #ifdef PNG_FREE_ME_SUPPORTED
  191198. info_ptr->free_me |= PNG_FREE_SCAL;
  191199. #endif
  191200. }
  191201. #endif
  191202. #endif
  191203. #endif
  191204. #if defined(PNG_pHYs_SUPPORTED)
  191205. void PNGAPI
  191206. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  191207. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  191208. {
  191209. png_debug1(1, "in %s storage function\n", "pHYs");
  191210. if (png_ptr == NULL || info_ptr == NULL)
  191211. return;
  191212. info_ptr->x_pixels_per_unit = res_x;
  191213. info_ptr->y_pixels_per_unit = res_y;
  191214. info_ptr->phys_unit_type = (png_byte)unit_type;
  191215. info_ptr->valid |= PNG_INFO_pHYs;
  191216. }
  191217. #endif
  191218. void PNGAPI
  191219. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  191220. png_colorp palette, int num_palette)
  191221. {
  191222. png_debug1(1, "in %s storage function\n", "PLTE");
  191223. if (png_ptr == NULL || info_ptr == NULL)
  191224. return;
  191225. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  191226. {
  191227. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191228. png_error(png_ptr, "Invalid palette length");
  191229. else
  191230. {
  191231. png_warning(png_ptr, "Invalid palette length");
  191232. return;
  191233. }
  191234. }
  191235. /*
  191236. * It may not actually be necessary to set png_ptr->palette here;
  191237. * we do it for backward compatibility with the way the png_handle_tRNS
  191238. * function used to do the allocation.
  191239. */
  191240. #ifdef PNG_FREE_ME_SUPPORTED
  191241. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  191242. #endif
  191243. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  191244. of num_palette entries,
  191245. in case of an invalid PNG file that has too-large sample values. */
  191246. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  191247. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  191248. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  191249. png_sizeof(png_color));
  191250. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  191251. info_ptr->palette = png_ptr->palette;
  191252. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  191253. #ifdef PNG_FREE_ME_SUPPORTED
  191254. info_ptr->free_me |= PNG_FREE_PLTE;
  191255. #else
  191256. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  191257. #endif
  191258. info_ptr->valid |= PNG_INFO_PLTE;
  191259. }
  191260. #if defined(PNG_sBIT_SUPPORTED)
  191261. void PNGAPI
  191262. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  191263. png_color_8p sig_bit)
  191264. {
  191265. png_debug1(1, "in %s storage function\n", "sBIT");
  191266. if (png_ptr == NULL || info_ptr == NULL)
  191267. return;
  191268. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  191269. info_ptr->valid |= PNG_INFO_sBIT;
  191270. }
  191271. #endif
  191272. #if defined(PNG_sRGB_SUPPORTED)
  191273. void PNGAPI
  191274. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  191275. {
  191276. png_debug1(1, "in %s storage function\n", "sRGB");
  191277. if (png_ptr == NULL || info_ptr == NULL)
  191278. return;
  191279. info_ptr->srgb_intent = (png_byte)intent;
  191280. info_ptr->valid |= PNG_INFO_sRGB;
  191281. }
  191282. void PNGAPI
  191283. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  191284. int intent)
  191285. {
  191286. #if defined(PNG_gAMA_SUPPORTED)
  191287. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191288. float file_gamma;
  191289. #endif
  191290. #ifdef PNG_FIXED_POINT_SUPPORTED
  191291. png_fixed_point int_file_gamma;
  191292. #endif
  191293. #endif
  191294. #if defined(PNG_cHRM_SUPPORTED)
  191295. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191296. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  191297. #endif
  191298. #ifdef PNG_FIXED_POINT_SUPPORTED
  191299. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  191300. int_green_y, int_blue_x, int_blue_y;
  191301. #endif
  191302. #endif
  191303. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  191304. if (png_ptr == NULL || info_ptr == NULL)
  191305. return;
  191306. png_set_sRGB(png_ptr, info_ptr, intent);
  191307. #if defined(PNG_gAMA_SUPPORTED)
  191308. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191309. file_gamma = (float).45455;
  191310. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  191311. #endif
  191312. #ifdef PNG_FIXED_POINT_SUPPORTED
  191313. int_file_gamma = 45455L;
  191314. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  191315. #endif
  191316. #endif
  191317. #if defined(PNG_cHRM_SUPPORTED)
  191318. #ifdef PNG_FIXED_POINT_SUPPORTED
  191319. int_white_x = 31270L;
  191320. int_white_y = 32900L;
  191321. int_red_x = 64000L;
  191322. int_red_y = 33000L;
  191323. int_green_x = 30000L;
  191324. int_green_y = 60000L;
  191325. int_blue_x = 15000L;
  191326. int_blue_y = 6000L;
  191327. png_set_cHRM_fixed(png_ptr, info_ptr,
  191328. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  191329. int_blue_x, int_blue_y);
  191330. #endif
  191331. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191332. white_x = (float).3127;
  191333. white_y = (float).3290;
  191334. red_x = (float).64;
  191335. red_y = (float).33;
  191336. green_x = (float).30;
  191337. green_y = (float).60;
  191338. blue_x = (float).15;
  191339. blue_y = (float).06;
  191340. png_set_cHRM(png_ptr, info_ptr,
  191341. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  191342. #endif
  191343. #endif
  191344. }
  191345. #endif
  191346. #if defined(PNG_iCCP_SUPPORTED)
  191347. void PNGAPI
  191348. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  191349. png_charp name, int compression_type,
  191350. png_charp profile, png_uint_32 proflen)
  191351. {
  191352. png_charp new_iccp_name;
  191353. png_charp new_iccp_profile;
  191354. png_debug1(1, "in %s storage function\n", "iCCP");
  191355. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  191356. return;
  191357. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  191358. if (new_iccp_name == NULL)
  191359. {
  191360. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  191361. return;
  191362. }
  191363. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  191364. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  191365. if (new_iccp_profile == NULL)
  191366. {
  191367. png_free (png_ptr, new_iccp_name);
  191368. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  191369. return;
  191370. }
  191371. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  191372. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  191373. info_ptr->iccp_proflen = proflen;
  191374. info_ptr->iccp_name = new_iccp_name;
  191375. info_ptr->iccp_profile = new_iccp_profile;
  191376. /* Compression is always zero but is here so the API and info structure
  191377. * does not have to change if we introduce multiple compression types */
  191378. info_ptr->iccp_compression = (png_byte)compression_type;
  191379. #ifdef PNG_FREE_ME_SUPPORTED
  191380. info_ptr->free_me |= PNG_FREE_ICCP;
  191381. #endif
  191382. info_ptr->valid |= PNG_INFO_iCCP;
  191383. }
  191384. #endif
  191385. #if defined(PNG_TEXT_SUPPORTED)
  191386. void PNGAPI
  191387. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  191388. int num_text)
  191389. {
  191390. int ret;
  191391. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  191392. if (ret)
  191393. png_error(png_ptr, "Insufficient memory to store text");
  191394. }
  191395. int /* PRIVATE */
  191396. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  191397. int num_text)
  191398. {
  191399. int i;
  191400. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  191401. "text" : (png_const_charp)png_ptr->chunk_name));
  191402. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  191403. return(0);
  191404. /* Make sure we have enough space in the "text" array in info_struct
  191405. * to hold all of the incoming text_ptr objects.
  191406. */
  191407. if (info_ptr->num_text + num_text > info_ptr->max_text)
  191408. {
  191409. if (info_ptr->text != NULL)
  191410. {
  191411. png_textp old_text;
  191412. int old_max;
  191413. old_max = info_ptr->max_text;
  191414. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  191415. old_text = info_ptr->text;
  191416. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  191417. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  191418. if (info_ptr->text == NULL)
  191419. {
  191420. png_free(png_ptr, old_text);
  191421. return(1);
  191422. }
  191423. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  191424. png_sizeof(png_text)));
  191425. png_free(png_ptr, old_text);
  191426. }
  191427. else
  191428. {
  191429. info_ptr->max_text = num_text + 8;
  191430. info_ptr->num_text = 0;
  191431. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  191432. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  191433. if (info_ptr->text == NULL)
  191434. return(1);
  191435. #ifdef PNG_FREE_ME_SUPPORTED
  191436. info_ptr->free_me |= PNG_FREE_TEXT;
  191437. #endif
  191438. }
  191439. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  191440. info_ptr->max_text);
  191441. }
  191442. for (i = 0; i < num_text; i++)
  191443. {
  191444. png_size_t text_length,key_len;
  191445. png_size_t lang_len,lang_key_len;
  191446. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  191447. if (text_ptr[i].key == NULL)
  191448. continue;
  191449. key_len = png_strlen(text_ptr[i].key);
  191450. if(text_ptr[i].compression <= 0)
  191451. {
  191452. lang_len = 0;
  191453. lang_key_len = 0;
  191454. }
  191455. else
  191456. #ifdef PNG_iTXt_SUPPORTED
  191457. {
  191458. /* set iTXt data */
  191459. if (text_ptr[i].lang != NULL)
  191460. lang_len = png_strlen(text_ptr[i].lang);
  191461. else
  191462. lang_len = 0;
  191463. if (text_ptr[i].lang_key != NULL)
  191464. lang_key_len = png_strlen(text_ptr[i].lang_key);
  191465. else
  191466. lang_key_len = 0;
  191467. }
  191468. #else
  191469. {
  191470. png_warning(png_ptr, "iTXt chunk not supported.");
  191471. continue;
  191472. }
  191473. #endif
  191474. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  191475. {
  191476. text_length = 0;
  191477. #ifdef PNG_iTXt_SUPPORTED
  191478. if(text_ptr[i].compression > 0)
  191479. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  191480. else
  191481. #endif
  191482. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  191483. }
  191484. else
  191485. {
  191486. text_length = png_strlen(text_ptr[i].text);
  191487. textp->compression = text_ptr[i].compression;
  191488. }
  191489. textp->key = (png_charp)png_malloc_warn(png_ptr,
  191490. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  191491. if (textp->key == NULL)
  191492. return(1);
  191493. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  191494. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  191495. (int)textp->key);
  191496. png_memcpy(textp->key, text_ptr[i].key,
  191497. (png_size_t)(key_len));
  191498. *(textp->key+key_len) = '\0';
  191499. #ifdef PNG_iTXt_SUPPORTED
  191500. if (text_ptr[i].compression > 0)
  191501. {
  191502. textp->lang=textp->key + key_len + 1;
  191503. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  191504. *(textp->lang+lang_len) = '\0';
  191505. textp->lang_key=textp->lang + lang_len + 1;
  191506. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  191507. *(textp->lang_key+lang_key_len) = '\0';
  191508. textp->text=textp->lang_key + lang_key_len + 1;
  191509. }
  191510. else
  191511. #endif
  191512. {
  191513. #ifdef PNG_iTXt_SUPPORTED
  191514. textp->lang=NULL;
  191515. textp->lang_key=NULL;
  191516. #endif
  191517. textp->text=textp->key + key_len + 1;
  191518. }
  191519. if(text_length)
  191520. png_memcpy(textp->text, text_ptr[i].text,
  191521. (png_size_t)(text_length));
  191522. *(textp->text+text_length) = '\0';
  191523. #ifdef PNG_iTXt_SUPPORTED
  191524. if(textp->compression > 0)
  191525. {
  191526. textp->text_length = 0;
  191527. textp->itxt_length = text_length;
  191528. }
  191529. else
  191530. #endif
  191531. {
  191532. textp->text_length = text_length;
  191533. #ifdef PNG_iTXt_SUPPORTED
  191534. textp->itxt_length = 0;
  191535. #endif
  191536. }
  191537. info_ptr->num_text++;
  191538. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  191539. }
  191540. return(0);
  191541. }
  191542. #endif
  191543. #if defined(PNG_tIME_SUPPORTED)
  191544. void PNGAPI
  191545. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  191546. {
  191547. png_debug1(1, "in %s storage function\n", "tIME");
  191548. if (png_ptr == NULL || info_ptr == NULL ||
  191549. (png_ptr->mode & PNG_WROTE_tIME))
  191550. return;
  191551. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  191552. info_ptr->valid |= PNG_INFO_tIME;
  191553. }
  191554. #endif
  191555. #if defined(PNG_tRNS_SUPPORTED)
  191556. void PNGAPI
  191557. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  191558. png_bytep trans, int num_trans, png_color_16p trans_values)
  191559. {
  191560. png_debug1(1, "in %s storage function\n", "tRNS");
  191561. if (png_ptr == NULL || info_ptr == NULL)
  191562. return;
  191563. if (trans != NULL)
  191564. {
  191565. /*
  191566. * It may not actually be necessary to set png_ptr->trans here;
  191567. * we do it for backward compatibility with the way the png_handle_tRNS
  191568. * function used to do the allocation.
  191569. */
  191570. #ifdef PNG_FREE_ME_SUPPORTED
  191571. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  191572. #endif
  191573. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  191574. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  191575. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  191576. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  191577. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  191578. #ifdef PNG_FREE_ME_SUPPORTED
  191579. info_ptr->free_me |= PNG_FREE_TRNS;
  191580. #else
  191581. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  191582. #endif
  191583. }
  191584. if (trans_values != NULL)
  191585. {
  191586. png_memcpy(&(info_ptr->trans_values), trans_values,
  191587. png_sizeof(png_color_16));
  191588. if (num_trans == 0)
  191589. num_trans = 1;
  191590. }
  191591. info_ptr->num_trans = (png_uint_16)num_trans;
  191592. info_ptr->valid |= PNG_INFO_tRNS;
  191593. }
  191594. #endif
  191595. #if defined(PNG_sPLT_SUPPORTED)
  191596. void PNGAPI
  191597. png_set_sPLT(png_structp png_ptr,
  191598. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  191599. {
  191600. png_sPLT_tp np;
  191601. int i;
  191602. if (png_ptr == NULL || info_ptr == NULL)
  191603. return;
  191604. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  191605. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  191606. if (np == NULL)
  191607. {
  191608. png_warning(png_ptr, "No memory for sPLT palettes.");
  191609. return;
  191610. }
  191611. png_memcpy(np, info_ptr->splt_palettes,
  191612. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  191613. png_free(png_ptr, info_ptr->splt_palettes);
  191614. info_ptr->splt_palettes=NULL;
  191615. for (i = 0; i < nentries; i++)
  191616. {
  191617. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  191618. png_sPLT_tp from = entries + i;
  191619. to->name = (png_charp)png_malloc_warn(png_ptr,
  191620. png_strlen(from->name) + 1);
  191621. if (to->name == NULL)
  191622. {
  191623. png_warning(png_ptr,
  191624. "Out of memory while processing sPLT chunk");
  191625. }
  191626. /* TODO: use png_malloc_warn */
  191627. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  191628. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  191629. from->nentries * png_sizeof(png_sPLT_entry));
  191630. /* TODO: use png_malloc_warn */
  191631. png_memcpy(to->entries, from->entries,
  191632. from->nentries * png_sizeof(png_sPLT_entry));
  191633. if (to->entries == NULL)
  191634. {
  191635. png_warning(png_ptr,
  191636. "Out of memory while processing sPLT chunk");
  191637. png_free(png_ptr,to->name);
  191638. to->name = NULL;
  191639. }
  191640. to->nentries = from->nentries;
  191641. to->depth = from->depth;
  191642. }
  191643. info_ptr->splt_palettes = np;
  191644. info_ptr->splt_palettes_num += nentries;
  191645. info_ptr->valid |= PNG_INFO_sPLT;
  191646. #ifdef PNG_FREE_ME_SUPPORTED
  191647. info_ptr->free_me |= PNG_FREE_SPLT;
  191648. #endif
  191649. }
  191650. #endif /* PNG_sPLT_SUPPORTED */
  191651. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  191652. void PNGAPI
  191653. png_set_unknown_chunks(png_structp png_ptr,
  191654. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  191655. {
  191656. png_unknown_chunkp np;
  191657. int i;
  191658. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  191659. return;
  191660. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  191661. (info_ptr->unknown_chunks_num + num_unknowns) *
  191662. png_sizeof(png_unknown_chunk));
  191663. if (np == NULL)
  191664. {
  191665. png_warning(png_ptr,
  191666. "Out of memory while processing unknown chunk.");
  191667. return;
  191668. }
  191669. png_memcpy(np, info_ptr->unknown_chunks,
  191670. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  191671. png_free(png_ptr, info_ptr->unknown_chunks);
  191672. info_ptr->unknown_chunks=NULL;
  191673. for (i = 0; i < num_unknowns; i++)
  191674. {
  191675. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  191676. png_unknown_chunkp from = unknowns + i;
  191677. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  191678. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  191679. if (to->data == NULL)
  191680. {
  191681. png_warning(png_ptr,
  191682. "Out of memory while processing unknown chunk.");
  191683. }
  191684. else
  191685. {
  191686. png_memcpy(to->data, from->data, from->size);
  191687. to->size = from->size;
  191688. /* note our location in the read or write sequence */
  191689. to->location = (png_byte)(png_ptr->mode & 0xff);
  191690. }
  191691. }
  191692. info_ptr->unknown_chunks = np;
  191693. info_ptr->unknown_chunks_num += num_unknowns;
  191694. #ifdef PNG_FREE_ME_SUPPORTED
  191695. info_ptr->free_me |= PNG_FREE_UNKN;
  191696. #endif
  191697. }
  191698. void PNGAPI
  191699. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  191700. int chunk, int location)
  191701. {
  191702. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  191703. (int)info_ptr->unknown_chunks_num)
  191704. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  191705. }
  191706. #endif
  191707. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  191708. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  191709. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  191710. void PNGAPI
  191711. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  191712. {
  191713. /* This function is deprecated in favor of png_permit_mng_features()
  191714. and will be removed from libpng-1.3.0 */
  191715. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  191716. if (png_ptr == NULL)
  191717. return;
  191718. png_ptr->mng_features_permitted = (png_byte)
  191719. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  191720. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  191721. }
  191722. #endif
  191723. #endif
  191724. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  191725. png_uint_32 PNGAPI
  191726. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  191727. {
  191728. png_debug(1, "in png_permit_mng_features\n");
  191729. if (png_ptr == NULL)
  191730. return (png_uint_32)0;
  191731. png_ptr->mng_features_permitted =
  191732. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  191733. return (png_uint_32)png_ptr->mng_features_permitted;
  191734. }
  191735. #endif
  191736. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  191737. void PNGAPI
  191738. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  191739. chunk_list, int num_chunks)
  191740. {
  191741. png_bytep new_list, p;
  191742. int i, old_num_chunks;
  191743. if (png_ptr == NULL)
  191744. return;
  191745. if (num_chunks == 0)
  191746. {
  191747. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  191748. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  191749. else
  191750. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  191751. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  191752. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  191753. else
  191754. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  191755. return;
  191756. }
  191757. if (chunk_list == NULL)
  191758. return;
  191759. old_num_chunks=png_ptr->num_chunk_list;
  191760. new_list=(png_bytep)png_malloc(png_ptr,
  191761. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  191762. if(png_ptr->chunk_list != NULL)
  191763. {
  191764. png_memcpy(new_list, png_ptr->chunk_list,
  191765. (png_size_t)(5*old_num_chunks));
  191766. png_free(png_ptr, png_ptr->chunk_list);
  191767. png_ptr->chunk_list=NULL;
  191768. }
  191769. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  191770. (png_size_t)(5*num_chunks));
  191771. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  191772. *p=(png_byte)keep;
  191773. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  191774. png_ptr->chunk_list=new_list;
  191775. #ifdef PNG_FREE_ME_SUPPORTED
  191776. png_ptr->free_me |= PNG_FREE_LIST;
  191777. #endif
  191778. }
  191779. #endif
  191780. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  191781. void PNGAPI
  191782. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  191783. png_user_chunk_ptr read_user_chunk_fn)
  191784. {
  191785. png_debug(1, "in png_set_read_user_chunk_fn\n");
  191786. if (png_ptr == NULL)
  191787. return;
  191788. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  191789. png_ptr->user_chunk_ptr = user_chunk_ptr;
  191790. }
  191791. #endif
  191792. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  191793. void PNGAPI
  191794. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  191795. {
  191796. png_debug1(1, "in %s storage function\n", "rows");
  191797. if (png_ptr == NULL || info_ptr == NULL)
  191798. return;
  191799. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  191800. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  191801. info_ptr->row_pointers = row_pointers;
  191802. if(row_pointers)
  191803. info_ptr->valid |= PNG_INFO_IDAT;
  191804. }
  191805. #endif
  191806. #ifdef PNG_WRITE_SUPPORTED
  191807. void PNGAPI
  191808. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  191809. {
  191810. if (png_ptr == NULL)
  191811. return;
  191812. if(png_ptr->zbuf)
  191813. png_free(png_ptr, png_ptr->zbuf);
  191814. png_ptr->zbuf_size = (png_size_t)size;
  191815. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  191816. png_ptr->zstream.next_out = png_ptr->zbuf;
  191817. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  191818. }
  191819. #endif
  191820. void PNGAPI
  191821. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  191822. {
  191823. if (png_ptr && info_ptr)
  191824. info_ptr->valid &= ~(mask);
  191825. }
  191826. #ifndef PNG_1_0_X
  191827. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  191828. /* function was added to libpng 1.2.0 and should always exist by default */
  191829. void PNGAPI
  191830. png_set_asm_flags (png_structp png_ptr, png_uint_32 asm_flags)
  191831. {
  191832. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  191833. if (png_ptr != NULL)
  191834. png_ptr->asm_flags = 0;
  191835. }
  191836. /* this function was added to libpng 1.2.0 */
  191837. void PNGAPI
  191838. png_set_mmx_thresholds (png_structp png_ptr,
  191839. png_byte mmx_bitdepth_threshold,
  191840. png_uint_32 mmx_rowbytes_threshold)
  191841. {
  191842. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  191843. if (png_ptr == NULL)
  191844. return;
  191845. }
  191846. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  191847. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  191848. /* this function was added to libpng 1.2.6 */
  191849. void PNGAPI
  191850. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  191851. png_uint_32 user_height_max)
  191852. {
  191853. /* Images with dimensions larger than these limits will be
  191854. * rejected by png_set_IHDR(). To accept any PNG datastream
  191855. * regardless of dimensions, set both limits to 0x7ffffffL.
  191856. */
  191857. if(png_ptr == NULL) return;
  191858. png_ptr->user_width_max = user_width_max;
  191859. png_ptr->user_height_max = user_height_max;
  191860. }
  191861. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  191862. #endif /* ?PNG_1_0_X */
  191863. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  191864. /********* End of inlined file: pngset.c *********/
  191865. /********* Start of inlined file: pngtrans.c *********/
  191866. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  191867. *
  191868. * Last changed in libpng 1.2.17 May 15, 2007
  191869. * For conditions of distribution and use, see copyright notice in png.h
  191870. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  191871. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  191872. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  191873. */
  191874. #define PNG_INTERNAL
  191875. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  191876. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  191877. /* turn on BGR-to-RGB mapping */
  191878. void PNGAPI
  191879. png_set_bgr(png_structp png_ptr)
  191880. {
  191881. png_debug(1, "in png_set_bgr\n");
  191882. if(png_ptr == NULL) return;
  191883. png_ptr->transformations |= PNG_BGR;
  191884. }
  191885. #endif
  191886. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  191887. /* turn on 16 bit byte swapping */
  191888. void PNGAPI
  191889. png_set_swap(png_structp png_ptr)
  191890. {
  191891. png_debug(1, "in png_set_swap\n");
  191892. if(png_ptr == NULL) return;
  191893. if (png_ptr->bit_depth == 16)
  191894. png_ptr->transformations |= PNG_SWAP_BYTES;
  191895. }
  191896. #endif
  191897. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  191898. /* turn on pixel packing */
  191899. void PNGAPI
  191900. png_set_packing(png_structp png_ptr)
  191901. {
  191902. png_debug(1, "in png_set_packing\n");
  191903. if(png_ptr == NULL) return;
  191904. if (png_ptr->bit_depth < 8)
  191905. {
  191906. png_ptr->transformations |= PNG_PACK;
  191907. png_ptr->usr_bit_depth = 8;
  191908. }
  191909. }
  191910. #endif
  191911. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  191912. /* turn on packed pixel swapping */
  191913. void PNGAPI
  191914. png_set_packswap(png_structp png_ptr)
  191915. {
  191916. png_debug(1, "in png_set_packswap\n");
  191917. if(png_ptr == NULL) return;
  191918. if (png_ptr->bit_depth < 8)
  191919. png_ptr->transformations |= PNG_PACKSWAP;
  191920. }
  191921. #endif
  191922. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  191923. void PNGAPI
  191924. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  191925. {
  191926. png_debug(1, "in png_set_shift\n");
  191927. if(png_ptr == NULL) return;
  191928. png_ptr->transformations |= PNG_SHIFT;
  191929. png_ptr->shift = *true_bits;
  191930. }
  191931. #endif
  191932. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  191933. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  191934. int PNGAPI
  191935. png_set_interlace_handling(png_structp png_ptr)
  191936. {
  191937. png_debug(1, "in png_set_interlace handling\n");
  191938. if (png_ptr && png_ptr->interlaced)
  191939. {
  191940. png_ptr->transformations |= PNG_INTERLACE;
  191941. return (7);
  191942. }
  191943. return (1);
  191944. }
  191945. #endif
  191946. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  191947. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  191948. * The filler type has changed in v0.95 to allow future 2-byte fillers
  191949. * for 48-bit input data, as well as to avoid problems with some compilers
  191950. * that don't like bytes as parameters.
  191951. */
  191952. void PNGAPI
  191953. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  191954. {
  191955. png_debug(1, "in png_set_filler\n");
  191956. if(png_ptr == NULL) return;
  191957. png_ptr->transformations |= PNG_FILLER;
  191958. png_ptr->filler = (png_byte)filler;
  191959. if (filler_loc == PNG_FILLER_AFTER)
  191960. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  191961. else
  191962. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  191963. /* This should probably go in the "do_read_filler" routine.
  191964. * I attempted to do that in libpng-1.0.1a but that caused problems
  191965. * so I restored it in libpng-1.0.2a
  191966. */
  191967. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  191968. {
  191969. png_ptr->usr_channels = 4;
  191970. }
  191971. /* Also I added this in libpng-1.0.2a (what happens when we expand
  191972. * a less-than-8-bit grayscale to GA? */
  191973. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  191974. {
  191975. png_ptr->usr_channels = 2;
  191976. }
  191977. }
  191978. #if !defined(PNG_1_0_X)
  191979. /* Added to libpng-1.2.7 */
  191980. void PNGAPI
  191981. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  191982. {
  191983. png_debug(1, "in png_set_add_alpha\n");
  191984. if(png_ptr == NULL) return;
  191985. png_set_filler(png_ptr, filler, filler_loc);
  191986. png_ptr->transformations |= PNG_ADD_ALPHA;
  191987. }
  191988. #endif
  191989. #endif
  191990. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  191991. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  191992. void PNGAPI
  191993. png_set_swap_alpha(png_structp png_ptr)
  191994. {
  191995. png_debug(1, "in png_set_swap_alpha\n");
  191996. if(png_ptr == NULL) return;
  191997. png_ptr->transformations |= PNG_SWAP_ALPHA;
  191998. }
  191999. #endif
  192000. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  192001. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  192002. void PNGAPI
  192003. png_set_invert_alpha(png_structp png_ptr)
  192004. {
  192005. png_debug(1, "in png_set_invert_alpha\n");
  192006. if(png_ptr == NULL) return;
  192007. png_ptr->transformations |= PNG_INVERT_ALPHA;
  192008. }
  192009. #endif
  192010. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  192011. void PNGAPI
  192012. png_set_invert_mono(png_structp png_ptr)
  192013. {
  192014. png_debug(1, "in png_set_invert_mono\n");
  192015. if(png_ptr == NULL) return;
  192016. png_ptr->transformations |= PNG_INVERT_MONO;
  192017. }
  192018. /* invert monochrome grayscale data */
  192019. void /* PRIVATE */
  192020. png_do_invert(png_row_infop row_info, png_bytep row)
  192021. {
  192022. png_debug(1, "in png_do_invert\n");
  192023. /* This test removed from libpng version 1.0.13 and 1.2.0:
  192024. * if (row_info->bit_depth == 1 &&
  192025. */
  192026. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192027. if (row == NULL || row_info == NULL)
  192028. return;
  192029. #endif
  192030. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192031. {
  192032. png_bytep rp = row;
  192033. png_uint_32 i;
  192034. png_uint_32 istop = row_info->rowbytes;
  192035. for (i = 0; i < istop; i++)
  192036. {
  192037. *rp = (png_byte)(~(*rp));
  192038. rp++;
  192039. }
  192040. }
  192041. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  192042. row_info->bit_depth == 8)
  192043. {
  192044. png_bytep rp = row;
  192045. png_uint_32 i;
  192046. png_uint_32 istop = row_info->rowbytes;
  192047. for (i = 0; i < istop; i+=2)
  192048. {
  192049. *rp = (png_byte)(~(*rp));
  192050. rp+=2;
  192051. }
  192052. }
  192053. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  192054. row_info->bit_depth == 16)
  192055. {
  192056. png_bytep rp = row;
  192057. png_uint_32 i;
  192058. png_uint_32 istop = row_info->rowbytes;
  192059. for (i = 0; i < istop; i+=4)
  192060. {
  192061. *rp = (png_byte)(~(*rp));
  192062. *(rp+1) = (png_byte)(~(*(rp+1)));
  192063. rp+=4;
  192064. }
  192065. }
  192066. }
  192067. #endif
  192068. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  192069. /* swaps byte order on 16 bit depth images */
  192070. void /* PRIVATE */
  192071. png_do_swap(png_row_infop row_info, png_bytep row)
  192072. {
  192073. png_debug(1, "in png_do_swap\n");
  192074. if (
  192075. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192076. row != NULL && row_info != NULL &&
  192077. #endif
  192078. row_info->bit_depth == 16)
  192079. {
  192080. png_bytep rp = row;
  192081. png_uint_32 i;
  192082. png_uint_32 istop= row_info->width * row_info->channels;
  192083. for (i = 0; i < istop; i++, rp += 2)
  192084. {
  192085. png_byte t = *rp;
  192086. *rp = *(rp + 1);
  192087. *(rp + 1) = t;
  192088. }
  192089. }
  192090. }
  192091. #endif
  192092. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  192093. static PNG_CONST png_byte onebppswaptable[256] = {
  192094. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  192095. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  192096. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  192097. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  192098. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  192099. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  192100. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  192101. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  192102. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  192103. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  192104. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  192105. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  192106. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  192107. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  192108. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  192109. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  192110. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  192111. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  192112. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  192113. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  192114. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  192115. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  192116. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  192117. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  192118. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  192119. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  192120. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  192121. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  192122. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  192123. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  192124. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  192125. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  192126. };
  192127. static PNG_CONST png_byte twobppswaptable[256] = {
  192128. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  192129. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  192130. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  192131. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  192132. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  192133. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  192134. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  192135. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  192136. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  192137. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  192138. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  192139. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  192140. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  192141. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  192142. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  192143. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  192144. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  192145. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  192146. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  192147. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  192148. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  192149. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  192150. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  192151. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  192152. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  192153. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  192154. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  192155. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  192156. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  192157. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  192158. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  192159. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  192160. };
  192161. static PNG_CONST png_byte fourbppswaptable[256] = {
  192162. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  192163. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  192164. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  192165. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  192166. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  192167. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  192168. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  192169. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  192170. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  192171. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  192172. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  192173. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  192174. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  192175. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  192176. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  192177. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  192178. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  192179. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  192180. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  192181. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  192182. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  192183. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  192184. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  192185. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  192186. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  192187. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  192188. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  192189. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  192190. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  192191. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  192192. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  192193. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  192194. };
  192195. /* swaps pixel packing order within bytes */
  192196. void /* PRIVATE */
  192197. png_do_packswap(png_row_infop row_info, png_bytep row)
  192198. {
  192199. png_debug(1, "in png_do_packswap\n");
  192200. if (
  192201. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192202. row != NULL && row_info != NULL &&
  192203. #endif
  192204. row_info->bit_depth < 8)
  192205. {
  192206. png_bytep rp, end, table;
  192207. end = row + row_info->rowbytes;
  192208. if (row_info->bit_depth == 1)
  192209. table = (png_bytep)onebppswaptable;
  192210. else if (row_info->bit_depth == 2)
  192211. table = (png_bytep)twobppswaptable;
  192212. else if (row_info->bit_depth == 4)
  192213. table = (png_bytep)fourbppswaptable;
  192214. else
  192215. return;
  192216. for (rp = row; rp < end; rp++)
  192217. *rp = table[*rp];
  192218. }
  192219. }
  192220. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  192221. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  192222. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  192223. /* remove filler or alpha byte(s) */
  192224. void /* PRIVATE */
  192225. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  192226. {
  192227. png_debug(1, "in png_do_strip_filler\n");
  192228. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192229. if (row != NULL && row_info != NULL)
  192230. #endif
  192231. {
  192232. png_bytep sp=row;
  192233. png_bytep dp=row;
  192234. png_uint_32 row_width=row_info->width;
  192235. png_uint_32 i;
  192236. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  192237. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  192238. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  192239. row_info->channels == 4)
  192240. {
  192241. if (row_info->bit_depth == 8)
  192242. {
  192243. /* This converts from RGBX or RGBA to RGB */
  192244. if (flags & PNG_FLAG_FILLER_AFTER)
  192245. {
  192246. dp+=3; sp+=4;
  192247. for (i = 1; i < row_width; i++)
  192248. {
  192249. *dp++ = *sp++;
  192250. *dp++ = *sp++;
  192251. *dp++ = *sp++;
  192252. sp++;
  192253. }
  192254. }
  192255. /* This converts from XRGB or ARGB to RGB */
  192256. else
  192257. {
  192258. for (i = 0; i < row_width; i++)
  192259. {
  192260. sp++;
  192261. *dp++ = *sp++;
  192262. *dp++ = *sp++;
  192263. *dp++ = *sp++;
  192264. }
  192265. }
  192266. row_info->pixel_depth = 24;
  192267. row_info->rowbytes = row_width * 3;
  192268. }
  192269. else /* if (row_info->bit_depth == 16) */
  192270. {
  192271. if (flags & PNG_FLAG_FILLER_AFTER)
  192272. {
  192273. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  192274. sp += 8; dp += 6;
  192275. for (i = 1; i < row_width; i++)
  192276. {
  192277. /* This could be (although png_memcpy is probably slower):
  192278. png_memcpy(dp, sp, 6);
  192279. sp += 8;
  192280. dp += 6;
  192281. */
  192282. *dp++ = *sp++;
  192283. *dp++ = *sp++;
  192284. *dp++ = *sp++;
  192285. *dp++ = *sp++;
  192286. *dp++ = *sp++;
  192287. *dp++ = *sp++;
  192288. sp += 2;
  192289. }
  192290. }
  192291. else
  192292. {
  192293. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  192294. for (i = 0; i < row_width; i++)
  192295. {
  192296. /* This could be (although png_memcpy is probably slower):
  192297. png_memcpy(dp, sp, 6);
  192298. sp += 8;
  192299. dp += 6;
  192300. */
  192301. sp+=2;
  192302. *dp++ = *sp++;
  192303. *dp++ = *sp++;
  192304. *dp++ = *sp++;
  192305. *dp++ = *sp++;
  192306. *dp++ = *sp++;
  192307. *dp++ = *sp++;
  192308. }
  192309. }
  192310. row_info->pixel_depth = 48;
  192311. row_info->rowbytes = row_width * 6;
  192312. }
  192313. row_info->channels = 3;
  192314. }
  192315. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  192316. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  192317. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  192318. row_info->channels == 2)
  192319. {
  192320. if (row_info->bit_depth == 8)
  192321. {
  192322. /* This converts from GX or GA to G */
  192323. if (flags & PNG_FLAG_FILLER_AFTER)
  192324. {
  192325. for (i = 0; i < row_width; i++)
  192326. {
  192327. *dp++ = *sp++;
  192328. sp++;
  192329. }
  192330. }
  192331. /* This converts from XG or AG to G */
  192332. else
  192333. {
  192334. for (i = 0; i < row_width; i++)
  192335. {
  192336. sp++;
  192337. *dp++ = *sp++;
  192338. }
  192339. }
  192340. row_info->pixel_depth = 8;
  192341. row_info->rowbytes = row_width;
  192342. }
  192343. else /* if (row_info->bit_depth == 16) */
  192344. {
  192345. if (flags & PNG_FLAG_FILLER_AFTER)
  192346. {
  192347. /* This converts from GGXX or GGAA to GG */
  192348. sp += 4; dp += 2;
  192349. for (i = 1; i < row_width; i++)
  192350. {
  192351. *dp++ = *sp++;
  192352. *dp++ = *sp++;
  192353. sp += 2;
  192354. }
  192355. }
  192356. else
  192357. {
  192358. /* This converts from XXGG or AAGG to GG */
  192359. for (i = 0; i < row_width; i++)
  192360. {
  192361. sp += 2;
  192362. *dp++ = *sp++;
  192363. *dp++ = *sp++;
  192364. }
  192365. }
  192366. row_info->pixel_depth = 16;
  192367. row_info->rowbytes = row_width * 2;
  192368. }
  192369. row_info->channels = 1;
  192370. }
  192371. if (flags & PNG_FLAG_STRIP_ALPHA)
  192372. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  192373. }
  192374. }
  192375. #endif
  192376. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  192377. /* swaps red and blue bytes within a pixel */
  192378. void /* PRIVATE */
  192379. png_do_bgr(png_row_infop row_info, png_bytep row)
  192380. {
  192381. png_debug(1, "in png_do_bgr\n");
  192382. if (
  192383. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192384. row != NULL && row_info != NULL &&
  192385. #endif
  192386. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192387. {
  192388. png_uint_32 row_width = row_info->width;
  192389. if (row_info->bit_depth == 8)
  192390. {
  192391. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192392. {
  192393. png_bytep rp;
  192394. png_uint_32 i;
  192395. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  192396. {
  192397. png_byte save = *rp;
  192398. *rp = *(rp + 2);
  192399. *(rp + 2) = save;
  192400. }
  192401. }
  192402. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192403. {
  192404. png_bytep rp;
  192405. png_uint_32 i;
  192406. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  192407. {
  192408. png_byte save = *rp;
  192409. *rp = *(rp + 2);
  192410. *(rp + 2) = save;
  192411. }
  192412. }
  192413. }
  192414. else if (row_info->bit_depth == 16)
  192415. {
  192416. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192417. {
  192418. png_bytep rp;
  192419. png_uint_32 i;
  192420. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  192421. {
  192422. png_byte save = *rp;
  192423. *rp = *(rp + 4);
  192424. *(rp + 4) = save;
  192425. save = *(rp + 1);
  192426. *(rp + 1) = *(rp + 5);
  192427. *(rp + 5) = save;
  192428. }
  192429. }
  192430. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192431. {
  192432. png_bytep rp;
  192433. png_uint_32 i;
  192434. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  192435. {
  192436. png_byte save = *rp;
  192437. *rp = *(rp + 4);
  192438. *(rp + 4) = save;
  192439. save = *(rp + 1);
  192440. *(rp + 1) = *(rp + 5);
  192441. *(rp + 5) = save;
  192442. }
  192443. }
  192444. }
  192445. }
  192446. }
  192447. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  192448. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  192449. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  192450. defined(PNG_LEGACY_SUPPORTED)
  192451. void PNGAPI
  192452. png_set_user_transform_info(png_structp png_ptr, png_voidp
  192453. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  192454. {
  192455. png_debug(1, "in png_set_user_transform_info\n");
  192456. if(png_ptr == NULL) return;
  192457. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  192458. png_ptr->user_transform_ptr = user_transform_ptr;
  192459. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  192460. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  192461. #else
  192462. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  192463. png_warning(png_ptr,
  192464. "This version of libpng does not support user transform info");
  192465. #endif
  192466. }
  192467. #endif
  192468. /* This function returns a pointer to the user_transform_ptr associated with
  192469. * the user transform functions. The application should free any memory
  192470. * associated with this pointer before png_write_destroy and png_read_destroy
  192471. * are called.
  192472. */
  192473. png_voidp PNGAPI
  192474. png_get_user_transform_ptr(png_structp png_ptr)
  192475. {
  192476. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  192477. if (png_ptr == NULL) return (NULL);
  192478. return ((png_voidp)png_ptr->user_transform_ptr);
  192479. #else
  192480. return (NULL);
  192481. #endif
  192482. }
  192483. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  192484. /********* End of inlined file: pngtrans.c *********/
  192485. /********* Start of inlined file: pngwio.c *********/
  192486. /* pngwio.c - functions for data output
  192487. *
  192488. * Last changed in libpng 1.2.13 November 13, 2006
  192489. * For conditions of distribution and use, see copyright notice in png.h
  192490. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  192491. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  192492. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  192493. *
  192494. * This file provides a location for all output. Users who need
  192495. * special handling are expected to write functions that have the same
  192496. * arguments as these and perform similar functions, but that possibly
  192497. * use different output methods. Note that you shouldn't change these
  192498. * functions, but rather write replacement functions and then change
  192499. * them at run time with png_set_write_fn(...).
  192500. */
  192501. #define PNG_INTERNAL
  192502. #ifdef PNG_WRITE_SUPPORTED
  192503. /* Write the data to whatever output you are using. The default routine
  192504. writes to a file pointer. Note that this routine sometimes gets called
  192505. with very small lengths, so you should implement some kind of simple
  192506. buffering if you are using unbuffered writes. This should never be asked
  192507. to write more than 64K on a 16 bit machine. */
  192508. void /* PRIVATE */
  192509. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  192510. {
  192511. if (png_ptr->write_data_fn != NULL )
  192512. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  192513. else
  192514. png_error(png_ptr, "Call to NULL write function");
  192515. }
  192516. #if !defined(PNG_NO_STDIO)
  192517. /* This is the function that does the actual writing of data. If you are
  192518. not writing to a standard C stream, you should create a replacement
  192519. write_data function and use it at run time with png_set_write_fn(), rather
  192520. than changing the library. */
  192521. #ifndef USE_FAR_KEYWORD
  192522. void PNGAPI
  192523. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  192524. {
  192525. png_uint_32 check;
  192526. if(png_ptr == NULL) return;
  192527. #if defined(_WIN32_WCE)
  192528. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  192529. check = 0;
  192530. #else
  192531. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  192532. #endif
  192533. if (check != length)
  192534. png_error(png_ptr, "Write Error");
  192535. }
  192536. #else
  192537. /* this is the model-independent version. Since the standard I/O library
  192538. can't handle far buffers in the medium and small models, we have to copy
  192539. the data.
  192540. */
  192541. #define NEAR_BUF_SIZE 1024
  192542. #define MIN(a,b) (a <= b ? a : b)
  192543. void PNGAPI
  192544. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  192545. {
  192546. png_uint_32 check;
  192547. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  192548. png_FILE_p io_ptr;
  192549. if(png_ptr == NULL) return;
  192550. /* Check if data really is near. If so, use usual code. */
  192551. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  192552. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  192553. if ((png_bytep)near_data == data)
  192554. {
  192555. #if defined(_WIN32_WCE)
  192556. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  192557. check = 0;
  192558. #else
  192559. check = fwrite(near_data, 1, length, io_ptr);
  192560. #endif
  192561. }
  192562. else
  192563. {
  192564. png_byte buf[NEAR_BUF_SIZE];
  192565. png_size_t written, remaining, err;
  192566. check = 0;
  192567. remaining = length;
  192568. do
  192569. {
  192570. written = MIN(NEAR_BUF_SIZE, remaining);
  192571. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  192572. #if defined(_WIN32_WCE)
  192573. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  192574. err = 0;
  192575. #else
  192576. err = fwrite(buf, 1, written, io_ptr);
  192577. #endif
  192578. if (err != written)
  192579. break;
  192580. else
  192581. check += err;
  192582. data += written;
  192583. remaining -= written;
  192584. }
  192585. while (remaining != 0);
  192586. }
  192587. if (check != length)
  192588. png_error(png_ptr, "Write Error");
  192589. }
  192590. #endif
  192591. #endif
  192592. /* This function is called to output any data pending writing (normally
  192593. to disk). After png_flush is called, there should be no data pending
  192594. writing in any buffers. */
  192595. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  192596. void /* PRIVATE */
  192597. png_flush(png_structp png_ptr)
  192598. {
  192599. if (png_ptr->output_flush_fn != NULL)
  192600. (*(png_ptr->output_flush_fn))(png_ptr);
  192601. }
  192602. #if !defined(PNG_NO_STDIO)
  192603. void PNGAPI
  192604. png_default_flush(png_structp png_ptr)
  192605. {
  192606. #if !defined(_WIN32_WCE)
  192607. png_FILE_p io_ptr;
  192608. #endif
  192609. if(png_ptr == NULL) return;
  192610. #if !defined(_WIN32_WCE)
  192611. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  192612. if (io_ptr != NULL)
  192613. fflush(io_ptr);
  192614. #endif
  192615. }
  192616. #endif
  192617. #endif
  192618. /* This function allows the application to supply new output functions for
  192619. libpng if standard C streams aren't being used.
  192620. This function takes as its arguments:
  192621. png_ptr - pointer to a png output data structure
  192622. io_ptr - pointer to user supplied structure containing info about
  192623. the output functions. May be NULL.
  192624. write_data_fn - pointer to a new output function that takes as its
  192625. arguments a pointer to a png_struct, a pointer to
  192626. data to be written, and a 32-bit unsigned int that is
  192627. the number of bytes to be written. The new write
  192628. function should call png_error(png_ptr, "Error msg")
  192629. to exit and output any fatal error messages.
  192630. flush_data_fn - pointer to a new flush function that takes as its
  192631. arguments a pointer to a png_struct. After a call to
  192632. the flush function, there should be no data in any buffers
  192633. or pending transmission. If the output method doesn't do
  192634. any buffering of ouput, a function prototype must still be
  192635. supplied although it doesn't have to do anything. If
  192636. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  192637. time, output_flush_fn will be ignored, although it must be
  192638. supplied for compatibility. */
  192639. void PNGAPI
  192640. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  192641. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  192642. {
  192643. if(png_ptr == NULL) return;
  192644. png_ptr->io_ptr = io_ptr;
  192645. #if !defined(PNG_NO_STDIO)
  192646. if (write_data_fn != NULL)
  192647. png_ptr->write_data_fn = write_data_fn;
  192648. else
  192649. png_ptr->write_data_fn = png_default_write_data;
  192650. #else
  192651. png_ptr->write_data_fn = write_data_fn;
  192652. #endif
  192653. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  192654. #if !defined(PNG_NO_STDIO)
  192655. if (output_flush_fn != NULL)
  192656. png_ptr->output_flush_fn = output_flush_fn;
  192657. else
  192658. png_ptr->output_flush_fn = png_default_flush;
  192659. #else
  192660. png_ptr->output_flush_fn = output_flush_fn;
  192661. #endif
  192662. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  192663. /* It is an error to read while writing a png file */
  192664. if (png_ptr->read_data_fn != NULL)
  192665. {
  192666. png_ptr->read_data_fn = NULL;
  192667. png_warning(png_ptr,
  192668. "Attempted to set both read_data_fn and write_data_fn in");
  192669. png_warning(png_ptr,
  192670. "the same structure. Resetting read_data_fn to NULL.");
  192671. }
  192672. }
  192673. #if defined(USE_FAR_KEYWORD)
  192674. #if defined(_MSC_VER)
  192675. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  192676. {
  192677. void *near_ptr;
  192678. void FAR *far_ptr;
  192679. FP_OFF(near_ptr) = FP_OFF(ptr);
  192680. far_ptr = (void FAR *)near_ptr;
  192681. if(check != 0)
  192682. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  192683. png_error(png_ptr,"segment lost in conversion");
  192684. return(near_ptr);
  192685. }
  192686. # else
  192687. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  192688. {
  192689. void *near_ptr;
  192690. void FAR *far_ptr;
  192691. near_ptr = (void FAR *)ptr;
  192692. far_ptr = (void FAR *)near_ptr;
  192693. if(check != 0)
  192694. if(far_ptr != ptr)
  192695. png_error(png_ptr,"segment lost in conversion");
  192696. return(near_ptr);
  192697. }
  192698. # endif
  192699. # endif
  192700. #endif /* PNG_WRITE_SUPPORTED */
  192701. /********* End of inlined file: pngwio.c *********/
  192702. /********* Start of inlined file: pngwrite.c *********/
  192703. /* pngwrite.c - general routines to write a PNG file
  192704. *
  192705. * Last changed in libpng 1.2.15 January 5, 2007
  192706. * For conditions of distribution and use, see copyright notice in png.h
  192707. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  192708. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  192709. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  192710. */
  192711. /* get internal access to png.h */
  192712. #define PNG_INTERNAL
  192713. #ifdef PNG_WRITE_SUPPORTED
  192714. /* Writes all the PNG information. This is the suggested way to use the
  192715. * library. If you have a new chunk to add, make a function to write it,
  192716. * and put it in the correct location here. If you want the chunk written
  192717. * after the image data, put it in png_write_end(). I strongly encourage
  192718. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  192719. * the chunk, as that will keep the code from breaking if you want to just
  192720. * write a plain PNG file. If you have long comments, I suggest writing
  192721. * them in png_write_end(), and compressing them.
  192722. */
  192723. void PNGAPI
  192724. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  192725. {
  192726. png_debug(1, "in png_write_info_before_PLTE\n");
  192727. if (png_ptr == NULL || info_ptr == NULL)
  192728. return;
  192729. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  192730. {
  192731. png_write_sig(png_ptr); /* write PNG signature */
  192732. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  192733. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  192734. {
  192735. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  192736. png_ptr->mng_features_permitted=0;
  192737. }
  192738. #endif
  192739. /* write IHDR information. */
  192740. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  192741. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  192742. info_ptr->filter_type,
  192743. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  192744. info_ptr->interlace_type);
  192745. #else
  192746. 0);
  192747. #endif
  192748. /* the rest of these check to see if the valid field has the appropriate
  192749. flag set, and if it does, writes the chunk. */
  192750. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  192751. if (info_ptr->valid & PNG_INFO_gAMA)
  192752. {
  192753. # ifdef PNG_FLOATING_POINT_SUPPORTED
  192754. png_write_gAMA(png_ptr, info_ptr->gamma);
  192755. #else
  192756. #ifdef PNG_FIXED_POINT_SUPPORTED
  192757. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  192758. # endif
  192759. #endif
  192760. }
  192761. #endif
  192762. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  192763. if (info_ptr->valid & PNG_INFO_sRGB)
  192764. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  192765. #endif
  192766. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  192767. if (info_ptr->valid & PNG_INFO_iCCP)
  192768. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  192769. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  192770. #endif
  192771. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  192772. if (info_ptr->valid & PNG_INFO_sBIT)
  192773. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  192774. #endif
  192775. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  192776. if (info_ptr->valid & PNG_INFO_cHRM)
  192777. {
  192778. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192779. png_write_cHRM(png_ptr,
  192780. info_ptr->x_white, info_ptr->y_white,
  192781. info_ptr->x_red, info_ptr->y_red,
  192782. info_ptr->x_green, info_ptr->y_green,
  192783. info_ptr->x_blue, info_ptr->y_blue);
  192784. #else
  192785. # ifdef PNG_FIXED_POINT_SUPPORTED
  192786. png_write_cHRM_fixed(png_ptr,
  192787. info_ptr->int_x_white, info_ptr->int_y_white,
  192788. info_ptr->int_x_red, info_ptr->int_y_red,
  192789. info_ptr->int_x_green, info_ptr->int_y_green,
  192790. info_ptr->int_x_blue, info_ptr->int_y_blue);
  192791. # endif
  192792. #endif
  192793. }
  192794. #endif
  192795. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  192796. if (info_ptr->unknown_chunks_num)
  192797. {
  192798. png_unknown_chunk *up;
  192799. png_debug(5, "writing extra chunks\n");
  192800. for (up = info_ptr->unknown_chunks;
  192801. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  192802. up++)
  192803. {
  192804. int keep=png_handle_as_unknown(png_ptr, up->name);
  192805. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  192806. up->location && !(up->location & PNG_HAVE_PLTE) &&
  192807. !(up->location & PNG_HAVE_IDAT) &&
  192808. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  192809. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  192810. {
  192811. png_write_chunk(png_ptr, up->name, up->data, up->size);
  192812. }
  192813. }
  192814. }
  192815. #endif
  192816. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  192817. }
  192818. }
  192819. void PNGAPI
  192820. png_write_info(png_structp png_ptr, png_infop info_ptr)
  192821. {
  192822. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  192823. int i;
  192824. #endif
  192825. png_debug(1, "in png_write_info\n");
  192826. if (png_ptr == NULL || info_ptr == NULL)
  192827. return;
  192828. png_write_info_before_PLTE(png_ptr, info_ptr);
  192829. if (info_ptr->valid & PNG_INFO_PLTE)
  192830. png_write_PLTE(png_ptr, info_ptr->palette,
  192831. (png_uint_32)info_ptr->num_palette);
  192832. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192833. png_error(png_ptr, "Valid palette required for paletted images");
  192834. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  192835. if (info_ptr->valid & PNG_INFO_tRNS)
  192836. {
  192837. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  192838. /* invert the alpha channel (in tRNS) */
  192839. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  192840. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192841. {
  192842. int j;
  192843. for (j=0; j<(int)info_ptr->num_trans; j++)
  192844. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  192845. }
  192846. #endif
  192847. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  192848. info_ptr->num_trans, info_ptr->color_type);
  192849. }
  192850. #endif
  192851. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  192852. if (info_ptr->valid & PNG_INFO_bKGD)
  192853. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  192854. #endif
  192855. #if defined(PNG_WRITE_hIST_SUPPORTED)
  192856. if (info_ptr->valid & PNG_INFO_hIST)
  192857. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  192858. #endif
  192859. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  192860. if (info_ptr->valid & PNG_INFO_oFFs)
  192861. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  192862. info_ptr->offset_unit_type);
  192863. #endif
  192864. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  192865. if (info_ptr->valid & PNG_INFO_pCAL)
  192866. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  192867. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  192868. info_ptr->pcal_units, info_ptr->pcal_params);
  192869. #endif
  192870. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  192871. if (info_ptr->valid & PNG_INFO_sCAL)
  192872. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  192873. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  192874. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  192875. #else
  192876. #ifdef PNG_FIXED_POINT_SUPPORTED
  192877. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  192878. info_ptr->scal_s_width, info_ptr->scal_s_height);
  192879. #else
  192880. png_warning(png_ptr,
  192881. "png_write_sCAL not supported; sCAL chunk not written.");
  192882. #endif
  192883. #endif
  192884. #endif
  192885. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  192886. if (info_ptr->valid & PNG_INFO_pHYs)
  192887. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  192888. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  192889. #endif
  192890. #if defined(PNG_WRITE_tIME_SUPPORTED)
  192891. if (info_ptr->valid & PNG_INFO_tIME)
  192892. {
  192893. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  192894. png_ptr->mode |= PNG_WROTE_tIME;
  192895. }
  192896. #endif
  192897. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  192898. if (info_ptr->valid & PNG_INFO_sPLT)
  192899. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  192900. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  192901. #endif
  192902. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  192903. /* Check to see if we need to write text chunks */
  192904. for (i = 0; i < info_ptr->num_text; i++)
  192905. {
  192906. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  192907. info_ptr->text[i].compression);
  192908. /* an internationalized chunk? */
  192909. if (info_ptr->text[i].compression > 0)
  192910. {
  192911. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  192912. /* write international chunk */
  192913. png_write_iTXt(png_ptr,
  192914. info_ptr->text[i].compression,
  192915. info_ptr->text[i].key,
  192916. info_ptr->text[i].lang,
  192917. info_ptr->text[i].lang_key,
  192918. info_ptr->text[i].text);
  192919. #else
  192920. png_warning(png_ptr, "Unable to write international text");
  192921. #endif
  192922. /* Mark this chunk as written */
  192923. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  192924. }
  192925. /* If we want a compressed text chunk */
  192926. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  192927. {
  192928. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  192929. /* write compressed chunk */
  192930. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  192931. info_ptr->text[i].text, 0,
  192932. info_ptr->text[i].compression);
  192933. #else
  192934. png_warning(png_ptr, "Unable to write compressed text");
  192935. #endif
  192936. /* Mark this chunk as written */
  192937. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  192938. }
  192939. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  192940. {
  192941. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  192942. /* write uncompressed chunk */
  192943. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  192944. info_ptr->text[i].text,
  192945. 0);
  192946. #else
  192947. png_warning(png_ptr, "Unable to write uncompressed text");
  192948. #endif
  192949. /* Mark this chunk as written */
  192950. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  192951. }
  192952. }
  192953. #endif
  192954. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  192955. if (info_ptr->unknown_chunks_num)
  192956. {
  192957. png_unknown_chunk *up;
  192958. png_debug(5, "writing extra chunks\n");
  192959. for (up = info_ptr->unknown_chunks;
  192960. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  192961. up++)
  192962. {
  192963. int keep=png_handle_as_unknown(png_ptr, up->name);
  192964. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  192965. up->location && (up->location & PNG_HAVE_PLTE) &&
  192966. !(up->location & PNG_HAVE_IDAT) &&
  192967. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  192968. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  192969. {
  192970. png_write_chunk(png_ptr, up->name, up->data, up->size);
  192971. }
  192972. }
  192973. }
  192974. #endif
  192975. }
  192976. /* Writes the end of the PNG file. If you don't want to write comments or
  192977. * time information, you can pass NULL for info. If you already wrote these
  192978. * in png_write_info(), do not write them again here. If you have long
  192979. * comments, I suggest writing them here, and compressing them.
  192980. */
  192981. void PNGAPI
  192982. png_write_end(png_structp png_ptr, png_infop info_ptr)
  192983. {
  192984. png_debug(1, "in png_write_end\n");
  192985. if (png_ptr == NULL)
  192986. return;
  192987. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  192988. png_error(png_ptr, "No IDATs written into file");
  192989. /* see if user wants us to write information chunks */
  192990. if (info_ptr != NULL)
  192991. {
  192992. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  192993. int i; /* local index variable */
  192994. #endif
  192995. #if defined(PNG_WRITE_tIME_SUPPORTED)
  192996. /* check to see if user has supplied a time chunk */
  192997. if ((info_ptr->valid & PNG_INFO_tIME) &&
  192998. !(png_ptr->mode & PNG_WROTE_tIME))
  192999. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  193000. #endif
  193001. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  193002. /* loop through comment chunks */
  193003. for (i = 0; i < info_ptr->num_text; i++)
  193004. {
  193005. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  193006. info_ptr->text[i].compression);
  193007. /* an internationalized chunk? */
  193008. if (info_ptr->text[i].compression > 0)
  193009. {
  193010. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  193011. /* write international chunk */
  193012. png_write_iTXt(png_ptr,
  193013. info_ptr->text[i].compression,
  193014. info_ptr->text[i].key,
  193015. info_ptr->text[i].lang,
  193016. info_ptr->text[i].lang_key,
  193017. info_ptr->text[i].text);
  193018. #else
  193019. png_warning(png_ptr, "Unable to write international text");
  193020. #endif
  193021. /* Mark this chunk as written */
  193022. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  193023. }
  193024. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  193025. {
  193026. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  193027. /* write compressed chunk */
  193028. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  193029. info_ptr->text[i].text, 0,
  193030. info_ptr->text[i].compression);
  193031. #else
  193032. png_warning(png_ptr, "Unable to write compressed text");
  193033. #endif
  193034. /* Mark this chunk as written */
  193035. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  193036. }
  193037. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  193038. {
  193039. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  193040. /* write uncompressed chunk */
  193041. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  193042. info_ptr->text[i].text, 0);
  193043. #else
  193044. png_warning(png_ptr, "Unable to write uncompressed text");
  193045. #endif
  193046. /* Mark this chunk as written */
  193047. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  193048. }
  193049. }
  193050. #endif
  193051. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  193052. if (info_ptr->unknown_chunks_num)
  193053. {
  193054. png_unknown_chunk *up;
  193055. png_debug(5, "writing extra chunks\n");
  193056. for (up = info_ptr->unknown_chunks;
  193057. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  193058. up++)
  193059. {
  193060. int keep=png_handle_as_unknown(png_ptr, up->name);
  193061. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  193062. up->location && (up->location & PNG_AFTER_IDAT) &&
  193063. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  193064. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  193065. {
  193066. png_write_chunk(png_ptr, up->name, up->data, up->size);
  193067. }
  193068. }
  193069. }
  193070. #endif
  193071. }
  193072. png_ptr->mode |= PNG_AFTER_IDAT;
  193073. /* write end of PNG file */
  193074. png_write_IEND(png_ptr);
  193075. }
  193076. #if defined(PNG_WRITE_tIME_SUPPORTED)
  193077. #if !defined(_WIN32_WCE)
  193078. /* "time.h" functions are not supported on WindowsCE */
  193079. void PNGAPI
  193080. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  193081. {
  193082. png_debug(1, "in png_convert_from_struct_tm\n");
  193083. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  193084. ptime->month = (png_byte)(ttime->tm_mon + 1);
  193085. ptime->day = (png_byte)ttime->tm_mday;
  193086. ptime->hour = (png_byte)ttime->tm_hour;
  193087. ptime->minute = (png_byte)ttime->tm_min;
  193088. ptime->second = (png_byte)ttime->tm_sec;
  193089. }
  193090. void PNGAPI
  193091. png_convert_from_time_t(png_timep ptime, time_t ttime)
  193092. {
  193093. struct tm *tbuf;
  193094. png_debug(1, "in png_convert_from_time_t\n");
  193095. tbuf = gmtime(&ttime);
  193096. png_convert_from_struct_tm(ptime, tbuf);
  193097. }
  193098. #endif
  193099. #endif
  193100. /* Initialize png_ptr structure, and allocate any memory needed */
  193101. png_structp PNGAPI
  193102. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  193103. png_error_ptr error_fn, png_error_ptr warn_fn)
  193104. {
  193105. #ifdef PNG_USER_MEM_SUPPORTED
  193106. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  193107. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  193108. }
  193109. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  193110. png_structp PNGAPI
  193111. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  193112. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  193113. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  193114. {
  193115. #endif /* PNG_USER_MEM_SUPPORTED */
  193116. png_structp png_ptr;
  193117. #ifdef PNG_SETJMP_SUPPORTED
  193118. #ifdef USE_FAR_KEYWORD
  193119. jmp_buf jmpbuf;
  193120. #endif
  193121. #endif
  193122. int i;
  193123. png_debug(1, "in png_create_write_struct\n");
  193124. #ifdef PNG_USER_MEM_SUPPORTED
  193125. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  193126. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  193127. #else
  193128. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  193129. #endif /* PNG_USER_MEM_SUPPORTED */
  193130. if (png_ptr == NULL)
  193131. return (NULL);
  193132. /* added at libpng-1.2.6 */
  193133. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  193134. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  193135. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  193136. #endif
  193137. #ifdef PNG_SETJMP_SUPPORTED
  193138. #ifdef USE_FAR_KEYWORD
  193139. if (setjmp(jmpbuf))
  193140. #else
  193141. if (setjmp(png_ptr->jmpbuf))
  193142. #endif
  193143. {
  193144. png_free(png_ptr, png_ptr->zbuf);
  193145. png_ptr->zbuf=NULL;
  193146. png_destroy_struct(png_ptr);
  193147. return (NULL);
  193148. }
  193149. #ifdef USE_FAR_KEYWORD
  193150. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  193151. #endif
  193152. #endif
  193153. #ifdef PNG_USER_MEM_SUPPORTED
  193154. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  193155. #endif /* PNG_USER_MEM_SUPPORTED */
  193156. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  193157. i=0;
  193158. do
  193159. {
  193160. if(user_png_ver[i] != png_libpng_ver[i])
  193161. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  193162. } while (png_libpng_ver[i++]);
  193163. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  193164. {
  193165. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  193166. * we must recompile any applications that use any older library version.
  193167. * For versions after libpng 1.0, we will be compatible, so we need
  193168. * only check the first digit.
  193169. */
  193170. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  193171. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  193172. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  193173. {
  193174. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193175. char msg[80];
  193176. if (user_png_ver)
  193177. {
  193178. png_snprintf(msg, 80,
  193179. "Application was compiled with png.h from libpng-%.20s",
  193180. user_png_ver);
  193181. png_warning(png_ptr, msg);
  193182. }
  193183. png_snprintf(msg, 80,
  193184. "Application is running with png.c from libpng-%.20s",
  193185. png_libpng_ver);
  193186. png_warning(png_ptr, msg);
  193187. #endif
  193188. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  193189. png_ptr->flags=0;
  193190. #endif
  193191. png_error(png_ptr,
  193192. "Incompatible libpng version in application and library");
  193193. }
  193194. }
  193195. /* initialize zbuf - compression buffer */
  193196. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  193197. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  193198. (png_uint_32)png_ptr->zbuf_size);
  193199. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  193200. png_flush_ptr_NULL);
  193201. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  193202. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  193203. 1, png_doublep_NULL, png_doublep_NULL);
  193204. #endif
  193205. #ifdef PNG_SETJMP_SUPPORTED
  193206. /* Applications that neglect to set up their own setjmp() and then encounter
  193207. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  193208. abort instead of returning. */
  193209. #ifdef USE_FAR_KEYWORD
  193210. if (setjmp(jmpbuf))
  193211. PNG_ABORT();
  193212. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  193213. #else
  193214. if (setjmp(png_ptr->jmpbuf))
  193215. PNG_ABORT();
  193216. #endif
  193217. #endif
  193218. return (png_ptr);
  193219. }
  193220. /* Initialize png_ptr structure, and allocate any memory needed */
  193221. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  193222. /* Deprecated. */
  193223. #undef png_write_init
  193224. void PNGAPI
  193225. png_write_init(png_structp png_ptr)
  193226. {
  193227. /* We only come here via pre-1.0.7-compiled applications */
  193228. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  193229. }
  193230. void PNGAPI
  193231. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  193232. png_size_t png_struct_size, png_size_t png_info_size)
  193233. {
  193234. /* We only come here via pre-1.0.12-compiled applications */
  193235. if(png_ptr == NULL) return;
  193236. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193237. if(png_sizeof(png_struct) > png_struct_size ||
  193238. png_sizeof(png_info) > png_info_size)
  193239. {
  193240. char msg[80];
  193241. png_ptr->warning_fn=NULL;
  193242. if (user_png_ver)
  193243. {
  193244. png_snprintf(msg, 80,
  193245. "Application was compiled with png.h from libpng-%.20s",
  193246. user_png_ver);
  193247. png_warning(png_ptr, msg);
  193248. }
  193249. png_snprintf(msg, 80,
  193250. "Application is running with png.c from libpng-%.20s",
  193251. png_libpng_ver);
  193252. png_warning(png_ptr, msg);
  193253. }
  193254. #endif
  193255. if(png_sizeof(png_struct) > png_struct_size)
  193256. {
  193257. png_ptr->error_fn=NULL;
  193258. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  193259. png_ptr->flags=0;
  193260. #endif
  193261. png_error(png_ptr,
  193262. "The png struct allocated by the application for writing is too small.");
  193263. }
  193264. if(png_sizeof(png_info) > png_info_size)
  193265. {
  193266. png_ptr->error_fn=NULL;
  193267. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  193268. png_ptr->flags=0;
  193269. #endif
  193270. png_error(png_ptr,
  193271. "The info struct allocated by the application for writing is too small.");
  193272. }
  193273. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  193274. }
  193275. #endif /* PNG_1_0_X || PNG_1_2_X */
  193276. void PNGAPI
  193277. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  193278. png_size_t png_struct_size)
  193279. {
  193280. png_structp png_ptr=*ptr_ptr;
  193281. #ifdef PNG_SETJMP_SUPPORTED
  193282. jmp_buf tmp_jmp; /* to save current jump buffer */
  193283. #endif
  193284. int i = 0;
  193285. if (png_ptr == NULL)
  193286. return;
  193287. do
  193288. {
  193289. if (user_png_ver[i] != png_libpng_ver[i])
  193290. {
  193291. #ifdef PNG_LEGACY_SUPPORTED
  193292. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  193293. #else
  193294. png_ptr->warning_fn=NULL;
  193295. png_warning(png_ptr,
  193296. "Application uses deprecated png_write_init() and should be recompiled.");
  193297. break;
  193298. #endif
  193299. }
  193300. } while (png_libpng_ver[i++]);
  193301. png_debug(1, "in png_write_init_3\n");
  193302. #ifdef PNG_SETJMP_SUPPORTED
  193303. /* save jump buffer and error functions */
  193304. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  193305. #endif
  193306. if (png_sizeof(png_struct) > png_struct_size)
  193307. {
  193308. png_destroy_struct(png_ptr);
  193309. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  193310. *ptr_ptr = png_ptr;
  193311. }
  193312. /* reset all variables to 0 */
  193313. png_memset(png_ptr, 0, png_sizeof (png_struct));
  193314. /* added at libpng-1.2.6 */
  193315. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  193316. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  193317. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  193318. #endif
  193319. #ifdef PNG_SETJMP_SUPPORTED
  193320. /* restore jump buffer */
  193321. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  193322. #endif
  193323. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  193324. png_flush_ptr_NULL);
  193325. /* initialize zbuf - compression buffer */
  193326. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  193327. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  193328. (png_uint_32)png_ptr->zbuf_size);
  193329. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  193330. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  193331. 1, png_doublep_NULL, png_doublep_NULL);
  193332. #endif
  193333. }
  193334. /* Write a few rows of image data. If the image is interlaced,
  193335. * either you will have to write the 7 sub images, or, if you
  193336. * have called png_set_interlace_handling(), you will have to
  193337. * "write" the image seven times.
  193338. */
  193339. void PNGAPI
  193340. png_write_rows(png_structp png_ptr, png_bytepp row,
  193341. png_uint_32 num_rows)
  193342. {
  193343. png_uint_32 i; /* row counter */
  193344. png_bytepp rp; /* row pointer */
  193345. png_debug(1, "in png_write_rows\n");
  193346. if (png_ptr == NULL)
  193347. return;
  193348. /* loop through the rows */
  193349. for (i = 0, rp = row; i < num_rows; i++, rp++)
  193350. {
  193351. png_write_row(png_ptr, *rp);
  193352. }
  193353. }
  193354. /* Write the image. You only need to call this function once, even
  193355. * if you are writing an interlaced image.
  193356. */
  193357. void PNGAPI
  193358. png_write_image(png_structp png_ptr, png_bytepp image)
  193359. {
  193360. png_uint_32 i; /* row index */
  193361. int pass, num_pass; /* pass variables */
  193362. png_bytepp rp; /* points to current row */
  193363. if (png_ptr == NULL)
  193364. return;
  193365. png_debug(1, "in png_write_image\n");
  193366. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  193367. /* intialize interlace handling. If image is not interlaced,
  193368. this will set pass to 1 */
  193369. num_pass = png_set_interlace_handling(png_ptr);
  193370. #else
  193371. num_pass = 1;
  193372. #endif
  193373. /* loop through passes */
  193374. for (pass = 0; pass < num_pass; pass++)
  193375. {
  193376. /* loop through image */
  193377. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  193378. {
  193379. png_write_row(png_ptr, *rp);
  193380. }
  193381. }
  193382. }
  193383. /* called by user to write a row of image data */
  193384. void PNGAPI
  193385. png_write_row(png_structp png_ptr, png_bytep row)
  193386. {
  193387. if (png_ptr == NULL)
  193388. return;
  193389. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  193390. png_ptr->row_number, png_ptr->pass);
  193391. /* initialize transformations and other stuff if first time */
  193392. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  193393. {
  193394. /* make sure we wrote the header info */
  193395. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  193396. png_error(png_ptr,
  193397. "png_write_info was never called before png_write_row.");
  193398. /* check for transforms that have been set but were defined out */
  193399. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  193400. if (png_ptr->transformations & PNG_INVERT_MONO)
  193401. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  193402. #endif
  193403. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  193404. if (png_ptr->transformations & PNG_FILLER)
  193405. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  193406. #endif
  193407. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  193408. if (png_ptr->transformations & PNG_PACKSWAP)
  193409. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  193410. #endif
  193411. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  193412. if (png_ptr->transformations & PNG_PACK)
  193413. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  193414. #endif
  193415. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  193416. if (png_ptr->transformations & PNG_SHIFT)
  193417. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  193418. #endif
  193419. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  193420. if (png_ptr->transformations & PNG_BGR)
  193421. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  193422. #endif
  193423. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  193424. if (png_ptr->transformations & PNG_SWAP_BYTES)
  193425. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  193426. #endif
  193427. png_write_start_row(png_ptr);
  193428. }
  193429. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  193430. /* if interlaced and not interested in row, return */
  193431. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  193432. {
  193433. switch (png_ptr->pass)
  193434. {
  193435. case 0:
  193436. if (png_ptr->row_number & 0x07)
  193437. {
  193438. png_write_finish_row(png_ptr);
  193439. return;
  193440. }
  193441. break;
  193442. case 1:
  193443. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  193444. {
  193445. png_write_finish_row(png_ptr);
  193446. return;
  193447. }
  193448. break;
  193449. case 2:
  193450. if ((png_ptr->row_number & 0x07) != 4)
  193451. {
  193452. png_write_finish_row(png_ptr);
  193453. return;
  193454. }
  193455. break;
  193456. case 3:
  193457. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  193458. {
  193459. png_write_finish_row(png_ptr);
  193460. return;
  193461. }
  193462. break;
  193463. case 4:
  193464. if ((png_ptr->row_number & 0x03) != 2)
  193465. {
  193466. png_write_finish_row(png_ptr);
  193467. return;
  193468. }
  193469. break;
  193470. case 5:
  193471. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  193472. {
  193473. png_write_finish_row(png_ptr);
  193474. return;
  193475. }
  193476. break;
  193477. case 6:
  193478. if (!(png_ptr->row_number & 0x01))
  193479. {
  193480. png_write_finish_row(png_ptr);
  193481. return;
  193482. }
  193483. break;
  193484. }
  193485. }
  193486. #endif
  193487. /* set up row info for transformations */
  193488. png_ptr->row_info.color_type = png_ptr->color_type;
  193489. png_ptr->row_info.width = png_ptr->usr_width;
  193490. png_ptr->row_info.channels = png_ptr->usr_channels;
  193491. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  193492. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  193493. png_ptr->row_info.channels);
  193494. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  193495. png_ptr->row_info.width);
  193496. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  193497. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  193498. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  193499. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  193500. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  193501. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  193502. /* Copy user's row into buffer, leaving room for filter byte. */
  193503. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  193504. png_ptr->row_info.rowbytes);
  193505. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  193506. /* handle interlacing */
  193507. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  193508. (png_ptr->transformations & PNG_INTERLACE))
  193509. {
  193510. png_do_write_interlace(&(png_ptr->row_info),
  193511. png_ptr->row_buf + 1, png_ptr->pass);
  193512. /* this should always get caught above, but still ... */
  193513. if (!(png_ptr->row_info.width))
  193514. {
  193515. png_write_finish_row(png_ptr);
  193516. return;
  193517. }
  193518. }
  193519. #endif
  193520. /* handle other transformations */
  193521. if (png_ptr->transformations)
  193522. png_do_write_transformations(png_ptr);
  193523. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193524. /* Write filter_method 64 (intrapixel differencing) only if
  193525. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  193526. * 2. Libpng did not write a PNG signature (this filter_method is only
  193527. * used in PNG datastreams that are embedded in MNG datastreams) and
  193528. * 3. The application called png_permit_mng_features with a mask that
  193529. * included PNG_FLAG_MNG_FILTER_64 and
  193530. * 4. The filter_method is 64 and
  193531. * 5. The color_type is RGB or RGBA
  193532. */
  193533. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  193534. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  193535. {
  193536. /* Intrapixel differencing */
  193537. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  193538. }
  193539. #endif
  193540. /* Find a filter if necessary, filter the row and write it out. */
  193541. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  193542. if (png_ptr->write_row_fn != NULL)
  193543. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  193544. }
  193545. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  193546. /* Set the automatic flush interval or 0 to turn flushing off */
  193547. void PNGAPI
  193548. png_set_flush(png_structp png_ptr, int nrows)
  193549. {
  193550. png_debug(1, "in png_set_flush\n");
  193551. if (png_ptr == NULL)
  193552. return;
  193553. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  193554. }
  193555. /* flush the current output buffers now */
  193556. void PNGAPI
  193557. png_write_flush(png_structp png_ptr)
  193558. {
  193559. int wrote_IDAT;
  193560. png_debug(1, "in png_write_flush\n");
  193561. if (png_ptr == NULL)
  193562. return;
  193563. /* We have already written out all of the data */
  193564. if (png_ptr->row_number >= png_ptr->num_rows)
  193565. return;
  193566. do
  193567. {
  193568. int ret;
  193569. /* compress the data */
  193570. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  193571. wrote_IDAT = 0;
  193572. /* check for compression errors */
  193573. if (ret != Z_OK)
  193574. {
  193575. if (png_ptr->zstream.msg != NULL)
  193576. png_error(png_ptr, png_ptr->zstream.msg);
  193577. else
  193578. png_error(png_ptr, "zlib error");
  193579. }
  193580. if (!(png_ptr->zstream.avail_out))
  193581. {
  193582. /* write the IDAT and reset the zlib output buffer */
  193583. png_write_IDAT(png_ptr, png_ptr->zbuf,
  193584. png_ptr->zbuf_size);
  193585. png_ptr->zstream.next_out = png_ptr->zbuf;
  193586. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193587. wrote_IDAT = 1;
  193588. }
  193589. } while(wrote_IDAT == 1);
  193590. /* If there is any data left to be output, write it into a new IDAT */
  193591. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  193592. {
  193593. /* write the IDAT and reset the zlib output buffer */
  193594. png_write_IDAT(png_ptr, png_ptr->zbuf,
  193595. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  193596. png_ptr->zstream.next_out = png_ptr->zbuf;
  193597. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193598. }
  193599. png_ptr->flush_rows = 0;
  193600. png_flush(png_ptr);
  193601. }
  193602. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  193603. /* free all memory used by the write */
  193604. void PNGAPI
  193605. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  193606. {
  193607. png_structp png_ptr = NULL;
  193608. png_infop info_ptr = NULL;
  193609. #ifdef PNG_USER_MEM_SUPPORTED
  193610. png_free_ptr free_fn = NULL;
  193611. png_voidp mem_ptr = NULL;
  193612. #endif
  193613. png_debug(1, "in png_destroy_write_struct\n");
  193614. if (png_ptr_ptr != NULL)
  193615. {
  193616. png_ptr = *png_ptr_ptr;
  193617. #ifdef PNG_USER_MEM_SUPPORTED
  193618. free_fn = png_ptr->free_fn;
  193619. mem_ptr = png_ptr->mem_ptr;
  193620. #endif
  193621. }
  193622. if (info_ptr_ptr != NULL)
  193623. info_ptr = *info_ptr_ptr;
  193624. if (info_ptr != NULL)
  193625. {
  193626. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  193627. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  193628. if (png_ptr->num_chunk_list)
  193629. {
  193630. png_free(png_ptr, png_ptr->chunk_list);
  193631. png_ptr->chunk_list=NULL;
  193632. png_ptr->num_chunk_list=0;
  193633. }
  193634. #endif
  193635. #ifdef PNG_USER_MEM_SUPPORTED
  193636. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  193637. (png_voidp)mem_ptr);
  193638. #else
  193639. png_destroy_struct((png_voidp)info_ptr);
  193640. #endif
  193641. *info_ptr_ptr = NULL;
  193642. }
  193643. if (png_ptr != NULL)
  193644. {
  193645. png_write_destroy(png_ptr);
  193646. #ifdef PNG_USER_MEM_SUPPORTED
  193647. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  193648. (png_voidp)mem_ptr);
  193649. #else
  193650. png_destroy_struct((png_voidp)png_ptr);
  193651. #endif
  193652. *png_ptr_ptr = NULL;
  193653. }
  193654. }
  193655. /* Free any memory used in png_ptr struct (old method) */
  193656. void /* PRIVATE */
  193657. png_write_destroy(png_structp png_ptr)
  193658. {
  193659. #ifdef PNG_SETJMP_SUPPORTED
  193660. jmp_buf tmp_jmp; /* save jump buffer */
  193661. #endif
  193662. png_error_ptr error_fn;
  193663. png_error_ptr warning_fn;
  193664. png_voidp error_ptr;
  193665. #ifdef PNG_USER_MEM_SUPPORTED
  193666. png_free_ptr free_fn;
  193667. #endif
  193668. png_debug(1, "in png_write_destroy\n");
  193669. /* free any memory zlib uses */
  193670. deflateEnd(&png_ptr->zstream);
  193671. /* free our memory. png_free checks NULL for us. */
  193672. png_free(png_ptr, png_ptr->zbuf);
  193673. png_free(png_ptr, png_ptr->row_buf);
  193674. png_free(png_ptr, png_ptr->prev_row);
  193675. png_free(png_ptr, png_ptr->sub_row);
  193676. png_free(png_ptr, png_ptr->up_row);
  193677. png_free(png_ptr, png_ptr->avg_row);
  193678. png_free(png_ptr, png_ptr->paeth_row);
  193679. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  193680. png_free(png_ptr, png_ptr->time_buffer);
  193681. #endif
  193682. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  193683. png_free(png_ptr, png_ptr->prev_filters);
  193684. png_free(png_ptr, png_ptr->filter_weights);
  193685. png_free(png_ptr, png_ptr->inv_filter_weights);
  193686. png_free(png_ptr, png_ptr->filter_costs);
  193687. png_free(png_ptr, png_ptr->inv_filter_costs);
  193688. #endif
  193689. #ifdef PNG_SETJMP_SUPPORTED
  193690. /* reset structure */
  193691. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  193692. #endif
  193693. error_fn = png_ptr->error_fn;
  193694. warning_fn = png_ptr->warning_fn;
  193695. error_ptr = png_ptr->error_ptr;
  193696. #ifdef PNG_USER_MEM_SUPPORTED
  193697. free_fn = png_ptr->free_fn;
  193698. #endif
  193699. png_memset(png_ptr, 0, png_sizeof (png_struct));
  193700. png_ptr->error_fn = error_fn;
  193701. png_ptr->warning_fn = warning_fn;
  193702. png_ptr->error_ptr = error_ptr;
  193703. #ifdef PNG_USER_MEM_SUPPORTED
  193704. png_ptr->free_fn = free_fn;
  193705. #endif
  193706. #ifdef PNG_SETJMP_SUPPORTED
  193707. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  193708. #endif
  193709. }
  193710. /* Allow the application to select one or more row filters to use. */
  193711. void PNGAPI
  193712. png_set_filter(png_structp png_ptr, int method, int filters)
  193713. {
  193714. png_debug(1, "in png_set_filter\n");
  193715. if (png_ptr == NULL)
  193716. return;
  193717. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193718. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  193719. (method == PNG_INTRAPIXEL_DIFFERENCING))
  193720. method = PNG_FILTER_TYPE_BASE;
  193721. #endif
  193722. if (method == PNG_FILTER_TYPE_BASE)
  193723. {
  193724. switch (filters & (PNG_ALL_FILTERS | 0x07))
  193725. {
  193726. #ifndef PNG_NO_WRITE_FILTER
  193727. case 5:
  193728. case 6:
  193729. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  193730. #endif /* PNG_NO_WRITE_FILTER */
  193731. case PNG_FILTER_VALUE_NONE:
  193732. png_ptr->do_filter=PNG_FILTER_NONE; break;
  193733. #ifndef PNG_NO_WRITE_FILTER
  193734. case PNG_FILTER_VALUE_SUB:
  193735. png_ptr->do_filter=PNG_FILTER_SUB; break;
  193736. case PNG_FILTER_VALUE_UP:
  193737. png_ptr->do_filter=PNG_FILTER_UP; break;
  193738. case PNG_FILTER_VALUE_AVG:
  193739. png_ptr->do_filter=PNG_FILTER_AVG; break;
  193740. case PNG_FILTER_VALUE_PAETH:
  193741. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  193742. default: png_ptr->do_filter = (png_byte)filters; break;
  193743. #else
  193744. default: png_warning(png_ptr, "Unknown row filter for method 0");
  193745. #endif /* PNG_NO_WRITE_FILTER */
  193746. }
  193747. /* If we have allocated the row_buf, this means we have already started
  193748. * with the image and we should have allocated all of the filter buffers
  193749. * that have been selected. If prev_row isn't already allocated, then
  193750. * it is too late to start using the filters that need it, since we
  193751. * will be missing the data in the previous row. If an application
  193752. * wants to start and stop using particular filters during compression,
  193753. * it should start out with all of the filters, and then add and
  193754. * remove them after the start of compression.
  193755. */
  193756. if (png_ptr->row_buf != NULL)
  193757. {
  193758. #ifndef PNG_NO_WRITE_FILTER
  193759. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  193760. {
  193761. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  193762. (png_ptr->rowbytes + 1));
  193763. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  193764. }
  193765. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  193766. {
  193767. if (png_ptr->prev_row == NULL)
  193768. {
  193769. png_warning(png_ptr, "Can't add Up filter after starting");
  193770. png_ptr->do_filter &= ~PNG_FILTER_UP;
  193771. }
  193772. else
  193773. {
  193774. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  193775. (png_ptr->rowbytes + 1));
  193776. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  193777. }
  193778. }
  193779. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  193780. {
  193781. if (png_ptr->prev_row == NULL)
  193782. {
  193783. png_warning(png_ptr, "Can't add Average filter after starting");
  193784. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  193785. }
  193786. else
  193787. {
  193788. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  193789. (png_ptr->rowbytes + 1));
  193790. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  193791. }
  193792. }
  193793. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  193794. png_ptr->paeth_row == NULL)
  193795. {
  193796. if (png_ptr->prev_row == NULL)
  193797. {
  193798. png_warning(png_ptr, "Can't add Paeth filter after starting");
  193799. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  193800. }
  193801. else
  193802. {
  193803. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  193804. (png_ptr->rowbytes + 1));
  193805. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  193806. }
  193807. }
  193808. if (png_ptr->do_filter == PNG_NO_FILTERS)
  193809. #endif /* PNG_NO_WRITE_FILTER */
  193810. png_ptr->do_filter = PNG_FILTER_NONE;
  193811. }
  193812. }
  193813. else
  193814. png_error(png_ptr, "Unknown custom filter method");
  193815. }
  193816. /* This allows us to influence the way in which libpng chooses the "best"
  193817. * filter for the current scanline. While the "minimum-sum-of-absolute-
  193818. * differences metric is relatively fast and effective, there is some
  193819. * question as to whether it can be improved upon by trying to keep the
  193820. * filtered data going to zlib more consistent, hopefully resulting in
  193821. * better compression.
  193822. */
  193823. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  193824. void PNGAPI
  193825. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  193826. int num_weights, png_doublep filter_weights,
  193827. png_doublep filter_costs)
  193828. {
  193829. int i;
  193830. png_debug(1, "in png_set_filter_heuristics\n");
  193831. if (png_ptr == NULL)
  193832. return;
  193833. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  193834. {
  193835. png_warning(png_ptr, "Unknown filter heuristic method");
  193836. return;
  193837. }
  193838. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  193839. {
  193840. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  193841. }
  193842. if (num_weights < 0 || filter_weights == NULL ||
  193843. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  193844. {
  193845. num_weights = 0;
  193846. }
  193847. png_ptr->num_prev_filters = (png_byte)num_weights;
  193848. png_ptr->heuristic_method = (png_byte)heuristic_method;
  193849. if (num_weights > 0)
  193850. {
  193851. if (png_ptr->prev_filters == NULL)
  193852. {
  193853. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  193854. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  193855. /* To make sure that the weighting starts out fairly */
  193856. for (i = 0; i < num_weights; i++)
  193857. {
  193858. png_ptr->prev_filters[i] = 255;
  193859. }
  193860. }
  193861. if (png_ptr->filter_weights == NULL)
  193862. {
  193863. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  193864. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  193865. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  193866. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  193867. for (i = 0; i < num_weights; i++)
  193868. {
  193869. png_ptr->inv_filter_weights[i] =
  193870. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  193871. }
  193872. }
  193873. for (i = 0; i < num_weights; i++)
  193874. {
  193875. if (filter_weights[i] < 0.0)
  193876. {
  193877. png_ptr->inv_filter_weights[i] =
  193878. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  193879. }
  193880. else
  193881. {
  193882. png_ptr->inv_filter_weights[i] =
  193883. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  193884. png_ptr->filter_weights[i] =
  193885. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  193886. }
  193887. }
  193888. }
  193889. /* If, in the future, there are other filter methods, this would
  193890. * need to be based on png_ptr->filter.
  193891. */
  193892. if (png_ptr->filter_costs == NULL)
  193893. {
  193894. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  193895. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  193896. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  193897. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  193898. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  193899. {
  193900. png_ptr->inv_filter_costs[i] =
  193901. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  193902. }
  193903. }
  193904. /* Here is where we set the relative costs of the different filters. We
  193905. * should take the desired compression level into account when setting
  193906. * the costs, so that Paeth, for instance, has a high relative cost at low
  193907. * compression levels, while it has a lower relative cost at higher
  193908. * compression settings. The filter types are in order of increasing
  193909. * relative cost, so it would be possible to do this with an algorithm.
  193910. */
  193911. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  193912. {
  193913. if (filter_costs == NULL || filter_costs[i] < 0.0)
  193914. {
  193915. png_ptr->inv_filter_costs[i] =
  193916. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  193917. }
  193918. else if (filter_costs[i] >= 1.0)
  193919. {
  193920. png_ptr->inv_filter_costs[i] =
  193921. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  193922. png_ptr->filter_costs[i] =
  193923. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  193924. }
  193925. }
  193926. }
  193927. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  193928. void PNGAPI
  193929. png_set_compression_level(png_structp png_ptr, int level)
  193930. {
  193931. png_debug(1, "in png_set_compression_level\n");
  193932. if (png_ptr == NULL)
  193933. return;
  193934. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  193935. png_ptr->zlib_level = level;
  193936. }
  193937. void PNGAPI
  193938. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  193939. {
  193940. png_debug(1, "in png_set_compression_mem_level\n");
  193941. if (png_ptr == NULL)
  193942. return;
  193943. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  193944. png_ptr->zlib_mem_level = mem_level;
  193945. }
  193946. void PNGAPI
  193947. png_set_compression_strategy(png_structp png_ptr, int strategy)
  193948. {
  193949. png_debug(1, "in png_set_compression_strategy\n");
  193950. if (png_ptr == NULL)
  193951. return;
  193952. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  193953. png_ptr->zlib_strategy = strategy;
  193954. }
  193955. void PNGAPI
  193956. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  193957. {
  193958. if (png_ptr == NULL)
  193959. return;
  193960. if (window_bits > 15)
  193961. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  193962. else if (window_bits < 8)
  193963. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  193964. #ifndef WBITS_8_OK
  193965. /* avoid libpng bug with 256-byte windows */
  193966. if (window_bits == 8)
  193967. {
  193968. png_warning(png_ptr, "Compression window is being reset to 512");
  193969. window_bits=9;
  193970. }
  193971. #endif
  193972. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  193973. png_ptr->zlib_window_bits = window_bits;
  193974. }
  193975. void PNGAPI
  193976. png_set_compression_method(png_structp png_ptr, int method)
  193977. {
  193978. png_debug(1, "in png_set_compression_method\n");
  193979. if (png_ptr == NULL)
  193980. return;
  193981. if (method != 8)
  193982. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  193983. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  193984. png_ptr->zlib_method = method;
  193985. }
  193986. void PNGAPI
  193987. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  193988. {
  193989. if (png_ptr == NULL)
  193990. return;
  193991. png_ptr->write_row_fn = write_row_fn;
  193992. }
  193993. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  193994. void PNGAPI
  193995. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  193996. write_user_transform_fn)
  193997. {
  193998. png_debug(1, "in png_set_write_user_transform_fn\n");
  193999. if (png_ptr == NULL)
  194000. return;
  194001. png_ptr->transformations |= PNG_USER_TRANSFORM;
  194002. png_ptr->write_user_transform_fn = write_user_transform_fn;
  194003. }
  194004. #endif
  194005. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  194006. void PNGAPI
  194007. png_write_png(png_structp png_ptr, png_infop info_ptr,
  194008. int transforms, voidp params)
  194009. {
  194010. if (png_ptr == NULL || info_ptr == NULL)
  194011. return;
  194012. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  194013. /* invert the alpha channel from opacity to transparency */
  194014. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  194015. png_set_invert_alpha(png_ptr);
  194016. #endif
  194017. /* Write the file header information. */
  194018. png_write_info(png_ptr, info_ptr);
  194019. /* ------ these transformations don't touch the info structure ------- */
  194020. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  194021. /* invert monochrome pixels */
  194022. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  194023. png_set_invert_mono(png_ptr);
  194024. #endif
  194025. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  194026. /* Shift the pixels up to a legal bit depth and fill in
  194027. * as appropriate to correctly scale the image.
  194028. */
  194029. if ((transforms & PNG_TRANSFORM_SHIFT)
  194030. && (info_ptr->valid & PNG_INFO_sBIT))
  194031. png_set_shift(png_ptr, &info_ptr->sig_bit);
  194032. #endif
  194033. #if defined(PNG_WRITE_PACK_SUPPORTED)
  194034. /* pack pixels into bytes */
  194035. if (transforms & PNG_TRANSFORM_PACKING)
  194036. png_set_packing(png_ptr);
  194037. #endif
  194038. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  194039. /* swap location of alpha bytes from ARGB to RGBA */
  194040. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  194041. png_set_swap_alpha(png_ptr);
  194042. #endif
  194043. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  194044. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  194045. * RGB (4 channels -> 3 channels). The second parameter is not used.
  194046. */
  194047. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  194048. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  194049. #endif
  194050. #if defined(PNG_WRITE_BGR_SUPPORTED)
  194051. /* flip BGR pixels to RGB */
  194052. if (transforms & PNG_TRANSFORM_BGR)
  194053. png_set_bgr(png_ptr);
  194054. #endif
  194055. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  194056. /* swap bytes of 16-bit files to most significant byte first */
  194057. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  194058. png_set_swap(png_ptr);
  194059. #endif
  194060. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  194061. /* swap bits of 1, 2, 4 bit packed pixel formats */
  194062. if (transforms & PNG_TRANSFORM_PACKSWAP)
  194063. png_set_packswap(png_ptr);
  194064. #endif
  194065. /* ----------------------- end of transformations ------------------- */
  194066. /* write the bits */
  194067. if (info_ptr->valid & PNG_INFO_IDAT)
  194068. png_write_image(png_ptr, info_ptr->row_pointers);
  194069. /* It is REQUIRED to call this to finish writing the rest of the file */
  194070. png_write_end(png_ptr, info_ptr);
  194071. transforms = transforms; /* quiet compiler warnings */
  194072. params = params;
  194073. }
  194074. #endif
  194075. #endif /* PNG_WRITE_SUPPORTED */
  194076. /********* End of inlined file: pngwrite.c *********/
  194077. /********* Start of inlined file: pngwtran.c *********/
  194078. /* pngwtran.c - transforms the data in a row for PNG writers
  194079. *
  194080. * Last changed in libpng 1.2.9 April 14, 2006
  194081. * For conditions of distribution and use, see copyright notice in png.h
  194082. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  194083. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194084. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194085. */
  194086. #define PNG_INTERNAL
  194087. #ifdef PNG_WRITE_SUPPORTED
  194088. /* Transform the data according to the user's wishes. The order of
  194089. * transformations is significant.
  194090. */
  194091. void /* PRIVATE */
  194092. png_do_write_transformations(png_structp png_ptr)
  194093. {
  194094. png_debug(1, "in png_do_write_transformations\n");
  194095. if (png_ptr == NULL)
  194096. return;
  194097. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  194098. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  194099. if(png_ptr->write_user_transform_fn != NULL)
  194100. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  194101. (png_ptr, /* png_ptr */
  194102. &(png_ptr->row_info), /* row_info: */
  194103. /* png_uint_32 width; width of row */
  194104. /* png_uint_32 rowbytes; number of bytes in row */
  194105. /* png_byte color_type; color type of pixels */
  194106. /* png_byte bit_depth; bit depth of samples */
  194107. /* png_byte channels; number of channels (1-4) */
  194108. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  194109. png_ptr->row_buf + 1); /* start of pixel data for row */
  194110. #endif
  194111. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  194112. if (png_ptr->transformations & PNG_FILLER)
  194113. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  194114. png_ptr->flags);
  194115. #endif
  194116. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  194117. if (png_ptr->transformations & PNG_PACKSWAP)
  194118. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194119. #endif
  194120. #if defined(PNG_WRITE_PACK_SUPPORTED)
  194121. if (png_ptr->transformations & PNG_PACK)
  194122. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  194123. (png_uint_32)png_ptr->bit_depth);
  194124. #endif
  194125. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  194126. if (png_ptr->transformations & PNG_SWAP_BYTES)
  194127. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194128. #endif
  194129. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  194130. if (png_ptr->transformations & PNG_SHIFT)
  194131. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  194132. &(png_ptr->shift));
  194133. #endif
  194134. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  194135. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  194136. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194137. #endif
  194138. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  194139. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  194140. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194141. #endif
  194142. #if defined(PNG_WRITE_BGR_SUPPORTED)
  194143. if (png_ptr->transformations & PNG_BGR)
  194144. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194145. #endif
  194146. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  194147. if (png_ptr->transformations & PNG_INVERT_MONO)
  194148. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194149. #endif
  194150. }
  194151. #if defined(PNG_WRITE_PACK_SUPPORTED)
  194152. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  194153. * row_info bit depth should be 8 (one pixel per byte). The channels
  194154. * should be 1 (this only happens on grayscale and paletted images).
  194155. */
  194156. void /* PRIVATE */
  194157. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  194158. {
  194159. png_debug(1, "in png_do_pack\n");
  194160. if (row_info->bit_depth == 8 &&
  194161. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194162. row != NULL && row_info != NULL &&
  194163. #endif
  194164. row_info->channels == 1)
  194165. {
  194166. switch ((int)bit_depth)
  194167. {
  194168. case 1:
  194169. {
  194170. png_bytep sp, dp;
  194171. int mask, v;
  194172. png_uint_32 i;
  194173. png_uint_32 row_width = row_info->width;
  194174. sp = row;
  194175. dp = row;
  194176. mask = 0x80;
  194177. v = 0;
  194178. for (i = 0; i < row_width; i++)
  194179. {
  194180. if (*sp != 0)
  194181. v |= mask;
  194182. sp++;
  194183. if (mask > 1)
  194184. mask >>= 1;
  194185. else
  194186. {
  194187. mask = 0x80;
  194188. *dp = (png_byte)v;
  194189. dp++;
  194190. v = 0;
  194191. }
  194192. }
  194193. if (mask != 0x80)
  194194. *dp = (png_byte)v;
  194195. break;
  194196. }
  194197. case 2:
  194198. {
  194199. png_bytep sp, dp;
  194200. int shift, v;
  194201. png_uint_32 i;
  194202. png_uint_32 row_width = row_info->width;
  194203. sp = row;
  194204. dp = row;
  194205. shift = 6;
  194206. v = 0;
  194207. for (i = 0; i < row_width; i++)
  194208. {
  194209. png_byte value;
  194210. value = (png_byte)(*sp & 0x03);
  194211. v |= (value << shift);
  194212. if (shift == 0)
  194213. {
  194214. shift = 6;
  194215. *dp = (png_byte)v;
  194216. dp++;
  194217. v = 0;
  194218. }
  194219. else
  194220. shift -= 2;
  194221. sp++;
  194222. }
  194223. if (shift != 6)
  194224. *dp = (png_byte)v;
  194225. break;
  194226. }
  194227. case 4:
  194228. {
  194229. png_bytep sp, dp;
  194230. int shift, v;
  194231. png_uint_32 i;
  194232. png_uint_32 row_width = row_info->width;
  194233. sp = row;
  194234. dp = row;
  194235. shift = 4;
  194236. v = 0;
  194237. for (i = 0; i < row_width; i++)
  194238. {
  194239. png_byte value;
  194240. value = (png_byte)(*sp & 0x0f);
  194241. v |= (value << shift);
  194242. if (shift == 0)
  194243. {
  194244. shift = 4;
  194245. *dp = (png_byte)v;
  194246. dp++;
  194247. v = 0;
  194248. }
  194249. else
  194250. shift -= 4;
  194251. sp++;
  194252. }
  194253. if (shift != 4)
  194254. *dp = (png_byte)v;
  194255. break;
  194256. }
  194257. }
  194258. row_info->bit_depth = (png_byte)bit_depth;
  194259. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  194260. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  194261. row_info->width);
  194262. }
  194263. }
  194264. #endif
  194265. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  194266. /* Shift pixel values to take advantage of whole range. Pass the
  194267. * true number of bits in bit_depth. The row should be packed
  194268. * according to row_info->bit_depth. Thus, if you had a row of
  194269. * bit depth 4, but the pixels only had values from 0 to 7, you
  194270. * would pass 3 as bit_depth, and this routine would translate the
  194271. * data to 0 to 15.
  194272. */
  194273. void /* PRIVATE */
  194274. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  194275. {
  194276. png_debug(1, "in png_do_shift\n");
  194277. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194278. if (row != NULL && row_info != NULL &&
  194279. #else
  194280. if (
  194281. #endif
  194282. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  194283. {
  194284. int shift_start[4], shift_dec[4];
  194285. int channels = 0;
  194286. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  194287. {
  194288. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  194289. shift_dec[channels] = bit_depth->red;
  194290. channels++;
  194291. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  194292. shift_dec[channels] = bit_depth->green;
  194293. channels++;
  194294. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  194295. shift_dec[channels] = bit_depth->blue;
  194296. channels++;
  194297. }
  194298. else
  194299. {
  194300. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  194301. shift_dec[channels] = bit_depth->gray;
  194302. channels++;
  194303. }
  194304. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  194305. {
  194306. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  194307. shift_dec[channels] = bit_depth->alpha;
  194308. channels++;
  194309. }
  194310. /* with low row depths, could only be grayscale, so one channel */
  194311. if (row_info->bit_depth < 8)
  194312. {
  194313. png_bytep bp = row;
  194314. png_uint_32 i;
  194315. png_byte mask;
  194316. png_uint_32 row_bytes = row_info->rowbytes;
  194317. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  194318. mask = 0x55;
  194319. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  194320. mask = 0x11;
  194321. else
  194322. mask = 0xff;
  194323. for (i = 0; i < row_bytes; i++, bp++)
  194324. {
  194325. png_uint_16 v;
  194326. int j;
  194327. v = *bp;
  194328. *bp = 0;
  194329. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  194330. {
  194331. if (j > 0)
  194332. *bp |= (png_byte)((v << j) & 0xff);
  194333. else
  194334. *bp |= (png_byte)((v >> (-j)) & mask);
  194335. }
  194336. }
  194337. }
  194338. else if (row_info->bit_depth == 8)
  194339. {
  194340. png_bytep bp = row;
  194341. png_uint_32 i;
  194342. png_uint_32 istop = channels * row_info->width;
  194343. for (i = 0; i < istop; i++, bp++)
  194344. {
  194345. png_uint_16 v;
  194346. int j;
  194347. int c = (int)(i%channels);
  194348. v = *bp;
  194349. *bp = 0;
  194350. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  194351. {
  194352. if (j > 0)
  194353. *bp |= (png_byte)((v << j) & 0xff);
  194354. else
  194355. *bp |= (png_byte)((v >> (-j)) & 0xff);
  194356. }
  194357. }
  194358. }
  194359. else
  194360. {
  194361. png_bytep bp;
  194362. png_uint_32 i;
  194363. png_uint_32 istop = channels * row_info->width;
  194364. for (bp = row, i = 0; i < istop; i++)
  194365. {
  194366. int c = (int)(i%channels);
  194367. png_uint_16 value, v;
  194368. int j;
  194369. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  194370. value = 0;
  194371. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  194372. {
  194373. if (j > 0)
  194374. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  194375. else
  194376. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  194377. }
  194378. *bp++ = (png_byte)(value >> 8);
  194379. *bp++ = (png_byte)(value & 0xff);
  194380. }
  194381. }
  194382. }
  194383. }
  194384. #endif
  194385. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  194386. void /* PRIVATE */
  194387. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  194388. {
  194389. png_debug(1, "in png_do_write_swap_alpha\n");
  194390. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194391. if (row != NULL && row_info != NULL)
  194392. #endif
  194393. {
  194394. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194395. {
  194396. /* This converts from ARGB to RGBA */
  194397. if (row_info->bit_depth == 8)
  194398. {
  194399. png_bytep sp, dp;
  194400. png_uint_32 i;
  194401. png_uint_32 row_width = row_info->width;
  194402. for (i = 0, sp = dp = row; i < row_width; i++)
  194403. {
  194404. png_byte save = *(sp++);
  194405. *(dp++) = *(sp++);
  194406. *(dp++) = *(sp++);
  194407. *(dp++) = *(sp++);
  194408. *(dp++) = save;
  194409. }
  194410. }
  194411. /* This converts from AARRGGBB to RRGGBBAA */
  194412. else
  194413. {
  194414. png_bytep sp, dp;
  194415. png_uint_32 i;
  194416. png_uint_32 row_width = row_info->width;
  194417. for (i = 0, sp = dp = row; i < row_width; i++)
  194418. {
  194419. png_byte save[2];
  194420. save[0] = *(sp++);
  194421. save[1] = *(sp++);
  194422. *(dp++) = *(sp++);
  194423. *(dp++) = *(sp++);
  194424. *(dp++) = *(sp++);
  194425. *(dp++) = *(sp++);
  194426. *(dp++) = *(sp++);
  194427. *(dp++) = *(sp++);
  194428. *(dp++) = save[0];
  194429. *(dp++) = save[1];
  194430. }
  194431. }
  194432. }
  194433. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  194434. {
  194435. /* This converts from AG to GA */
  194436. if (row_info->bit_depth == 8)
  194437. {
  194438. png_bytep sp, dp;
  194439. png_uint_32 i;
  194440. png_uint_32 row_width = row_info->width;
  194441. for (i = 0, sp = dp = row; i < row_width; i++)
  194442. {
  194443. png_byte save = *(sp++);
  194444. *(dp++) = *(sp++);
  194445. *(dp++) = save;
  194446. }
  194447. }
  194448. /* This converts from AAGG to GGAA */
  194449. else
  194450. {
  194451. png_bytep sp, dp;
  194452. png_uint_32 i;
  194453. png_uint_32 row_width = row_info->width;
  194454. for (i = 0, sp = dp = row; i < row_width; i++)
  194455. {
  194456. png_byte save[2];
  194457. save[0] = *(sp++);
  194458. save[1] = *(sp++);
  194459. *(dp++) = *(sp++);
  194460. *(dp++) = *(sp++);
  194461. *(dp++) = save[0];
  194462. *(dp++) = save[1];
  194463. }
  194464. }
  194465. }
  194466. }
  194467. }
  194468. #endif
  194469. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  194470. void /* PRIVATE */
  194471. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  194472. {
  194473. png_debug(1, "in png_do_write_invert_alpha\n");
  194474. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194475. if (row != NULL && row_info != NULL)
  194476. #endif
  194477. {
  194478. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194479. {
  194480. /* This inverts the alpha channel in RGBA */
  194481. if (row_info->bit_depth == 8)
  194482. {
  194483. png_bytep sp, dp;
  194484. png_uint_32 i;
  194485. png_uint_32 row_width = row_info->width;
  194486. for (i = 0, sp = dp = row; i < row_width; i++)
  194487. {
  194488. /* does nothing
  194489. *(dp++) = *(sp++);
  194490. *(dp++) = *(sp++);
  194491. *(dp++) = *(sp++);
  194492. */
  194493. sp+=3; dp = sp;
  194494. *(dp++) = (png_byte)(255 - *(sp++));
  194495. }
  194496. }
  194497. /* This inverts the alpha channel in RRGGBBAA */
  194498. else
  194499. {
  194500. png_bytep sp, dp;
  194501. png_uint_32 i;
  194502. png_uint_32 row_width = row_info->width;
  194503. for (i = 0, sp = dp = row; i < row_width; i++)
  194504. {
  194505. /* does nothing
  194506. *(dp++) = *(sp++);
  194507. *(dp++) = *(sp++);
  194508. *(dp++) = *(sp++);
  194509. *(dp++) = *(sp++);
  194510. *(dp++) = *(sp++);
  194511. *(dp++) = *(sp++);
  194512. */
  194513. sp+=6; dp = sp;
  194514. *(dp++) = (png_byte)(255 - *(sp++));
  194515. *(dp++) = (png_byte)(255 - *(sp++));
  194516. }
  194517. }
  194518. }
  194519. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  194520. {
  194521. /* This inverts the alpha channel in GA */
  194522. if (row_info->bit_depth == 8)
  194523. {
  194524. png_bytep sp, dp;
  194525. png_uint_32 i;
  194526. png_uint_32 row_width = row_info->width;
  194527. for (i = 0, sp = dp = row; i < row_width; i++)
  194528. {
  194529. *(dp++) = *(sp++);
  194530. *(dp++) = (png_byte)(255 - *(sp++));
  194531. }
  194532. }
  194533. /* This inverts the alpha channel in GGAA */
  194534. else
  194535. {
  194536. png_bytep sp, dp;
  194537. png_uint_32 i;
  194538. png_uint_32 row_width = row_info->width;
  194539. for (i = 0, sp = dp = row; i < row_width; i++)
  194540. {
  194541. /* does nothing
  194542. *(dp++) = *(sp++);
  194543. *(dp++) = *(sp++);
  194544. */
  194545. sp+=2; dp = sp;
  194546. *(dp++) = (png_byte)(255 - *(sp++));
  194547. *(dp++) = (png_byte)(255 - *(sp++));
  194548. }
  194549. }
  194550. }
  194551. }
  194552. }
  194553. #endif
  194554. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194555. /* undoes intrapixel differencing */
  194556. void /* PRIVATE */
  194557. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  194558. {
  194559. png_debug(1, "in png_do_write_intrapixel\n");
  194560. if (
  194561. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194562. row != NULL && row_info != NULL &&
  194563. #endif
  194564. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  194565. {
  194566. int bytes_per_pixel;
  194567. png_uint_32 row_width = row_info->width;
  194568. if (row_info->bit_depth == 8)
  194569. {
  194570. png_bytep rp;
  194571. png_uint_32 i;
  194572. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194573. bytes_per_pixel = 3;
  194574. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194575. bytes_per_pixel = 4;
  194576. else
  194577. return;
  194578. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194579. {
  194580. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  194581. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  194582. }
  194583. }
  194584. else if (row_info->bit_depth == 16)
  194585. {
  194586. png_bytep rp;
  194587. png_uint_32 i;
  194588. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194589. bytes_per_pixel = 6;
  194590. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194591. bytes_per_pixel = 8;
  194592. else
  194593. return;
  194594. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194595. {
  194596. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  194597. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  194598. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  194599. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  194600. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  194601. *(rp ) = (png_byte)((red >> 8) & 0xff);
  194602. *(rp+1) = (png_byte)(red & 0xff);
  194603. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  194604. *(rp+5) = (png_byte)(blue & 0xff);
  194605. }
  194606. }
  194607. }
  194608. }
  194609. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  194610. #endif /* PNG_WRITE_SUPPORTED */
  194611. /********* End of inlined file: pngwtran.c *********/
  194612. /********* Start of inlined file: pngwutil.c *********/
  194613. /* pngwutil.c - utilities to write a PNG file
  194614. *
  194615. * Last changed in libpng 1.2.20 Septhember 3, 2007
  194616. * For conditions of distribution and use, see copyright notice in png.h
  194617. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194618. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194619. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194620. */
  194621. #define PNG_INTERNAL
  194622. #ifdef PNG_WRITE_SUPPORTED
  194623. /* Place a 32-bit number into a buffer in PNG byte order. We work
  194624. * with unsigned numbers for convenience, although one supported
  194625. * ancillary chunk uses signed (two's complement) numbers.
  194626. */
  194627. void PNGAPI
  194628. png_save_uint_32(png_bytep buf, png_uint_32 i)
  194629. {
  194630. buf[0] = (png_byte)((i >> 24) & 0xff);
  194631. buf[1] = (png_byte)((i >> 16) & 0xff);
  194632. buf[2] = (png_byte)((i >> 8) & 0xff);
  194633. buf[3] = (png_byte)(i & 0xff);
  194634. }
  194635. /* The png_save_int_32 function assumes integers are stored in two's
  194636. * complement format. If this isn't the case, then this routine needs to
  194637. * be modified to write data in two's complement format.
  194638. */
  194639. void PNGAPI
  194640. png_save_int_32(png_bytep buf, png_int_32 i)
  194641. {
  194642. buf[0] = (png_byte)((i >> 24) & 0xff);
  194643. buf[1] = (png_byte)((i >> 16) & 0xff);
  194644. buf[2] = (png_byte)((i >> 8) & 0xff);
  194645. buf[3] = (png_byte)(i & 0xff);
  194646. }
  194647. /* Place a 16-bit number into a buffer in PNG byte order.
  194648. * The parameter is declared unsigned int, not png_uint_16,
  194649. * just to avoid potential problems on pre-ANSI C compilers.
  194650. */
  194651. void PNGAPI
  194652. png_save_uint_16(png_bytep buf, unsigned int i)
  194653. {
  194654. buf[0] = (png_byte)((i >> 8) & 0xff);
  194655. buf[1] = (png_byte)(i & 0xff);
  194656. }
  194657. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  194658. * representing the chunk name. The array must be at least 4 bytes in
  194659. * length, and does not need to be null terminated. To be safe, pass the
  194660. * pre-defined chunk names here, and if you need a new one, define it
  194661. * where the others are defined. The length is the length of the data.
  194662. * All the data must be present. If that is not possible, use the
  194663. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  194664. * functions instead.
  194665. */
  194666. void PNGAPI
  194667. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  194668. png_bytep data, png_size_t length)
  194669. {
  194670. if(png_ptr == NULL) return;
  194671. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  194672. png_write_chunk_data(png_ptr, data, length);
  194673. png_write_chunk_end(png_ptr);
  194674. }
  194675. /* Write the start of a PNG chunk. The type is the chunk type.
  194676. * The total_length is the sum of the lengths of all the data you will be
  194677. * passing in png_write_chunk_data().
  194678. */
  194679. void PNGAPI
  194680. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  194681. png_uint_32 length)
  194682. {
  194683. png_byte buf[4];
  194684. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  194685. if(png_ptr == NULL) return;
  194686. /* write the length */
  194687. png_save_uint_32(buf, length);
  194688. png_write_data(png_ptr, buf, (png_size_t)4);
  194689. /* write the chunk name */
  194690. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  194691. /* reset the crc and run it over the chunk name */
  194692. png_reset_crc(png_ptr);
  194693. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  194694. }
  194695. /* Write the data of a PNG chunk started with png_write_chunk_start().
  194696. * Note that multiple calls to this function are allowed, and that the
  194697. * sum of the lengths from these calls *must* add up to the total_length
  194698. * given to png_write_chunk_start().
  194699. */
  194700. void PNGAPI
  194701. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  194702. {
  194703. /* write the data, and run the CRC over it */
  194704. if(png_ptr == NULL) return;
  194705. if (data != NULL && length > 0)
  194706. {
  194707. png_calculate_crc(png_ptr, data, length);
  194708. png_write_data(png_ptr, data, length);
  194709. }
  194710. }
  194711. /* Finish a chunk started with png_write_chunk_start(). */
  194712. void PNGAPI
  194713. png_write_chunk_end(png_structp png_ptr)
  194714. {
  194715. png_byte buf[4];
  194716. if(png_ptr == NULL) return;
  194717. /* write the crc */
  194718. png_save_uint_32(buf, png_ptr->crc);
  194719. png_write_data(png_ptr, buf, (png_size_t)4);
  194720. }
  194721. /* Simple function to write the signature. If we have already written
  194722. * the magic bytes of the signature, or more likely, the PNG stream is
  194723. * being embedded into another stream and doesn't need its own signature,
  194724. * we should call png_set_sig_bytes() to tell libpng how many of the
  194725. * bytes have already been written.
  194726. */
  194727. void /* PRIVATE */
  194728. png_write_sig(png_structp png_ptr)
  194729. {
  194730. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  194731. /* write the rest of the 8 byte signature */
  194732. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  194733. (png_size_t)8 - png_ptr->sig_bytes);
  194734. if(png_ptr->sig_bytes < 3)
  194735. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  194736. }
  194737. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  194738. /*
  194739. * This pair of functions encapsulates the operation of (a) compressing a
  194740. * text string, and (b) issuing it later as a series of chunk data writes.
  194741. * The compression_state structure is shared context for these functions
  194742. * set up by the caller in order to make the whole mess thread-safe.
  194743. */
  194744. typedef struct
  194745. {
  194746. char *input; /* the uncompressed input data */
  194747. int input_len; /* its length */
  194748. int num_output_ptr; /* number of output pointers used */
  194749. int max_output_ptr; /* size of output_ptr */
  194750. png_charpp output_ptr; /* array of pointers to output */
  194751. } compression_state;
  194752. /* compress given text into storage in the png_ptr structure */
  194753. static int /* PRIVATE */
  194754. png_text_compress(png_structp png_ptr,
  194755. png_charp text, png_size_t text_len, int compression,
  194756. compression_state *comp)
  194757. {
  194758. int ret;
  194759. comp->num_output_ptr = 0;
  194760. comp->max_output_ptr = 0;
  194761. comp->output_ptr = NULL;
  194762. comp->input = NULL;
  194763. comp->input_len = 0;
  194764. /* we may just want to pass the text right through */
  194765. if (compression == PNG_TEXT_COMPRESSION_NONE)
  194766. {
  194767. comp->input = text;
  194768. comp->input_len = text_len;
  194769. return((int)text_len);
  194770. }
  194771. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  194772. {
  194773. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194774. char msg[50];
  194775. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  194776. png_warning(png_ptr, msg);
  194777. #else
  194778. png_warning(png_ptr, "Unknown compression type");
  194779. #endif
  194780. }
  194781. /* We can't write the chunk until we find out how much data we have,
  194782. * which means we need to run the compressor first and save the
  194783. * output. This shouldn't be a problem, as the vast majority of
  194784. * comments should be reasonable, but we will set up an array of
  194785. * malloc'd pointers to be sure.
  194786. *
  194787. * If we knew the application was well behaved, we could simplify this
  194788. * greatly by assuming we can always malloc an output buffer large
  194789. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  194790. * and malloc this directly. The only time this would be a bad idea is
  194791. * if we can't malloc more than 64K and we have 64K of random input
  194792. * data, or if the input string is incredibly large (although this
  194793. * wouldn't cause a failure, just a slowdown due to swapping).
  194794. */
  194795. /* set up the compression buffers */
  194796. png_ptr->zstream.avail_in = (uInt)text_len;
  194797. png_ptr->zstream.next_in = (Bytef *)text;
  194798. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194799. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  194800. /* this is the same compression loop as in png_write_row() */
  194801. do
  194802. {
  194803. /* compress the data */
  194804. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  194805. if (ret != Z_OK)
  194806. {
  194807. /* error */
  194808. if (png_ptr->zstream.msg != NULL)
  194809. png_error(png_ptr, png_ptr->zstream.msg);
  194810. else
  194811. png_error(png_ptr, "zlib error");
  194812. }
  194813. /* check to see if we need more room */
  194814. if (!(png_ptr->zstream.avail_out))
  194815. {
  194816. /* make sure the output array has room */
  194817. if (comp->num_output_ptr >= comp->max_output_ptr)
  194818. {
  194819. int old_max;
  194820. old_max = comp->max_output_ptr;
  194821. comp->max_output_ptr = comp->num_output_ptr + 4;
  194822. if (comp->output_ptr != NULL)
  194823. {
  194824. png_charpp old_ptr;
  194825. old_ptr = comp->output_ptr;
  194826. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194827. (png_uint_32)(comp->max_output_ptr *
  194828. png_sizeof (png_charpp)));
  194829. png_memcpy(comp->output_ptr, old_ptr, old_max
  194830. * png_sizeof (png_charp));
  194831. png_free(png_ptr, old_ptr);
  194832. }
  194833. else
  194834. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194835. (png_uint_32)(comp->max_output_ptr *
  194836. png_sizeof (png_charp)));
  194837. }
  194838. /* save the data */
  194839. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  194840. (png_uint_32)png_ptr->zbuf_size);
  194841. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  194842. png_ptr->zbuf_size);
  194843. comp->num_output_ptr++;
  194844. /* and reset the buffer */
  194845. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194846. png_ptr->zstream.next_out = png_ptr->zbuf;
  194847. }
  194848. /* continue until we don't have any more to compress */
  194849. } while (png_ptr->zstream.avail_in);
  194850. /* finish the compression */
  194851. do
  194852. {
  194853. /* tell zlib we are finished */
  194854. ret = deflate(&png_ptr->zstream, Z_FINISH);
  194855. if (ret == Z_OK)
  194856. {
  194857. /* check to see if we need more room */
  194858. if (!(png_ptr->zstream.avail_out))
  194859. {
  194860. /* check to make sure our output array has room */
  194861. if (comp->num_output_ptr >= comp->max_output_ptr)
  194862. {
  194863. int old_max;
  194864. old_max = comp->max_output_ptr;
  194865. comp->max_output_ptr = comp->num_output_ptr + 4;
  194866. if (comp->output_ptr != NULL)
  194867. {
  194868. png_charpp old_ptr;
  194869. old_ptr = comp->output_ptr;
  194870. /* This could be optimized to realloc() */
  194871. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194872. (png_uint_32)(comp->max_output_ptr *
  194873. png_sizeof (png_charpp)));
  194874. png_memcpy(comp->output_ptr, old_ptr,
  194875. old_max * png_sizeof (png_charp));
  194876. png_free(png_ptr, old_ptr);
  194877. }
  194878. else
  194879. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194880. (png_uint_32)(comp->max_output_ptr *
  194881. png_sizeof (png_charp)));
  194882. }
  194883. /* save off the data */
  194884. comp->output_ptr[comp->num_output_ptr] =
  194885. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  194886. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  194887. png_ptr->zbuf_size);
  194888. comp->num_output_ptr++;
  194889. /* and reset the buffer pointers */
  194890. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194891. png_ptr->zstream.next_out = png_ptr->zbuf;
  194892. }
  194893. }
  194894. else if (ret != Z_STREAM_END)
  194895. {
  194896. /* we got an error */
  194897. if (png_ptr->zstream.msg != NULL)
  194898. png_error(png_ptr, png_ptr->zstream.msg);
  194899. else
  194900. png_error(png_ptr, "zlib error");
  194901. }
  194902. } while (ret != Z_STREAM_END);
  194903. /* text length is number of buffers plus last buffer */
  194904. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  194905. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  194906. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  194907. return((int)text_len);
  194908. }
  194909. /* ship the compressed text out via chunk writes */
  194910. static void /* PRIVATE */
  194911. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  194912. {
  194913. int i;
  194914. /* handle the no-compression case */
  194915. if (comp->input)
  194916. {
  194917. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  194918. (png_size_t)comp->input_len);
  194919. return;
  194920. }
  194921. /* write saved output buffers, if any */
  194922. for (i = 0; i < comp->num_output_ptr; i++)
  194923. {
  194924. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  194925. png_ptr->zbuf_size);
  194926. png_free(png_ptr, comp->output_ptr[i]);
  194927. comp->output_ptr[i]=NULL;
  194928. }
  194929. if (comp->max_output_ptr != 0)
  194930. png_free(png_ptr, comp->output_ptr);
  194931. comp->output_ptr=NULL;
  194932. /* write anything left in zbuf */
  194933. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  194934. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  194935. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  194936. /* reset zlib for another zTXt/iTXt or image data */
  194937. deflateReset(&png_ptr->zstream);
  194938. png_ptr->zstream.data_type = Z_BINARY;
  194939. }
  194940. #endif
  194941. /* Write the IHDR chunk, and update the png_struct with the necessary
  194942. * information. Note that the rest of this code depends upon this
  194943. * information being correct.
  194944. */
  194945. void /* PRIVATE */
  194946. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  194947. int bit_depth, int color_type, int compression_type, int filter_type,
  194948. int interlace_type)
  194949. {
  194950. #ifdef PNG_USE_LOCAL_ARRAYS
  194951. PNG_IHDR;
  194952. #endif
  194953. png_byte buf[13]; /* buffer to store the IHDR info */
  194954. png_debug(1, "in png_write_IHDR\n");
  194955. /* Check that we have valid input data from the application info */
  194956. switch (color_type)
  194957. {
  194958. case PNG_COLOR_TYPE_GRAY:
  194959. switch (bit_depth)
  194960. {
  194961. case 1:
  194962. case 2:
  194963. case 4:
  194964. case 8:
  194965. case 16: png_ptr->channels = 1; break;
  194966. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  194967. }
  194968. break;
  194969. case PNG_COLOR_TYPE_RGB:
  194970. if (bit_depth != 8 && bit_depth != 16)
  194971. png_error(png_ptr, "Invalid bit depth for RGB image");
  194972. png_ptr->channels = 3;
  194973. break;
  194974. case PNG_COLOR_TYPE_PALETTE:
  194975. switch (bit_depth)
  194976. {
  194977. case 1:
  194978. case 2:
  194979. case 4:
  194980. case 8: png_ptr->channels = 1; break;
  194981. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  194982. }
  194983. break;
  194984. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194985. if (bit_depth != 8 && bit_depth != 16)
  194986. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  194987. png_ptr->channels = 2;
  194988. break;
  194989. case PNG_COLOR_TYPE_RGB_ALPHA:
  194990. if (bit_depth != 8 && bit_depth != 16)
  194991. png_error(png_ptr, "Invalid bit depth for RGBA image");
  194992. png_ptr->channels = 4;
  194993. break;
  194994. default:
  194995. png_error(png_ptr, "Invalid image color type specified");
  194996. }
  194997. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  194998. {
  194999. png_warning(png_ptr, "Invalid compression type specified");
  195000. compression_type = PNG_COMPRESSION_TYPE_BASE;
  195001. }
  195002. /* Write filter_method 64 (intrapixel differencing) only if
  195003. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  195004. * 2. Libpng did not write a PNG signature (this filter_method is only
  195005. * used in PNG datastreams that are embedded in MNG datastreams) and
  195006. * 3. The application called png_permit_mng_features with a mask that
  195007. * included PNG_FLAG_MNG_FILTER_64 and
  195008. * 4. The filter_method is 64 and
  195009. * 5. The color_type is RGB or RGBA
  195010. */
  195011. if (
  195012. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195013. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  195014. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  195015. (color_type == PNG_COLOR_TYPE_RGB ||
  195016. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  195017. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  195018. #endif
  195019. filter_type != PNG_FILTER_TYPE_BASE)
  195020. {
  195021. png_warning(png_ptr, "Invalid filter type specified");
  195022. filter_type = PNG_FILTER_TYPE_BASE;
  195023. }
  195024. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  195025. if (interlace_type != PNG_INTERLACE_NONE &&
  195026. interlace_type != PNG_INTERLACE_ADAM7)
  195027. {
  195028. png_warning(png_ptr, "Invalid interlace type specified");
  195029. interlace_type = PNG_INTERLACE_ADAM7;
  195030. }
  195031. #else
  195032. interlace_type=PNG_INTERLACE_NONE;
  195033. #endif
  195034. /* save off the relevent information */
  195035. png_ptr->bit_depth = (png_byte)bit_depth;
  195036. png_ptr->color_type = (png_byte)color_type;
  195037. png_ptr->interlaced = (png_byte)interlace_type;
  195038. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195039. png_ptr->filter_type = (png_byte)filter_type;
  195040. #endif
  195041. png_ptr->compression_type = (png_byte)compression_type;
  195042. png_ptr->width = width;
  195043. png_ptr->height = height;
  195044. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  195045. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  195046. /* set the usr info, so any transformations can modify it */
  195047. png_ptr->usr_width = png_ptr->width;
  195048. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  195049. png_ptr->usr_channels = png_ptr->channels;
  195050. /* pack the header information into the buffer */
  195051. png_save_uint_32(buf, width);
  195052. png_save_uint_32(buf + 4, height);
  195053. buf[8] = (png_byte)bit_depth;
  195054. buf[9] = (png_byte)color_type;
  195055. buf[10] = (png_byte)compression_type;
  195056. buf[11] = (png_byte)filter_type;
  195057. buf[12] = (png_byte)interlace_type;
  195058. /* write the chunk */
  195059. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  195060. /* initialize zlib with PNG info */
  195061. png_ptr->zstream.zalloc = png_zalloc;
  195062. png_ptr->zstream.zfree = png_zfree;
  195063. png_ptr->zstream.opaque = (voidpf)png_ptr;
  195064. if (!(png_ptr->do_filter))
  195065. {
  195066. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  195067. png_ptr->bit_depth < 8)
  195068. png_ptr->do_filter = PNG_FILTER_NONE;
  195069. else
  195070. png_ptr->do_filter = PNG_ALL_FILTERS;
  195071. }
  195072. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  195073. {
  195074. if (png_ptr->do_filter != PNG_FILTER_NONE)
  195075. png_ptr->zlib_strategy = Z_FILTERED;
  195076. else
  195077. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  195078. }
  195079. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  195080. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  195081. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  195082. png_ptr->zlib_mem_level = 8;
  195083. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  195084. png_ptr->zlib_window_bits = 15;
  195085. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  195086. png_ptr->zlib_method = 8;
  195087. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  195088. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  195089. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  195090. png_error(png_ptr, "zlib failed to initialize compressor");
  195091. png_ptr->zstream.next_out = png_ptr->zbuf;
  195092. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195093. /* libpng is not interested in zstream.data_type */
  195094. /* set it to a predefined value, to avoid its evaluation inside zlib */
  195095. png_ptr->zstream.data_type = Z_BINARY;
  195096. png_ptr->mode = PNG_HAVE_IHDR;
  195097. }
  195098. /* write the palette. We are careful not to trust png_color to be in the
  195099. * correct order for PNG, so people can redefine it to any convenient
  195100. * structure.
  195101. */
  195102. void /* PRIVATE */
  195103. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  195104. {
  195105. #ifdef PNG_USE_LOCAL_ARRAYS
  195106. PNG_PLTE;
  195107. #endif
  195108. png_uint_32 i;
  195109. png_colorp pal_ptr;
  195110. png_byte buf[3];
  195111. png_debug(1, "in png_write_PLTE\n");
  195112. if ((
  195113. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195114. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  195115. #endif
  195116. num_pal == 0) || num_pal > 256)
  195117. {
  195118. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195119. {
  195120. png_error(png_ptr, "Invalid number of colors in palette");
  195121. }
  195122. else
  195123. {
  195124. png_warning(png_ptr, "Invalid number of colors in palette");
  195125. return;
  195126. }
  195127. }
  195128. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  195129. {
  195130. png_warning(png_ptr,
  195131. "Ignoring request to write a PLTE chunk in grayscale PNG");
  195132. return;
  195133. }
  195134. png_ptr->num_palette = (png_uint_16)num_pal;
  195135. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  195136. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  195137. #ifndef PNG_NO_POINTER_INDEXING
  195138. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  195139. {
  195140. buf[0] = pal_ptr->red;
  195141. buf[1] = pal_ptr->green;
  195142. buf[2] = pal_ptr->blue;
  195143. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  195144. }
  195145. #else
  195146. /* This is a little slower but some buggy compilers need to do this instead */
  195147. pal_ptr=palette;
  195148. for (i = 0; i < num_pal; i++)
  195149. {
  195150. buf[0] = pal_ptr[i].red;
  195151. buf[1] = pal_ptr[i].green;
  195152. buf[2] = pal_ptr[i].blue;
  195153. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  195154. }
  195155. #endif
  195156. png_write_chunk_end(png_ptr);
  195157. png_ptr->mode |= PNG_HAVE_PLTE;
  195158. }
  195159. /* write an IDAT chunk */
  195160. void /* PRIVATE */
  195161. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  195162. {
  195163. #ifdef PNG_USE_LOCAL_ARRAYS
  195164. PNG_IDAT;
  195165. #endif
  195166. png_debug(1, "in png_write_IDAT\n");
  195167. /* Optimize the CMF field in the zlib stream. */
  195168. /* This hack of the zlib stream is compliant to the stream specification. */
  195169. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  195170. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  195171. {
  195172. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  195173. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  195174. {
  195175. /* Avoid memory underflows and multiplication overflows. */
  195176. /* The conditions below are practically always satisfied;
  195177. however, they still must be checked. */
  195178. if (length >= 2 &&
  195179. png_ptr->height < 16384 && png_ptr->width < 16384)
  195180. {
  195181. png_uint_32 uncompressed_idat_size = png_ptr->height *
  195182. ((png_ptr->width *
  195183. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  195184. unsigned int z_cinfo = z_cmf >> 4;
  195185. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  195186. while (uncompressed_idat_size <= half_z_window_size &&
  195187. half_z_window_size >= 256)
  195188. {
  195189. z_cinfo--;
  195190. half_z_window_size >>= 1;
  195191. }
  195192. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  195193. if (data[0] != (png_byte)z_cmf)
  195194. {
  195195. data[0] = (png_byte)z_cmf;
  195196. data[1] &= 0xe0;
  195197. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  195198. }
  195199. }
  195200. }
  195201. else
  195202. png_error(png_ptr,
  195203. "Invalid zlib compression method or flags in IDAT");
  195204. }
  195205. png_write_chunk(png_ptr, png_IDAT, data, length);
  195206. png_ptr->mode |= PNG_HAVE_IDAT;
  195207. }
  195208. /* write an IEND chunk */
  195209. void /* PRIVATE */
  195210. png_write_IEND(png_structp png_ptr)
  195211. {
  195212. #ifdef PNG_USE_LOCAL_ARRAYS
  195213. PNG_IEND;
  195214. #endif
  195215. png_debug(1, "in png_write_IEND\n");
  195216. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  195217. (png_size_t)0);
  195218. png_ptr->mode |= PNG_HAVE_IEND;
  195219. }
  195220. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  195221. /* write a gAMA chunk */
  195222. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195223. void /* PRIVATE */
  195224. png_write_gAMA(png_structp png_ptr, double file_gamma)
  195225. {
  195226. #ifdef PNG_USE_LOCAL_ARRAYS
  195227. PNG_gAMA;
  195228. #endif
  195229. png_uint_32 igamma;
  195230. png_byte buf[4];
  195231. png_debug(1, "in png_write_gAMA\n");
  195232. /* file_gamma is saved in 1/100,000ths */
  195233. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  195234. png_save_uint_32(buf, igamma);
  195235. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  195236. }
  195237. #endif
  195238. #ifdef PNG_FIXED_POINT_SUPPORTED
  195239. void /* PRIVATE */
  195240. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  195241. {
  195242. #ifdef PNG_USE_LOCAL_ARRAYS
  195243. PNG_gAMA;
  195244. #endif
  195245. png_byte buf[4];
  195246. png_debug(1, "in png_write_gAMA\n");
  195247. /* file_gamma is saved in 1/100,000ths */
  195248. png_save_uint_32(buf, (png_uint_32)file_gamma);
  195249. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  195250. }
  195251. #endif
  195252. #endif
  195253. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  195254. /* write a sRGB chunk */
  195255. void /* PRIVATE */
  195256. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  195257. {
  195258. #ifdef PNG_USE_LOCAL_ARRAYS
  195259. PNG_sRGB;
  195260. #endif
  195261. png_byte buf[1];
  195262. png_debug(1, "in png_write_sRGB\n");
  195263. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  195264. png_warning(png_ptr,
  195265. "Invalid sRGB rendering intent specified");
  195266. buf[0]=(png_byte)srgb_intent;
  195267. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  195268. }
  195269. #endif
  195270. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  195271. /* write an iCCP chunk */
  195272. void /* PRIVATE */
  195273. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  195274. png_charp profile, int profile_len)
  195275. {
  195276. #ifdef PNG_USE_LOCAL_ARRAYS
  195277. PNG_iCCP;
  195278. #endif
  195279. png_size_t name_len;
  195280. png_charp new_name;
  195281. compression_state comp;
  195282. int embedded_profile_len = 0;
  195283. png_debug(1, "in png_write_iCCP\n");
  195284. comp.num_output_ptr = 0;
  195285. comp.max_output_ptr = 0;
  195286. comp.output_ptr = NULL;
  195287. comp.input = NULL;
  195288. comp.input_len = 0;
  195289. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  195290. &new_name)) == 0)
  195291. {
  195292. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  195293. return;
  195294. }
  195295. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  195296. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  195297. if (profile == NULL)
  195298. profile_len = 0;
  195299. if (profile_len > 3)
  195300. embedded_profile_len =
  195301. ((*( (png_bytep)profile ))<<24) |
  195302. ((*( (png_bytep)profile+1))<<16) |
  195303. ((*( (png_bytep)profile+2))<< 8) |
  195304. ((*( (png_bytep)profile+3)) );
  195305. if (profile_len < embedded_profile_len)
  195306. {
  195307. png_warning(png_ptr,
  195308. "Embedded profile length too large in iCCP chunk");
  195309. return;
  195310. }
  195311. if (profile_len > embedded_profile_len)
  195312. {
  195313. png_warning(png_ptr,
  195314. "Truncating profile to actual length in iCCP chunk");
  195315. profile_len = embedded_profile_len;
  195316. }
  195317. if (profile_len)
  195318. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  195319. PNG_COMPRESSION_TYPE_BASE, &comp);
  195320. /* make sure we include the NULL after the name and the compression type */
  195321. png_write_chunk_start(png_ptr, png_iCCP,
  195322. (png_uint_32)name_len+profile_len+2);
  195323. new_name[name_len+1]=0x00;
  195324. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  195325. if (profile_len)
  195326. png_write_compressed_data_out(png_ptr, &comp);
  195327. png_write_chunk_end(png_ptr);
  195328. png_free(png_ptr, new_name);
  195329. }
  195330. #endif
  195331. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  195332. /* write a sPLT chunk */
  195333. void /* PRIVATE */
  195334. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  195335. {
  195336. #ifdef PNG_USE_LOCAL_ARRAYS
  195337. PNG_sPLT;
  195338. #endif
  195339. png_size_t name_len;
  195340. png_charp new_name;
  195341. png_byte entrybuf[10];
  195342. int entry_size = (spalette->depth == 8 ? 6 : 10);
  195343. int palette_size = entry_size * spalette->nentries;
  195344. png_sPLT_entryp ep;
  195345. #ifdef PNG_NO_POINTER_INDEXING
  195346. int i;
  195347. #endif
  195348. png_debug(1, "in png_write_sPLT\n");
  195349. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  195350. spalette->name, &new_name))==0)
  195351. {
  195352. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  195353. return;
  195354. }
  195355. /* make sure we include the NULL after the name */
  195356. png_write_chunk_start(png_ptr, png_sPLT,
  195357. (png_uint_32)(name_len + 2 + palette_size));
  195358. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  195359. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  195360. /* loop through each palette entry, writing appropriately */
  195361. #ifndef PNG_NO_POINTER_INDEXING
  195362. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  195363. {
  195364. if (spalette->depth == 8)
  195365. {
  195366. entrybuf[0] = (png_byte)ep->red;
  195367. entrybuf[1] = (png_byte)ep->green;
  195368. entrybuf[2] = (png_byte)ep->blue;
  195369. entrybuf[3] = (png_byte)ep->alpha;
  195370. png_save_uint_16(entrybuf + 4, ep->frequency);
  195371. }
  195372. else
  195373. {
  195374. png_save_uint_16(entrybuf + 0, ep->red);
  195375. png_save_uint_16(entrybuf + 2, ep->green);
  195376. png_save_uint_16(entrybuf + 4, ep->blue);
  195377. png_save_uint_16(entrybuf + 6, ep->alpha);
  195378. png_save_uint_16(entrybuf + 8, ep->frequency);
  195379. }
  195380. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  195381. }
  195382. #else
  195383. ep=spalette->entries;
  195384. for (i=0; i>spalette->nentries; i++)
  195385. {
  195386. if (spalette->depth == 8)
  195387. {
  195388. entrybuf[0] = (png_byte)ep[i].red;
  195389. entrybuf[1] = (png_byte)ep[i].green;
  195390. entrybuf[2] = (png_byte)ep[i].blue;
  195391. entrybuf[3] = (png_byte)ep[i].alpha;
  195392. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  195393. }
  195394. else
  195395. {
  195396. png_save_uint_16(entrybuf + 0, ep[i].red);
  195397. png_save_uint_16(entrybuf + 2, ep[i].green);
  195398. png_save_uint_16(entrybuf + 4, ep[i].blue);
  195399. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  195400. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  195401. }
  195402. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  195403. }
  195404. #endif
  195405. png_write_chunk_end(png_ptr);
  195406. png_free(png_ptr, new_name);
  195407. }
  195408. #endif
  195409. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  195410. /* write the sBIT chunk */
  195411. void /* PRIVATE */
  195412. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  195413. {
  195414. #ifdef PNG_USE_LOCAL_ARRAYS
  195415. PNG_sBIT;
  195416. #endif
  195417. png_byte buf[4];
  195418. png_size_t size;
  195419. png_debug(1, "in png_write_sBIT\n");
  195420. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  195421. if (color_type & PNG_COLOR_MASK_COLOR)
  195422. {
  195423. png_byte maxbits;
  195424. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  195425. png_ptr->usr_bit_depth);
  195426. if (sbit->red == 0 || sbit->red > maxbits ||
  195427. sbit->green == 0 || sbit->green > maxbits ||
  195428. sbit->blue == 0 || sbit->blue > maxbits)
  195429. {
  195430. png_warning(png_ptr, "Invalid sBIT depth specified");
  195431. return;
  195432. }
  195433. buf[0] = sbit->red;
  195434. buf[1] = sbit->green;
  195435. buf[2] = sbit->blue;
  195436. size = 3;
  195437. }
  195438. else
  195439. {
  195440. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  195441. {
  195442. png_warning(png_ptr, "Invalid sBIT depth specified");
  195443. return;
  195444. }
  195445. buf[0] = sbit->gray;
  195446. size = 1;
  195447. }
  195448. if (color_type & PNG_COLOR_MASK_ALPHA)
  195449. {
  195450. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  195451. {
  195452. png_warning(png_ptr, "Invalid sBIT depth specified");
  195453. return;
  195454. }
  195455. buf[size++] = sbit->alpha;
  195456. }
  195457. png_write_chunk(png_ptr, png_sBIT, buf, size);
  195458. }
  195459. #endif
  195460. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  195461. /* write the cHRM chunk */
  195462. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195463. void /* PRIVATE */
  195464. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  195465. double red_x, double red_y, double green_x, double green_y,
  195466. double blue_x, double blue_y)
  195467. {
  195468. #ifdef PNG_USE_LOCAL_ARRAYS
  195469. PNG_cHRM;
  195470. #endif
  195471. png_byte buf[32];
  195472. png_uint_32 itemp;
  195473. png_debug(1, "in png_write_cHRM\n");
  195474. /* each value is saved in 1/100,000ths */
  195475. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  195476. white_x + white_y > 1.0)
  195477. {
  195478. png_warning(png_ptr, "Invalid cHRM white point specified");
  195479. #if !defined(PNG_NO_CONSOLE_IO)
  195480. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  195481. #endif
  195482. return;
  195483. }
  195484. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  195485. png_save_uint_32(buf, itemp);
  195486. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  195487. png_save_uint_32(buf + 4, itemp);
  195488. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  195489. {
  195490. png_warning(png_ptr, "Invalid cHRM red point specified");
  195491. return;
  195492. }
  195493. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  195494. png_save_uint_32(buf + 8, itemp);
  195495. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  195496. png_save_uint_32(buf + 12, itemp);
  195497. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  195498. {
  195499. png_warning(png_ptr, "Invalid cHRM green point specified");
  195500. return;
  195501. }
  195502. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  195503. png_save_uint_32(buf + 16, itemp);
  195504. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  195505. png_save_uint_32(buf + 20, itemp);
  195506. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  195507. {
  195508. png_warning(png_ptr, "Invalid cHRM blue point specified");
  195509. return;
  195510. }
  195511. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  195512. png_save_uint_32(buf + 24, itemp);
  195513. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  195514. png_save_uint_32(buf + 28, itemp);
  195515. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  195516. }
  195517. #endif
  195518. #ifdef PNG_FIXED_POINT_SUPPORTED
  195519. void /* PRIVATE */
  195520. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  195521. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  195522. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  195523. png_fixed_point blue_y)
  195524. {
  195525. #ifdef PNG_USE_LOCAL_ARRAYS
  195526. PNG_cHRM;
  195527. #endif
  195528. png_byte buf[32];
  195529. png_debug(1, "in png_write_cHRM\n");
  195530. /* each value is saved in 1/100,000ths */
  195531. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  195532. {
  195533. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  195534. #if !defined(PNG_NO_CONSOLE_IO)
  195535. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  195536. #endif
  195537. return;
  195538. }
  195539. png_save_uint_32(buf, (png_uint_32)white_x);
  195540. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  195541. if (red_x + red_y > 100000L)
  195542. {
  195543. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  195544. return;
  195545. }
  195546. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  195547. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  195548. if (green_x + green_y > 100000L)
  195549. {
  195550. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  195551. return;
  195552. }
  195553. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  195554. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  195555. if (blue_x + blue_y > 100000L)
  195556. {
  195557. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  195558. return;
  195559. }
  195560. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  195561. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  195562. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  195563. }
  195564. #endif
  195565. #endif
  195566. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  195567. /* write the tRNS chunk */
  195568. void /* PRIVATE */
  195569. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  195570. int num_trans, int color_type)
  195571. {
  195572. #ifdef PNG_USE_LOCAL_ARRAYS
  195573. PNG_tRNS;
  195574. #endif
  195575. png_byte buf[6];
  195576. png_debug(1, "in png_write_tRNS\n");
  195577. if (color_type == PNG_COLOR_TYPE_PALETTE)
  195578. {
  195579. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  195580. {
  195581. png_warning(png_ptr,"Invalid number of transparent colors specified");
  195582. return;
  195583. }
  195584. /* write the chunk out as it is */
  195585. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  195586. }
  195587. else if (color_type == PNG_COLOR_TYPE_GRAY)
  195588. {
  195589. /* one 16 bit value */
  195590. if(tran->gray >= (1 << png_ptr->bit_depth))
  195591. {
  195592. png_warning(png_ptr,
  195593. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  195594. return;
  195595. }
  195596. png_save_uint_16(buf, tran->gray);
  195597. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  195598. }
  195599. else if (color_type == PNG_COLOR_TYPE_RGB)
  195600. {
  195601. /* three 16 bit values */
  195602. png_save_uint_16(buf, tran->red);
  195603. png_save_uint_16(buf + 2, tran->green);
  195604. png_save_uint_16(buf + 4, tran->blue);
  195605. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  195606. {
  195607. png_warning(png_ptr,
  195608. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  195609. return;
  195610. }
  195611. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  195612. }
  195613. else
  195614. {
  195615. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  195616. }
  195617. }
  195618. #endif
  195619. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  195620. /* write the background chunk */
  195621. void /* PRIVATE */
  195622. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  195623. {
  195624. #ifdef PNG_USE_LOCAL_ARRAYS
  195625. PNG_bKGD;
  195626. #endif
  195627. png_byte buf[6];
  195628. png_debug(1, "in png_write_bKGD\n");
  195629. if (color_type == PNG_COLOR_TYPE_PALETTE)
  195630. {
  195631. if (
  195632. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195633. (png_ptr->num_palette ||
  195634. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  195635. #endif
  195636. back->index > png_ptr->num_palette)
  195637. {
  195638. png_warning(png_ptr, "Invalid background palette index");
  195639. return;
  195640. }
  195641. buf[0] = back->index;
  195642. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  195643. }
  195644. else if (color_type & PNG_COLOR_MASK_COLOR)
  195645. {
  195646. png_save_uint_16(buf, back->red);
  195647. png_save_uint_16(buf + 2, back->green);
  195648. png_save_uint_16(buf + 4, back->blue);
  195649. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  195650. {
  195651. png_warning(png_ptr,
  195652. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  195653. return;
  195654. }
  195655. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  195656. }
  195657. else
  195658. {
  195659. if(back->gray >= (1 << png_ptr->bit_depth))
  195660. {
  195661. png_warning(png_ptr,
  195662. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  195663. return;
  195664. }
  195665. png_save_uint_16(buf, back->gray);
  195666. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  195667. }
  195668. }
  195669. #endif
  195670. #if defined(PNG_WRITE_hIST_SUPPORTED)
  195671. /* write the histogram */
  195672. void /* PRIVATE */
  195673. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  195674. {
  195675. #ifdef PNG_USE_LOCAL_ARRAYS
  195676. PNG_hIST;
  195677. #endif
  195678. int i;
  195679. png_byte buf[3];
  195680. png_debug(1, "in png_write_hIST\n");
  195681. if (num_hist > (int)png_ptr->num_palette)
  195682. {
  195683. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  195684. png_ptr->num_palette);
  195685. png_warning(png_ptr, "Invalid number of histogram entries specified");
  195686. return;
  195687. }
  195688. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  195689. for (i = 0; i < num_hist; i++)
  195690. {
  195691. png_save_uint_16(buf, hist[i]);
  195692. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  195693. }
  195694. png_write_chunk_end(png_ptr);
  195695. }
  195696. #endif
  195697. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  195698. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  195699. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  195700. * and if invalid, correct the keyword rather than discarding the entire
  195701. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  195702. * length, forbids leading or trailing whitespace, multiple internal spaces,
  195703. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  195704. *
  195705. * The new_key is allocated to hold the corrected keyword and must be freed
  195706. * by the calling routine. This avoids problems with trying to write to
  195707. * static keywords without having to have duplicate copies of the strings.
  195708. */
  195709. png_size_t /* PRIVATE */
  195710. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  195711. {
  195712. png_size_t key_len;
  195713. png_charp kp, dp;
  195714. int kflag;
  195715. int kwarn=0;
  195716. png_debug(1, "in png_check_keyword\n");
  195717. *new_key = NULL;
  195718. if (key == NULL || (key_len = png_strlen(key)) == 0)
  195719. {
  195720. png_warning(png_ptr, "zero length keyword");
  195721. return ((png_size_t)0);
  195722. }
  195723. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  195724. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  195725. if (*new_key == NULL)
  195726. {
  195727. png_warning(png_ptr, "Out of memory while procesing keyword");
  195728. return ((png_size_t)0);
  195729. }
  195730. /* Replace non-printing characters with a blank and print a warning */
  195731. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  195732. {
  195733. if ((png_byte)*kp < 0x20 ||
  195734. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  195735. {
  195736. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  195737. char msg[40];
  195738. png_snprintf(msg, 40,
  195739. "invalid keyword character 0x%02X", (png_byte)*kp);
  195740. png_warning(png_ptr, msg);
  195741. #else
  195742. png_warning(png_ptr, "invalid character in keyword");
  195743. #endif
  195744. *dp = ' ';
  195745. }
  195746. else
  195747. {
  195748. *dp = *kp;
  195749. }
  195750. }
  195751. *dp = '\0';
  195752. /* Remove any trailing white space. */
  195753. kp = *new_key + key_len - 1;
  195754. if (*kp == ' ')
  195755. {
  195756. png_warning(png_ptr, "trailing spaces removed from keyword");
  195757. while (*kp == ' ')
  195758. {
  195759. *(kp--) = '\0';
  195760. key_len--;
  195761. }
  195762. }
  195763. /* Remove any leading white space. */
  195764. kp = *new_key;
  195765. if (*kp == ' ')
  195766. {
  195767. png_warning(png_ptr, "leading spaces removed from keyword");
  195768. while (*kp == ' ')
  195769. {
  195770. kp++;
  195771. key_len--;
  195772. }
  195773. }
  195774. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  195775. /* Remove multiple internal spaces. */
  195776. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  195777. {
  195778. if (*kp == ' ' && kflag == 0)
  195779. {
  195780. *(dp++) = *kp;
  195781. kflag = 1;
  195782. }
  195783. else if (*kp == ' ')
  195784. {
  195785. key_len--;
  195786. kwarn=1;
  195787. }
  195788. else
  195789. {
  195790. *(dp++) = *kp;
  195791. kflag = 0;
  195792. }
  195793. }
  195794. *dp = '\0';
  195795. if(kwarn)
  195796. png_warning(png_ptr, "extra interior spaces removed from keyword");
  195797. if (key_len == 0)
  195798. {
  195799. png_free(png_ptr, *new_key);
  195800. *new_key=NULL;
  195801. png_warning(png_ptr, "Zero length keyword");
  195802. }
  195803. if (key_len > 79)
  195804. {
  195805. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  195806. new_key[79] = '\0';
  195807. key_len = 79;
  195808. }
  195809. return (key_len);
  195810. }
  195811. #endif
  195812. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  195813. /* write a tEXt chunk */
  195814. void /* PRIVATE */
  195815. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  195816. png_size_t text_len)
  195817. {
  195818. #ifdef PNG_USE_LOCAL_ARRAYS
  195819. PNG_tEXt;
  195820. #endif
  195821. png_size_t key_len;
  195822. png_charp new_key;
  195823. png_debug(1, "in png_write_tEXt\n");
  195824. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  195825. {
  195826. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  195827. return;
  195828. }
  195829. if (text == NULL || *text == '\0')
  195830. text_len = 0;
  195831. else
  195832. text_len = png_strlen(text);
  195833. /* make sure we include the 0 after the key */
  195834. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  195835. /*
  195836. * We leave it to the application to meet PNG-1.0 requirements on the
  195837. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  195838. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  195839. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  195840. */
  195841. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  195842. if (text_len)
  195843. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  195844. png_write_chunk_end(png_ptr);
  195845. png_free(png_ptr, new_key);
  195846. }
  195847. #endif
  195848. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  195849. /* write a compressed text chunk */
  195850. void /* PRIVATE */
  195851. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  195852. png_size_t text_len, int compression)
  195853. {
  195854. #ifdef PNG_USE_LOCAL_ARRAYS
  195855. PNG_zTXt;
  195856. #endif
  195857. png_size_t key_len;
  195858. char buf[1];
  195859. png_charp new_key;
  195860. compression_state comp;
  195861. png_debug(1, "in png_write_zTXt\n");
  195862. comp.num_output_ptr = 0;
  195863. comp.max_output_ptr = 0;
  195864. comp.output_ptr = NULL;
  195865. comp.input = NULL;
  195866. comp.input_len = 0;
  195867. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  195868. {
  195869. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  195870. return;
  195871. }
  195872. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  195873. {
  195874. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  195875. png_free(png_ptr, new_key);
  195876. return;
  195877. }
  195878. text_len = png_strlen(text);
  195879. /* compute the compressed data; do it now for the length */
  195880. text_len = png_text_compress(png_ptr, text, text_len, compression,
  195881. &comp);
  195882. /* write start of chunk */
  195883. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  195884. (key_len+text_len+2));
  195885. /* write key */
  195886. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  195887. png_free(png_ptr, new_key);
  195888. buf[0] = (png_byte)compression;
  195889. /* write compression */
  195890. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  195891. /* write the compressed data */
  195892. png_write_compressed_data_out(png_ptr, &comp);
  195893. /* close the chunk */
  195894. png_write_chunk_end(png_ptr);
  195895. }
  195896. #endif
  195897. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  195898. /* write an iTXt chunk */
  195899. void /* PRIVATE */
  195900. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  195901. png_charp lang, png_charp lang_key, png_charp text)
  195902. {
  195903. #ifdef PNG_USE_LOCAL_ARRAYS
  195904. PNG_iTXt;
  195905. #endif
  195906. png_size_t lang_len, key_len, lang_key_len, text_len;
  195907. png_charp new_lang, new_key;
  195908. png_byte cbuf[2];
  195909. compression_state comp;
  195910. png_debug(1, "in png_write_iTXt\n");
  195911. comp.num_output_ptr = 0;
  195912. comp.max_output_ptr = 0;
  195913. comp.output_ptr = NULL;
  195914. comp.input = NULL;
  195915. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  195916. {
  195917. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  195918. return;
  195919. }
  195920. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  195921. {
  195922. png_warning(png_ptr, "Empty language field in iTXt chunk");
  195923. new_lang = NULL;
  195924. lang_len = 0;
  195925. }
  195926. if (lang_key == NULL)
  195927. lang_key_len = 0;
  195928. else
  195929. lang_key_len = png_strlen(lang_key);
  195930. if (text == NULL)
  195931. text_len = 0;
  195932. else
  195933. text_len = png_strlen(text);
  195934. /* compute the compressed data; do it now for the length */
  195935. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  195936. &comp);
  195937. /* make sure we include the compression flag, the compression byte,
  195938. * and the NULs after the key, lang, and lang_key parts */
  195939. png_write_chunk_start(png_ptr, png_iTXt,
  195940. (png_uint_32)(
  195941. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  195942. + key_len
  195943. + lang_len
  195944. + lang_key_len
  195945. + text_len));
  195946. /*
  195947. * We leave it to the application to meet PNG-1.0 requirements on the
  195948. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  195949. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  195950. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  195951. */
  195952. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  195953. /* set the compression flag */
  195954. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  195955. compression == PNG_TEXT_COMPRESSION_NONE)
  195956. cbuf[0] = 0;
  195957. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  195958. cbuf[0] = 1;
  195959. /* set the compression method */
  195960. cbuf[1] = 0;
  195961. png_write_chunk_data(png_ptr, cbuf, 2);
  195962. cbuf[0] = 0;
  195963. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  195964. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  195965. png_write_compressed_data_out(png_ptr, &comp);
  195966. png_write_chunk_end(png_ptr);
  195967. png_free(png_ptr, new_key);
  195968. if (new_lang)
  195969. png_free(png_ptr, new_lang);
  195970. }
  195971. #endif
  195972. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  195973. /* write the oFFs chunk */
  195974. void /* PRIVATE */
  195975. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  195976. int unit_type)
  195977. {
  195978. #ifdef PNG_USE_LOCAL_ARRAYS
  195979. PNG_oFFs;
  195980. #endif
  195981. png_byte buf[9];
  195982. png_debug(1, "in png_write_oFFs\n");
  195983. if (unit_type >= PNG_OFFSET_LAST)
  195984. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  195985. png_save_int_32(buf, x_offset);
  195986. png_save_int_32(buf + 4, y_offset);
  195987. buf[8] = (png_byte)unit_type;
  195988. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  195989. }
  195990. #endif
  195991. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  195992. /* write the pCAL chunk (described in the PNG extensions document) */
  195993. void /* PRIVATE */
  195994. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  195995. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  195996. {
  195997. #ifdef PNG_USE_LOCAL_ARRAYS
  195998. PNG_pCAL;
  195999. #endif
  196000. png_size_t purpose_len, units_len, total_len;
  196001. png_uint_32p params_len;
  196002. png_byte buf[10];
  196003. png_charp new_purpose;
  196004. int i;
  196005. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  196006. if (type >= PNG_EQUATION_LAST)
  196007. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  196008. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  196009. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  196010. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  196011. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  196012. total_len = purpose_len + units_len + 10;
  196013. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  196014. *png_sizeof(png_uint_32)));
  196015. /* Find the length of each parameter, making sure we don't count the
  196016. null terminator for the last parameter. */
  196017. for (i = 0; i < nparams; i++)
  196018. {
  196019. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  196020. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  196021. total_len += (png_size_t)params_len[i];
  196022. }
  196023. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  196024. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  196025. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  196026. png_save_int_32(buf, X0);
  196027. png_save_int_32(buf + 4, X1);
  196028. buf[8] = (png_byte)type;
  196029. buf[9] = (png_byte)nparams;
  196030. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  196031. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  196032. png_free(png_ptr, new_purpose);
  196033. for (i = 0; i < nparams; i++)
  196034. {
  196035. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  196036. (png_size_t)params_len[i]);
  196037. }
  196038. png_free(png_ptr, params_len);
  196039. png_write_chunk_end(png_ptr);
  196040. }
  196041. #endif
  196042. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  196043. /* write the sCAL chunk */
  196044. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  196045. void /* PRIVATE */
  196046. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  196047. {
  196048. #ifdef PNG_USE_LOCAL_ARRAYS
  196049. PNG_sCAL;
  196050. #endif
  196051. char buf[64];
  196052. png_size_t total_len;
  196053. png_debug(1, "in png_write_sCAL\n");
  196054. buf[0] = (char)unit;
  196055. #if defined(_WIN32_WCE)
  196056. /* sprintf() function is not supported on WindowsCE */
  196057. {
  196058. wchar_t wc_buf[32];
  196059. size_t wc_len;
  196060. swprintf(wc_buf, TEXT("%12.12e"), width);
  196061. wc_len = wcslen(wc_buf);
  196062. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  196063. total_len = wc_len + 2;
  196064. swprintf(wc_buf, TEXT("%12.12e"), height);
  196065. wc_len = wcslen(wc_buf);
  196066. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  196067. NULL, NULL);
  196068. total_len += wc_len;
  196069. }
  196070. #else
  196071. png_snprintf(buf + 1, 63, "%12.12e", width);
  196072. total_len = 1 + png_strlen(buf + 1) + 1;
  196073. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  196074. total_len += png_strlen(buf + total_len);
  196075. #endif
  196076. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  196077. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  196078. }
  196079. #else
  196080. #ifdef PNG_FIXED_POINT_SUPPORTED
  196081. void /* PRIVATE */
  196082. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  196083. png_charp height)
  196084. {
  196085. #ifdef PNG_USE_LOCAL_ARRAYS
  196086. PNG_sCAL;
  196087. #endif
  196088. png_byte buf[64];
  196089. png_size_t wlen, hlen, total_len;
  196090. png_debug(1, "in png_write_sCAL_s\n");
  196091. wlen = png_strlen(width);
  196092. hlen = png_strlen(height);
  196093. total_len = wlen + hlen + 2;
  196094. if (total_len > 64)
  196095. {
  196096. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  196097. return;
  196098. }
  196099. buf[0] = (png_byte)unit;
  196100. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  196101. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  196102. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  196103. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  196104. }
  196105. #endif
  196106. #endif
  196107. #endif
  196108. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  196109. /* write the pHYs chunk */
  196110. void /* PRIVATE */
  196111. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  196112. png_uint_32 y_pixels_per_unit,
  196113. int unit_type)
  196114. {
  196115. #ifdef PNG_USE_LOCAL_ARRAYS
  196116. PNG_pHYs;
  196117. #endif
  196118. png_byte buf[9];
  196119. png_debug(1, "in png_write_pHYs\n");
  196120. if (unit_type >= PNG_RESOLUTION_LAST)
  196121. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  196122. png_save_uint_32(buf, x_pixels_per_unit);
  196123. png_save_uint_32(buf + 4, y_pixels_per_unit);
  196124. buf[8] = (png_byte)unit_type;
  196125. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  196126. }
  196127. #endif
  196128. #if defined(PNG_WRITE_tIME_SUPPORTED)
  196129. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  196130. * or png_convert_from_time_t(), or fill in the structure yourself.
  196131. */
  196132. void /* PRIVATE */
  196133. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  196134. {
  196135. #ifdef PNG_USE_LOCAL_ARRAYS
  196136. PNG_tIME;
  196137. #endif
  196138. png_byte buf[7];
  196139. png_debug(1, "in png_write_tIME\n");
  196140. if (mod_time->month > 12 || mod_time->month < 1 ||
  196141. mod_time->day > 31 || mod_time->day < 1 ||
  196142. mod_time->hour > 23 || mod_time->second > 60)
  196143. {
  196144. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  196145. return;
  196146. }
  196147. png_save_uint_16(buf, mod_time->year);
  196148. buf[2] = mod_time->month;
  196149. buf[3] = mod_time->day;
  196150. buf[4] = mod_time->hour;
  196151. buf[5] = mod_time->minute;
  196152. buf[6] = mod_time->second;
  196153. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  196154. }
  196155. #endif
  196156. /* initializes the row writing capability of libpng */
  196157. void /* PRIVATE */
  196158. png_write_start_row(png_structp png_ptr)
  196159. {
  196160. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  196161. #ifdef PNG_USE_LOCAL_ARRAYS
  196162. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196163. /* start of interlace block */
  196164. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196165. /* offset to next interlace block */
  196166. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196167. /* start of interlace block in the y direction */
  196168. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196169. /* offset to next interlace block in the y direction */
  196170. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196171. #endif
  196172. #endif
  196173. png_size_t buf_size;
  196174. png_debug(1, "in png_write_start_row\n");
  196175. buf_size = (png_size_t)(PNG_ROWBYTES(
  196176. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  196177. /* set up row buffer */
  196178. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  196179. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  196180. #ifndef PNG_NO_WRITE_FILTERING
  196181. /* set up filtering buffer, if using this filter */
  196182. if (png_ptr->do_filter & PNG_FILTER_SUB)
  196183. {
  196184. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  196185. (png_ptr->rowbytes + 1));
  196186. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  196187. }
  196188. /* We only need to keep the previous row if we are using one of these. */
  196189. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  196190. {
  196191. /* set up previous row buffer */
  196192. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  196193. png_memset(png_ptr->prev_row, 0, buf_size);
  196194. if (png_ptr->do_filter & PNG_FILTER_UP)
  196195. {
  196196. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  196197. (png_ptr->rowbytes + 1));
  196198. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  196199. }
  196200. if (png_ptr->do_filter & PNG_FILTER_AVG)
  196201. {
  196202. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  196203. (png_ptr->rowbytes + 1));
  196204. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  196205. }
  196206. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  196207. {
  196208. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  196209. (png_ptr->rowbytes + 1));
  196210. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  196211. }
  196212. #endif /* PNG_NO_WRITE_FILTERING */
  196213. }
  196214. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  196215. /* if interlaced, we need to set up width and height of pass */
  196216. if (png_ptr->interlaced)
  196217. {
  196218. if (!(png_ptr->transformations & PNG_INTERLACE))
  196219. {
  196220. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196221. png_pass_ystart[0]) / png_pass_yinc[0];
  196222. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  196223. png_pass_start[0]) / png_pass_inc[0];
  196224. }
  196225. else
  196226. {
  196227. png_ptr->num_rows = png_ptr->height;
  196228. png_ptr->usr_width = png_ptr->width;
  196229. }
  196230. }
  196231. else
  196232. #endif
  196233. {
  196234. png_ptr->num_rows = png_ptr->height;
  196235. png_ptr->usr_width = png_ptr->width;
  196236. }
  196237. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196238. png_ptr->zstream.next_out = png_ptr->zbuf;
  196239. }
  196240. /* Internal use only. Called when finished processing a row of data. */
  196241. void /* PRIVATE */
  196242. png_write_finish_row(png_structp png_ptr)
  196243. {
  196244. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  196245. #ifdef PNG_USE_LOCAL_ARRAYS
  196246. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196247. /* start of interlace block */
  196248. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196249. /* offset to next interlace block */
  196250. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196251. /* start of interlace block in the y direction */
  196252. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196253. /* offset to next interlace block in the y direction */
  196254. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196255. #endif
  196256. #endif
  196257. int ret;
  196258. png_debug(1, "in png_write_finish_row\n");
  196259. /* next row */
  196260. png_ptr->row_number++;
  196261. /* see if we are done */
  196262. if (png_ptr->row_number < png_ptr->num_rows)
  196263. return;
  196264. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  196265. /* if interlaced, go to next pass */
  196266. if (png_ptr->interlaced)
  196267. {
  196268. png_ptr->row_number = 0;
  196269. if (png_ptr->transformations & PNG_INTERLACE)
  196270. {
  196271. png_ptr->pass++;
  196272. }
  196273. else
  196274. {
  196275. /* loop until we find a non-zero width or height pass */
  196276. do
  196277. {
  196278. png_ptr->pass++;
  196279. if (png_ptr->pass >= 7)
  196280. break;
  196281. png_ptr->usr_width = (png_ptr->width +
  196282. png_pass_inc[png_ptr->pass] - 1 -
  196283. png_pass_start[png_ptr->pass]) /
  196284. png_pass_inc[png_ptr->pass];
  196285. png_ptr->num_rows = (png_ptr->height +
  196286. png_pass_yinc[png_ptr->pass] - 1 -
  196287. png_pass_ystart[png_ptr->pass]) /
  196288. png_pass_yinc[png_ptr->pass];
  196289. if (png_ptr->transformations & PNG_INTERLACE)
  196290. break;
  196291. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  196292. }
  196293. /* reset the row above the image for the next pass */
  196294. if (png_ptr->pass < 7)
  196295. {
  196296. if (png_ptr->prev_row != NULL)
  196297. png_memset(png_ptr->prev_row, 0,
  196298. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  196299. png_ptr->usr_bit_depth,png_ptr->width))+1);
  196300. return;
  196301. }
  196302. }
  196303. #endif
  196304. /* if we get here, we've just written the last row, so we need
  196305. to flush the compressor */
  196306. do
  196307. {
  196308. /* tell the compressor we are done */
  196309. ret = deflate(&png_ptr->zstream, Z_FINISH);
  196310. /* check for an error */
  196311. if (ret == Z_OK)
  196312. {
  196313. /* check to see if we need more room */
  196314. if (!(png_ptr->zstream.avail_out))
  196315. {
  196316. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  196317. png_ptr->zstream.next_out = png_ptr->zbuf;
  196318. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196319. }
  196320. }
  196321. else if (ret != Z_STREAM_END)
  196322. {
  196323. if (png_ptr->zstream.msg != NULL)
  196324. png_error(png_ptr, png_ptr->zstream.msg);
  196325. else
  196326. png_error(png_ptr, "zlib error");
  196327. }
  196328. } while (ret != Z_STREAM_END);
  196329. /* write any extra space */
  196330. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  196331. {
  196332. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  196333. png_ptr->zstream.avail_out);
  196334. }
  196335. deflateReset(&png_ptr->zstream);
  196336. png_ptr->zstream.data_type = Z_BINARY;
  196337. }
  196338. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  196339. /* Pick out the correct pixels for the interlace pass.
  196340. * The basic idea here is to go through the row with a source
  196341. * pointer and a destination pointer (sp and dp), and copy the
  196342. * correct pixels for the pass. As the row gets compacted,
  196343. * sp will always be >= dp, so we should never overwrite anything.
  196344. * See the default: case for the easiest code to understand.
  196345. */
  196346. void /* PRIVATE */
  196347. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  196348. {
  196349. #ifdef PNG_USE_LOCAL_ARRAYS
  196350. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196351. /* start of interlace block */
  196352. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196353. /* offset to next interlace block */
  196354. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196355. #endif
  196356. png_debug(1, "in png_do_write_interlace\n");
  196357. /* we don't have to do anything on the last pass (6) */
  196358. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196359. if (row != NULL && row_info != NULL && pass < 6)
  196360. #else
  196361. if (pass < 6)
  196362. #endif
  196363. {
  196364. /* each pixel depth is handled separately */
  196365. switch (row_info->pixel_depth)
  196366. {
  196367. case 1:
  196368. {
  196369. png_bytep sp;
  196370. png_bytep dp;
  196371. int shift;
  196372. int d;
  196373. int value;
  196374. png_uint_32 i;
  196375. png_uint_32 row_width = row_info->width;
  196376. dp = row;
  196377. d = 0;
  196378. shift = 7;
  196379. for (i = png_pass_start[pass]; i < row_width;
  196380. i += png_pass_inc[pass])
  196381. {
  196382. sp = row + (png_size_t)(i >> 3);
  196383. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  196384. d |= (value << shift);
  196385. if (shift == 0)
  196386. {
  196387. shift = 7;
  196388. *dp++ = (png_byte)d;
  196389. d = 0;
  196390. }
  196391. else
  196392. shift--;
  196393. }
  196394. if (shift != 7)
  196395. *dp = (png_byte)d;
  196396. break;
  196397. }
  196398. case 2:
  196399. {
  196400. png_bytep sp;
  196401. png_bytep dp;
  196402. int shift;
  196403. int d;
  196404. int value;
  196405. png_uint_32 i;
  196406. png_uint_32 row_width = row_info->width;
  196407. dp = row;
  196408. shift = 6;
  196409. d = 0;
  196410. for (i = png_pass_start[pass]; i < row_width;
  196411. i += png_pass_inc[pass])
  196412. {
  196413. sp = row + (png_size_t)(i >> 2);
  196414. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  196415. d |= (value << shift);
  196416. if (shift == 0)
  196417. {
  196418. shift = 6;
  196419. *dp++ = (png_byte)d;
  196420. d = 0;
  196421. }
  196422. else
  196423. shift -= 2;
  196424. }
  196425. if (shift != 6)
  196426. *dp = (png_byte)d;
  196427. break;
  196428. }
  196429. case 4:
  196430. {
  196431. png_bytep sp;
  196432. png_bytep dp;
  196433. int shift;
  196434. int d;
  196435. int value;
  196436. png_uint_32 i;
  196437. png_uint_32 row_width = row_info->width;
  196438. dp = row;
  196439. shift = 4;
  196440. d = 0;
  196441. for (i = png_pass_start[pass]; i < row_width;
  196442. i += png_pass_inc[pass])
  196443. {
  196444. sp = row + (png_size_t)(i >> 1);
  196445. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  196446. d |= (value << shift);
  196447. if (shift == 0)
  196448. {
  196449. shift = 4;
  196450. *dp++ = (png_byte)d;
  196451. d = 0;
  196452. }
  196453. else
  196454. shift -= 4;
  196455. }
  196456. if (shift != 4)
  196457. *dp = (png_byte)d;
  196458. break;
  196459. }
  196460. default:
  196461. {
  196462. png_bytep sp;
  196463. png_bytep dp;
  196464. png_uint_32 i;
  196465. png_uint_32 row_width = row_info->width;
  196466. png_size_t pixel_bytes;
  196467. /* start at the beginning */
  196468. dp = row;
  196469. /* find out how many bytes each pixel takes up */
  196470. pixel_bytes = (row_info->pixel_depth >> 3);
  196471. /* loop through the row, only looking at the pixels that
  196472. matter */
  196473. for (i = png_pass_start[pass]; i < row_width;
  196474. i += png_pass_inc[pass])
  196475. {
  196476. /* find out where the original pixel is */
  196477. sp = row + (png_size_t)i * pixel_bytes;
  196478. /* move the pixel */
  196479. if (dp != sp)
  196480. png_memcpy(dp, sp, pixel_bytes);
  196481. /* next pixel */
  196482. dp += pixel_bytes;
  196483. }
  196484. break;
  196485. }
  196486. }
  196487. /* set new row width */
  196488. row_info->width = (row_info->width +
  196489. png_pass_inc[pass] - 1 -
  196490. png_pass_start[pass]) /
  196491. png_pass_inc[pass];
  196492. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  196493. row_info->width);
  196494. }
  196495. }
  196496. #endif
  196497. /* This filters the row, chooses which filter to use, if it has not already
  196498. * been specified by the application, and then writes the row out with the
  196499. * chosen filter.
  196500. */
  196501. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  196502. #define PNG_HISHIFT 10
  196503. #define PNG_LOMASK ((png_uint_32)0xffffL)
  196504. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  196505. void /* PRIVATE */
  196506. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  196507. {
  196508. png_bytep best_row;
  196509. #ifndef PNG_NO_WRITE_FILTER
  196510. png_bytep prev_row, row_buf;
  196511. png_uint_32 mins, bpp;
  196512. png_byte filter_to_do = png_ptr->do_filter;
  196513. png_uint_32 row_bytes = row_info->rowbytes;
  196514. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196515. int num_p_filters = (int)png_ptr->num_prev_filters;
  196516. #endif
  196517. png_debug(1, "in png_write_find_filter\n");
  196518. /* find out how many bytes offset each pixel is */
  196519. bpp = (row_info->pixel_depth + 7) >> 3;
  196520. prev_row = png_ptr->prev_row;
  196521. #endif
  196522. best_row = png_ptr->row_buf;
  196523. #ifndef PNG_NO_WRITE_FILTER
  196524. row_buf = best_row;
  196525. mins = PNG_MAXSUM;
  196526. /* The prediction method we use is to find which method provides the
  196527. * smallest value when summing the absolute values of the distances
  196528. * from zero, using anything >= 128 as negative numbers. This is known
  196529. * as the "minimum sum of absolute differences" heuristic. Other
  196530. * heuristics are the "weighted minimum sum of absolute differences"
  196531. * (experimental and can in theory improve compression), and the "zlib
  196532. * predictive" method (not implemented yet), which does test compressions
  196533. * of lines using different filter methods, and then chooses the
  196534. * (series of) filter(s) that give minimum compressed data size (VERY
  196535. * computationally expensive).
  196536. *
  196537. * GRR 980525: consider also
  196538. * (1) minimum sum of absolute differences from running average (i.e.,
  196539. * keep running sum of non-absolute differences & count of bytes)
  196540. * [track dispersion, too? restart average if dispersion too large?]
  196541. * (1b) minimum sum of absolute differences from sliding average, probably
  196542. * with window size <= deflate window (usually 32K)
  196543. * (2) minimum sum of squared differences from zero or running average
  196544. * (i.e., ~ root-mean-square approach)
  196545. */
  196546. /* We don't need to test the 'no filter' case if this is the only filter
  196547. * that has been chosen, as it doesn't actually do anything to the data.
  196548. */
  196549. if ((filter_to_do & PNG_FILTER_NONE) &&
  196550. filter_to_do != PNG_FILTER_NONE)
  196551. {
  196552. png_bytep rp;
  196553. png_uint_32 sum = 0;
  196554. png_uint_32 i;
  196555. int v;
  196556. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  196557. {
  196558. v = *rp;
  196559. sum += (v < 128) ? v : 256 - v;
  196560. }
  196561. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196562. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196563. {
  196564. png_uint_32 sumhi, sumlo;
  196565. int j;
  196566. sumlo = sum & PNG_LOMASK;
  196567. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  196568. /* Reduce the sum if we match any of the previous rows */
  196569. for (j = 0; j < num_p_filters; j++)
  196570. {
  196571. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  196572. {
  196573. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  196574. PNG_WEIGHT_SHIFT;
  196575. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  196576. PNG_WEIGHT_SHIFT;
  196577. }
  196578. }
  196579. /* Factor in the cost of this filter (this is here for completeness,
  196580. * but it makes no sense to have a "cost" for the NONE filter, as
  196581. * it has the minimum possible computational cost - none).
  196582. */
  196583. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  196584. PNG_COST_SHIFT;
  196585. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  196586. PNG_COST_SHIFT;
  196587. if (sumhi > PNG_HIMASK)
  196588. sum = PNG_MAXSUM;
  196589. else
  196590. sum = (sumhi << PNG_HISHIFT) + sumlo;
  196591. }
  196592. #endif
  196593. mins = sum;
  196594. }
  196595. /* sub filter */
  196596. if (filter_to_do == PNG_FILTER_SUB)
  196597. /* it's the only filter so no testing is needed */
  196598. {
  196599. png_bytep rp, lp, dp;
  196600. png_uint_32 i;
  196601. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  196602. i++, rp++, dp++)
  196603. {
  196604. *dp = *rp;
  196605. }
  196606. for (lp = row_buf + 1; i < row_bytes;
  196607. i++, rp++, lp++, dp++)
  196608. {
  196609. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  196610. }
  196611. best_row = png_ptr->sub_row;
  196612. }
  196613. else if (filter_to_do & PNG_FILTER_SUB)
  196614. {
  196615. png_bytep rp, dp, lp;
  196616. png_uint_32 sum = 0, lmins = mins;
  196617. png_uint_32 i;
  196618. int v;
  196619. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196620. /* We temporarily increase the "minimum sum" by the factor we
  196621. * would reduce the sum of this filter, so that we can do the
  196622. * early exit comparison without scaling the sum each time.
  196623. */
  196624. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196625. {
  196626. int j;
  196627. png_uint_32 lmhi, lmlo;
  196628. lmlo = lmins & PNG_LOMASK;
  196629. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  196630. for (j = 0; j < num_p_filters; j++)
  196631. {
  196632. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  196633. {
  196634. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  196635. PNG_WEIGHT_SHIFT;
  196636. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  196637. PNG_WEIGHT_SHIFT;
  196638. }
  196639. }
  196640. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  196641. PNG_COST_SHIFT;
  196642. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  196643. PNG_COST_SHIFT;
  196644. if (lmhi > PNG_HIMASK)
  196645. lmins = PNG_MAXSUM;
  196646. else
  196647. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  196648. }
  196649. #endif
  196650. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  196651. i++, rp++, dp++)
  196652. {
  196653. v = *dp = *rp;
  196654. sum += (v < 128) ? v : 256 - v;
  196655. }
  196656. for (lp = row_buf + 1; i < row_bytes;
  196657. i++, rp++, lp++, dp++)
  196658. {
  196659. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  196660. sum += (v < 128) ? v : 256 - v;
  196661. if (sum > lmins) /* We are already worse, don't continue. */
  196662. break;
  196663. }
  196664. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196665. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196666. {
  196667. int j;
  196668. png_uint_32 sumhi, sumlo;
  196669. sumlo = sum & PNG_LOMASK;
  196670. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  196671. for (j = 0; j < num_p_filters; j++)
  196672. {
  196673. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  196674. {
  196675. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  196676. PNG_WEIGHT_SHIFT;
  196677. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  196678. PNG_WEIGHT_SHIFT;
  196679. }
  196680. }
  196681. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  196682. PNG_COST_SHIFT;
  196683. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  196684. PNG_COST_SHIFT;
  196685. if (sumhi > PNG_HIMASK)
  196686. sum = PNG_MAXSUM;
  196687. else
  196688. sum = (sumhi << PNG_HISHIFT) + sumlo;
  196689. }
  196690. #endif
  196691. if (sum < mins)
  196692. {
  196693. mins = sum;
  196694. best_row = png_ptr->sub_row;
  196695. }
  196696. }
  196697. /* up filter */
  196698. if (filter_to_do == PNG_FILTER_UP)
  196699. {
  196700. png_bytep rp, dp, pp;
  196701. png_uint_32 i;
  196702. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  196703. pp = prev_row + 1; i < row_bytes;
  196704. i++, rp++, pp++, dp++)
  196705. {
  196706. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  196707. }
  196708. best_row = png_ptr->up_row;
  196709. }
  196710. else if (filter_to_do & PNG_FILTER_UP)
  196711. {
  196712. png_bytep rp, dp, pp;
  196713. png_uint_32 sum = 0, lmins = mins;
  196714. png_uint_32 i;
  196715. int v;
  196716. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196717. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196718. {
  196719. int j;
  196720. png_uint_32 lmhi, lmlo;
  196721. lmlo = lmins & PNG_LOMASK;
  196722. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  196723. for (j = 0; j < num_p_filters; j++)
  196724. {
  196725. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  196726. {
  196727. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  196728. PNG_WEIGHT_SHIFT;
  196729. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  196730. PNG_WEIGHT_SHIFT;
  196731. }
  196732. }
  196733. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  196734. PNG_COST_SHIFT;
  196735. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  196736. PNG_COST_SHIFT;
  196737. if (lmhi > PNG_HIMASK)
  196738. lmins = PNG_MAXSUM;
  196739. else
  196740. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  196741. }
  196742. #endif
  196743. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  196744. pp = prev_row + 1; i < row_bytes; i++)
  196745. {
  196746. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  196747. sum += (v < 128) ? v : 256 - v;
  196748. if (sum > lmins) /* We are already worse, don't continue. */
  196749. break;
  196750. }
  196751. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196752. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196753. {
  196754. int j;
  196755. png_uint_32 sumhi, sumlo;
  196756. sumlo = sum & PNG_LOMASK;
  196757. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  196758. for (j = 0; j < num_p_filters; j++)
  196759. {
  196760. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  196761. {
  196762. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  196763. PNG_WEIGHT_SHIFT;
  196764. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  196765. PNG_WEIGHT_SHIFT;
  196766. }
  196767. }
  196768. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  196769. PNG_COST_SHIFT;
  196770. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  196771. PNG_COST_SHIFT;
  196772. if (sumhi > PNG_HIMASK)
  196773. sum = PNG_MAXSUM;
  196774. else
  196775. sum = (sumhi << PNG_HISHIFT) + sumlo;
  196776. }
  196777. #endif
  196778. if (sum < mins)
  196779. {
  196780. mins = sum;
  196781. best_row = png_ptr->up_row;
  196782. }
  196783. }
  196784. /* avg filter */
  196785. if (filter_to_do == PNG_FILTER_AVG)
  196786. {
  196787. png_bytep rp, dp, pp, lp;
  196788. png_uint_32 i;
  196789. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  196790. pp = prev_row + 1; i < bpp; i++)
  196791. {
  196792. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  196793. }
  196794. for (lp = row_buf + 1; i < row_bytes; i++)
  196795. {
  196796. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  196797. & 0xff);
  196798. }
  196799. best_row = png_ptr->avg_row;
  196800. }
  196801. else if (filter_to_do & PNG_FILTER_AVG)
  196802. {
  196803. png_bytep rp, dp, pp, lp;
  196804. png_uint_32 sum = 0, lmins = mins;
  196805. png_uint_32 i;
  196806. int v;
  196807. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196808. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196809. {
  196810. int j;
  196811. png_uint_32 lmhi, lmlo;
  196812. lmlo = lmins & PNG_LOMASK;
  196813. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  196814. for (j = 0; j < num_p_filters; j++)
  196815. {
  196816. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  196817. {
  196818. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  196819. PNG_WEIGHT_SHIFT;
  196820. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  196821. PNG_WEIGHT_SHIFT;
  196822. }
  196823. }
  196824. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196825. PNG_COST_SHIFT;
  196826. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196827. PNG_COST_SHIFT;
  196828. if (lmhi > PNG_HIMASK)
  196829. lmins = PNG_MAXSUM;
  196830. else
  196831. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  196832. }
  196833. #endif
  196834. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  196835. pp = prev_row + 1; i < bpp; i++)
  196836. {
  196837. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  196838. sum += (v < 128) ? v : 256 - v;
  196839. }
  196840. for (lp = row_buf + 1; i < row_bytes; i++)
  196841. {
  196842. v = *dp++ =
  196843. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  196844. sum += (v < 128) ? v : 256 - v;
  196845. if (sum > lmins) /* We are already worse, don't continue. */
  196846. break;
  196847. }
  196848. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196849. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196850. {
  196851. int j;
  196852. png_uint_32 sumhi, sumlo;
  196853. sumlo = sum & PNG_LOMASK;
  196854. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  196855. for (j = 0; j < num_p_filters; j++)
  196856. {
  196857. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  196858. {
  196859. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  196860. PNG_WEIGHT_SHIFT;
  196861. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  196862. PNG_WEIGHT_SHIFT;
  196863. }
  196864. }
  196865. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196866. PNG_COST_SHIFT;
  196867. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196868. PNG_COST_SHIFT;
  196869. if (sumhi > PNG_HIMASK)
  196870. sum = PNG_MAXSUM;
  196871. else
  196872. sum = (sumhi << PNG_HISHIFT) + sumlo;
  196873. }
  196874. #endif
  196875. if (sum < mins)
  196876. {
  196877. mins = sum;
  196878. best_row = png_ptr->avg_row;
  196879. }
  196880. }
  196881. /* Paeth filter */
  196882. if (filter_to_do == PNG_FILTER_PAETH)
  196883. {
  196884. png_bytep rp, dp, pp, cp, lp;
  196885. png_uint_32 i;
  196886. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  196887. pp = prev_row + 1; i < bpp; i++)
  196888. {
  196889. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  196890. }
  196891. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  196892. {
  196893. int a, b, c, pa, pb, pc, p;
  196894. b = *pp++;
  196895. c = *cp++;
  196896. a = *lp++;
  196897. p = b - c;
  196898. pc = a - c;
  196899. #ifdef PNG_USE_ABS
  196900. pa = abs(p);
  196901. pb = abs(pc);
  196902. pc = abs(p + pc);
  196903. #else
  196904. pa = p < 0 ? -p : p;
  196905. pb = pc < 0 ? -pc : pc;
  196906. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196907. #endif
  196908. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196909. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  196910. }
  196911. best_row = png_ptr->paeth_row;
  196912. }
  196913. else if (filter_to_do & PNG_FILTER_PAETH)
  196914. {
  196915. png_bytep rp, dp, pp, cp, lp;
  196916. png_uint_32 sum = 0, lmins = mins;
  196917. png_uint_32 i;
  196918. int v;
  196919. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196920. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196921. {
  196922. int j;
  196923. png_uint_32 lmhi, lmlo;
  196924. lmlo = lmins & PNG_LOMASK;
  196925. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  196926. for (j = 0; j < num_p_filters; j++)
  196927. {
  196928. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  196929. {
  196930. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  196931. PNG_WEIGHT_SHIFT;
  196932. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  196933. PNG_WEIGHT_SHIFT;
  196934. }
  196935. }
  196936. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  196937. PNG_COST_SHIFT;
  196938. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  196939. PNG_COST_SHIFT;
  196940. if (lmhi > PNG_HIMASK)
  196941. lmins = PNG_MAXSUM;
  196942. else
  196943. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  196944. }
  196945. #endif
  196946. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  196947. pp = prev_row + 1; i < bpp; i++)
  196948. {
  196949. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  196950. sum += (v < 128) ? v : 256 - v;
  196951. }
  196952. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  196953. {
  196954. int a, b, c, pa, pb, pc, p;
  196955. b = *pp++;
  196956. c = *cp++;
  196957. a = *lp++;
  196958. #ifndef PNG_SLOW_PAETH
  196959. p = b - c;
  196960. pc = a - c;
  196961. #ifdef PNG_USE_ABS
  196962. pa = abs(p);
  196963. pb = abs(pc);
  196964. pc = abs(p + pc);
  196965. #else
  196966. pa = p < 0 ? -p : p;
  196967. pb = pc < 0 ? -pc : pc;
  196968. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196969. #endif
  196970. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196971. #else /* PNG_SLOW_PAETH */
  196972. p = a + b - c;
  196973. pa = abs(p - a);
  196974. pb = abs(p - b);
  196975. pc = abs(p - c);
  196976. if (pa <= pb && pa <= pc)
  196977. p = a;
  196978. else if (pb <= pc)
  196979. p = b;
  196980. else
  196981. p = c;
  196982. #endif /* PNG_SLOW_PAETH */
  196983. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  196984. sum += (v < 128) ? v : 256 - v;
  196985. if (sum > lmins) /* We are already worse, don't continue. */
  196986. break;
  196987. }
  196988. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196989. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196990. {
  196991. int j;
  196992. png_uint_32 sumhi, sumlo;
  196993. sumlo = sum & PNG_LOMASK;
  196994. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  196995. for (j = 0; j < num_p_filters; j++)
  196996. {
  196997. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  196998. {
  196999. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  197000. PNG_WEIGHT_SHIFT;
  197001. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  197002. PNG_WEIGHT_SHIFT;
  197003. }
  197004. }
  197005. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  197006. PNG_COST_SHIFT;
  197007. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  197008. PNG_COST_SHIFT;
  197009. if (sumhi > PNG_HIMASK)
  197010. sum = PNG_MAXSUM;
  197011. else
  197012. sum = (sumhi << PNG_HISHIFT) + sumlo;
  197013. }
  197014. #endif
  197015. if (sum < mins)
  197016. {
  197017. best_row = png_ptr->paeth_row;
  197018. }
  197019. }
  197020. #endif /* PNG_NO_WRITE_FILTER */
  197021. /* Do the actual writing of the filtered row data from the chosen filter. */
  197022. png_write_filtered_row(png_ptr, best_row);
  197023. #ifndef PNG_NO_WRITE_FILTER
  197024. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197025. /* Save the type of filter we picked this time for future calculations */
  197026. if (png_ptr->num_prev_filters > 0)
  197027. {
  197028. int j;
  197029. for (j = 1; j < num_p_filters; j++)
  197030. {
  197031. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  197032. }
  197033. png_ptr->prev_filters[j] = best_row[0];
  197034. }
  197035. #endif
  197036. #endif /* PNG_NO_WRITE_FILTER */
  197037. }
  197038. /* Do the actual writing of a previously filtered row. */
  197039. void /* PRIVATE */
  197040. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  197041. {
  197042. png_debug(1, "in png_write_filtered_row\n");
  197043. png_debug1(2, "filter = %d\n", filtered_row[0]);
  197044. /* set up the zlib input buffer */
  197045. png_ptr->zstream.next_in = filtered_row;
  197046. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  197047. /* repeat until we have compressed all the data */
  197048. do
  197049. {
  197050. int ret; /* return of zlib */
  197051. /* compress the data */
  197052. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  197053. /* check for compression errors */
  197054. if (ret != Z_OK)
  197055. {
  197056. if (png_ptr->zstream.msg != NULL)
  197057. png_error(png_ptr, png_ptr->zstream.msg);
  197058. else
  197059. png_error(png_ptr, "zlib error");
  197060. }
  197061. /* see if it is time to write another IDAT */
  197062. if (!(png_ptr->zstream.avail_out))
  197063. {
  197064. /* write the IDAT and reset the zlib output buffer */
  197065. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  197066. png_ptr->zstream.next_out = png_ptr->zbuf;
  197067. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197068. }
  197069. /* repeat until all data has been compressed */
  197070. } while (png_ptr->zstream.avail_in);
  197071. /* swap the current and previous rows */
  197072. if (png_ptr->prev_row != NULL)
  197073. {
  197074. png_bytep tptr;
  197075. tptr = png_ptr->prev_row;
  197076. png_ptr->prev_row = png_ptr->row_buf;
  197077. png_ptr->row_buf = tptr;
  197078. }
  197079. /* finish row - updates counters and flushes zlib if last row */
  197080. png_write_finish_row(png_ptr);
  197081. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  197082. png_ptr->flush_rows++;
  197083. if (png_ptr->flush_dist > 0 &&
  197084. png_ptr->flush_rows >= png_ptr->flush_dist)
  197085. {
  197086. png_write_flush(png_ptr);
  197087. }
  197088. #endif
  197089. }
  197090. #endif /* PNG_WRITE_SUPPORTED */
  197091. /********* End of inlined file: pngwutil.c *********/
  197092. }
  197093. }
  197094. #ifdef _MSC_VER
  197095. #pragma warning (pop)
  197096. #endif
  197097. BEGIN_JUCE_NAMESPACE
  197098. using namespace pnglibNamespace;
  197099. using ::malloc;
  197100. using ::free;
  197101. static void pngReadCallback (png_structp pngReadStruct, png_bytep data, png_size_t length) throw()
  197102. {
  197103. InputStream* const in = (InputStream*) png_get_io_ptr (pngReadStruct);
  197104. in->read (data, (int) length);
  197105. }
  197106. struct PNGErrorStruct {};
  197107. static void pngErrorCallback (png_structp, png_const_charp)
  197108. {
  197109. throw PNGErrorStruct();
  197110. }
  197111. Image* juce_loadPNGImageFromStream (InputStream& in) throw()
  197112. {
  197113. Image* image = 0;
  197114. png_structp pngReadStruct;
  197115. png_infop pngInfoStruct;
  197116. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  197117. if (pngReadStruct != 0)
  197118. {
  197119. pngInfoStruct = png_create_info_struct (pngReadStruct);
  197120. if (pngInfoStruct == 0)
  197121. {
  197122. png_destroy_read_struct (&pngReadStruct, 0, 0);
  197123. return 0;
  197124. }
  197125. png_set_error_fn (pngReadStruct, 0, pngErrorCallback, pngErrorCallback);
  197126. // read the header..
  197127. png_set_read_fn (pngReadStruct, &in, pngReadCallback);
  197128. png_uint_32 width, height;
  197129. int bitDepth, colorType, interlaceType;
  197130. try
  197131. {
  197132. png_read_info (pngReadStruct, pngInfoStruct);
  197133. png_get_IHDR (pngReadStruct, pngInfoStruct,
  197134. &width, &height,
  197135. &bitDepth, &colorType,
  197136. &interlaceType, 0, 0);
  197137. }
  197138. catch (...)
  197139. {
  197140. png_destroy_read_struct (&pngReadStruct, 0, 0);
  197141. return 0;
  197142. }
  197143. if (bitDepth == 16)
  197144. png_set_strip_16 (pngReadStruct);
  197145. if (colorType == PNG_COLOR_TYPE_PALETTE)
  197146. png_set_expand (pngReadStruct);
  197147. if (bitDepth < 8)
  197148. png_set_expand (pngReadStruct);
  197149. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  197150. png_set_expand (pngReadStruct);
  197151. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  197152. png_set_gray_to_rgb (pngReadStruct);
  197153. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  197154. const bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  197155. || pngInfoStruct->num_trans > 0;
  197156. // Load the image into a temp buffer in the pnglib format..
  197157. uint8* const tempBuffer = (uint8*) juce_malloc (height * (width << 2));
  197158. png_bytepp rows = (png_bytepp) juce_malloc (sizeof (png_bytep) * height);
  197159. int y;
  197160. for (y = (int) height; --y >= 0;)
  197161. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  197162. bool crashed = false;
  197163. try
  197164. {
  197165. png_read_image (pngReadStruct, rows);
  197166. png_read_end (pngReadStruct, pngInfoStruct);
  197167. }
  197168. catch (...)
  197169. {
  197170. crashed = true;
  197171. }
  197172. juce_free (rows);
  197173. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  197174. if (crashed)
  197175. return 0;
  197176. // now convert the data to a juce image format..
  197177. image = new Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  197178. width, height, hasAlphaChan);
  197179. int stride, pixelStride;
  197180. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  197181. uint8* srcRow = tempBuffer;
  197182. uint8* destRow = pixels;
  197183. for (y = 0; y < (int) height; ++y)
  197184. {
  197185. const uint8* src = srcRow;
  197186. srcRow += (width << 2);
  197187. uint8* dest = destRow;
  197188. destRow += stride;
  197189. if (hasAlphaChan)
  197190. {
  197191. for (int i = width; --i >= 0;)
  197192. {
  197193. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  197194. ((PixelARGB*) dest)->premultiply();
  197195. dest += pixelStride;
  197196. src += 4;
  197197. }
  197198. }
  197199. else
  197200. {
  197201. for (int i = width; --i >= 0;)
  197202. {
  197203. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  197204. dest += pixelStride;
  197205. src += 4;
  197206. }
  197207. }
  197208. }
  197209. image->releasePixelDataReadWrite (pixels);
  197210. juce_free (tempBuffer);
  197211. }
  197212. return image;
  197213. }
  197214. static void pngWriteDataCallback (png_structp png_ptr, png_bytep data, png_size_t length) throw()
  197215. {
  197216. OutputStream* const out = (OutputStream*) png_ptr->io_ptr;
  197217. const bool ok = out->write (data, length);
  197218. (void) ok;
  197219. jassert (ok);
  197220. }
  197221. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw()
  197222. {
  197223. const int width = image.getWidth();
  197224. const int height = image.getHeight();
  197225. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  197226. if (pngWriteStruct == 0)
  197227. return false;
  197228. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  197229. if (pngInfoStruct == 0)
  197230. {
  197231. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  197232. return false;
  197233. }
  197234. png_set_write_fn (pngWriteStruct, &out, pngWriteDataCallback, 0);
  197235. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  197236. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  197237. : PNG_COLOR_TYPE_RGB,
  197238. PNG_INTERLACE_NONE,
  197239. PNG_COMPRESSION_TYPE_BASE,
  197240. PNG_FILTER_TYPE_BASE);
  197241. png_bytep rowData = (png_bytep) juce_malloc (width * 4 * sizeof (png_byte));
  197242. png_color_8 sig_bit;
  197243. sig_bit.red = 8;
  197244. sig_bit.green = 8;
  197245. sig_bit.blue = 8;
  197246. sig_bit.alpha = 8;
  197247. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  197248. png_write_info (pngWriteStruct, pngInfoStruct);
  197249. png_set_shift (pngWriteStruct, &sig_bit);
  197250. png_set_packing (pngWriteStruct);
  197251. for (int y = 0; y < height; ++y)
  197252. {
  197253. uint8* dst = (uint8*) rowData;
  197254. int stride, pixelStride;
  197255. const uint8* pixels = image.lockPixelDataReadOnly (0, y, width, 1, stride, pixelStride);
  197256. const uint8* src = pixels;
  197257. if (image.hasAlphaChannel())
  197258. {
  197259. for (int i = width; --i >= 0;)
  197260. {
  197261. PixelARGB p (*(const PixelARGB*) src);
  197262. p.unpremultiply();
  197263. *dst++ = p.getRed();
  197264. *dst++ = p.getGreen();
  197265. *dst++ = p.getBlue();
  197266. *dst++ = p.getAlpha();
  197267. src += pixelStride;
  197268. }
  197269. }
  197270. else
  197271. {
  197272. for (int i = width; --i >= 0;)
  197273. {
  197274. *dst++ = ((const PixelRGB*) src)->getRed();
  197275. *dst++ = ((const PixelRGB*) src)->getGreen();
  197276. *dst++ = ((const PixelRGB*) src)->getBlue();
  197277. src += pixelStride;
  197278. }
  197279. }
  197280. png_write_rows (pngWriteStruct, &rowData, 1);
  197281. image.releasePixelDataReadOnly (pixels);
  197282. }
  197283. juce_free (rowData);
  197284. png_write_end (pngWriteStruct, pngInfoStruct);
  197285. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  197286. out.flush();
  197287. return true;
  197288. }
  197289. END_JUCE_NAMESPACE
  197290. /********* End of inlined file: juce_PNGLoader.cpp *********/
  197291. #endif
  197292. //==============================================================================
  197293. #if JUCE_WIN32
  197294. /********* Start of inlined file: juce_win32_Files.cpp *********/
  197295. #ifdef _MSC_VER
  197296. #pragma warning (disable: 4514)
  197297. #pragma warning (push)
  197298. #endif
  197299. #include <ctime>
  197300. #ifndef _WIN32_IE
  197301. #define _WIN32_IE 0x0400
  197302. #endif
  197303. #include <shlobj.h>
  197304. #ifndef CSIDL_MYMUSIC
  197305. #define CSIDL_MYMUSIC 0x000d
  197306. #endif
  197307. #ifndef CSIDL_MYVIDEO
  197308. #define CSIDL_MYVIDEO 0x000e
  197309. #endif
  197310. BEGIN_JUCE_NAMESPACE
  197311. #ifdef _MSC_VER
  197312. #pragma warning (pop)
  197313. #endif
  197314. const tchar File::separator = T('\\');
  197315. const tchar* File::separatorString = T("\\");
  197316. bool juce_fileExists (const String& fileName,
  197317. const bool dontCountDirectories) throw()
  197318. {
  197319. if (fileName.isEmpty())
  197320. return false;
  197321. const DWORD attr = GetFileAttributes (fileName);
  197322. return dontCountDirectories ? ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
  197323. : (attr != 0xffffffff);
  197324. }
  197325. bool juce_isDirectory (const String& fileName) throw()
  197326. {
  197327. const DWORD attr = GetFileAttributes (fileName);
  197328. return (attr != 0xffffffff)
  197329. && ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0);
  197330. }
  197331. bool juce_canWriteToFile (const String& fileName) throw()
  197332. {
  197333. const DWORD attr = GetFileAttributes (fileName);
  197334. return ((attr & FILE_ATTRIBUTE_READONLY) == 0);
  197335. }
  197336. bool juce_setFileReadOnly (const String& fileName,
  197337. bool isReadOnly)
  197338. {
  197339. DWORD attr = GetFileAttributes (fileName);
  197340. if (attr == 0xffffffff)
  197341. return false;
  197342. if (isReadOnly != juce_canWriteToFile (fileName))
  197343. return true;
  197344. if (isReadOnly)
  197345. attr |= FILE_ATTRIBUTE_READONLY;
  197346. else
  197347. attr &= ~FILE_ATTRIBUTE_READONLY;
  197348. return SetFileAttributes (fileName, attr) != FALSE;
  197349. }
  197350. bool File::isHidden() const throw()
  197351. {
  197352. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  197353. }
  197354. bool juce_deleteFile (const String& fileName) throw()
  197355. {
  197356. if (juce_isDirectory (fileName))
  197357. return RemoveDirectory (fileName) != 0;
  197358. return DeleteFile (fileName) != 0;
  197359. }
  197360. bool juce_moveFile (const String& source, const String& dest) throw()
  197361. {
  197362. return MoveFile (source, dest) != 0;
  197363. }
  197364. bool juce_copyFile (const String& source, const String& dest) throw()
  197365. {
  197366. return CopyFile (source, dest, false) != 0;
  197367. }
  197368. void juce_createDirectory (const String& fileName) throw()
  197369. {
  197370. if (! juce_fileExists (fileName, true))
  197371. {
  197372. CreateDirectory (fileName, 0);
  197373. }
  197374. }
  197375. // return 0 if not possible
  197376. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  197377. {
  197378. HANDLE h;
  197379. if (forWriting)
  197380. {
  197381. h = CreateFile (fileName, GENERIC_WRITE, FILE_SHARE_READ, 0,
  197382. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  197383. if (h != INVALID_HANDLE_VALUE)
  197384. SetFilePointer (h, 0, 0, FILE_END);
  197385. else
  197386. h = 0;
  197387. }
  197388. else
  197389. {
  197390. h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  197391. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  197392. if (h == INVALID_HANDLE_VALUE)
  197393. h = 0;
  197394. }
  197395. return (void*) h;
  197396. }
  197397. void juce_fileClose (void* handle) throw()
  197398. {
  197399. CloseHandle (handle);
  197400. }
  197401. int juce_fileRead (void* handle, void* buffer, int size) throw()
  197402. {
  197403. DWORD num = 0;
  197404. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  197405. return num;
  197406. }
  197407. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  197408. {
  197409. DWORD num;
  197410. WriteFile ((HANDLE) handle,
  197411. buffer, size,
  197412. &num, 0);
  197413. return num;
  197414. }
  197415. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  197416. {
  197417. LARGE_INTEGER li;
  197418. li.QuadPart = pos;
  197419. li.LowPart = SetFilePointer ((HANDLE) handle,
  197420. li.LowPart,
  197421. &li.HighPart,
  197422. FILE_BEGIN); // (returns -1 if it fails)
  197423. return li.QuadPart;
  197424. }
  197425. int64 juce_fileGetPosition (void* handle) throw()
  197426. {
  197427. LARGE_INTEGER li;
  197428. li.QuadPart = 0;
  197429. li.LowPart = SetFilePointer ((HANDLE) handle,
  197430. 0, &li.HighPart,
  197431. FILE_CURRENT); // (returns -1 if it fails)
  197432. return jmax ((int64) 0, li.QuadPart);
  197433. }
  197434. void juce_fileFlush (void* handle) throw()
  197435. {
  197436. FlushFileBuffers ((HANDLE) handle);
  197437. }
  197438. int64 juce_getFileSize (const String& fileName) throw()
  197439. {
  197440. WIN32_FILE_ATTRIBUTE_DATA attributes;
  197441. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  197442. {
  197443. return (((int64) attributes.nFileSizeHigh) << 32)
  197444. | attributes.nFileSizeLow;
  197445. }
  197446. return 0;
  197447. }
  197448. static int64 fileTimeToTime (const FILETIME* const ft) throw()
  197449. {
  197450. // tell me if this fails!
  197451. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME));
  197452. #if JUCE_GCC
  197453. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000LL) / 10000;
  197454. #else
  197455. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000) / 10000;
  197456. #endif
  197457. }
  197458. static void timeToFileTime (const int64 time, FILETIME* const ft) throw()
  197459. {
  197460. #if JUCE_GCC
  197461. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000LL;
  197462. #else
  197463. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000;
  197464. #endif
  197465. }
  197466. void juce_getFileTimes (const String& fileName,
  197467. int64& modificationTime,
  197468. int64& accessTime,
  197469. int64& creationTime) throw()
  197470. {
  197471. WIN32_FILE_ATTRIBUTE_DATA attributes;
  197472. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  197473. {
  197474. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  197475. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  197476. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  197477. }
  197478. else
  197479. {
  197480. creationTime = accessTime = modificationTime = 0;
  197481. }
  197482. }
  197483. bool juce_setFileTimes (const String& fileName,
  197484. int64 modificationTime,
  197485. int64 accessTime,
  197486. int64 creationTime) throw()
  197487. {
  197488. FILETIME m, a, c;
  197489. if (modificationTime > 0)
  197490. timeToFileTime (modificationTime, &m);
  197491. if (accessTime > 0)
  197492. timeToFileTime (accessTime, &a);
  197493. if (creationTime > 0)
  197494. timeToFileTime (creationTime, &c);
  197495. void* const h = juce_fileOpen (fileName, true);
  197496. bool ok = false;
  197497. if (h != 0)
  197498. {
  197499. ok = SetFileTime ((HANDLE) h,
  197500. (creationTime > 0) ? &c : 0,
  197501. (accessTime > 0) ? &a : 0,
  197502. (modificationTime > 0) ? &m : 0) != 0;
  197503. juce_fileClose (h);
  197504. }
  197505. return ok;
  197506. }
  197507. // return '\0' separated list of strings
  197508. const StringArray juce_getFileSystemRoots() throw()
  197509. {
  197510. TCHAR buffer [2048];
  197511. buffer[0] = 0;
  197512. buffer[1] = 0;
  197513. GetLogicalDriveStrings (2048, buffer);
  197514. TCHAR* n = buffer;
  197515. StringArray roots;
  197516. while (*n != 0)
  197517. {
  197518. roots.add (String (n));
  197519. while (*n++ != 0)
  197520. {
  197521. }
  197522. }
  197523. roots.sort (true);
  197524. return roots;
  197525. }
  197526. const String juce_getVolumeLabel (const String& filenameOnVolume,
  197527. int& volumeSerialNumber) throw()
  197528. {
  197529. TCHAR n [4];
  197530. n[0] = *(const TCHAR*) filenameOnVolume;
  197531. n[1] = L':';
  197532. n[2] = L'\\';
  197533. n[3] = 0;
  197534. TCHAR dest [64];
  197535. DWORD serialNum;
  197536. if (! GetVolumeInformation (n, dest, 64, (DWORD*) &serialNum, 0, 0, 0, 0))
  197537. {
  197538. dest[0] = 0;
  197539. serialNum = 0;
  197540. }
  197541. volumeSerialNumber = serialNum;
  197542. return String (dest);
  197543. }
  197544. int64 File::getBytesFreeOnVolume() const throw()
  197545. {
  197546. String fn (getFullPathName());
  197547. if (fn[1] == T(':'))
  197548. fn = fn.substring (0, 2) + T("\\");
  197549. ULARGE_INTEGER spc;
  197550. ULARGE_INTEGER tot;
  197551. ULARGE_INTEGER totFree;
  197552. if (GetDiskFreeSpaceEx (fn, &spc, &tot, &totFree))
  197553. return (int64)(spc.QuadPart);
  197554. return 0;
  197555. }
  197556. static unsigned int getWindowsDriveType (const String& fileName) throw()
  197557. {
  197558. TCHAR n[4];
  197559. n[0] = *(const TCHAR*) fileName;
  197560. n[1] = L':';
  197561. n[2] = L'\\';
  197562. n[3] = 0;
  197563. return GetDriveType (n);
  197564. }
  197565. bool File::isOnCDRomDrive() const throw()
  197566. {
  197567. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  197568. }
  197569. bool File::isOnHardDisk() const throw()
  197570. {
  197571. if (fullPath.isEmpty())
  197572. return false;
  197573. const unsigned int n = getWindowsDriveType (getFullPathName());
  197574. if (fullPath.toLowerCase()[0] <= 'b'
  197575. && fullPath[1] == T(':'))
  197576. {
  197577. return n != DRIVE_REMOVABLE;
  197578. }
  197579. else
  197580. {
  197581. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  197582. }
  197583. }
  197584. bool File::isOnRemovableDrive() const throw()
  197585. {
  197586. if (fullPath.isEmpty())
  197587. return false;
  197588. const unsigned int n = getWindowsDriveType (getFullPathName());
  197589. return n == DRIVE_CDROM
  197590. || n == DRIVE_REMOTE
  197591. || n == DRIVE_REMOVABLE
  197592. || n == DRIVE_RAMDISK;
  197593. }
  197594. #define MAX_PATH_CHARS (MAX_PATH + 256)
  197595. static const File juce_getSpecialFolderPath (int type) throw()
  197596. {
  197597. WCHAR path [MAX_PATH_CHARS];
  197598. if (SHGetSpecialFolderPath (0, path, type, 0))
  197599. return File (String (path));
  197600. return File::nonexistent;
  197601. }
  197602. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  197603. {
  197604. int csidlType = 0;
  197605. switch (type)
  197606. {
  197607. case userHomeDirectory:
  197608. case userDocumentsDirectory:
  197609. csidlType = CSIDL_PERSONAL;
  197610. break;
  197611. case userDesktopDirectory:
  197612. csidlType = CSIDL_DESKTOP;
  197613. break;
  197614. case userApplicationDataDirectory:
  197615. csidlType = CSIDL_APPDATA;
  197616. break;
  197617. case commonApplicationDataDirectory:
  197618. csidlType = CSIDL_COMMON_APPDATA;
  197619. break;
  197620. case globalApplicationsDirectory:
  197621. csidlType = CSIDL_PROGRAM_FILES;
  197622. break;
  197623. case userMusicDirectory:
  197624. csidlType = CSIDL_MYMUSIC;
  197625. break;
  197626. case userMoviesDirectory:
  197627. csidlType = CSIDL_MYVIDEO;
  197628. break;
  197629. case tempDirectory:
  197630. {
  197631. WCHAR dest [2048];
  197632. dest[0] = 0;
  197633. GetTempPath (2048, dest);
  197634. return File (String (dest));
  197635. }
  197636. case currentExecutableFile:
  197637. case currentApplicationFile:
  197638. {
  197639. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  197640. WCHAR dest [MAX_PATH_CHARS];
  197641. dest[0] = 0;
  197642. GetModuleFileName (moduleHandle, dest, MAX_PATH_CHARS);
  197643. return File (String (dest));
  197644. }
  197645. break;
  197646. default:
  197647. jassertfalse // unknown type?
  197648. return File::nonexistent;
  197649. }
  197650. return juce_getSpecialFolderPath (csidlType);
  197651. }
  197652. void juce_setCurrentExecutableFileName (const String&) throw()
  197653. {
  197654. // n/a on windows
  197655. }
  197656. const File File::getCurrentWorkingDirectory() throw()
  197657. {
  197658. WCHAR dest [MAX_PATH_CHARS];
  197659. dest[0] = 0;
  197660. GetCurrentDirectory (MAX_PATH_CHARS, dest);
  197661. return File (String (dest));
  197662. }
  197663. bool File::setAsCurrentWorkingDirectory() const throw()
  197664. {
  197665. return SetCurrentDirectory (getFullPathName()) != FALSE;
  197666. }
  197667. template <class FindDataType>
  197668. static void getFindFileInfo (FindDataType& findData,
  197669. String& filename, bool* const isDir, bool* const isHidden,
  197670. int64* const fileSize, Time* const modTime, Time* const creationTime,
  197671. bool* const isReadOnly) throw()
  197672. {
  197673. filename = findData.cFileName;
  197674. if (isDir != 0)
  197675. *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  197676. if (isHidden != 0)
  197677. *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  197678. if (fileSize != 0)
  197679. *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  197680. if (modTime != 0)
  197681. *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  197682. if (creationTime != 0)
  197683. *creationTime = fileTimeToTime (&findData.ftCreationTime);
  197684. if (isReadOnly != 0)
  197685. *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  197686. }
  197687. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResult,
  197688. bool* isDir, bool* isHidden, int64* fileSize,
  197689. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  197690. {
  197691. String wc (directory);
  197692. if (! wc.endsWithChar (File::separator))
  197693. wc += File::separator;
  197694. wc += wildCard;
  197695. WIN32_FIND_DATA findData;
  197696. HANDLE h = FindFirstFile (wc, &findData);
  197697. if (h != INVALID_HANDLE_VALUE)
  197698. {
  197699. getFindFileInfo (findData, firstResult, isDir, isHidden, fileSize,
  197700. modTime, creationTime, isReadOnly);
  197701. return h;
  197702. }
  197703. firstResult = String::empty;
  197704. return 0;
  197705. }
  197706. bool juce_findFileNext (void* handle, String& resultFile,
  197707. bool* isDir, bool* isHidden, int64* fileSize,
  197708. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  197709. {
  197710. WIN32_FIND_DATA findData;
  197711. if (handle != 0 && FindNextFile ((HANDLE) handle, &findData) != 0)
  197712. {
  197713. getFindFileInfo (findData, resultFile, isDir, isHidden, fileSize,
  197714. modTime, creationTime, isReadOnly);
  197715. return true;
  197716. }
  197717. resultFile = String::empty;
  197718. return false;
  197719. }
  197720. void juce_findFileClose (void* handle) throw()
  197721. {
  197722. FindClose (handle);
  197723. }
  197724. bool juce_launchFile (const String& fileName,
  197725. const String& parameters) throw()
  197726. {
  197727. HINSTANCE hInstance = 0;
  197728. JUCE_TRY
  197729. {
  197730. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  197731. }
  197732. JUCE_CATCH_ALL
  197733. return hInstance > (HINSTANCE) 32;
  197734. }
  197735. struct NamedPipeInternal
  197736. {
  197737. HANDLE pipeH;
  197738. HANDLE cancelEvent;
  197739. bool connected, createdPipe;
  197740. NamedPipeInternal()
  197741. : pipeH (0),
  197742. cancelEvent (0),
  197743. connected (false),
  197744. createdPipe (false)
  197745. {
  197746. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  197747. }
  197748. ~NamedPipeInternal()
  197749. {
  197750. disconnect();
  197751. if (pipeH != 0)
  197752. CloseHandle (pipeH);
  197753. CloseHandle (cancelEvent);
  197754. }
  197755. bool connect (const int timeOutMs)
  197756. {
  197757. if (! createdPipe)
  197758. return true;
  197759. if (! connected)
  197760. {
  197761. OVERLAPPED over;
  197762. zerostruct (over);
  197763. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  197764. if (ConnectNamedPipe (pipeH, &over))
  197765. {
  197766. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  197767. }
  197768. else
  197769. {
  197770. const int err = GetLastError();
  197771. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  197772. {
  197773. HANDLE handles[] = { over.hEvent, cancelEvent };
  197774. if (WaitForMultipleObjects (2, handles, FALSE,
  197775. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  197776. connected = true;
  197777. }
  197778. else if (err == ERROR_PIPE_CONNECTED)
  197779. {
  197780. connected = true;
  197781. }
  197782. }
  197783. CloseHandle (over.hEvent);
  197784. }
  197785. return connected;
  197786. }
  197787. void disconnect()
  197788. {
  197789. if (connected)
  197790. {
  197791. DisconnectNamedPipe (pipeH);
  197792. connected = false;
  197793. }
  197794. }
  197795. };
  197796. void NamedPipe::close()
  197797. {
  197798. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197799. delete intern;
  197800. internal = 0;
  197801. }
  197802. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  197803. {
  197804. close();
  197805. NamedPipeInternal* const intern = new NamedPipeInternal();
  197806. String file ("\\\\.\\pipe\\");
  197807. file += pipeName;
  197808. intern->createdPipe = createPipe;
  197809. if (createPipe)
  197810. {
  197811. intern->pipeH = CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  197812. 1, 64, 64, 0, NULL);
  197813. }
  197814. else
  197815. {
  197816. intern->pipeH = CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING,
  197817. FILE_FLAG_OVERLAPPED, 0);
  197818. }
  197819. if (intern->pipeH != INVALID_HANDLE_VALUE)
  197820. {
  197821. internal = intern;
  197822. return true;
  197823. }
  197824. delete intern;
  197825. return false;
  197826. }
  197827. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  197828. {
  197829. int bytesRead = -1;
  197830. bool waitAgain = true;
  197831. while (waitAgain && internal != 0)
  197832. {
  197833. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197834. waitAgain = false;
  197835. if (! intern->connect (timeOutMilliseconds))
  197836. break;
  197837. if (maxBytesToRead <= 0)
  197838. return 0;
  197839. OVERLAPPED over;
  197840. zerostruct (over);
  197841. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  197842. unsigned long numRead;
  197843. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  197844. {
  197845. bytesRead = (int) numRead;
  197846. }
  197847. else if (GetLastError() == ERROR_IO_PENDING)
  197848. {
  197849. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  197850. if (WaitForMultipleObjects (2, handles, FALSE,
  197851. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  197852. : INFINITE) == WAIT_OBJECT_0)
  197853. {
  197854. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  197855. {
  197856. bytesRead = (int) numRead;
  197857. }
  197858. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  197859. {
  197860. intern->disconnect();
  197861. waitAgain = true;
  197862. }
  197863. }
  197864. }
  197865. else
  197866. {
  197867. waitAgain = internal != 0;
  197868. Sleep (5);
  197869. }
  197870. CloseHandle (over.hEvent);
  197871. }
  197872. return bytesRead;
  197873. }
  197874. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  197875. {
  197876. int bytesWritten = -1;
  197877. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197878. if (intern != 0 && intern->connect (timeOutMilliseconds))
  197879. {
  197880. if (numBytesToWrite <= 0)
  197881. return 0;
  197882. OVERLAPPED over;
  197883. zerostruct (over);
  197884. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  197885. unsigned long numWritten;
  197886. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  197887. {
  197888. bytesWritten = (int) numWritten;
  197889. }
  197890. else if (GetLastError() == ERROR_IO_PENDING)
  197891. {
  197892. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  197893. if (WaitForMultipleObjects (2, handles, FALSE, timeOutMilliseconds >= 0 ? timeOutMilliseconds
  197894. : INFINITE) == WAIT_OBJECT_0)
  197895. {
  197896. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  197897. {
  197898. bytesWritten = (int) numWritten;
  197899. }
  197900. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  197901. {
  197902. intern->disconnect();
  197903. }
  197904. }
  197905. }
  197906. CloseHandle (over.hEvent);
  197907. }
  197908. return bytesWritten;
  197909. }
  197910. void NamedPipe::cancelPendingReads()
  197911. {
  197912. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197913. if (intern != 0)
  197914. SetEvent (intern->cancelEvent);
  197915. }
  197916. END_JUCE_NAMESPACE
  197917. /********* End of inlined file: juce_win32_Files.cpp *********/
  197918. /********* Start of inlined file: juce_win32_Network.cpp *********/
  197919. #ifdef _MSC_VER
  197920. #pragma warning (disable: 4514)
  197921. #pragma warning (push)
  197922. #endif
  197923. #include <wininet.h>
  197924. #include <nb30.h>
  197925. #include <iphlpapi.h>
  197926. #include <mapi.h>
  197927. BEGIN_JUCE_NAMESPACE
  197928. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  197929. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  197930. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  197931. #ifndef DOXYGEN
  197932. // use with DynamicLibraryLoader to simplify importing functions
  197933. //
  197934. // functionName: function to import
  197935. // localFunctionName: name you want to use to actually call it (must be different)
  197936. // returnType: the return type
  197937. // object: the DynamicLibraryLoader to use
  197938. // params: list of params (bracketed)
  197939. //
  197940. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  197941. typedef returnType (WINAPI *type##localFunctionName) params; \
  197942. type##localFunctionName localFunctionName \
  197943. = (type##localFunctionName)object.findProcAddress (#functionName);
  197944. // loads and unloads a DLL automatically
  197945. class JUCE_API DynamicLibraryLoader
  197946. {
  197947. public:
  197948. DynamicLibraryLoader (const String& name);
  197949. ~DynamicLibraryLoader();
  197950. void* findProcAddress (const String& functionName);
  197951. private:
  197952. void* libHandle;
  197953. };
  197954. #endif
  197955. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  197956. /********* End of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  197957. #ifndef INTERNET_FLAG_NEED_FILE
  197958. #define INTERNET_FLAG_NEED_FILE 0x00000010
  197959. #endif
  197960. #ifdef _MSC_VER
  197961. #pragma warning (pop)
  197962. #endif
  197963. bool juce_isOnLine()
  197964. {
  197965. DWORD connectionType;
  197966. return InternetGetConnectedState (&connectionType, 0) != 0
  197967. || (connectionType & (INTERNET_CONNECTION_LAN | INTERNET_CONNECTION_PROXY)) != 0;
  197968. }
  197969. struct ConnectionAndRequestStruct
  197970. {
  197971. HINTERNET connection, request;
  197972. };
  197973. static HINTERNET sessionHandle = 0;
  197974. void* juce_openInternetFile (const String& url,
  197975. const String& headers,
  197976. const MemoryBlock& postData,
  197977. const bool isPost,
  197978. URL::OpenStreamProgressCallback* callback,
  197979. void* callbackContext,
  197980. int timeOutMs)
  197981. {
  197982. if (sessionHandle == 0)
  197983. sessionHandle = InternetOpen (_T("juce"),
  197984. INTERNET_OPEN_TYPE_PRECONFIG,
  197985. 0, 0, 0);
  197986. if (sessionHandle != 0)
  197987. {
  197988. // break up the url..
  197989. TCHAR file[1024], server[1024];
  197990. URL_COMPONENTS uc;
  197991. zerostruct (uc);
  197992. uc.dwStructSize = sizeof (uc);
  197993. uc.dwUrlPathLength = sizeof (file);
  197994. uc.dwHostNameLength = sizeof (server);
  197995. uc.lpszUrlPath = file;
  197996. uc.lpszHostName = server;
  197997. if (InternetCrackUrl (url, 0, 0, &uc))
  197998. {
  197999. if (timeOutMs == 0)
  198000. timeOutMs = 30000;
  198001. else if (timeOutMs < 0)
  198002. timeOutMs = -1;
  198003. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  198004. const bool isFtp = url.startsWithIgnoreCase (T("ftp:"));
  198005. HINTERNET connection = InternetConnect (sessionHandle,
  198006. uc.lpszHostName,
  198007. uc.nPort,
  198008. _T(""), _T(""),
  198009. isFtp ? INTERNET_SERVICE_FTP
  198010. : INTERNET_SERVICE_HTTP,
  198011. 0, 0);
  198012. if (connection != 0)
  198013. {
  198014. if (isFtp)
  198015. {
  198016. HINTERNET request = FtpOpenFile (connection,
  198017. uc.lpszUrlPath,
  198018. GENERIC_READ,
  198019. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  198020. 0);
  198021. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  198022. result->connection = connection;
  198023. result->request = request;
  198024. return result;
  198025. }
  198026. else
  198027. {
  198028. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  198029. HINTERNET request = HttpOpenRequest (connection,
  198030. isPost ? _T("POST")
  198031. : _T("GET"),
  198032. uc.lpszUrlPath,
  198033. 0, 0, mimeTypes,
  198034. INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE,
  198035. 0);
  198036. if (request != 0)
  198037. {
  198038. INTERNET_BUFFERS buffers;
  198039. zerostruct (buffers);
  198040. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  198041. buffers.lpcszHeader = (LPCTSTR) headers;
  198042. buffers.dwHeadersLength = headers.length();
  198043. buffers.dwBufferTotal = (DWORD) postData.getSize();
  198044. ConnectionAndRequestStruct* result = 0;
  198045. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  198046. {
  198047. int bytesSent = 0;
  198048. for (;;)
  198049. {
  198050. const int bytesToDo = jmin (1024, postData.getSize() - bytesSent);
  198051. DWORD bytesDone = 0;
  198052. if (bytesToDo > 0
  198053. && ! InternetWriteFile (request,
  198054. ((const char*) postData.getData()) + bytesSent,
  198055. bytesToDo, &bytesDone))
  198056. {
  198057. break;
  198058. }
  198059. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  198060. {
  198061. result = new ConnectionAndRequestStruct();
  198062. result->connection = connection;
  198063. result->request = request;
  198064. HttpEndRequest (request, 0, 0, 0);
  198065. return result;
  198066. }
  198067. bytesSent += bytesDone;
  198068. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  198069. break;
  198070. }
  198071. }
  198072. InternetCloseHandle (request);
  198073. }
  198074. InternetCloseHandle (connection);
  198075. }
  198076. }
  198077. }
  198078. }
  198079. return 0;
  198080. }
  198081. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  198082. {
  198083. DWORD bytesRead = 0;
  198084. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  198085. if (crs != 0)
  198086. InternetReadFile (crs->request,
  198087. buffer, bytesToRead,
  198088. &bytesRead);
  198089. return bytesRead;
  198090. }
  198091. int juce_seekInInternetFile (void* handle, int newPosition)
  198092. {
  198093. if (handle != 0)
  198094. {
  198095. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  198096. return InternetSetFilePointer (crs->request,
  198097. newPosition, 0,
  198098. FILE_BEGIN, 0);
  198099. }
  198100. else
  198101. {
  198102. return -1;
  198103. }
  198104. }
  198105. void juce_closeInternetFile (void* handle)
  198106. {
  198107. if (handle != 0)
  198108. {
  198109. ConnectionAndRequestStruct* const crs = (ConnectionAndRequestStruct*) handle;
  198110. InternetCloseHandle (crs->request);
  198111. InternetCloseHandle (crs->connection);
  198112. delete crs;
  198113. }
  198114. }
  198115. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  198116. {
  198117. int numFound = 0;
  198118. DynamicLibraryLoader dll ("iphlpapi.dll");
  198119. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  198120. if (getAdaptersInfo != 0)
  198121. {
  198122. ULONG len = sizeof (IP_ADAPTER_INFO);
  198123. MemoryBlock mb;
  198124. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  198125. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  198126. {
  198127. mb.setSize (len);
  198128. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  198129. }
  198130. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  198131. {
  198132. PIP_ADAPTER_INFO adapter = adapterInfo;
  198133. while (adapter != 0)
  198134. {
  198135. int64 mac = 0;
  198136. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  198137. mac = (mac << 8) | adapter->Address[i];
  198138. if (littleEndian)
  198139. mac = (int64) swapByteOrder ((uint64) mac);
  198140. if (numFound < maxNum && mac != 0)
  198141. addresses [numFound++] = mac;
  198142. adapter = adapter->Next;
  198143. }
  198144. }
  198145. }
  198146. return numFound;
  198147. }
  198148. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  198149. {
  198150. int numFound = 0;
  198151. DynamicLibraryLoader dll ("netapi32.dll");
  198152. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  198153. if (NetbiosCall != 0)
  198154. {
  198155. NCB ncb;
  198156. zerostruct (ncb);
  198157. typedef struct _ASTAT_
  198158. {
  198159. ADAPTER_STATUS adapt;
  198160. NAME_BUFFER NameBuff [30];
  198161. } ASTAT;
  198162. ASTAT astat;
  198163. zerostruct (astat);
  198164. LANA_ENUM enums;
  198165. zerostruct (enums);
  198166. ncb.ncb_command = NCBENUM;
  198167. ncb.ncb_buffer = (unsigned char*) &enums;
  198168. ncb.ncb_length = sizeof (LANA_ENUM);
  198169. NetbiosCall (&ncb);
  198170. for (int i = 0; i < enums.length; ++i)
  198171. {
  198172. zerostruct (ncb);
  198173. ncb.ncb_command = NCBRESET;
  198174. ncb.ncb_lana_num = enums.lana[i];
  198175. if (NetbiosCall (&ncb) == 0)
  198176. {
  198177. zerostruct (ncb);
  198178. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  198179. ncb.ncb_command = NCBASTAT;
  198180. ncb.ncb_lana_num = enums.lana[i];
  198181. ncb.ncb_buffer = (unsigned char*) &astat;
  198182. ncb.ncb_length = sizeof (ASTAT);
  198183. if (NetbiosCall (&ncb) == 0)
  198184. {
  198185. if (astat.adapt.adapter_type == 0xfe)
  198186. {
  198187. int64 mac = 0;
  198188. for (unsigned int i = 0; i < 6; ++i)
  198189. mac = (mac << 8) | astat.adapt.adapter_address[i];
  198190. if (littleEndian)
  198191. mac = (int64) swapByteOrder ((uint64) mac);
  198192. if (numFound < maxNum && mac != 0)
  198193. addresses [numFound++] = mac;
  198194. }
  198195. }
  198196. }
  198197. }
  198198. }
  198199. return numFound;
  198200. }
  198201. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  198202. {
  198203. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  198204. if (numFound == 0)
  198205. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  198206. return numFound;
  198207. }
  198208. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  198209. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  198210. const String& emailSubject,
  198211. const String& bodyText,
  198212. const StringArray& filesToAttach)
  198213. {
  198214. HMODULE h = LoadLibraryA ("MAPI32.dll");
  198215. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  198216. bool ok = false;
  198217. if (mapiSendMail != 0)
  198218. {
  198219. MapiMessage message;
  198220. zerostruct (message);
  198221. message.lpszSubject = (LPSTR) (LPCSTR) emailSubject;
  198222. message.lpszNoteText = (LPSTR) (LPCSTR) bodyText;
  198223. MapiRecipDesc recip;
  198224. zerostruct (recip);
  198225. recip.ulRecipClass = MAPI_TO;
  198226. recip.lpszName = (LPSTR) (LPCSTR) targetEmailAddress;
  198227. message.nRecipCount = 1;
  198228. message.lpRecips = &recip;
  198229. MemoryBlock mb (sizeof (MapiFileDesc) * filesToAttach.size());
  198230. mb.fillWith (0);
  198231. MapiFileDesc* files = (MapiFileDesc*) mb.getData();
  198232. message.nFileCount = filesToAttach.size();
  198233. message.lpFiles = files;
  198234. for (int i = 0; i < filesToAttach.size(); ++i)
  198235. {
  198236. files[i].nPosition = (ULONG) -1;
  198237. files[i].lpszPathName = (LPSTR) (LPCSTR) filesToAttach [i];
  198238. }
  198239. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  198240. }
  198241. FreeLibrary (h);
  198242. return ok;
  198243. }
  198244. END_JUCE_NAMESPACE
  198245. /********* End of inlined file: juce_win32_Network.cpp *********/
  198246. /********* Start of inlined file: juce_win32_Misc.cpp *********/
  198247. BEGIN_JUCE_NAMESPACE
  198248. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198249. bool AlertWindow::showNativeDialogBox (const String& title,
  198250. const String& bodyText,
  198251. bool isOkCancel)
  198252. {
  198253. return MessageBox (0, bodyText, title,
  198254. (isOkCancel) ? MB_OKCANCEL
  198255. : MB_OK) == IDOK;
  198256. }
  198257. #endif
  198258. void PlatformUtilities::beep()
  198259. {
  198260. MessageBeep (MB_OK);
  198261. }
  198262. #if JUCE_MSVC
  198263. #pragma warning (disable : 4127) // "Conditional expression is constant" warning
  198264. #endif
  198265. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198266. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  198267. {
  198268. if (OpenClipboard (0) != 0)
  198269. {
  198270. if (EmptyClipboard() != 0)
  198271. {
  198272. const int len = text.length();
  198273. if (len > 0)
  198274. {
  198275. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  198276. (len + 1) * sizeof (wchar_t));
  198277. if (bufH != 0)
  198278. {
  198279. wchar_t* const data = (wchar_t*) GlobalLock (bufH);
  198280. text.copyToBuffer (data, len);
  198281. GlobalUnlock (bufH);
  198282. SetClipboardData (CF_UNICODETEXT, bufH);
  198283. }
  198284. }
  198285. }
  198286. CloseClipboard();
  198287. }
  198288. }
  198289. const String SystemClipboard::getTextFromClipboard() throw()
  198290. {
  198291. String result;
  198292. if (OpenClipboard (0) != 0)
  198293. {
  198294. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  198295. if (bufH != 0)
  198296. {
  198297. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  198298. if (data != 0)
  198299. {
  198300. result = String (data, (int) (GlobalSize (bufH) / sizeof (tchar)));
  198301. GlobalUnlock (bufH);
  198302. }
  198303. }
  198304. CloseClipboard();
  198305. }
  198306. return result;
  198307. }
  198308. #endif
  198309. END_JUCE_NAMESPACE
  198310. /********* End of inlined file: juce_win32_Misc.cpp *********/
  198311. /********* Start of inlined file: juce_win32_PlatformUtils.cpp *********/
  198312. #ifdef _MSC_VER
  198313. #pragma warning (disable: 4514)
  198314. #pragma warning (push)
  198315. #endif
  198316. #include <float.h>
  198317. BEGIN_JUCE_NAMESPACE
  198318. #ifdef _MSC_VER
  198319. #pragma warning (pop)
  198320. #endif
  198321. static HKEY findKeyForPath (String name,
  198322. const bool createForWriting,
  198323. String& valueName) throw()
  198324. {
  198325. HKEY rootKey = 0;
  198326. if (name.startsWithIgnoreCase (T("HKEY_CURRENT_USER\\")))
  198327. rootKey = HKEY_CURRENT_USER;
  198328. else if (name.startsWithIgnoreCase (T("HKEY_LOCAL_MACHINE\\")))
  198329. rootKey = HKEY_LOCAL_MACHINE;
  198330. else if (name.startsWithIgnoreCase (T("HKEY_CLASSES_ROOT\\")))
  198331. rootKey = HKEY_CLASSES_ROOT;
  198332. if (rootKey != 0)
  198333. {
  198334. name = name.substring (name.indexOfChar (T('\\')) + 1);
  198335. const int lastSlash = name.lastIndexOfChar (T('\\'));
  198336. valueName = name.substring (lastSlash + 1);
  198337. name = name.substring (0, lastSlash);
  198338. HKEY key;
  198339. DWORD result;
  198340. if (createForWriting)
  198341. {
  198342. if (RegCreateKeyEx (rootKey, name, 0, L"", REG_OPTION_NON_VOLATILE,
  198343. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  198344. return key;
  198345. }
  198346. else
  198347. {
  198348. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  198349. return key;
  198350. }
  198351. }
  198352. return 0;
  198353. }
  198354. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  198355. const String& defaultValue)
  198356. {
  198357. String valueName, s;
  198358. HKEY k = findKeyForPath (regValuePath, false, valueName);
  198359. if (k != 0)
  198360. {
  198361. WCHAR buffer [2048];
  198362. unsigned long bufferSize = sizeof (buffer);
  198363. DWORD type = REG_SZ;
  198364. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  198365. s = buffer;
  198366. else
  198367. s = defaultValue;
  198368. RegCloseKey (k);
  198369. }
  198370. return s;
  198371. }
  198372. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  198373. const String& value)
  198374. {
  198375. String valueName;
  198376. HKEY k = findKeyForPath (regValuePath, true, valueName);
  198377. if (k != 0)
  198378. {
  198379. RegSetValueEx (k, valueName, 0, REG_SZ,
  198380. (const BYTE*) (const WCHAR*) value,
  198381. sizeof (WCHAR) * (value.length() + 1));
  198382. RegCloseKey (k);
  198383. }
  198384. }
  198385. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  198386. {
  198387. bool exists = false;
  198388. String valueName;
  198389. HKEY k = findKeyForPath (regValuePath, false, valueName);
  198390. if (k != 0)
  198391. {
  198392. unsigned char buffer [2048];
  198393. unsigned long bufferSize = sizeof (buffer);
  198394. DWORD type = 0;
  198395. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  198396. exists = true;
  198397. RegCloseKey (k);
  198398. }
  198399. return exists;
  198400. }
  198401. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  198402. {
  198403. String valueName;
  198404. HKEY k = findKeyForPath (regValuePath, true, valueName);
  198405. if (k != 0)
  198406. {
  198407. RegDeleteValue (k, valueName);
  198408. RegCloseKey (k);
  198409. }
  198410. }
  198411. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  198412. {
  198413. String valueName;
  198414. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  198415. if (k != 0)
  198416. {
  198417. RegDeleteKey (k, valueName);
  198418. RegCloseKey (k);
  198419. }
  198420. }
  198421. bool juce_IsRunningInWine() throw()
  198422. {
  198423. HKEY key;
  198424. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  198425. {
  198426. RegCloseKey (key);
  198427. return true;
  198428. }
  198429. return false;
  198430. }
  198431. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams() throw()
  198432. {
  198433. String s (::GetCommandLineW());
  198434. StringArray tokens;
  198435. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  198436. return tokens.joinIntoString (T(" "), 1);
  198437. }
  198438. static void* currentModuleHandle = 0;
  198439. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  198440. {
  198441. if (currentModuleHandle == 0)
  198442. currentModuleHandle = GetModuleHandle (0);
  198443. return currentModuleHandle;
  198444. }
  198445. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  198446. {
  198447. currentModuleHandle = newHandle;
  198448. }
  198449. void PlatformUtilities::fpuReset()
  198450. {
  198451. #if JUCE_MSVC
  198452. _clearfp();
  198453. #endif
  198454. }
  198455. END_JUCE_NAMESPACE
  198456. /********* End of inlined file: juce_win32_PlatformUtils.cpp *********/
  198457. /********* Start of inlined file: juce_win32_SystemStats.cpp *********/
  198458. // Auto-link the other win32 libs that are needed by library calls..
  198459. #if defined (JUCE_DLL_BUILD) && JUCE_MSVC
  198460. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  198461. // Auto-links to various win32 libs that are needed by library calls..
  198462. #pragma comment(lib, "kernel32.lib")
  198463. #pragma comment(lib, "user32.lib")
  198464. #pragma comment(lib, "shell32.lib")
  198465. #pragma comment(lib, "gdi32.lib")
  198466. #pragma comment(lib, "vfw32.lib")
  198467. #pragma comment(lib, "comdlg32.lib")
  198468. #pragma comment(lib, "winmm.lib")
  198469. #pragma comment(lib, "wininet.lib")
  198470. #pragma comment(lib, "ole32.lib")
  198471. #pragma comment(lib, "advapi32.lib")
  198472. #pragma comment(lib, "ws2_32.lib")
  198473. #pragma comment(lib, "comsupp.lib")
  198474. #if JUCE_OPENGL
  198475. #pragma comment(lib, "OpenGL32.Lib")
  198476. #pragma comment(lib, "GlU32.Lib")
  198477. #endif
  198478. #if JUCE_QUICKTIME
  198479. #pragma comment (lib, "QTMLClient.lib")
  198480. #endif
  198481. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  198482. #endif
  198483. BEGIN_JUCE_NAMESPACE
  198484. extern void juce_updateMultiMonitorInfo() throw();
  198485. extern void juce_initialiseThreadEvents() throw();
  198486. void Logger::outputDebugString (const String& text) throw()
  198487. {
  198488. OutputDebugString (text + T("\n"));
  198489. }
  198490. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  198491. {
  198492. String text;
  198493. va_list args;
  198494. va_start (args, format);
  198495. text.vprintf(format, args);
  198496. outputDebugString (text);
  198497. }
  198498. static int64 hiResTicksPerSecond;
  198499. static double hiResTicksScaleFactor;
  198500. #if JUCE_USE_INTRINSICS
  198501. // CPU info functions using intrinsics...
  198502. #pragma intrinsic (__cpuid)
  198503. #pragma intrinsic (__rdtsc)
  198504. /*static unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0) throw()
  198505. {
  198506. int info [4];
  198507. __cpuid (info, 1);
  198508. if (familyModel != 0)
  198509. *familyModel = info [0];
  198510. if (extFeatures != 0)
  198511. *extFeatures = info[1];
  198512. return info[3];
  198513. }*/
  198514. const String SystemStats::getCpuVendor() throw()
  198515. {
  198516. int info [4];
  198517. __cpuid (info, 0);
  198518. char v [12];
  198519. memcpy (v, info + 1, 4);
  198520. memcpy (v + 4, info + 3, 4);
  198521. memcpy (v + 8, info + 2, 4);
  198522. return String (v, 12);
  198523. }
  198524. #else
  198525. // CPU info functions using old fashioned inline asm...
  198526. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0)
  198527. {
  198528. unsigned int cpu = 0;
  198529. unsigned int ext = 0;
  198530. unsigned int family = 0;
  198531. #if JUCE_GCC
  198532. unsigned int dummy = 0;
  198533. #endif
  198534. #ifndef __MINGW32__
  198535. __try
  198536. #endif
  198537. {
  198538. #if JUCE_GCC
  198539. __asm__ ("cpuid" : "=a" (family), "=b" (ext), "=c" (dummy),"=d" (cpu) : "a" (1));
  198540. #else
  198541. __asm
  198542. {
  198543. mov eax, 1
  198544. cpuid
  198545. mov cpu, edx
  198546. mov family, eax
  198547. mov ext, ebx
  198548. }
  198549. #endif
  198550. }
  198551. #ifndef __MINGW32__
  198552. __except (EXCEPTION_EXECUTE_HANDLER)
  198553. {
  198554. return 0;
  198555. }
  198556. #endif
  198557. if (familyModel != 0)
  198558. *familyModel = family;
  198559. if (extFeatures != 0)
  198560. *extFeatures = ext;
  198561. return cpu;
  198562. }*/
  198563. static void juce_getCpuVendor (char* const v)
  198564. {
  198565. int vendor[4];
  198566. zeromem (vendor, 16);
  198567. #ifdef JUCE_64BIT
  198568. #else
  198569. #ifndef __MINGW32__
  198570. __try
  198571. #endif
  198572. {
  198573. #if JUCE_GCC
  198574. unsigned int dummy = 0;
  198575. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  198576. #else
  198577. __asm
  198578. {
  198579. mov eax, 0
  198580. cpuid
  198581. mov [vendor], ebx
  198582. mov [vendor + 4], edx
  198583. mov [vendor + 8], ecx
  198584. }
  198585. #endif
  198586. }
  198587. #ifndef __MINGW32__
  198588. __except (EXCEPTION_EXECUTE_HANDLER)
  198589. {
  198590. *v = 0;
  198591. }
  198592. #endif
  198593. #endif
  198594. memcpy (v, vendor, 16);
  198595. }
  198596. const String SystemStats::getCpuVendor() throw()
  198597. {
  198598. char v [16];
  198599. juce_getCpuVendor (v);
  198600. return String (v, 16);
  198601. }
  198602. #endif
  198603. struct CPUFlags
  198604. {
  198605. bool hasMMX : 1;
  198606. bool hasSSE : 1;
  198607. bool hasSSE2 : 1;
  198608. bool has3DNow : 1;
  198609. };
  198610. static CPUFlags cpuFlags;
  198611. bool SystemStats::hasMMX() throw()
  198612. {
  198613. return cpuFlags.hasMMX;
  198614. }
  198615. bool SystemStats::hasSSE() throw()
  198616. {
  198617. return cpuFlags.hasSSE;
  198618. }
  198619. bool SystemStats::hasSSE2() throw()
  198620. {
  198621. return cpuFlags.hasSSE2;
  198622. }
  198623. bool SystemStats::has3DNow() throw()
  198624. {
  198625. return cpuFlags.has3DNow;
  198626. }
  198627. void SystemStats::initialiseStats() throw()
  198628. {
  198629. juce_initialiseThreadEvents();
  198630. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  198631. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  198632. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  198633. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  198634. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  198635. #else
  198636. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  198637. #endif
  198638. LARGE_INTEGER f;
  198639. QueryPerformanceFrequency (&f);
  198640. hiResTicksPerSecond = f.QuadPart;
  198641. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  198642. String s (SystemStats::getJUCEVersion());
  198643. #ifdef JUCE_DEBUG
  198644. const MMRESULT res = timeBeginPeriod (1);
  198645. jassert (res == TIMERR_NOERROR);
  198646. #else
  198647. timeBeginPeriod (1);
  198648. #endif
  198649. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  198650. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  198651. #endif
  198652. }
  198653. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  198654. {
  198655. OSVERSIONINFO info;
  198656. info.dwOSVersionInfoSize = sizeof (info);
  198657. GetVersionEx (&info);
  198658. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  198659. {
  198660. switch (info.dwMajorVersion)
  198661. {
  198662. case 5:
  198663. return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  198664. case 6:
  198665. return WinVista;
  198666. default:
  198667. jassertfalse // !! not a supported OS!
  198668. break;
  198669. }
  198670. }
  198671. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  198672. {
  198673. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  198674. return Win98;
  198675. }
  198676. return UnknownOS;
  198677. }
  198678. const String SystemStats::getOperatingSystemName() throw()
  198679. {
  198680. const char* name = "Unknown OS";
  198681. switch (getOperatingSystemType())
  198682. {
  198683. case WinVista:
  198684. name = "Windows Vista";
  198685. break;
  198686. case WinXP:
  198687. name = "Windows XP";
  198688. break;
  198689. case Win2000:
  198690. name = "Windows 2000";
  198691. break;
  198692. case Win98:
  198693. name = "Windows 98";
  198694. break;
  198695. default:
  198696. jassertfalse // !! new type of OS?
  198697. break;
  198698. }
  198699. return name;
  198700. }
  198701. bool SystemStats::isOperatingSystem64Bit() throw()
  198702. {
  198703. #ifdef _WIN64
  198704. return true;
  198705. #else
  198706. typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  198707. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  198708. BOOL isWow64 = FALSE;
  198709. return (fnIsWow64Process != 0)
  198710. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  198711. && (isWow64 != FALSE);
  198712. #endif
  198713. }
  198714. int SystemStats::getMemorySizeInMegabytes() throw()
  198715. {
  198716. MEMORYSTATUS mem;
  198717. GlobalMemoryStatus (&mem);
  198718. return (int) (mem.dwTotalPhys / (1024 * 1024)) + 1;
  198719. }
  198720. int SystemStats::getNumCpus() throw()
  198721. {
  198722. SYSTEM_INFO systemInfo;
  198723. GetSystemInfo (&systemInfo);
  198724. return systemInfo.dwNumberOfProcessors;
  198725. }
  198726. uint32 juce_millisecondsSinceStartup() throw()
  198727. {
  198728. return (uint32) GetTickCount();
  198729. }
  198730. int64 Time::getHighResolutionTicks() throw()
  198731. {
  198732. LARGE_INTEGER ticks;
  198733. QueryPerformanceCounter (&ticks);
  198734. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  198735. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  198736. // fix for a very obscure PCI hardware bug that can make the counter
  198737. // sometimes jump forwards by a few seconds..
  198738. static int64 hiResTicksOffset = 0;
  198739. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  198740. if (offsetDrift > (hiResTicksPerSecond >> 1))
  198741. hiResTicksOffset = newOffset;
  198742. return ticks.QuadPart + hiResTicksOffset;
  198743. }
  198744. double Time::getMillisecondCounterHiRes() throw()
  198745. {
  198746. return getHighResolutionTicks() * hiResTicksScaleFactor;
  198747. }
  198748. int64 Time::getHighResolutionTicksPerSecond() throw()
  198749. {
  198750. return hiResTicksPerSecond;
  198751. }
  198752. int64 SystemStats::getClockCycleCounter() throw()
  198753. {
  198754. #if JUCE_USE_INTRINSICS
  198755. // MS intrinsics version...
  198756. return __rdtsc();
  198757. #elif JUCE_GCC
  198758. // GNU inline asm version...
  198759. unsigned int hi = 0, lo = 0;
  198760. __asm__ __volatile__ (
  198761. "xor %%eax, %%eax \n\
  198762. xor %%edx, %%edx \n\
  198763. rdtsc \n\
  198764. movl %%eax, %[lo] \n\
  198765. movl %%edx, %[hi]"
  198766. :
  198767. : [hi] "m" (hi),
  198768. [lo] "m" (lo)
  198769. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  198770. return (int64) ((((uint64) hi) << 32) | lo);
  198771. #else
  198772. // MSVC inline asm version...
  198773. unsigned int hi = 0, lo = 0;
  198774. __asm
  198775. {
  198776. xor eax, eax
  198777. xor edx, edx
  198778. rdtsc
  198779. mov lo, eax
  198780. mov hi, edx
  198781. }
  198782. return (int64) ((((uint64) hi) << 32) | lo);
  198783. #endif
  198784. }
  198785. int SystemStats::getCpuSpeedInMegaherz() throw()
  198786. {
  198787. const int64 cycles = SystemStats::getClockCycleCounter();
  198788. const uint32 millis = Time::getMillisecondCounter();
  198789. int lastResult = 0;
  198790. for (;;)
  198791. {
  198792. int n = 1000000;
  198793. while (--n > 0) {}
  198794. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  198795. const int64 cyclesNow = SystemStats::getClockCycleCounter();
  198796. if (millisElapsed > 80)
  198797. {
  198798. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  198799. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  198800. return newResult;
  198801. lastResult = newResult;
  198802. }
  198803. }
  198804. }
  198805. bool Time::setSystemTimeToThisTime() const throw()
  198806. {
  198807. SYSTEMTIME st;
  198808. st.wDayOfWeek = 0;
  198809. st.wYear = (WORD) getYear();
  198810. st.wMonth = (WORD) (getMonth() + 1);
  198811. st.wDay = (WORD) getDayOfMonth();
  198812. st.wHour = (WORD) getHours();
  198813. st.wMinute = (WORD) getMinutes();
  198814. st.wSecond = (WORD) getSeconds();
  198815. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  198816. // do this twice because of daylight saving conversion problems - the
  198817. // first one sets it up, the second one kicks it in.
  198818. return SetLocalTime (&st) != 0
  198819. && SetLocalTime (&st) != 0;
  198820. }
  198821. int SystemStats::getPageSize() throw()
  198822. {
  198823. SYSTEM_INFO systemInfo;
  198824. GetSystemInfo (&systemInfo);
  198825. return systemInfo.dwPageSize;
  198826. }
  198827. END_JUCE_NAMESPACE
  198828. /********* End of inlined file: juce_win32_SystemStats.cpp *********/
  198829. /********* Start of inlined file: juce_win32_Threads.cpp *********/
  198830. #ifdef _MSC_VER
  198831. #pragma warning (disable: 4514)
  198832. #pragma warning (push)
  198833. #include <crtdbg.h>
  198834. #endif
  198835. #include <process.h>
  198836. BEGIN_JUCE_NAMESPACE
  198837. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198838. extern HWND juce_messageWindowHandle;
  198839. #endif
  198840. #ifdef _MSC_VER
  198841. #pragma warning (pop)
  198842. #endif
  198843. CriticalSection::CriticalSection() throw()
  198844. {
  198845. // (just to check the MS haven't changed this structure and broken things...)
  198846. #if _MSC_VER >= 1400
  198847. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  198848. #else
  198849. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  198850. #endif
  198851. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  198852. }
  198853. CriticalSection::~CriticalSection() throw()
  198854. {
  198855. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  198856. }
  198857. void CriticalSection::enter() const throw()
  198858. {
  198859. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  198860. }
  198861. bool CriticalSection::tryEnter() const throw()
  198862. {
  198863. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  198864. }
  198865. void CriticalSection::exit() const throw()
  198866. {
  198867. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  198868. }
  198869. WaitableEvent::WaitableEvent() throw()
  198870. : internal (CreateEvent (0, FALSE, FALSE, 0))
  198871. {
  198872. }
  198873. WaitableEvent::~WaitableEvent() throw()
  198874. {
  198875. CloseHandle (internal);
  198876. }
  198877. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  198878. {
  198879. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  198880. }
  198881. void WaitableEvent::signal() const throw()
  198882. {
  198883. SetEvent (internal);
  198884. }
  198885. void WaitableEvent::reset() const throw()
  198886. {
  198887. ResetEvent (internal);
  198888. }
  198889. void JUCE_API juce_threadEntryPoint (void*);
  198890. static unsigned int __stdcall threadEntryProc (void* userData) throw()
  198891. {
  198892. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198893. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  198894. GetCurrentThreadId(), TRUE);
  198895. #endif
  198896. juce_threadEntryPoint (userData);
  198897. _endthreadex(0);
  198898. return 0;
  198899. }
  198900. void juce_CloseThreadHandle (void* handle) throw()
  198901. {
  198902. CloseHandle ((HANDLE) handle);
  198903. }
  198904. void* juce_createThread (void* userData) throw()
  198905. {
  198906. unsigned int threadId;
  198907. return (void*) _beginthreadex (0, 0,
  198908. &threadEntryProc,
  198909. userData,
  198910. 0, &threadId);
  198911. }
  198912. void juce_killThread (void* handle) throw()
  198913. {
  198914. if (handle != 0)
  198915. {
  198916. #ifdef JUCE_DEBUG
  198917. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  198918. #endif
  198919. TerminateThread (handle, 0);
  198920. }
  198921. }
  198922. void juce_setCurrentThreadName (const String& name) throw()
  198923. {
  198924. #if defined (JUCE_DEBUG) && JUCE_MSVC
  198925. struct
  198926. {
  198927. DWORD dwType;
  198928. LPCSTR szName;
  198929. DWORD dwThreadID;
  198930. DWORD dwFlags;
  198931. } info;
  198932. info.dwType = 0x1000;
  198933. info.szName = name;
  198934. info.dwThreadID = GetCurrentThreadId();
  198935. info.dwFlags = 0;
  198936. #define MS_VC_EXCEPTION 0x406d1388
  198937. __try
  198938. {
  198939. RaiseException (MS_VC_EXCEPTION, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  198940. }
  198941. __except (EXCEPTION_CONTINUE_EXECUTION)
  198942. {}
  198943. #else
  198944. (void) name;
  198945. #endif
  198946. }
  198947. int Thread::getCurrentThreadId() throw()
  198948. {
  198949. return (int) GetCurrentThreadId();
  198950. }
  198951. // priority 1 to 10 where 5=normal, 1=low
  198952. void juce_setThreadPriority (void* threadHandle, int priority) throw()
  198953. {
  198954. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  198955. if (priority < 1)
  198956. pri = THREAD_PRIORITY_IDLE;
  198957. else if (priority < 2)
  198958. pri = THREAD_PRIORITY_LOWEST;
  198959. else if (priority < 5)
  198960. pri = THREAD_PRIORITY_BELOW_NORMAL;
  198961. else if (priority < 7)
  198962. pri = THREAD_PRIORITY_NORMAL;
  198963. else if (priority < 9)
  198964. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  198965. else if (priority < 10)
  198966. pri = THREAD_PRIORITY_HIGHEST;
  198967. if (threadHandle == 0)
  198968. threadHandle = GetCurrentThread();
  198969. SetThreadPriority (threadHandle, pri);
  198970. }
  198971. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  198972. {
  198973. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  198974. }
  198975. static HANDLE sleepEvent = 0;
  198976. void juce_initialiseThreadEvents() throw()
  198977. {
  198978. if (sleepEvent == 0)
  198979. #ifdef JUCE_DEBUG
  198980. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  198981. #else
  198982. sleepEvent = CreateEvent (0, 0, 0, 0);
  198983. #endif
  198984. }
  198985. void Thread::yield() throw()
  198986. {
  198987. Sleep (0);
  198988. }
  198989. void JUCE_CALLTYPE Thread::sleep (const int millisecs) throw()
  198990. {
  198991. if (millisecs >= 10)
  198992. {
  198993. Sleep (millisecs);
  198994. }
  198995. else
  198996. {
  198997. jassert (sleepEvent != 0);
  198998. // unlike Sleep() this is guaranteed to return to the current thread after
  198999. // the time expires, so we'll use this for short waits, which are more likely
  199000. // to need to be accurate
  199001. WaitForSingleObject (sleepEvent, millisecs);
  199002. }
  199003. }
  199004. static int lastProcessPriority = -1;
  199005. // called by WindowDriver because Windows does wierd things to process priority
  199006. // when you swap apps, and this forces an update when the app is brought to the front.
  199007. void juce_repeatLastProcessPriority() throw()
  199008. {
  199009. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  199010. {
  199011. DWORD p;
  199012. switch (lastProcessPriority)
  199013. {
  199014. case Process::LowPriority:
  199015. p = IDLE_PRIORITY_CLASS;
  199016. break;
  199017. case Process::NormalPriority:
  199018. p = NORMAL_PRIORITY_CLASS;
  199019. break;
  199020. case Process::HighPriority:
  199021. p = HIGH_PRIORITY_CLASS;
  199022. break;
  199023. case Process::RealtimePriority:
  199024. p = REALTIME_PRIORITY_CLASS;
  199025. break;
  199026. default:
  199027. jassertfalse // bad priority value
  199028. return;
  199029. }
  199030. SetPriorityClass (GetCurrentProcess(), p);
  199031. }
  199032. }
  199033. void Process::setPriority (ProcessPriority prior)
  199034. {
  199035. if (lastProcessPriority != (int) prior)
  199036. {
  199037. lastProcessPriority = (int) prior;
  199038. juce_repeatLastProcessPriority();
  199039. }
  199040. }
  199041. bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  199042. {
  199043. return IsDebuggerPresent() != FALSE;
  199044. }
  199045. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  199046. {
  199047. return juce_isRunningUnderDebugger();
  199048. }
  199049. void Process::raisePrivilege()
  199050. {
  199051. jassertfalse // xxx not implemented
  199052. }
  199053. void Process::lowerPrivilege()
  199054. {
  199055. jassertfalse // xxx not implemented
  199056. }
  199057. void Process::terminate()
  199058. {
  199059. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  199060. _CrtDumpMemoryLeaks();
  199061. #endif
  199062. // bullet in the head in case there's a problem shutting down..
  199063. ExitProcess (0);
  199064. }
  199065. void* Process::loadDynamicLibrary (const String& name)
  199066. {
  199067. void* result = 0;
  199068. JUCE_TRY
  199069. {
  199070. result = (void*) LoadLibrary (name);
  199071. }
  199072. JUCE_CATCH_ALL
  199073. return result;
  199074. }
  199075. void Process::freeDynamicLibrary (void* h)
  199076. {
  199077. JUCE_TRY
  199078. {
  199079. if (h != 0)
  199080. FreeLibrary ((HMODULE) h);
  199081. }
  199082. JUCE_CATCH_ALL
  199083. }
  199084. void* Process::getProcedureEntryPoint (void* h, const String& name)
  199085. {
  199086. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name)
  199087. : 0;
  199088. }
  199089. InterProcessLock::InterProcessLock (const String& name_) throw()
  199090. : internal (0),
  199091. name (name_),
  199092. reentrancyLevel (0)
  199093. {
  199094. }
  199095. InterProcessLock::~InterProcessLock() throw()
  199096. {
  199097. exit();
  199098. }
  199099. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  199100. {
  199101. if (reentrancyLevel++ == 0)
  199102. {
  199103. internal = CreateMutex (0, TRUE, name);
  199104. if (internal != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  199105. {
  199106. if (timeOutMillisecs == 0
  199107. || WaitForSingleObject (internal, (timeOutMillisecs < 0) ? INFINITE : timeOutMillisecs)
  199108. == WAIT_TIMEOUT)
  199109. {
  199110. ReleaseMutex (internal);
  199111. CloseHandle (internal);
  199112. internal = 0;
  199113. }
  199114. }
  199115. }
  199116. return (internal != 0);
  199117. }
  199118. void InterProcessLock::exit() throw()
  199119. {
  199120. if (--reentrancyLevel == 0 && internal != 0)
  199121. {
  199122. ReleaseMutex (internal);
  199123. CloseHandle (internal);
  199124. internal = 0;
  199125. }
  199126. }
  199127. END_JUCE_NAMESPACE
  199128. /********* End of inlined file: juce_win32_Threads.cpp *********/
  199129. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  199130. BEGIN_JUCE_NAMESPACE
  199131. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  199132. {
  199133. libHandle = LoadLibrary (name);
  199134. }
  199135. DynamicLibraryLoader::~DynamicLibraryLoader()
  199136. {
  199137. FreeLibrary ((HMODULE) libHandle);
  199138. }
  199139. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  199140. {
  199141. return (void*) GetProcAddress ((HMODULE) libHandle, functionName);
  199142. }
  199143. END_JUCE_NAMESPACE
  199144. /********* End of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  199145. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  199146. /********* Start of inlined file: juce_win32_ASIO.cpp *********/
  199147. #undef WINDOWS
  199148. #if JUCE_ASIO
  199149. /*
  199150. This is very frustrating - we only need to use a handful of definitions from
  199151. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  199152. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  199153. implementation...
  199154. ..unfortunately that would break Steinberg's license agreement for use of
  199155. their SDK, so I'm not allowed to do this.
  199156. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  199157. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  199158. (see www.steinberg.net/Steinberg/Developers.asp).
  199159. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  199160. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  199161. if you prefer). Make sure that your header search path will find the
  199162. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  199163. files are actually needed - so to simplify things, you could just copy
  199164. these into your JUCE directory).
  199165. */
  199166. #include "iasiodrv.h" // if you're compiling and this line causes an error because
  199167. // you don't have the ASIO SDK installed, you can disable ASIO
  199168. // support by commenting-out the "#define JUCE_ASIO" line in
  199169. // juce_Config.h
  199170. BEGIN_JUCE_NAMESPACE
  199171. // #define ASIO_DEBUGGING
  199172. #ifdef ASIO_DEBUGGING
  199173. #define log(a) { Logger::writeToLog (a); DBG (a) }
  199174. #else
  199175. #define log(a) {}
  199176. #endif
  199177. #ifdef ASIO_DEBUGGING
  199178. static void logError (const String& context, long error)
  199179. {
  199180. String err ("unknown error");
  199181. if (error == ASE_NotPresent)
  199182. err = "Not Present";
  199183. else if (error == ASE_HWMalfunction)
  199184. err = "Hardware Malfunction";
  199185. else if (error == ASE_InvalidParameter)
  199186. err = "Invalid Parameter";
  199187. else if (error == ASE_InvalidMode)
  199188. err = "Invalid Mode";
  199189. else if (error == ASE_SPNotAdvancing)
  199190. err = "Sample position not advancing";
  199191. else if (error == ASE_NoClock)
  199192. err = "No Clock";
  199193. else if (error == ASE_NoMemory)
  199194. err = "Out of memory";
  199195. log (T("!!error: ") + context + T(" - ") + err);
  199196. }
  199197. #else
  199198. #define logError(a, b) {}
  199199. #endif
  199200. class ASIOAudioIODevice;
  199201. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  199202. static const int maxASIOChannels = 160;
  199203. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  199204. private Timer
  199205. {
  199206. public:
  199207. Component ourWindow;
  199208. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber)
  199209. : AudioIODevice (name_, T("ASIO")),
  199210. asioObject (0),
  199211. classId (classId_),
  199212. currentBitDepth (16),
  199213. currentSampleRate (0),
  199214. tempBuffer (0),
  199215. isOpen_ (false),
  199216. isStarted (false),
  199217. postOutput (true),
  199218. insideControlPanelModalLoop (false),
  199219. shouldUsePreferredSize (false)
  199220. {
  199221. name = name_;
  199222. ourWindow.addToDesktop (0);
  199223. windowHandle = ourWindow.getWindowHandle();
  199224. jassert (currentASIODev [slotNumber] == 0);
  199225. currentASIODev [slotNumber] = this;
  199226. openDevice();
  199227. }
  199228. ~ASIOAudioIODevice()
  199229. {
  199230. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  199231. if (currentASIODev[i] == this)
  199232. currentASIODev[i] = 0;
  199233. close();
  199234. log ("ASIO - exiting");
  199235. removeCurrentDriver();
  199236. juce_free (tempBuffer);
  199237. }
  199238. void updateSampleRates()
  199239. {
  199240. // find a list of sample rates..
  199241. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  199242. sampleRates.clear();
  199243. if (asioObject != 0)
  199244. {
  199245. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  199246. {
  199247. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  199248. if (err == 0)
  199249. {
  199250. sampleRates.add ((int) possibleSampleRates[index]);
  199251. log (T("rate: ") + String ((int) possibleSampleRates[index]));
  199252. }
  199253. else if (err != ASE_NoClock)
  199254. {
  199255. logError (T("CanSampleRate"), err);
  199256. }
  199257. }
  199258. if (sampleRates.size() == 0)
  199259. {
  199260. double cr = 0;
  199261. const long err = asioObject->getSampleRate (&cr);
  199262. log (T("No sample rates supported - current rate: ") + String ((int) cr));
  199263. if (err == 0)
  199264. sampleRates.add ((int) cr);
  199265. }
  199266. }
  199267. }
  199268. const StringArray getOutputChannelNames()
  199269. {
  199270. return outputChannelNames;
  199271. }
  199272. const StringArray getInputChannelNames()
  199273. {
  199274. return inputChannelNames;
  199275. }
  199276. int getNumSampleRates()
  199277. {
  199278. return sampleRates.size();
  199279. }
  199280. double getSampleRate (int index)
  199281. {
  199282. return sampleRates [index];
  199283. }
  199284. int getNumBufferSizesAvailable()
  199285. {
  199286. return bufferSizes.size();
  199287. }
  199288. int getBufferSizeSamples (int index)
  199289. {
  199290. return bufferSizes [index];
  199291. }
  199292. int getDefaultBufferSize()
  199293. {
  199294. return preferredSize;
  199295. }
  199296. const String open (const BitArray& inputChannels,
  199297. const BitArray& outputChannels,
  199298. double sr,
  199299. int bufferSizeSamples)
  199300. {
  199301. close();
  199302. currentCallback = 0;
  199303. if (bufferSizeSamples <= 0)
  199304. shouldUsePreferredSize = true;
  199305. if (asioObject == 0 || ! isASIOOpen)
  199306. {
  199307. log ("Warning: device not open");
  199308. const String err (openDevice());
  199309. if (asioObject == 0 || ! isASIOOpen)
  199310. return err;
  199311. }
  199312. isStarted = false;
  199313. bufferIndex = -1;
  199314. long err = 0;
  199315. long newPreferredSize = 0;
  199316. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  199317. minSize = 0;
  199318. maxSize = 0;
  199319. newPreferredSize = 0;
  199320. granularity = 0;
  199321. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  199322. {
  199323. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  199324. shouldUsePreferredSize = true;
  199325. preferredSize = newPreferredSize;
  199326. }
  199327. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  199328. // dynamic changes to the buffer size...
  199329. shouldUsePreferredSize = shouldUsePreferredSize
  199330. || getName().containsIgnoreCase (T("Digidesign"));
  199331. if (shouldUsePreferredSize)
  199332. {
  199333. log ("Using preferred size for buffer..");
  199334. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  199335. {
  199336. bufferSizeSamples = preferredSize;
  199337. }
  199338. else
  199339. {
  199340. bufferSizeSamples = 1024;
  199341. logError ("GetBufferSize1", err);
  199342. }
  199343. shouldUsePreferredSize = false;
  199344. }
  199345. int sampleRate = roundDoubleToInt (sr);
  199346. currentSampleRate = sampleRate;
  199347. currentBlockSizeSamples = bufferSizeSamples;
  199348. currentChansOut.clear();
  199349. currentChansIn.clear();
  199350. zeromem (inBuffers, sizeof (inBuffers));
  199351. zeromem (outBuffers, sizeof (outBuffers));
  199352. updateSampleRates();
  199353. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  199354. sampleRate = sampleRates[0];
  199355. jassert (sampleRate != 0);
  199356. if (sampleRate == 0)
  199357. sampleRate = 44100;
  199358. long numSources = 32;
  199359. ASIOClockSource clocks[32];
  199360. zeromem (clocks, sizeof (clocks));
  199361. asioObject->getClockSources (clocks, &numSources);
  199362. bool isSourceSet = false;
  199363. // careful not to remove this loop because it does more than just logging!
  199364. int i;
  199365. for (i = 0; i < numSources; ++i)
  199366. {
  199367. String s ("clock: ");
  199368. s += clocks[i].name;
  199369. if (clocks[i].isCurrentSource)
  199370. {
  199371. isSourceSet = true;
  199372. s << " (cur)";
  199373. }
  199374. log (s);
  199375. }
  199376. if (numSources > 1 && ! isSourceSet)
  199377. {
  199378. log ("setting clock source");
  199379. asioObject->setClockSource (clocks[0].index);
  199380. Thread::sleep (20);
  199381. }
  199382. else
  199383. {
  199384. if (numSources == 0)
  199385. {
  199386. log ("ASIO - no clock sources!");
  199387. }
  199388. }
  199389. double cr = 0;
  199390. err = asioObject->getSampleRate (&cr);
  199391. if (err == 0)
  199392. {
  199393. currentSampleRate = cr;
  199394. }
  199395. else
  199396. {
  199397. logError ("GetSampleRate", err);
  199398. currentSampleRate = 0;
  199399. }
  199400. error = String::empty;
  199401. needToReset = false;
  199402. isReSync = false;
  199403. err = 0;
  199404. bool buffersCreated = false;
  199405. if (currentSampleRate != sampleRate)
  199406. {
  199407. log (T("ASIO samplerate: ") + String (currentSampleRate) + T(" to ") + String (sampleRate));
  199408. err = asioObject->setSampleRate (sampleRate);
  199409. if (err == ASE_NoClock && numSources > 0)
  199410. {
  199411. log ("trying to set a clock source..");
  199412. Thread::sleep (10);
  199413. err = asioObject->setClockSource (clocks[0].index);
  199414. if (err != 0)
  199415. {
  199416. logError ("SetClock", err);
  199417. }
  199418. Thread::sleep (10);
  199419. err = asioObject->setSampleRate (sampleRate);
  199420. }
  199421. }
  199422. if (err == 0)
  199423. {
  199424. currentSampleRate = sampleRate;
  199425. if (needToReset)
  199426. {
  199427. if (isReSync)
  199428. {
  199429. log ("Resync request");
  199430. }
  199431. log ("! Resetting ASIO after sample rate change");
  199432. removeCurrentDriver();
  199433. loadDriver();
  199434. const String error (initDriver());
  199435. if (error.isNotEmpty())
  199436. {
  199437. log (T("ASIOInit: ") + error);
  199438. }
  199439. needToReset = false;
  199440. isReSync = false;
  199441. }
  199442. numActiveInputChans = 0;
  199443. numActiveOutputChans = 0;
  199444. ASIOBufferInfo* info = bufferInfos;
  199445. int i;
  199446. for (i = 0; i < totalNumInputChans; ++i)
  199447. {
  199448. if (inputChannels[i])
  199449. {
  199450. currentChansIn.setBit (i);
  199451. info->isInput = 1;
  199452. info->channelNum = i;
  199453. info->buffers[0] = info->buffers[1] = 0;
  199454. ++info;
  199455. ++numActiveInputChans;
  199456. }
  199457. }
  199458. for (i = 0; i < totalNumOutputChans; ++i)
  199459. {
  199460. if (outputChannels[i])
  199461. {
  199462. currentChansOut.setBit (i);
  199463. info->isInput = 0;
  199464. info->channelNum = i;
  199465. info->buffers[0] = info->buffers[1] = 0;
  199466. ++info;
  199467. ++numActiveOutputChans;
  199468. }
  199469. }
  199470. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  199471. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  199472. if (currentASIODev[0] == this)
  199473. {
  199474. callbacks.bufferSwitch = &bufferSwitchCallback0;
  199475. callbacks.asioMessage = &asioMessagesCallback0;
  199476. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  199477. }
  199478. else if (currentASIODev[1] == this)
  199479. {
  199480. callbacks.bufferSwitch = &bufferSwitchCallback1;
  199481. callbacks.asioMessage = &asioMessagesCallback1;
  199482. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  199483. }
  199484. else if (currentASIODev[2] == this)
  199485. {
  199486. callbacks.bufferSwitch = &bufferSwitchCallback2;
  199487. callbacks.asioMessage = &asioMessagesCallback2;
  199488. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  199489. }
  199490. else
  199491. {
  199492. jassertfalse
  199493. }
  199494. log ("disposing buffers");
  199495. err = asioObject->disposeBuffers();
  199496. log (T("creating buffers: ") + String (totalBuffers) + T(", ") + String (currentBlockSizeSamples));
  199497. err = asioObject->createBuffers (bufferInfos,
  199498. totalBuffers,
  199499. currentBlockSizeSamples,
  199500. &callbacks);
  199501. if (err != 0)
  199502. {
  199503. currentBlockSizeSamples = preferredSize;
  199504. logError ("create buffers 2", err);
  199505. asioObject->disposeBuffers();
  199506. err = asioObject->createBuffers (bufferInfos,
  199507. totalBuffers,
  199508. currentBlockSizeSamples,
  199509. &callbacks);
  199510. }
  199511. if (err == 0)
  199512. {
  199513. buffersCreated = true;
  199514. juce_free (tempBuffer);
  199515. tempBuffer = (float*) juce_calloc (totalBuffers * currentBlockSizeSamples * sizeof (float) + 128);
  199516. int n = 0;
  199517. Array <int> types;
  199518. currentBitDepth = 16;
  199519. for (i = 0; i < jmin (totalNumInputChans, maxASIOChannels); ++i)
  199520. {
  199521. if (inputChannels[i])
  199522. {
  199523. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  199524. ASIOChannelInfo channelInfo;
  199525. zerostruct (channelInfo);
  199526. channelInfo.channel = i;
  199527. channelInfo.isInput = 1;
  199528. asioObject->getChannelInfo (&channelInfo);
  199529. types.addIfNotAlreadyThere (channelInfo.type);
  199530. typeToFormatParameters (channelInfo.type,
  199531. inputChannelBitDepths[n],
  199532. inputChannelBytesPerSample[n],
  199533. inputChannelIsFloat[n],
  199534. inputChannelLittleEndian[n]);
  199535. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  199536. ++n;
  199537. }
  199538. }
  199539. jassert (numActiveInputChans == n);
  199540. n = 0;
  199541. for (i = 0; i < jmin (totalNumOutputChans, maxASIOChannels); ++i)
  199542. {
  199543. if (outputChannels[i])
  199544. {
  199545. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  199546. ASIOChannelInfo channelInfo;
  199547. zerostruct (channelInfo);
  199548. channelInfo.channel = i;
  199549. channelInfo.isInput = 0;
  199550. asioObject->getChannelInfo (&channelInfo);
  199551. types.addIfNotAlreadyThere (channelInfo.type);
  199552. typeToFormatParameters (channelInfo.type,
  199553. outputChannelBitDepths[n],
  199554. outputChannelBytesPerSample[n],
  199555. outputChannelIsFloat[n],
  199556. outputChannelLittleEndian[n]);
  199557. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  199558. ++n;
  199559. }
  199560. }
  199561. jassert (numActiveOutputChans == n);
  199562. for (i = types.size(); --i >= 0;)
  199563. {
  199564. log (T("channel format: ") + String (types[i]));
  199565. }
  199566. jassert (n <= totalBuffers);
  199567. for (i = 0; i < numActiveOutputChans; ++i)
  199568. {
  199569. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  199570. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  199571. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  199572. {
  199573. log ("!! Null buffers");
  199574. }
  199575. else
  199576. {
  199577. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  199578. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  199579. }
  199580. }
  199581. inputLatency = outputLatency = 0;
  199582. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  199583. {
  199584. log ("ASIO - no latencies");
  199585. }
  199586. else
  199587. {
  199588. log (T("ASIO latencies: ")
  199589. + String ((int) outputLatency)
  199590. + T(", ")
  199591. + String ((int) inputLatency));
  199592. }
  199593. isOpen_ = true;
  199594. log ("starting ASIO");
  199595. calledback = false;
  199596. err = asioObject->start();
  199597. if (err != 0)
  199598. {
  199599. isOpen_ = false;
  199600. log ("ASIO - stop on failure");
  199601. Thread::sleep (10);
  199602. asioObject->stop();
  199603. error = "Can't start device";
  199604. Thread::sleep (10);
  199605. }
  199606. else
  199607. {
  199608. int count = 300;
  199609. while (--count > 0 && ! calledback)
  199610. Thread::sleep (10);
  199611. isStarted = true;
  199612. if (! calledback)
  199613. {
  199614. error = "Device didn't start correctly";
  199615. log ("ASIO didn't callback - stopping..");
  199616. asioObject->stop();
  199617. }
  199618. }
  199619. }
  199620. else
  199621. {
  199622. error = "Can't create i/o buffers";
  199623. }
  199624. }
  199625. else
  199626. {
  199627. error = "Can't set sample rate: ";
  199628. error << sampleRate;
  199629. }
  199630. if (error.isNotEmpty())
  199631. {
  199632. logError (error, err);
  199633. if (asioObject != 0 && buffersCreated)
  199634. asioObject->disposeBuffers();
  199635. Thread::sleep (20);
  199636. isStarted = false;
  199637. isOpen_ = false;
  199638. close();
  199639. }
  199640. needToReset = false;
  199641. isReSync = false;
  199642. return error;
  199643. }
  199644. void close()
  199645. {
  199646. error = String::empty;
  199647. stopTimer();
  199648. stop();
  199649. if (isASIOOpen && isOpen_)
  199650. {
  199651. const ScopedLock sl (callbackLock);
  199652. isOpen_ = false;
  199653. isStarted = false;
  199654. needToReset = false;
  199655. isReSync = false;
  199656. log ("ASIO - stopping");
  199657. if (asioObject != 0)
  199658. {
  199659. Thread::sleep (20);
  199660. asioObject->stop();
  199661. Thread::sleep (10);
  199662. asioObject->disposeBuffers();
  199663. }
  199664. Thread::sleep (10);
  199665. }
  199666. }
  199667. bool isOpen()
  199668. {
  199669. return isOpen_ || insideControlPanelModalLoop;
  199670. }
  199671. int getCurrentBufferSizeSamples()
  199672. {
  199673. return currentBlockSizeSamples;
  199674. }
  199675. double getCurrentSampleRate()
  199676. {
  199677. return currentSampleRate;
  199678. }
  199679. const BitArray getActiveOutputChannels() const
  199680. {
  199681. return currentChansOut;
  199682. }
  199683. const BitArray getActiveInputChannels() const
  199684. {
  199685. return currentChansIn;
  199686. }
  199687. int getCurrentBitDepth()
  199688. {
  199689. return currentBitDepth;
  199690. }
  199691. int getOutputLatencyInSamples()
  199692. {
  199693. return outputLatency + currentBlockSizeSamples / 4;
  199694. }
  199695. int getInputLatencyInSamples()
  199696. {
  199697. return inputLatency + currentBlockSizeSamples / 4;
  199698. }
  199699. void start (AudioIODeviceCallback* callback)
  199700. {
  199701. if (callback != 0)
  199702. {
  199703. callback->audioDeviceAboutToStart (this);
  199704. const ScopedLock sl (callbackLock);
  199705. currentCallback = callback;
  199706. }
  199707. }
  199708. void stop()
  199709. {
  199710. AudioIODeviceCallback* const lastCallback = currentCallback;
  199711. {
  199712. const ScopedLock sl (callbackLock);
  199713. currentCallback = 0;
  199714. }
  199715. if (lastCallback != 0)
  199716. lastCallback->audioDeviceStopped();
  199717. }
  199718. bool isPlaying()
  199719. {
  199720. return isASIOOpen && (currentCallback != 0);
  199721. }
  199722. const String getLastError()
  199723. {
  199724. return error;
  199725. }
  199726. bool hasControlPanel() const
  199727. {
  199728. return true;
  199729. }
  199730. bool showControlPanel()
  199731. {
  199732. log ("ASIO - showing control panel");
  199733. Component modalWindow (String::empty);
  199734. modalWindow.setOpaque (true);
  199735. modalWindow.addToDesktop (0);
  199736. modalWindow.enterModalState();
  199737. bool done = false;
  199738. JUCE_TRY
  199739. {
  199740. close();
  199741. insideControlPanelModalLoop = true;
  199742. const uint32 started = Time::getMillisecondCounter();
  199743. if (asioObject != 0)
  199744. {
  199745. asioObject->controlPanel();
  199746. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  199747. log (T("spent: ") + String (spent));
  199748. if (spent > 300)
  199749. {
  199750. shouldUsePreferredSize = true;
  199751. done = true;
  199752. }
  199753. }
  199754. }
  199755. JUCE_CATCH_ALL
  199756. insideControlPanelModalLoop = false;
  199757. return done;
  199758. }
  199759. void resetRequest() throw()
  199760. {
  199761. needToReset = true;
  199762. }
  199763. void resyncRequest() throw()
  199764. {
  199765. needToReset = true;
  199766. isReSync = true;
  199767. }
  199768. void timerCallback()
  199769. {
  199770. if (! insideControlPanelModalLoop)
  199771. {
  199772. stopTimer();
  199773. // used to cause a reset
  199774. log ("! ASIO restart request!");
  199775. if (isOpen_)
  199776. {
  199777. AudioIODeviceCallback* const oldCallback = currentCallback;
  199778. close();
  199779. open (currentChansIn, currentChansOut,
  199780. currentSampleRate, currentBlockSizeSamples);
  199781. if (oldCallback != 0)
  199782. start (oldCallback);
  199783. }
  199784. }
  199785. else
  199786. {
  199787. startTimer (100);
  199788. }
  199789. }
  199790. juce_UseDebuggingNewOperator
  199791. private:
  199792. IASIO* volatile asioObject;
  199793. ASIOCallbacks callbacks;
  199794. void* windowHandle;
  199795. CLSID classId;
  199796. String error;
  199797. long totalNumInputChans, totalNumOutputChans;
  199798. StringArray inputChannelNames, outputChannelNames;
  199799. Array<int> sampleRates, bufferSizes;
  199800. long inputLatency, outputLatency;
  199801. long minSize, maxSize, preferredSize, granularity;
  199802. int volatile currentBlockSizeSamples;
  199803. int volatile currentBitDepth;
  199804. double volatile currentSampleRate;
  199805. BitArray currentChansOut, currentChansIn;
  199806. AudioIODeviceCallback* volatile currentCallback;
  199807. CriticalSection callbackLock;
  199808. ASIOBufferInfo bufferInfos [maxASIOChannels];
  199809. float* inBuffers [maxASIOChannels];
  199810. float* outBuffers [maxASIOChannels];
  199811. int inputChannelBitDepths [maxASIOChannels];
  199812. int outputChannelBitDepths [maxASIOChannels];
  199813. int inputChannelBytesPerSample [maxASIOChannels];
  199814. int outputChannelBytesPerSample [maxASIOChannels];
  199815. bool inputChannelIsFloat [maxASIOChannels];
  199816. bool outputChannelIsFloat [maxASIOChannels];
  199817. bool inputChannelLittleEndian [maxASIOChannels];
  199818. bool outputChannelLittleEndian [maxASIOChannels];
  199819. WaitableEvent event1;
  199820. float* tempBuffer;
  199821. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  199822. bool isOpen_, isStarted;
  199823. bool volatile isASIOOpen;
  199824. bool volatile calledback;
  199825. bool volatile littleEndian, postOutput, needToReset, isReSync;
  199826. bool volatile insideControlPanelModalLoop;
  199827. bool volatile shouldUsePreferredSize;
  199828. void removeCurrentDriver()
  199829. {
  199830. if (asioObject != 0)
  199831. {
  199832. asioObject->Release();
  199833. asioObject = 0;
  199834. }
  199835. }
  199836. bool loadDriver()
  199837. {
  199838. removeCurrentDriver();
  199839. JUCE_TRY
  199840. {
  199841. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  199842. classId, (void**) &asioObject) == S_OK)
  199843. {
  199844. return true;
  199845. }
  199846. }
  199847. JUCE_CATCH_ALL
  199848. asioObject = 0;
  199849. return false;
  199850. }
  199851. const String initDriver()
  199852. {
  199853. if (asioObject != 0)
  199854. {
  199855. char buffer [256];
  199856. zeromem (buffer, sizeof (buffer));
  199857. if (! asioObject->init (windowHandle))
  199858. {
  199859. asioObject->getErrorMessage (buffer);
  199860. return String (buffer, sizeof (buffer) - 1);
  199861. }
  199862. // just in case any daft drivers expect this to be called..
  199863. asioObject->getDriverName (buffer);
  199864. return String::empty;
  199865. }
  199866. return "No Driver";
  199867. }
  199868. const String openDevice()
  199869. {
  199870. // use this in case the driver starts opening dialog boxes..
  199871. Component modalWindow (String::empty);
  199872. modalWindow.setOpaque (true);
  199873. modalWindow.addToDesktop (0);
  199874. modalWindow.enterModalState();
  199875. // open the device and get its info..
  199876. log (T("opening ASIO device: ") + getName());
  199877. needToReset = false;
  199878. isReSync = false;
  199879. outputChannelNames.clear();
  199880. inputChannelNames.clear();
  199881. bufferSizes.clear();
  199882. sampleRates.clear();
  199883. isASIOOpen = false;
  199884. isOpen_ = false;
  199885. totalNumInputChans = 0;
  199886. totalNumOutputChans = 0;
  199887. numActiveInputChans = 0;
  199888. numActiveOutputChans = 0;
  199889. currentCallback = 0;
  199890. error = String::empty;
  199891. if (getName().isEmpty())
  199892. return error;
  199893. long err = 0;
  199894. if (loadDriver())
  199895. {
  199896. if ((error = initDriver()).isEmpty())
  199897. {
  199898. numActiveInputChans = 0;
  199899. numActiveOutputChans = 0;
  199900. totalNumInputChans = 0;
  199901. totalNumOutputChans = 0;
  199902. if (asioObject != 0
  199903. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  199904. {
  199905. log (String ((int) totalNumInputChans) + T(" in, ") + String ((int) totalNumOutputChans) + T(" out"));
  199906. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  199907. {
  199908. // find a list of buffer sizes..
  199909. log (String ((int) minSize) + T(" ") + String ((int) maxSize) + T(" ") + String ((int)preferredSize) + T(" ") + String ((int)granularity));
  199910. if (granularity >= 0)
  199911. {
  199912. granularity = jmax (1, (int) granularity);
  199913. for (int i = jmax (minSize, (int) granularity); i < jmin (6400, maxSize); i += granularity)
  199914. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  199915. }
  199916. else if (granularity < 0)
  199917. {
  199918. for (int i = 0; i < 18; ++i)
  199919. {
  199920. const int s = (1 << i);
  199921. if (s >= minSize && s <= maxSize)
  199922. bufferSizes.add (s);
  199923. }
  199924. }
  199925. if (! bufferSizes.contains (preferredSize))
  199926. bufferSizes.insert (0, preferredSize);
  199927. double currentRate = 0;
  199928. asioObject->getSampleRate (&currentRate);
  199929. if (currentRate <= 0.0 || currentRate > 192001.0)
  199930. {
  199931. log ("setting sample rate");
  199932. err = asioObject->setSampleRate (44100.0);
  199933. if (err != 0)
  199934. {
  199935. logError ("setting sample rate", err);
  199936. }
  199937. asioObject->getSampleRate (&currentRate);
  199938. }
  199939. currentSampleRate = currentRate;
  199940. postOutput = (asioObject->outputReady() == 0);
  199941. if (postOutput)
  199942. {
  199943. log ("ASIO outputReady = ok");
  199944. }
  199945. updateSampleRates();
  199946. // ..because cubase does it at this point
  199947. inputLatency = outputLatency = 0;
  199948. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  199949. {
  199950. log ("ASIO - no latencies");
  199951. }
  199952. log (String ("latencies: ")
  199953. + String ((int) inputLatency)
  199954. + T(", ") + String ((int) outputLatency));
  199955. // create some dummy buffers now.. because cubase does..
  199956. numActiveInputChans = 0;
  199957. numActiveOutputChans = 0;
  199958. ASIOBufferInfo* info = bufferInfos;
  199959. int i, numChans = 0;
  199960. for (i = 0; i < jmin (2, totalNumInputChans); ++i)
  199961. {
  199962. info->isInput = 1;
  199963. info->channelNum = i;
  199964. info->buffers[0] = info->buffers[1] = 0;
  199965. ++info;
  199966. ++numChans;
  199967. }
  199968. const int outputBufferIndex = numChans;
  199969. for (i = 0; i < jmin (2, totalNumOutputChans); ++i)
  199970. {
  199971. info->isInput = 0;
  199972. info->channelNum = i;
  199973. info->buffers[0] = info->buffers[1] = 0;
  199974. ++info;
  199975. ++numChans;
  199976. }
  199977. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  199978. if (currentASIODev[0] == this)
  199979. {
  199980. callbacks.bufferSwitch = &bufferSwitchCallback0;
  199981. callbacks.asioMessage = &asioMessagesCallback0;
  199982. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  199983. }
  199984. else if (currentASIODev[1] == this)
  199985. {
  199986. callbacks.bufferSwitch = &bufferSwitchCallback1;
  199987. callbacks.asioMessage = &asioMessagesCallback1;
  199988. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  199989. }
  199990. else if (currentASIODev[2] == this)
  199991. {
  199992. callbacks.bufferSwitch = &bufferSwitchCallback2;
  199993. callbacks.asioMessage = &asioMessagesCallback2;
  199994. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  199995. }
  199996. else
  199997. {
  199998. jassertfalse
  199999. }
  200000. log (T("creating buffers (dummy): ") + String (numChans)
  200001. + T(", ") + String ((int) preferredSize));
  200002. if (preferredSize > 0)
  200003. {
  200004. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  200005. if (err != 0)
  200006. {
  200007. logError ("dummy buffers", err);
  200008. }
  200009. }
  200010. long newInps = 0, newOuts = 0;
  200011. asioObject->getChannels (&newInps, &newOuts);
  200012. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  200013. {
  200014. totalNumInputChans = newInps;
  200015. totalNumOutputChans = newOuts;
  200016. log (String ((int) totalNumInputChans) + T(" in; ")
  200017. + String ((int) totalNumOutputChans) + T(" out"));
  200018. }
  200019. updateSampleRates();
  200020. ASIOChannelInfo channelInfo;
  200021. channelInfo.type = 0;
  200022. for (i = 0; i < totalNumInputChans; ++i)
  200023. {
  200024. zerostruct (channelInfo);
  200025. channelInfo.channel = i;
  200026. channelInfo.isInput = 1;
  200027. asioObject->getChannelInfo (&channelInfo);
  200028. inputChannelNames.add (String (channelInfo.name));
  200029. }
  200030. for (i = 0; i < totalNumOutputChans; ++i)
  200031. {
  200032. zerostruct (channelInfo);
  200033. channelInfo.channel = i;
  200034. channelInfo.isInput = 0;
  200035. asioObject->getChannelInfo (&channelInfo);
  200036. outputChannelNames.add (String (channelInfo.name));
  200037. typeToFormatParameters (channelInfo.type,
  200038. outputChannelBitDepths[i],
  200039. outputChannelBytesPerSample[i],
  200040. outputChannelIsFloat[i],
  200041. outputChannelLittleEndian[i]);
  200042. if (i < 2)
  200043. {
  200044. // clear the channels that are used with the dummy stuff
  200045. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  200046. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  200047. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  200048. }
  200049. }
  200050. outputChannelNames.trim();
  200051. inputChannelNames.trim();
  200052. outputChannelNames.appendNumbersToDuplicates (false, true);
  200053. inputChannelNames.appendNumbersToDuplicates (false, true);
  200054. // start and stop because cubase does it..
  200055. asioObject->getLatencies (&inputLatency, &outputLatency);
  200056. if ((err = asioObject->start()) != 0)
  200057. {
  200058. // ignore an error here, as it might start later after setting other stuff up
  200059. logError ("ASIO start", err);
  200060. }
  200061. Thread::sleep (100);
  200062. asioObject->stop();
  200063. }
  200064. else
  200065. {
  200066. error = "Can't detect buffer sizes";
  200067. }
  200068. }
  200069. else
  200070. {
  200071. error = "Can't detect asio channels";
  200072. }
  200073. }
  200074. }
  200075. else
  200076. {
  200077. error = "No such device";
  200078. }
  200079. if (error.isNotEmpty())
  200080. {
  200081. logError (error, err);
  200082. if (asioObject != 0)
  200083. asioObject->disposeBuffers();
  200084. removeCurrentDriver();
  200085. isASIOOpen = false;
  200086. }
  200087. else
  200088. {
  200089. isASIOOpen = true;
  200090. log ("ASIO device open");
  200091. }
  200092. isOpen_ = false;
  200093. needToReset = false;
  200094. isReSync = false;
  200095. return error;
  200096. }
  200097. void callback (const long index) throw()
  200098. {
  200099. if (isStarted)
  200100. {
  200101. bufferIndex = index;
  200102. processBuffer();
  200103. }
  200104. else
  200105. {
  200106. if (postOutput && (asioObject != 0))
  200107. asioObject->outputReady();
  200108. }
  200109. calledback = true;
  200110. }
  200111. void processBuffer() throw()
  200112. {
  200113. const ASIOBufferInfo* const infos = bufferInfos;
  200114. const int bi = bufferIndex;
  200115. const ScopedLock sl (callbackLock);
  200116. if (needToReset)
  200117. {
  200118. needToReset = false;
  200119. if (isReSync)
  200120. {
  200121. log ("! ASIO resync");
  200122. isReSync = false;
  200123. }
  200124. else
  200125. {
  200126. startTimer (20);
  200127. }
  200128. }
  200129. if (bi >= 0)
  200130. {
  200131. const int samps = currentBlockSizeSamples;
  200132. if (currentCallback != 0)
  200133. {
  200134. int i;
  200135. for (i = 0; i < numActiveInputChans; ++i)
  200136. {
  200137. float* const dst = inBuffers[i];
  200138. jassert (dst != 0);
  200139. const char* const src = (const char*) (infos[i].buffers[bi]);
  200140. if (inputChannelIsFloat[i])
  200141. {
  200142. memcpy (dst, src, samps * sizeof (float));
  200143. }
  200144. else
  200145. {
  200146. jassert (dst == tempBuffer + (samps * i));
  200147. switch (inputChannelBitDepths[i])
  200148. {
  200149. case 16:
  200150. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  200151. samps, inputChannelLittleEndian[i]);
  200152. break;
  200153. case 24:
  200154. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  200155. samps, inputChannelLittleEndian[i]);
  200156. break;
  200157. case 32:
  200158. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  200159. samps, inputChannelLittleEndian[i]);
  200160. break;
  200161. case 64:
  200162. jassertfalse
  200163. break;
  200164. }
  200165. }
  200166. }
  200167. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  200168. numActiveInputChans,
  200169. outBuffers,
  200170. numActiveOutputChans,
  200171. samps);
  200172. for (i = 0; i < numActiveOutputChans; ++i)
  200173. {
  200174. float* const src = outBuffers[i];
  200175. jassert (src != 0);
  200176. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  200177. if (outputChannelIsFloat[i])
  200178. {
  200179. memcpy (dst, src, samps * sizeof (float));
  200180. }
  200181. else
  200182. {
  200183. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  200184. switch (outputChannelBitDepths[i])
  200185. {
  200186. case 16:
  200187. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  200188. samps, outputChannelLittleEndian[i]);
  200189. break;
  200190. case 24:
  200191. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  200192. samps, outputChannelLittleEndian[i]);
  200193. break;
  200194. case 32:
  200195. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  200196. samps, outputChannelLittleEndian[i]);
  200197. break;
  200198. case 64:
  200199. jassertfalse
  200200. break;
  200201. }
  200202. }
  200203. }
  200204. }
  200205. else
  200206. {
  200207. for (int i = 0; i < numActiveOutputChans; ++i)
  200208. {
  200209. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  200210. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  200211. }
  200212. }
  200213. }
  200214. if (postOutput)
  200215. asioObject->outputReady();
  200216. }
  200217. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long) throw()
  200218. {
  200219. if (currentASIODev[0] != 0)
  200220. currentASIODev[0]->callback (index);
  200221. return 0;
  200222. }
  200223. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long) throw()
  200224. {
  200225. if (currentASIODev[1] != 0)
  200226. currentASIODev[1]->callback (index);
  200227. return 0;
  200228. }
  200229. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long) throw()
  200230. {
  200231. if (currentASIODev[2] != 0)
  200232. currentASIODev[2]->callback (index);
  200233. return 0;
  200234. }
  200235. static void bufferSwitchCallback0 (long index, long) throw()
  200236. {
  200237. if (currentASIODev[0] != 0)
  200238. currentASIODev[0]->callback (index);
  200239. }
  200240. static void bufferSwitchCallback1 (long index, long) throw()
  200241. {
  200242. if (currentASIODev[1] != 0)
  200243. currentASIODev[1]->callback (index);
  200244. }
  200245. static void bufferSwitchCallback2 (long index, long) throw()
  200246. {
  200247. if (currentASIODev[2] != 0)
  200248. currentASIODev[2]->callback (index);
  200249. }
  200250. static long asioMessagesCallback0 (long selector, long value, void*, double*) throw()
  200251. {
  200252. return asioMessagesCallback (selector, value, 0);
  200253. }
  200254. static long asioMessagesCallback1 (long selector, long value, void*, double*) throw()
  200255. {
  200256. return asioMessagesCallback (selector, value, 1);
  200257. }
  200258. static long asioMessagesCallback2 (long selector, long value, void*, double*) throw()
  200259. {
  200260. return asioMessagesCallback (selector, value, 2);
  200261. }
  200262. static long asioMessagesCallback (long selector, long value, const int deviceIndex) throw()
  200263. {
  200264. switch (selector)
  200265. {
  200266. case kAsioSelectorSupported:
  200267. if (value == kAsioResetRequest
  200268. || value == kAsioEngineVersion
  200269. || value == kAsioResyncRequest
  200270. || value == kAsioLatenciesChanged
  200271. || value == kAsioSupportsInputMonitor)
  200272. return 1;
  200273. break;
  200274. case kAsioBufferSizeChange:
  200275. break;
  200276. case kAsioResetRequest:
  200277. if (currentASIODev[deviceIndex] != 0)
  200278. currentASIODev[deviceIndex]->resetRequest();
  200279. return 1;
  200280. case kAsioResyncRequest:
  200281. if (currentASIODev[deviceIndex] != 0)
  200282. currentASIODev[deviceIndex]->resyncRequest();
  200283. return 1;
  200284. case kAsioLatenciesChanged:
  200285. return 1;
  200286. case kAsioEngineVersion:
  200287. return 2;
  200288. case kAsioSupportsTimeInfo:
  200289. case kAsioSupportsTimeCode:
  200290. return 0;
  200291. }
  200292. return 0;
  200293. }
  200294. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  200295. {
  200296. }
  200297. static void convertInt16ToFloat (const char* src,
  200298. float* dest,
  200299. const int srcStrideBytes,
  200300. int numSamples,
  200301. const bool littleEndian) throw()
  200302. {
  200303. const double g = 1.0 / 32768.0;
  200304. if (littleEndian)
  200305. {
  200306. while (--numSamples >= 0)
  200307. {
  200308. *dest++ = (float) (g * (short) littleEndianShort (src));
  200309. src += srcStrideBytes;
  200310. }
  200311. }
  200312. else
  200313. {
  200314. while (--numSamples >= 0)
  200315. {
  200316. *dest++ = (float) (g * (short) bigEndianShort (src));
  200317. src += srcStrideBytes;
  200318. }
  200319. }
  200320. }
  200321. static void convertFloatToInt16 (const float* src,
  200322. char* dest,
  200323. const int dstStrideBytes,
  200324. int numSamples,
  200325. const bool littleEndian) throw()
  200326. {
  200327. const double maxVal = (double) 0x7fff;
  200328. if (littleEndian)
  200329. {
  200330. while (--numSamples >= 0)
  200331. {
  200332. *(uint16*) dest = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  200333. dest += dstStrideBytes;
  200334. }
  200335. }
  200336. else
  200337. {
  200338. while (--numSamples >= 0)
  200339. {
  200340. *(uint16*) dest = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  200341. dest += dstStrideBytes;
  200342. }
  200343. }
  200344. }
  200345. static void convertInt24ToFloat (const char* src,
  200346. float* dest,
  200347. const int srcStrideBytes,
  200348. int numSamples,
  200349. const bool littleEndian) throw()
  200350. {
  200351. const double g = 1.0 / 0x7fffff;
  200352. if (littleEndian)
  200353. {
  200354. while (--numSamples >= 0)
  200355. {
  200356. *dest++ = (float) (g * littleEndian24Bit (src));
  200357. src += srcStrideBytes;
  200358. }
  200359. }
  200360. else
  200361. {
  200362. while (--numSamples >= 0)
  200363. {
  200364. *dest++ = (float) (g * bigEndian24Bit (src));
  200365. src += srcStrideBytes;
  200366. }
  200367. }
  200368. }
  200369. static void convertFloatToInt24 (const float* src,
  200370. char* dest,
  200371. const int dstStrideBytes,
  200372. int numSamples,
  200373. const bool littleEndian) throw()
  200374. {
  200375. const double maxVal = (double) 0x7fffff;
  200376. if (littleEndian)
  200377. {
  200378. while (--numSamples >= 0)
  200379. {
  200380. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  200381. dest += dstStrideBytes;
  200382. }
  200383. }
  200384. else
  200385. {
  200386. while (--numSamples >= 0)
  200387. {
  200388. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  200389. dest += dstStrideBytes;
  200390. }
  200391. }
  200392. }
  200393. static void convertInt32ToFloat (const char* src,
  200394. float* dest,
  200395. const int srcStrideBytes,
  200396. int numSamples,
  200397. const bool littleEndian) throw()
  200398. {
  200399. const double g = 1.0 / 0x7fffffff;
  200400. if (littleEndian)
  200401. {
  200402. while (--numSamples >= 0)
  200403. {
  200404. *dest++ = (float) (g * (int) littleEndianInt (src));
  200405. src += srcStrideBytes;
  200406. }
  200407. }
  200408. else
  200409. {
  200410. while (--numSamples >= 0)
  200411. {
  200412. *dest++ = (float) (g * (int) bigEndianInt (src));
  200413. src += srcStrideBytes;
  200414. }
  200415. }
  200416. }
  200417. static void convertFloatToInt32 (const float* src,
  200418. char* dest,
  200419. const int dstStrideBytes,
  200420. int numSamples,
  200421. const bool littleEndian) throw()
  200422. {
  200423. const double maxVal = (double) 0x7fffffff;
  200424. if (littleEndian)
  200425. {
  200426. while (--numSamples >= 0)
  200427. {
  200428. *(uint32*) dest = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  200429. dest += dstStrideBytes;
  200430. }
  200431. }
  200432. else
  200433. {
  200434. while (--numSamples >= 0)
  200435. {
  200436. *(uint32*) dest = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  200437. dest += dstStrideBytes;
  200438. }
  200439. }
  200440. }
  200441. static void typeToFormatParameters (const long type,
  200442. int& bitDepth,
  200443. int& byteStride,
  200444. bool& formatIsFloat,
  200445. bool& littleEndian) throw()
  200446. {
  200447. bitDepth = 0;
  200448. littleEndian = false;
  200449. formatIsFloat = false;
  200450. switch (type)
  200451. {
  200452. case ASIOSTInt16MSB:
  200453. case ASIOSTInt16LSB:
  200454. case ASIOSTInt32MSB16:
  200455. case ASIOSTInt32LSB16:
  200456. bitDepth = 16; break;
  200457. case ASIOSTFloat32MSB:
  200458. case ASIOSTFloat32LSB:
  200459. formatIsFloat = true;
  200460. bitDepth = 32; break;
  200461. case ASIOSTInt32MSB:
  200462. case ASIOSTInt32LSB:
  200463. bitDepth = 32; break;
  200464. case ASIOSTInt24MSB:
  200465. case ASIOSTInt24LSB:
  200466. case ASIOSTInt32MSB24:
  200467. case ASIOSTInt32LSB24:
  200468. case ASIOSTInt32MSB18:
  200469. case ASIOSTInt32MSB20:
  200470. case ASIOSTInt32LSB18:
  200471. case ASIOSTInt32LSB20:
  200472. bitDepth = 24; break;
  200473. case ASIOSTFloat64MSB:
  200474. case ASIOSTFloat64LSB:
  200475. default:
  200476. bitDepth = 64;
  200477. break;
  200478. }
  200479. switch (type)
  200480. {
  200481. case ASIOSTInt16MSB:
  200482. case ASIOSTInt32MSB16:
  200483. case ASIOSTFloat32MSB:
  200484. case ASIOSTFloat64MSB:
  200485. case ASIOSTInt32MSB:
  200486. case ASIOSTInt32MSB18:
  200487. case ASIOSTInt32MSB20:
  200488. case ASIOSTInt32MSB24:
  200489. case ASIOSTInt24MSB:
  200490. littleEndian = false; break;
  200491. case ASIOSTInt16LSB:
  200492. case ASIOSTInt32LSB16:
  200493. case ASIOSTFloat32LSB:
  200494. case ASIOSTFloat64LSB:
  200495. case ASIOSTInt32LSB:
  200496. case ASIOSTInt32LSB18:
  200497. case ASIOSTInt32LSB20:
  200498. case ASIOSTInt32LSB24:
  200499. case ASIOSTInt24LSB:
  200500. littleEndian = true; break;
  200501. default:
  200502. break;
  200503. }
  200504. switch (type)
  200505. {
  200506. case ASIOSTInt16LSB:
  200507. case ASIOSTInt16MSB:
  200508. byteStride = 2; break;
  200509. case ASIOSTInt24LSB:
  200510. case ASIOSTInt24MSB:
  200511. byteStride = 3; break;
  200512. case ASIOSTInt32MSB16:
  200513. case ASIOSTInt32LSB16:
  200514. case ASIOSTInt32MSB:
  200515. case ASIOSTInt32MSB18:
  200516. case ASIOSTInt32MSB20:
  200517. case ASIOSTInt32MSB24:
  200518. case ASIOSTInt32LSB:
  200519. case ASIOSTInt32LSB18:
  200520. case ASIOSTInt32LSB20:
  200521. case ASIOSTInt32LSB24:
  200522. case ASIOSTFloat32LSB:
  200523. case ASIOSTFloat32MSB:
  200524. byteStride = 4; break;
  200525. case ASIOSTFloat64MSB:
  200526. case ASIOSTFloat64LSB:
  200527. byteStride = 8; break;
  200528. default:
  200529. break;
  200530. }
  200531. }
  200532. };
  200533. class ASIOAudioIODeviceType : public AudioIODeviceType
  200534. {
  200535. public:
  200536. ASIOAudioIODeviceType()
  200537. : AudioIODeviceType (T("ASIO")),
  200538. classIds (2),
  200539. hasScanned (false)
  200540. {
  200541. CoInitialize (0);
  200542. }
  200543. ~ASIOAudioIODeviceType()
  200544. {
  200545. }
  200546. void scanForDevices()
  200547. {
  200548. hasScanned = true;
  200549. deviceNames.clear();
  200550. classIds.clear();
  200551. HKEY hk = 0;
  200552. int index = 0;
  200553. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  200554. {
  200555. for (;;)
  200556. {
  200557. char name [256];
  200558. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  200559. {
  200560. addDriverInfo (name, hk);
  200561. }
  200562. else
  200563. {
  200564. break;
  200565. }
  200566. }
  200567. RegCloseKey (hk);
  200568. }
  200569. }
  200570. const StringArray getDeviceNames (const bool /*wantInputNames*/) const
  200571. {
  200572. jassert (hasScanned); // need to call scanForDevices() before doing this
  200573. return deviceNames;
  200574. }
  200575. int getDefaultDeviceIndex (const bool) const
  200576. {
  200577. jassert (hasScanned); // need to call scanForDevices() before doing this
  200578. for (int i = deviceNames.size(); --i >= 0;)
  200579. if (deviceNames[i].containsIgnoreCase (T("asio4all")))
  200580. return i; // asio4all is a safe choice for a default..
  200581. #if JUCE_DEBUG
  200582. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase (T("digidesign")))
  200583. return 1; // (the digi m-box driver crashes the app when you run
  200584. // it in the debugger, which can be a bit annoying)
  200585. #endif
  200586. return 0;
  200587. }
  200588. static int findFreeSlot()
  200589. {
  200590. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  200591. if (currentASIODev[i] == 0)
  200592. return i;
  200593. jassertfalse; // unfortunately you can only have a finite number
  200594. // of ASIO devices open at the same time..
  200595. return -1;
  200596. }
  200597. int getIndexOfDevice (AudioIODevice* d, const bool /*asInput*/) const
  200598. {
  200599. jassert (hasScanned); // need to call scanForDevices() before doing this
  200600. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  200601. }
  200602. bool hasSeparateInputsAndOutputs() const { return false; }
  200603. AudioIODevice* createDevice (const String& outputDeviceName,
  200604. const String& inputDeviceName)
  200605. {
  200606. jassert (inputDeviceName == outputDeviceName);
  200607. (void) inputDeviceName;
  200608. jassert (hasScanned); // need to call scanForDevices() before doing this
  200609. const int index = deviceNames.indexOf (outputDeviceName);
  200610. if (index >= 0)
  200611. {
  200612. const int freeSlot = findFreeSlot();
  200613. if (freeSlot >= 0)
  200614. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot);
  200615. }
  200616. return 0;
  200617. }
  200618. juce_UseDebuggingNewOperator
  200619. private:
  200620. StringArray deviceNames;
  200621. OwnedArray <CLSID> classIds;
  200622. bool hasScanned;
  200623. static bool checkClassIsOk (const String& classId)
  200624. {
  200625. HKEY hk = 0;
  200626. bool ok = false;
  200627. if (RegOpenKeyA (HKEY_CLASSES_ROOT, "clsid", &hk) == ERROR_SUCCESS)
  200628. {
  200629. int index = 0;
  200630. for (;;)
  200631. {
  200632. char buf [512];
  200633. if (RegEnumKeyA (hk, index++, buf, 512) == ERROR_SUCCESS)
  200634. {
  200635. if (classId.equalsIgnoreCase (buf))
  200636. {
  200637. HKEY subKey, pathKey;
  200638. if (RegOpenKeyExA (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  200639. {
  200640. if (RegOpenKeyExA (subKey, "InprocServer32", 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  200641. {
  200642. char pathName [600];
  200643. DWORD dtype = REG_SZ;
  200644. DWORD dsize = sizeof (pathName);
  200645. if (RegQueryValueExA (pathKey, 0, 0, &dtype,
  200646. (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  200647. {
  200648. OFSTRUCT of;
  200649. zerostruct (of);
  200650. of.cBytes = sizeof (of);
  200651. ok = (OpenFile (String (pathName), &of, OF_EXIST) != 0);
  200652. }
  200653. RegCloseKey (pathKey);
  200654. }
  200655. RegCloseKey (subKey);
  200656. }
  200657. break;
  200658. }
  200659. }
  200660. else
  200661. {
  200662. break;
  200663. }
  200664. }
  200665. RegCloseKey (hk);
  200666. }
  200667. return ok;
  200668. }
  200669. void addDriverInfo (const String& keyName, HKEY hk)
  200670. {
  200671. HKEY subKey;
  200672. if (RegOpenKeyExA (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  200673. {
  200674. char buf [256];
  200675. DWORD dtype = REG_SZ;
  200676. DWORD dsize = sizeof (buf);
  200677. zeromem (buf, dsize);
  200678. if (RegQueryValueExA (subKey, "clsid", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  200679. {
  200680. if (dsize > 0 && checkClassIsOk (buf))
  200681. {
  200682. wchar_t classIdStr [130];
  200683. MultiByteToWideChar (CP_ACP, 0, buf, -1, classIdStr, 128);
  200684. String deviceName;
  200685. CLSID classId;
  200686. if (CLSIDFromString ((LPOLESTR) classIdStr, &classId) == S_OK)
  200687. {
  200688. dtype = REG_SZ;
  200689. dsize = sizeof (buf);
  200690. if (RegQueryValueExA (subKey, "description", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  200691. deviceName = buf;
  200692. else
  200693. deviceName = keyName;
  200694. log (T("found ") + deviceName);
  200695. deviceNames.add (deviceName);
  200696. classIds.add (new CLSID (classId));
  200697. }
  200698. }
  200699. RegCloseKey (subKey);
  200700. }
  200701. }
  200702. }
  200703. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  200704. const ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  200705. };
  200706. AudioIODeviceType* juce_createASIOAudioIODeviceType()
  200707. {
  200708. return new ASIOAudioIODeviceType();
  200709. }
  200710. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  200711. void* guid)
  200712. {
  200713. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  200714. if (freeSlot < 0)
  200715. return 0;
  200716. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot);
  200717. }
  200718. END_JUCE_NAMESPACE
  200719. #undef log
  200720. #endif
  200721. /********* End of inlined file: juce_win32_ASIO.cpp *********/
  200722. /********* Start of inlined file: juce_win32_AudioCDReader.cpp *********/
  200723. #ifdef _MSC_VER
  200724. #pragma warning (disable: 4514)
  200725. #pragma warning (push)
  200726. #endif
  200727. #include <stddef.h>
  200728. #if JUCE_USE_CDBURNER
  200729. // you'll need the Platform SDK for these headers - if you don't have it and don't
  200730. // need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  200731. // flag in juce_Config.h to avoid these includes.
  200732. #include <imapi.h>
  200733. #include <imapierror.h>
  200734. #endif
  200735. BEGIN_JUCE_NAMESPACE
  200736. #ifdef _MSC_VER
  200737. #pragma warning (pop)
  200738. #endif
  200739. //***************************************************************************
  200740. // %%% TARGET STATUS VALUES %%%
  200741. //***************************************************************************
  200742. #define STATUS_GOOD 0x00 // Status Good
  200743. #define STATUS_CHKCOND 0x02 // Check Condition
  200744. #define STATUS_CONDMET 0x04 // Condition Met
  200745. #define STATUS_BUSY 0x08 // Busy
  200746. #define STATUS_INTERM 0x10 // Intermediate
  200747. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  200748. #define STATUS_RESCONF 0x18 // Reservation conflict
  200749. #define STATUS_COMTERM 0x22 // Command Terminated
  200750. #define STATUS_QFULL 0x28 // Queue full
  200751. //***************************************************************************
  200752. // %%% SCSI MISCELLANEOUS EQUATES %%%
  200753. //***************************************************************************
  200754. #define MAXLUN 7 // Maximum Logical Unit Id
  200755. #define MAXTARG 7 // Maximum Target Id
  200756. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  200757. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  200758. //***************************************************************************
  200759. // %%% Commands for all Device Types %%%
  200760. //***************************************************************************
  200761. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  200762. #define SCSI_COMPARE 0x39 // Compare (O)
  200763. #define SCSI_COPY 0x18 // Copy (O)
  200764. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  200765. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  200766. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  200767. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  200768. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  200769. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  200770. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  200771. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  200772. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  200773. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  200774. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  200775. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  200776. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  200777. //***************************************************************************
  200778. // %%% Commands Unique to Direct Access Devices %%%
  200779. //***************************************************************************
  200780. #define SCSI_COMPARE 0x39 // Compare (O)
  200781. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  200782. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  200783. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  200784. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  200785. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  200786. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  200787. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  200788. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  200789. #define SCSI_READ_LONG 0x3E // Read Long (O)
  200790. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  200791. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  200792. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  200793. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  200794. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  200795. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  200796. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  200797. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  200798. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  200799. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  200800. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  200801. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  200802. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  200803. #define SCSI_VERIFY 0x2F // Verify (O)
  200804. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  200805. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  200806. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  200807. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  200808. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  200809. //***************************************************************************
  200810. // %%% Commands Unique to Sequential Access Devices %%%
  200811. //***************************************************************************
  200812. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  200813. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  200814. #define SCSI_LOCATE 0x2B // Locate (O)
  200815. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  200816. #define SCSI_READ_POS 0x34 // Read Position (O)
  200817. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  200818. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  200819. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  200820. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  200821. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  200822. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  200823. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  200824. //***************************************************************************
  200825. // %%% Commands Unique to Printer Devices %%%
  200826. //***************************************************************************
  200827. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  200828. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  200829. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  200830. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  200831. //***************************************************************************
  200832. // %%% Commands Unique to Processor Devices %%%
  200833. //***************************************************************************
  200834. #define SCSI_RECEIVE 0x08 // Receive (O)
  200835. #define SCSI_SEND 0x0A // Send (O)
  200836. //***************************************************************************
  200837. // %%% Commands Unique to Write-Once Devices %%%
  200838. //***************************************************************************
  200839. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  200840. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  200841. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  200842. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  200843. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  200844. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  200845. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  200846. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  200847. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  200848. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  200849. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  200850. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  200851. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  200852. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  200853. //***************************************************************************
  200854. // %%% Commands Unique to CD-ROM Devices %%%
  200855. //***************************************************************************
  200856. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  200857. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  200858. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  200859. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  200860. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  200861. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  200862. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  200863. #define SCSI_READHEADER 0x44 // Read Header (O)
  200864. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  200865. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  200866. //***************************************************************************
  200867. // %%% Commands Unique to Scanner Devices %%%
  200868. //***************************************************************************
  200869. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  200870. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  200871. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  200872. #define SCSI_SCAN 0x1B // Scan (O)
  200873. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  200874. //***************************************************************************
  200875. // %%% Commands Unique to Optical Memory Devices %%%
  200876. //***************************************************************************
  200877. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  200878. //***************************************************************************
  200879. // %%% Commands Unique to Medium Changer Devices %%%
  200880. //***************************************************************************
  200881. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  200882. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  200883. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  200884. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  200885. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  200886. //***************************************************************************
  200887. // %%% Commands Unique to Communication Devices %%%
  200888. //***************************************************************************
  200889. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  200890. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  200891. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  200892. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  200893. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  200894. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  200895. //***************************************************************************
  200896. // %%% Request Sense Data Format %%%
  200897. //***************************************************************************
  200898. typedef struct {
  200899. BYTE ErrorCode; // Error Code (70H or 71H)
  200900. BYTE SegmentNum; // Number of current segment descriptor
  200901. BYTE SenseKey; // Sense Key(See bit definitions too)
  200902. BYTE InfoByte0; // Information MSB
  200903. BYTE InfoByte1; // Information MID
  200904. BYTE InfoByte2; // Information MID
  200905. BYTE InfoByte3; // Information LSB
  200906. BYTE AddSenLen; // Additional Sense Length
  200907. BYTE ComSpecInf0; // Command Specific Information MSB
  200908. BYTE ComSpecInf1; // Command Specific Information MID
  200909. BYTE ComSpecInf2; // Command Specific Information MID
  200910. BYTE ComSpecInf3; // Command Specific Information LSB
  200911. BYTE AddSenseCode; // Additional Sense Code
  200912. BYTE AddSenQual; // Additional Sense Code Qualifier
  200913. BYTE FieldRepUCode; // Field Replaceable Unit Code
  200914. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  200915. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  200916. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  200917. BYTE AddSenseBytes; // Additional Sense Bytes
  200918. } SENSE_DATA_FMT;
  200919. //***************************************************************************
  200920. // %%% REQUEST SENSE ERROR CODE %%%
  200921. //***************************************************************************
  200922. #define SERROR_CURRENT 0x70 // Current Errors
  200923. #define SERROR_DEFERED 0x71 // Deferred Errors
  200924. //***************************************************************************
  200925. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  200926. //***************************************************************************
  200927. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  200928. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  200929. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  200930. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  200931. //***************************************************************************
  200932. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  200933. //***************************************************************************
  200934. #define KEY_NOSENSE 0x00 // No Sense
  200935. #define KEY_RECERROR 0x01 // Recovered Error
  200936. #define KEY_NOTREADY 0x02 // Not Ready
  200937. #define KEY_MEDIUMERR 0x03 // Medium Error
  200938. #define KEY_HARDERROR 0x04 // Hardware Error
  200939. #define KEY_ILLGLREQ 0x05 // Illegal Request
  200940. #define KEY_UNITATT 0x06 // Unit Attention
  200941. #define KEY_DATAPROT 0x07 // Data Protect
  200942. #define KEY_BLANKCHK 0x08 // Blank Check
  200943. #define KEY_VENDSPEC 0x09 // Vendor Specific
  200944. #define KEY_COPYABORT 0x0A // Copy Abort
  200945. #define KEY_EQUAL 0x0C // Equal (Search)
  200946. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  200947. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  200948. #define KEY_RESERVED 0x0F // Reserved
  200949. //***************************************************************************
  200950. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  200951. //***************************************************************************
  200952. #define DTYPE_DASD 0x00 // Disk Device
  200953. #define DTYPE_SEQD 0x01 // Tape Device
  200954. #define DTYPE_PRNT 0x02 // Printer
  200955. #define DTYPE_PROC 0x03 // Processor
  200956. #define DTYPE_WORM 0x04 // Write-once read-multiple
  200957. #define DTYPE_CROM 0x05 // CD-ROM device
  200958. #define DTYPE_SCAN 0x06 // Scanner device
  200959. #define DTYPE_OPTI 0x07 // Optical memory device
  200960. #define DTYPE_JUKE 0x08 // Medium Changer device
  200961. #define DTYPE_COMM 0x09 // Communications device
  200962. #define DTYPE_RESL 0x0A // Reserved (low)
  200963. #define DTYPE_RESH 0x1E // Reserved (high)
  200964. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  200965. //***************************************************************************
  200966. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  200967. //***************************************************************************
  200968. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  200969. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  200970. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  200971. #define ANSI_RESLO 0x3 // Reserved (low)
  200972. #define ANSI_RESHI 0x7 // Reserved (high)
  200973. typedef struct
  200974. {
  200975. USHORT Length;
  200976. UCHAR ScsiStatus;
  200977. UCHAR PathId;
  200978. UCHAR TargetId;
  200979. UCHAR Lun;
  200980. UCHAR CdbLength;
  200981. UCHAR SenseInfoLength;
  200982. UCHAR DataIn;
  200983. ULONG DataTransferLength;
  200984. ULONG TimeOutValue;
  200985. ULONG DataBufferOffset;
  200986. ULONG SenseInfoOffset;
  200987. UCHAR Cdb[16];
  200988. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  200989. typedef struct
  200990. {
  200991. USHORT Length;
  200992. UCHAR ScsiStatus;
  200993. UCHAR PathId;
  200994. UCHAR TargetId;
  200995. UCHAR Lun;
  200996. UCHAR CdbLength;
  200997. UCHAR SenseInfoLength;
  200998. UCHAR DataIn;
  200999. ULONG DataTransferLength;
  201000. ULONG TimeOutValue;
  201001. PVOID DataBuffer;
  201002. ULONG SenseInfoOffset;
  201003. UCHAR Cdb[16];
  201004. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  201005. typedef struct
  201006. {
  201007. SCSI_PASS_THROUGH_DIRECT spt;
  201008. ULONG Filler;
  201009. UCHAR ucSenseBuf[32];
  201010. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  201011. typedef struct
  201012. {
  201013. ULONG Length;
  201014. UCHAR PortNumber;
  201015. UCHAR PathId;
  201016. UCHAR TargetId;
  201017. UCHAR Lun;
  201018. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  201019. #define METHOD_BUFFERED 0
  201020. #define METHOD_IN_DIRECT 1
  201021. #define METHOD_OUT_DIRECT 2
  201022. #define METHOD_NEITHER 3
  201023. #define FILE_ANY_ACCESS 0
  201024. #ifndef FILE_READ_ACCESS
  201025. #define FILE_READ_ACCESS (0x0001)
  201026. #endif
  201027. #ifndef FILE_WRITE_ACCESS
  201028. #define FILE_WRITE_ACCESS (0x0002)
  201029. #endif
  201030. #define IOCTL_SCSI_BASE 0x00000004
  201031. #define SCSI_IOCTL_DATA_OUT 0
  201032. #define SCSI_IOCTL_DATA_IN 1
  201033. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  201034. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  201035. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  201036. )
  201037. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  201038. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  201039. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  201040. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  201041. #define SENSE_LEN 14
  201042. #define SRB_DIR_SCSI 0x00
  201043. #define SRB_POSTING 0x01
  201044. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  201045. #define SRB_DIR_IN 0x08
  201046. #define SRB_DIR_OUT 0x10
  201047. #define SRB_EVENT_NOTIFY 0x40
  201048. #define RESIDUAL_COUNT_SUPPORTED 0x02
  201049. #define MAX_SRB_TIMEOUT 1080001u
  201050. #define DEFAULT_SRB_TIMEOUT 1080001u
  201051. #define SC_HA_INQUIRY 0x00
  201052. #define SC_GET_DEV_TYPE 0x01
  201053. #define SC_EXEC_SCSI_CMD 0x02
  201054. #define SC_ABORT_SRB 0x03
  201055. #define SC_RESET_DEV 0x04
  201056. #define SC_SET_HA_PARMS 0x05
  201057. #define SC_GET_DISK_INFO 0x06
  201058. #define SC_RESCAN_SCSI_BUS 0x07
  201059. #define SC_GETSET_TIMEOUTS 0x08
  201060. #define SS_PENDING 0x00
  201061. #define SS_COMP 0x01
  201062. #define SS_ABORTED 0x02
  201063. #define SS_ABORT_FAIL 0x03
  201064. #define SS_ERR 0x04
  201065. #define SS_INVALID_CMD 0x80
  201066. #define SS_INVALID_HA 0x81
  201067. #define SS_NO_DEVICE 0x82
  201068. #define SS_INVALID_SRB 0xE0
  201069. #define SS_OLD_MANAGER 0xE1
  201070. #define SS_BUFFER_ALIGN 0xE1
  201071. #define SS_ILLEGAL_MODE 0xE2
  201072. #define SS_NO_ASPI 0xE3
  201073. #define SS_FAILED_INIT 0xE4
  201074. #define SS_ASPI_IS_BUSY 0xE5
  201075. #define SS_BUFFER_TO_BIG 0xE6
  201076. #define SS_BUFFER_TOO_BIG 0xE6
  201077. #define SS_MISMATCHED_COMPONENTS 0xE7
  201078. #define SS_NO_ADAPTERS 0xE8
  201079. #define SS_INSUFFICIENT_RESOURCES 0xE9
  201080. #define SS_ASPI_IS_SHUTDOWN 0xEA
  201081. #define SS_BAD_INSTALL 0xEB
  201082. #define HASTAT_OK 0x00
  201083. #define HASTAT_SEL_TO 0x11
  201084. #define HASTAT_DO_DU 0x12
  201085. #define HASTAT_BUS_FREE 0x13
  201086. #define HASTAT_PHASE_ERR 0x14
  201087. #define HASTAT_TIMEOUT 0x09
  201088. #define HASTAT_COMMAND_TIMEOUT 0x0B
  201089. #define HASTAT_MESSAGE_REJECT 0x0D
  201090. #define HASTAT_BUS_RESET 0x0E
  201091. #define HASTAT_PARITY_ERROR 0x0F
  201092. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  201093. #define PACKED
  201094. #pragma pack(1)
  201095. typedef struct
  201096. {
  201097. BYTE SRB_Cmd;
  201098. BYTE SRB_Status;
  201099. BYTE SRB_HaID;
  201100. BYTE SRB_Flags;
  201101. DWORD SRB_Hdr_Rsvd;
  201102. BYTE HA_Count;
  201103. BYTE HA_SCSI_ID;
  201104. BYTE HA_ManagerId[16];
  201105. BYTE HA_Identifier[16];
  201106. BYTE HA_Unique[16];
  201107. WORD HA_Rsvd1;
  201108. BYTE pad[20];
  201109. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  201110. typedef struct
  201111. {
  201112. BYTE SRB_Cmd;
  201113. BYTE SRB_Status;
  201114. BYTE SRB_HaID;
  201115. BYTE SRB_Flags;
  201116. DWORD SRB_Hdr_Rsvd;
  201117. BYTE SRB_Target;
  201118. BYTE SRB_Lun;
  201119. BYTE SRB_DeviceType;
  201120. BYTE SRB_Rsvd1;
  201121. BYTE pad[68];
  201122. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  201123. typedef struct
  201124. {
  201125. BYTE SRB_Cmd;
  201126. BYTE SRB_Status;
  201127. BYTE SRB_HaID;
  201128. BYTE SRB_Flags;
  201129. DWORD SRB_Hdr_Rsvd;
  201130. BYTE SRB_Target;
  201131. BYTE SRB_Lun;
  201132. WORD SRB_Rsvd1;
  201133. DWORD SRB_BufLen;
  201134. BYTE FAR *SRB_BufPointer;
  201135. BYTE SRB_SenseLen;
  201136. BYTE SRB_CDBLen;
  201137. BYTE SRB_HaStat;
  201138. BYTE SRB_TargStat;
  201139. VOID FAR *SRB_PostProc;
  201140. BYTE SRB_Rsvd2[20];
  201141. BYTE CDBByte[16];
  201142. BYTE SenseArea[SENSE_LEN+2];
  201143. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  201144. typedef struct
  201145. {
  201146. BYTE SRB_Cmd;
  201147. BYTE SRB_Status;
  201148. BYTE SRB_HaId;
  201149. BYTE SRB_Flags;
  201150. DWORD SRB_Hdr_Rsvd;
  201151. } PACKED SRB, *PSRB, FAR *LPSRB;
  201152. #pragma pack()
  201153. struct CDDeviceInfo
  201154. {
  201155. char vendor[9];
  201156. char productId[17];
  201157. char rev[5];
  201158. char vendorSpec[21];
  201159. BYTE ha;
  201160. BYTE tgt;
  201161. BYTE lun;
  201162. char scsiDriveLetter; // will be 0 if not using scsi
  201163. };
  201164. class CDReadBuffer
  201165. {
  201166. public:
  201167. int startFrame;
  201168. int numFrames;
  201169. int dataStartOffset;
  201170. int dataLength;
  201171. BYTE* buffer;
  201172. int bufferSize;
  201173. int index;
  201174. bool wantsIndex;
  201175. CDReadBuffer (const int numberOfFrames)
  201176. : startFrame (0),
  201177. numFrames (0),
  201178. dataStartOffset (0),
  201179. dataLength (0),
  201180. index (0),
  201181. wantsIndex (false)
  201182. {
  201183. bufferSize = 2352 * numberOfFrames;
  201184. buffer = (BYTE*) malloc (bufferSize);
  201185. }
  201186. ~CDReadBuffer()
  201187. {
  201188. free (buffer);
  201189. }
  201190. bool isZero() const
  201191. {
  201192. BYTE* p = buffer + dataStartOffset;
  201193. for (int i = dataLength; --i >= 0;)
  201194. if (*p++ != 0)
  201195. return false;
  201196. return true;
  201197. }
  201198. };
  201199. class CDDeviceHandle;
  201200. class CDController
  201201. {
  201202. public:
  201203. CDController();
  201204. virtual ~CDController();
  201205. virtual bool read (CDReadBuffer* t) = 0;
  201206. virtual void shutDown();
  201207. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  201208. int getLastIndex();
  201209. public:
  201210. bool initialised;
  201211. CDDeviceHandle* deviceInfo;
  201212. int framesToCheck, framesOverlap;
  201213. void prepare (SRB_ExecSCSICmd& s);
  201214. void perform (SRB_ExecSCSICmd& s);
  201215. void setPaused (bool paused);
  201216. };
  201217. #pragma pack(1)
  201218. struct TOCTRACK
  201219. {
  201220. BYTE rsvd;
  201221. BYTE ADR;
  201222. BYTE trackNumber;
  201223. BYTE rsvd2;
  201224. BYTE addr[4];
  201225. };
  201226. struct TOC
  201227. {
  201228. WORD tocLen;
  201229. BYTE firstTrack;
  201230. BYTE lastTrack;
  201231. TOCTRACK tracks[100];
  201232. };
  201233. #pragma pack()
  201234. enum
  201235. {
  201236. READTYPE_ANY = 0,
  201237. READTYPE_ATAPI1 = 1,
  201238. READTYPE_ATAPI2 = 2,
  201239. READTYPE_READ6 = 3,
  201240. READTYPE_READ10 = 4,
  201241. READTYPE_READ_D8 = 5,
  201242. READTYPE_READ_D4 = 6,
  201243. READTYPE_READ_D4_1 = 7,
  201244. READTYPE_READ10_2 = 8
  201245. };
  201246. class CDDeviceHandle
  201247. {
  201248. public:
  201249. CDDeviceHandle (const CDDeviceInfo* const device)
  201250. : scsiHandle (0),
  201251. readType (READTYPE_ANY),
  201252. controller (0)
  201253. {
  201254. memcpy (&info, device, sizeof (info));
  201255. }
  201256. ~CDDeviceHandle()
  201257. {
  201258. if (controller != 0)
  201259. {
  201260. controller->shutDown();
  201261. delete controller;
  201262. }
  201263. if (scsiHandle != 0)
  201264. CloseHandle (scsiHandle);
  201265. }
  201266. bool readTOC (TOC* lpToc, bool useMSF);
  201267. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  201268. void openDrawer (bool shouldBeOpen);
  201269. CDDeviceInfo info;
  201270. HANDLE scsiHandle;
  201271. BYTE readType;
  201272. private:
  201273. CDController* controller;
  201274. bool testController (const int readType,
  201275. CDController* const newController,
  201276. CDReadBuffer* const bufferToUse);
  201277. };
  201278. DWORD (*fGetASPI32SupportInfo)(void);
  201279. DWORD (*fSendASPI32Command)(LPSRB);
  201280. static HINSTANCE winAspiLib = 0;
  201281. static bool usingScsi = false;
  201282. static bool initialised = false;
  201283. static bool InitialiseCDRipper()
  201284. {
  201285. if (! initialised)
  201286. {
  201287. initialised = true;
  201288. OSVERSIONINFO info;
  201289. info.dwOSVersionInfoSize = sizeof (info);
  201290. GetVersionEx (&info);
  201291. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  201292. if (! usingScsi)
  201293. {
  201294. fGetASPI32SupportInfo = 0;
  201295. fSendASPI32Command = 0;
  201296. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  201297. if (winAspiLib != 0)
  201298. {
  201299. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  201300. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  201301. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  201302. return false;
  201303. }
  201304. else
  201305. {
  201306. usingScsi = true;
  201307. }
  201308. }
  201309. }
  201310. return true;
  201311. }
  201312. static void DeinitialiseCDRipper()
  201313. {
  201314. if (winAspiLib != 0)
  201315. {
  201316. fGetASPI32SupportInfo = 0;
  201317. fSendASPI32Command = 0;
  201318. FreeLibrary (winAspiLib);
  201319. winAspiLib = 0;
  201320. }
  201321. initialised = false;
  201322. }
  201323. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  201324. {
  201325. TCHAR devicePath[8];
  201326. devicePath[0] = '\\';
  201327. devicePath[1] = '\\';
  201328. devicePath[2] = '.';
  201329. devicePath[3] = '\\';
  201330. devicePath[4] = driveLetter;
  201331. devicePath[5] = ':';
  201332. devicePath[6] = 0;
  201333. OSVERSIONINFO info;
  201334. info.dwOSVersionInfoSize = sizeof (info);
  201335. GetVersionEx (&info);
  201336. DWORD flags = GENERIC_READ;
  201337. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  201338. flags = GENERIC_READ | GENERIC_WRITE;
  201339. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  201340. if (h == INVALID_HANDLE_VALUE)
  201341. {
  201342. flags ^= GENERIC_WRITE;
  201343. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  201344. }
  201345. return h;
  201346. }
  201347. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  201348. const char driveLetter,
  201349. HANDLE& deviceHandle,
  201350. const bool retryOnFailure = true)
  201351. {
  201352. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  201353. zerostruct (s);
  201354. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  201355. s.spt.CdbLength = srb->SRB_CDBLen;
  201356. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  201357. ? SCSI_IOCTL_DATA_IN
  201358. : ((srb->SRB_Flags & SRB_DIR_OUT)
  201359. ? SCSI_IOCTL_DATA_OUT
  201360. : SCSI_IOCTL_DATA_UNSPECIFIED));
  201361. s.spt.DataTransferLength = srb->SRB_BufLen;
  201362. s.spt.TimeOutValue = 5;
  201363. s.spt.DataBuffer = srb->SRB_BufPointer;
  201364. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  201365. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  201366. srb->SRB_Status = SS_ERR;
  201367. srb->SRB_TargStat = 0x0004;
  201368. DWORD bytesReturned = 0;
  201369. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  201370. &s, sizeof (s),
  201371. &s, sizeof (s),
  201372. &bytesReturned, 0) != 0)
  201373. {
  201374. srb->SRB_Status = SS_COMP;
  201375. }
  201376. else if (retryOnFailure)
  201377. {
  201378. const DWORD error = GetLastError();
  201379. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  201380. {
  201381. if (error != ERROR_INVALID_HANDLE)
  201382. CloseHandle (deviceHandle);
  201383. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  201384. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  201385. }
  201386. }
  201387. return srb->SRB_Status;
  201388. }
  201389. // Controller types..
  201390. class ControllerType1 : public CDController
  201391. {
  201392. public:
  201393. ControllerType1() {}
  201394. ~ControllerType1() {}
  201395. bool read (CDReadBuffer* rb)
  201396. {
  201397. if (rb->numFrames * 2352 > rb->bufferSize)
  201398. return false;
  201399. SRB_ExecSCSICmd s;
  201400. prepare (s);
  201401. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201402. s.SRB_BufLen = rb->bufferSize;
  201403. s.SRB_BufPointer = rb->buffer;
  201404. s.SRB_CDBLen = 12;
  201405. s.CDBByte[0] = 0xBE;
  201406. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  201407. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  201408. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  201409. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  201410. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  201411. perform (s);
  201412. if (s.SRB_Status != SS_COMP)
  201413. return false;
  201414. rb->dataLength = rb->numFrames * 2352;
  201415. rb->dataStartOffset = 0;
  201416. return true;
  201417. }
  201418. };
  201419. class ControllerType2 : public CDController
  201420. {
  201421. public:
  201422. ControllerType2() {}
  201423. ~ControllerType2() {}
  201424. void shutDown()
  201425. {
  201426. if (initialised)
  201427. {
  201428. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  201429. SRB_ExecSCSICmd s;
  201430. prepare (s);
  201431. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  201432. s.SRB_BufLen = 0x0C;
  201433. s.SRB_BufPointer = bufPointer;
  201434. s.SRB_CDBLen = 6;
  201435. s.CDBByte[0] = 0x15;
  201436. s.CDBByte[4] = 0x0C;
  201437. perform (s);
  201438. }
  201439. }
  201440. bool init()
  201441. {
  201442. SRB_ExecSCSICmd s;
  201443. s.SRB_Status = SS_ERR;
  201444. if (deviceInfo->readType == READTYPE_READ10_2)
  201445. {
  201446. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  201447. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  201448. for (int i = 0; i < 2; ++i)
  201449. {
  201450. prepare (s);
  201451. s.SRB_Flags = SRB_EVENT_NOTIFY;
  201452. s.SRB_BufLen = 0x14;
  201453. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  201454. s.SRB_CDBLen = 6;
  201455. s.CDBByte[0] = 0x15;
  201456. s.CDBByte[1] = 0x10;
  201457. s.CDBByte[4] = 0x14;
  201458. perform (s);
  201459. if (s.SRB_Status != SS_COMP)
  201460. return false;
  201461. }
  201462. }
  201463. else
  201464. {
  201465. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  201466. prepare (s);
  201467. s.SRB_Flags = SRB_EVENT_NOTIFY;
  201468. s.SRB_BufLen = 0x0C;
  201469. s.SRB_BufPointer = bufPointer;
  201470. s.SRB_CDBLen = 6;
  201471. s.CDBByte[0] = 0x15;
  201472. s.CDBByte[4] = 0x0C;
  201473. perform (s);
  201474. }
  201475. return s.SRB_Status == SS_COMP;
  201476. }
  201477. bool read (CDReadBuffer* rb)
  201478. {
  201479. if (rb->numFrames * 2352 > rb->bufferSize)
  201480. return false;
  201481. if (!initialised)
  201482. {
  201483. initialised = init();
  201484. if (!initialised)
  201485. return false;
  201486. }
  201487. SRB_ExecSCSICmd s;
  201488. prepare (s);
  201489. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201490. s.SRB_BufLen = rb->bufferSize;
  201491. s.SRB_BufPointer = rb->buffer;
  201492. s.SRB_CDBLen = 10;
  201493. s.CDBByte[0] = 0x28;
  201494. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  201495. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  201496. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  201497. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  201498. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  201499. perform (s);
  201500. if (s.SRB_Status != SS_COMP)
  201501. return false;
  201502. rb->dataLength = rb->numFrames * 2352;
  201503. rb->dataStartOffset = 0;
  201504. return true;
  201505. }
  201506. };
  201507. class ControllerType3 : public CDController
  201508. {
  201509. public:
  201510. ControllerType3() {}
  201511. ~ControllerType3() {}
  201512. bool read (CDReadBuffer* rb)
  201513. {
  201514. if (rb->numFrames * 2352 > rb->bufferSize)
  201515. return false;
  201516. if (!initialised)
  201517. {
  201518. setPaused (false);
  201519. initialised = true;
  201520. }
  201521. SRB_ExecSCSICmd s;
  201522. prepare (s);
  201523. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201524. s.SRB_BufLen = rb->numFrames * 2352;
  201525. s.SRB_BufPointer = rb->buffer;
  201526. s.SRB_CDBLen = 12;
  201527. s.CDBByte[0] = 0xD8;
  201528. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  201529. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  201530. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  201531. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  201532. perform (s);
  201533. if (s.SRB_Status != SS_COMP)
  201534. return false;
  201535. rb->dataLength = rb->numFrames * 2352;
  201536. rb->dataStartOffset = 0;
  201537. return true;
  201538. }
  201539. };
  201540. class ControllerType4 : public CDController
  201541. {
  201542. public:
  201543. ControllerType4() {}
  201544. ~ControllerType4() {}
  201545. bool selectD4Mode()
  201546. {
  201547. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  201548. SRB_ExecSCSICmd s;
  201549. prepare (s);
  201550. s.SRB_Flags = SRB_EVENT_NOTIFY;
  201551. s.SRB_CDBLen = 6;
  201552. s.SRB_BufLen = 12;
  201553. s.SRB_BufPointer = bufPointer;
  201554. s.CDBByte[0] = 0x15;
  201555. s.CDBByte[1] = 0x10;
  201556. s.CDBByte[4] = 0x08;
  201557. perform (s);
  201558. return s.SRB_Status == SS_COMP;
  201559. }
  201560. bool read (CDReadBuffer* rb)
  201561. {
  201562. if (rb->numFrames * 2352 > rb->bufferSize)
  201563. return false;
  201564. if (!initialised)
  201565. {
  201566. setPaused (true);
  201567. if (deviceInfo->readType == READTYPE_READ_D4_1)
  201568. selectD4Mode();
  201569. initialised = true;
  201570. }
  201571. SRB_ExecSCSICmd s;
  201572. prepare (s);
  201573. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201574. s.SRB_BufLen = rb->bufferSize;
  201575. s.SRB_BufPointer = rb->buffer;
  201576. s.SRB_CDBLen = 10;
  201577. s.CDBByte[0] = 0xD4;
  201578. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  201579. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  201580. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  201581. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  201582. perform (s);
  201583. if (s.SRB_Status != SS_COMP)
  201584. return false;
  201585. rb->dataLength = rb->numFrames * 2352;
  201586. rb->dataStartOffset = 0;
  201587. return true;
  201588. }
  201589. };
  201590. CDController::CDController() : initialised (false)
  201591. {
  201592. }
  201593. CDController::~CDController()
  201594. {
  201595. }
  201596. void CDController::prepare (SRB_ExecSCSICmd& s)
  201597. {
  201598. zerostruct (s);
  201599. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  201600. s.SRB_HaID = deviceInfo->info.ha;
  201601. s.SRB_Target = deviceInfo->info.tgt;
  201602. s.SRB_Lun = deviceInfo->info.lun;
  201603. s.SRB_SenseLen = SENSE_LEN;
  201604. }
  201605. void CDController::perform (SRB_ExecSCSICmd& s)
  201606. {
  201607. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  201608. s.SRB_PostProc = (void*)event;
  201609. ResetEvent (event);
  201610. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  201611. deviceInfo->info.scsiDriveLetter,
  201612. deviceInfo->scsiHandle)
  201613. : fSendASPI32Command ((LPSRB)&s);
  201614. if (status == SS_PENDING)
  201615. WaitForSingleObject (event, 4000);
  201616. CloseHandle (event);
  201617. }
  201618. void CDController::setPaused (bool paused)
  201619. {
  201620. SRB_ExecSCSICmd s;
  201621. prepare (s);
  201622. s.SRB_Flags = SRB_EVENT_NOTIFY;
  201623. s.SRB_CDBLen = 10;
  201624. s.CDBByte[0] = 0x4B;
  201625. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  201626. perform (s);
  201627. }
  201628. void CDController::shutDown()
  201629. {
  201630. }
  201631. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  201632. {
  201633. if (overlapBuffer != 0)
  201634. {
  201635. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  201636. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  201637. if (doJitter
  201638. && overlapBuffer->startFrame > 0
  201639. && overlapBuffer->numFrames > 0
  201640. && overlapBuffer->dataLength > 0)
  201641. {
  201642. const int numFrames = rb->numFrames;
  201643. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  201644. {
  201645. rb->startFrame -= framesOverlap;
  201646. if (framesToCheck < framesOverlap
  201647. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  201648. rb->numFrames += framesOverlap;
  201649. }
  201650. else
  201651. {
  201652. overlapBuffer->dataLength = 0;
  201653. overlapBuffer->startFrame = 0;
  201654. overlapBuffer->numFrames = 0;
  201655. }
  201656. }
  201657. if (! read (rb))
  201658. return false;
  201659. if (doJitter)
  201660. {
  201661. const int checkLen = framesToCheck * 2352;
  201662. const int maxToCheck = rb->dataLength - checkLen;
  201663. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  201664. return true;
  201665. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  201666. bool found = false;
  201667. for (int i = 0; i < maxToCheck; ++i)
  201668. {
  201669. if (!memcmp (p, rb->buffer + i, checkLen))
  201670. {
  201671. i += checkLen;
  201672. rb->dataStartOffset = i;
  201673. rb->dataLength -= i;
  201674. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  201675. found = true;
  201676. break;
  201677. }
  201678. }
  201679. rb->numFrames = rb->dataLength / 2352;
  201680. rb->dataLength = 2352 * rb->numFrames;
  201681. if (!found)
  201682. return false;
  201683. }
  201684. if (canDoJitter)
  201685. {
  201686. memcpy (overlapBuffer->buffer,
  201687. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  201688. 2352 * framesToCheck);
  201689. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  201690. overlapBuffer->numFrames = framesToCheck;
  201691. overlapBuffer->dataLength = 2352 * framesToCheck;
  201692. overlapBuffer->dataStartOffset = 0;
  201693. }
  201694. else
  201695. {
  201696. overlapBuffer->startFrame = 0;
  201697. overlapBuffer->numFrames = 0;
  201698. overlapBuffer->dataLength = 0;
  201699. }
  201700. return true;
  201701. }
  201702. else
  201703. {
  201704. return read (rb);
  201705. }
  201706. }
  201707. int CDController::getLastIndex()
  201708. {
  201709. char qdata[100];
  201710. SRB_ExecSCSICmd s;
  201711. prepare (s);
  201712. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201713. s.SRB_BufLen = sizeof (qdata);
  201714. s.SRB_BufPointer = (BYTE*)qdata;
  201715. s.SRB_CDBLen = 12;
  201716. s.CDBByte[0] = 0x42;
  201717. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  201718. s.CDBByte[2] = 64;
  201719. s.CDBByte[3] = 1; // get current position
  201720. s.CDBByte[7] = 0;
  201721. s.CDBByte[8] = (BYTE)sizeof (qdata);
  201722. perform (s);
  201723. if (s.SRB_Status == SS_COMP)
  201724. return qdata[7];
  201725. return 0;
  201726. }
  201727. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  201728. {
  201729. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  201730. SRB_ExecSCSICmd s;
  201731. zerostruct (s);
  201732. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  201733. s.SRB_HaID = info.ha;
  201734. s.SRB_Target = info.tgt;
  201735. s.SRB_Lun = info.lun;
  201736. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201737. s.SRB_BufLen = 0x324;
  201738. s.SRB_BufPointer = (BYTE*)lpToc;
  201739. s.SRB_SenseLen = 0x0E;
  201740. s.SRB_CDBLen = 0x0A;
  201741. s.SRB_PostProc = (void*)event;
  201742. s.CDBByte[0] = 0x43;
  201743. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  201744. s.CDBByte[7] = 0x03;
  201745. s.CDBByte[8] = 0x24;
  201746. ResetEvent (event);
  201747. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  201748. : fSendASPI32Command ((LPSRB)&s);
  201749. if (status == SS_PENDING)
  201750. WaitForSingleObject (event, 4000);
  201751. CloseHandle (event);
  201752. return (s.SRB_Status == SS_COMP);
  201753. }
  201754. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  201755. CDReadBuffer* const overlapBuffer)
  201756. {
  201757. if (controller == 0)
  201758. {
  201759. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  201760. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  201761. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  201762. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  201763. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  201764. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  201765. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  201766. }
  201767. buffer->index = 0;
  201768. if ((controller != 0)
  201769. && controller->readAudio (buffer, overlapBuffer))
  201770. {
  201771. if (buffer->wantsIndex)
  201772. buffer->index = controller->getLastIndex();
  201773. return true;
  201774. }
  201775. return false;
  201776. }
  201777. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  201778. {
  201779. if (shouldBeOpen)
  201780. {
  201781. if (controller != 0)
  201782. {
  201783. controller->shutDown();
  201784. delete controller;
  201785. controller = 0;
  201786. }
  201787. if (scsiHandle != 0)
  201788. {
  201789. CloseHandle (scsiHandle);
  201790. scsiHandle = 0;
  201791. }
  201792. }
  201793. SRB_ExecSCSICmd s;
  201794. zerostruct (s);
  201795. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  201796. s.SRB_HaID = info.ha;
  201797. s.SRB_Target = info.tgt;
  201798. s.SRB_Lun = info.lun;
  201799. s.SRB_SenseLen = SENSE_LEN;
  201800. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201801. s.SRB_BufLen = 0;
  201802. s.SRB_BufPointer = 0;
  201803. s.SRB_CDBLen = 12;
  201804. s.CDBByte[0] = 0x1b;
  201805. s.CDBByte[1] = (BYTE)(info.lun << 5);
  201806. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  201807. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  201808. s.SRB_PostProc = (void*)event;
  201809. ResetEvent (event);
  201810. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  201811. : fSendASPI32Command ((LPSRB)&s);
  201812. if (status == SS_PENDING)
  201813. WaitForSingleObject (event, 4000);
  201814. CloseHandle (event);
  201815. }
  201816. bool CDDeviceHandle::testController (const int type,
  201817. CDController* const newController,
  201818. CDReadBuffer* const rb)
  201819. {
  201820. controller = newController;
  201821. readType = (BYTE)type;
  201822. controller->deviceInfo = this;
  201823. controller->framesToCheck = 1;
  201824. controller->framesOverlap = 3;
  201825. bool passed = false;
  201826. memset (rb->buffer, 0xcd, rb->bufferSize);
  201827. if (controller->read (rb))
  201828. {
  201829. passed = true;
  201830. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  201831. int wrong = 0;
  201832. for (int i = rb->dataLength / 4; --i >= 0;)
  201833. {
  201834. if (*p++ == (int) 0xcdcdcdcd)
  201835. {
  201836. if (++wrong == 4)
  201837. {
  201838. passed = false;
  201839. break;
  201840. }
  201841. }
  201842. else
  201843. {
  201844. wrong = 0;
  201845. }
  201846. }
  201847. }
  201848. if (! passed)
  201849. {
  201850. controller->shutDown();
  201851. delete controller;
  201852. controller = 0;
  201853. }
  201854. return passed;
  201855. }
  201856. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  201857. {
  201858. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  201859. const int bufSize = 128;
  201860. BYTE buffer[bufSize];
  201861. zeromem (buffer, bufSize);
  201862. SRB_ExecSCSICmd s;
  201863. zerostruct (s);
  201864. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  201865. s.SRB_HaID = ha;
  201866. s.SRB_Target = tgt;
  201867. s.SRB_Lun = lun;
  201868. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201869. s.SRB_BufLen = bufSize;
  201870. s.SRB_BufPointer = buffer;
  201871. s.SRB_SenseLen = SENSE_LEN;
  201872. s.SRB_CDBLen = 6;
  201873. s.SRB_PostProc = (void*)event;
  201874. s.CDBByte[0] = SCSI_INQUIRY;
  201875. s.CDBByte[4] = 100;
  201876. ResetEvent (event);
  201877. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  201878. WaitForSingleObject (event, 4000);
  201879. CloseHandle (event);
  201880. if (s.SRB_Status == SS_COMP)
  201881. {
  201882. memcpy (dev->vendor, &buffer[8], 8);
  201883. memcpy (dev->productId, &buffer[16], 16);
  201884. memcpy (dev->rev, &buffer[32], 4);
  201885. memcpy (dev->vendorSpec, &buffer[36], 20);
  201886. }
  201887. }
  201888. static int FindCDDevices (CDDeviceInfo* const list,
  201889. int maxItems)
  201890. {
  201891. int count = 0;
  201892. if (usingScsi)
  201893. {
  201894. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  201895. {
  201896. TCHAR drivePath[8];
  201897. drivePath[0] = driveLetter;
  201898. drivePath[1] = ':';
  201899. drivePath[2] = '\\';
  201900. drivePath[3] = 0;
  201901. if (GetDriveType (drivePath) == DRIVE_CDROM)
  201902. {
  201903. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  201904. if (h != INVALID_HANDLE_VALUE)
  201905. {
  201906. BYTE buffer[100], passThroughStruct[1024];
  201907. zeromem (buffer, sizeof (buffer));
  201908. zeromem (passThroughStruct, sizeof (passThroughStruct));
  201909. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  201910. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  201911. p->spt.CdbLength = 6;
  201912. p->spt.SenseInfoLength = 24;
  201913. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  201914. p->spt.DataTransferLength = 100;
  201915. p->spt.TimeOutValue = 2;
  201916. p->spt.DataBuffer = buffer;
  201917. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  201918. p->spt.Cdb[0] = 0x12;
  201919. p->spt.Cdb[4] = 100;
  201920. DWORD bytesReturned = 0;
  201921. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  201922. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  201923. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  201924. &bytesReturned, 0) != 0)
  201925. {
  201926. zeromem (&list[count], sizeof (CDDeviceInfo));
  201927. list[count].scsiDriveLetter = driveLetter;
  201928. memcpy (list[count].vendor, &buffer[8], 8);
  201929. memcpy (list[count].productId, &buffer[16], 16);
  201930. memcpy (list[count].rev, &buffer[32], 4);
  201931. memcpy (list[count].vendorSpec, &buffer[36], 20);
  201932. zeromem (passThroughStruct, sizeof (passThroughStruct));
  201933. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  201934. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  201935. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  201936. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  201937. &bytesReturned, 0) != 0)
  201938. {
  201939. list[count].ha = scsiAddr->PortNumber;
  201940. list[count].tgt = scsiAddr->TargetId;
  201941. list[count].lun = scsiAddr->Lun;
  201942. ++count;
  201943. }
  201944. }
  201945. CloseHandle (h);
  201946. }
  201947. }
  201948. }
  201949. }
  201950. else
  201951. {
  201952. const DWORD d = fGetASPI32SupportInfo();
  201953. BYTE status = HIBYTE (LOWORD (d));
  201954. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  201955. return 0;
  201956. const int numAdapters = LOBYTE (LOWORD (d));
  201957. for (BYTE ha = 0; ha < numAdapters; ++ha)
  201958. {
  201959. SRB_HAInquiry s;
  201960. zerostruct (s);
  201961. s.SRB_Cmd = SC_HA_INQUIRY;
  201962. s.SRB_HaID = ha;
  201963. fSendASPI32Command ((LPSRB)&s);
  201964. if (s.SRB_Status == SS_COMP)
  201965. {
  201966. maxItems = (int)s.HA_Unique[3];
  201967. if (maxItems == 0)
  201968. maxItems = 8;
  201969. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  201970. {
  201971. for (BYTE lun = 0; lun < 8; ++lun)
  201972. {
  201973. SRB_GDEVBlock sb;
  201974. zerostruct (sb);
  201975. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  201976. sb.SRB_HaID = ha;
  201977. sb.SRB_Target = tgt;
  201978. sb.SRB_Lun = lun;
  201979. fSendASPI32Command ((LPSRB) &sb);
  201980. if (sb.SRB_Status == SS_COMP
  201981. && sb.SRB_DeviceType == DTYPE_CROM)
  201982. {
  201983. zeromem (&list[count], sizeof (CDDeviceInfo));
  201984. list[count].ha = ha;
  201985. list[count].tgt = tgt;
  201986. list[count].lun = lun;
  201987. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  201988. ++count;
  201989. }
  201990. }
  201991. }
  201992. }
  201993. }
  201994. }
  201995. return count;
  201996. }
  201997. static int ripperUsers = 0;
  201998. static bool initialisedOk = false;
  201999. class DeinitialiseTimer : private Timer,
  202000. private DeletedAtShutdown
  202001. {
  202002. DeinitialiseTimer (const DeinitialiseTimer&);
  202003. const DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  202004. public:
  202005. DeinitialiseTimer()
  202006. {
  202007. startTimer (4000);
  202008. }
  202009. ~DeinitialiseTimer()
  202010. {
  202011. if (--ripperUsers == 0)
  202012. DeinitialiseCDRipper();
  202013. }
  202014. void timerCallback()
  202015. {
  202016. delete this;
  202017. }
  202018. juce_UseDebuggingNewOperator
  202019. };
  202020. static void incUserCount()
  202021. {
  202022. if (ripperUsers++ == 0)
  202023. initialisedOk = InitialiseCDRipper();
  202024. }
  202025. static void decUserCount()
  202026. {
  202027. new DeinitialiseTimer();
  202028. }
  202029. struct CDDeviceWrapper
  202030. {
  202031. CDDeviceHandle* cdH;
  202032. CDReadBuffer* overlapBuffer;
  202033. bool jitter;
  202034. };
  202035. static int getAddressOf (const TOCTRACK* const t)
  202036. {
  202037. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  202038. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  202039. }
  202040. static int getMSFAddressOf (const TOCTRACK* const t)
  202041. {
  202042. return 60 * t->addr[1] + t->addr[2];
  202043. }
  202044. static const int samplesPerFrame = 44100 / 75;
  202045. static const int bytesPerFrame = samplesPerFrame * 4;
  202046. const StringArray AudioCDReader::getAvailableCDNames()
  202047. {
  202048. StringArray results;
  202049. incUserCount();
  202050. if (initialisedOk)
  202051. {
  202052. CDDeviceInfo list[8];
  202053. const int num = FindCDDevices (list, 8);
  202054. decUserCount();
  202055. for (int i = 0; i < num; ++i)
  202056. {
  202057. String s;
  202058. if (list[i].scsiDriveLetter > 0)
  202059. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << T(": ");
  202060. s << String (list[i].vendor).trim()
  202061. << T(" ") << String (list[i].productId).trim()
  202062. << T(" ") << String (list[i].rev).trim();
  202063. results.add (s);
  202064. }
  202065. }
  202066. return results;
  202067. }
  202068. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  202069. {
  202070. SRB_GDEVBlock s;
  202071. zerostruct (s);
  202072. s.SRB_Cmd = SC_GET_DEV_TYPE;
  202073. s.SRB_HaID = device->ha;
  202074. s.SRB_Target = device->tgt;
  202075. s.SRB_Lun = device->lun;
  202076. if (usingScsi)
  202077. {
  202078. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  202079. if (h != INVALID_HANDLE_VALUE)
  202080. {
  202081. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  202082. cdh->scsiHandle = h;
  202083. return cdh;
  202084. }
  202085. }
  202086. else
  202087. {
  202088. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  202089. && s.SRB_DeviceType == DTYPE_CROM)
  202090. {
  202091. return new CDDeviceHandle (device);
  202092. }
  202093. }
  202094. return 0;
  202095. }
  202096. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  202097. {
  202098. incUserCount();
  202099. if (initialisedOk)
  202100. {
  202101. CDDeviceInfo list[8];
  202102. const int num = FindCDDevices (list, 8);
  202103. if (((unsigned int) deviceIndex) < (unsigned int) num)
  202104. {
  202105. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  202106. if (handle != 0)
  202107. {
  202108. CDDeviceWrapper* const d = new CDDeviceWrapper();
  202109. d->cdH = handle;
  202110. d->overlapBuffer = new CDReadBuffer(3);
  202111. return new AudioCDReader (d);
  202112. }
  202113. }
  202114. }
  202115. decUserCount();
  202116. return 0;
  202117. }
  202118. AudioCDReader::AudioCDReader (void* handle_)
  202119. : AudioFormatReader (0, T("CD Audio")),
  202120. handle (handle_),
  202121. indexingEnabled (false),
  202122. lastIndex (0),
  202123. firstFrameInBuffer (0),
  202124. samplesInBuffer (0)
  202125. {
  202126. jassert (handle_ != 0);
  202127. refreshTrackLengths();
  202128. sampleRate = 44100.0;
  202129. bitsPerSample = 16;
  202130. lengthInSamples = getPositionOfTrackStart (numTracks);
  202131. numChannels = 2;
  202132. usesFloatingPointData = false;
  202133. buffer.setSize (4 * bytesPerFrame, true);
  202134. }
  202135. AudioCDReader::~AudioCDReader()
  202136. {
  202137. CDDeviceWrapper* const device = (CDDeviceWrapper*)handle;
  202138. delete device->cdH;
  202139. delete device->overlapBuffer;
  202140. delete device;
  202141. decUserCount();
  202142. }
  202143. bool AudioCDReader::read (int** destSamples,
  202144. int64 startSampleInFile,
  202145. int numSamples)
  202146. {
  202147. CDDeviceWrapper* const device = (CDDeviceWrapper*)handle;
  202148. bool ok = true;
  202149. int offset = 0;
  202150. if (startSampleInFile < 0)
  202151. {
  202152. int* l = destSamples[0];
  202153. int* r = destSamples[1];
  202154. numSamples += (int) startSampleInFile;
  202155. offset -= (int) startSampleInFile;
  202156. while (++startSampleInFile <= 0)
  202157. {
  202158. *l++ = 0;
  202159. if (r != 0)
  202160. *r++ = 0;
  202161. }
  202162. }
  202163. while (numSamples > 0)
  202164. {
  202165. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  202166. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  202167. if (startSampleInFile >= bufferStartSample
  202168. && startSampleInFile < bufferEndSample)
  202169. {
  202170. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  202171. int* const l = destSamples[0] + offset;
  202172. int* const r = destSamples[1] + offset;
  202173. const short* src = (const short*) buffer.getData();
  202174. src += 2 * (startSampleInFile - bufferStartSample);
  202175. for (int i = 0; i < toDo; ++i)
  202176. {
  202177. l[i] = src [i << 1] << 16;
  202178. if (r != 0)
  202179. r[i] = src [(i << 1) + 1] << 16;
  202180. }
  202181. offset += toDo;
  202182. startSampleInFile += toDo;
  202183. numSamples -= toDo;
  202184. }
  202185. else
  202186. {
  202187. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  202188. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  202189. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  202190. {
  202191. device->overlapBuffer->dataLength = 0;
  202192. device->overlapBuffer->startFrame = 0;
  202193. device->overlapBuffer->numFrames = 0;
  202194. device->jitter = false;
  202195. }
  202196. firstFrameInBuffer = frameNeeded;
  202197. lastIndex = 0;
  202198. CDReadBuffer readBuffer (framesInBuffer + 4);
  202199. readBuffer.wantsIndex = indexingEnabled;
  202200. int i;
  202201. for (i = 5; --i >= 0;)
  202202. {
  202203. readBuffer.startFrame = frameNeeded;
  202204. readBuffer.numFrames = framesInBuffer;
  202205. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  202206. break;
  202207. else
  202208. device->overlapBuffer->dataLength = 0;
  202209. }
  202210. if (i >= 0)
  202211. {
  202212. memcpy ((char*) buffer.getData(),
  202213. readBuffer.buffer + readBuffer.dataStartOffset,
  202214. readBuffer.dataLength);
  202215. samplesInBuffer = readBuffer.dataLength >> 2;
  202216. lastIndex = readBuffer.index;
  202217. }
  202218. else
  202219. {
  202220. int* l = destSamples[0] + offset;
  202221. int* r = destSamples[1] + offset;
  202222. while (--numSamples >= 0)
  202223. {
  202224. *l++ = 0;
  202225. if (r != 0)
  202226. *r++ = 0;
  202227. }
  202228. // sometimes the read fails for just the very last couple of blocks, so
  202229. // we'll ignore and errors in the last half-second of the disk..
  202230. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  202231. break;
  202232. }
  202233. }
  202234. }
  202235. return ok;
  202236. }
  202237. bool AudioCDReader::isCDStillPresent() const
  202238. {
  202239. TOC toc;
  202240. zerostruct (toc);
  202241. return ((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false);
  202242. }
  202243. int AudioCDReader::getNumTracks() const
  202244. {
  202245. return numTracks;
  202246. }
  202247. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  202248. {
  202249. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  202250. : 0;
  202251. }
  202252. void AudioCDReader::refreshTrackLengths()
  202253. {
  202254. zeromem (trackStarts, sizeof (trackStarts));
  202255. zeromem (audioTracks, sizeof (audioTracks));
  202256. TOC toc;
  202257. zerostruct (toc);
  202258. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  202259. {
  202260. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  202261. for (int i = 0; i <= numTracks; ++i)
  202262. {
  202263. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  202264. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  202265. }
  202266. }
  202267. else
  202268. {
  202269. numTracks = 0;
  202270. }
  202271. }
  202272. bool AudioCDReader::isTrackAudio (int trackNum) const
  202273. {
  202274. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  202275. : false;
  202276. }
  202277. void AudioCDReader::enableIndexScanning (bool b)
  202278. {
  202279. indexingEnabled = b;
  202280. }
  202281. int AudioCDReader::getLastIndex() const
  202282. {
  202283. return lastIndex;
  202284. }
  202285. const int framesPerIndexRead = 4;
  202286. int AudioCDReader::getIndexAt (int samplePos)
  202287. {
  202288. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  202289. const int frameNeeded = samplePos / samplesPerFrame;
  202290. device->overlapBuffer->dataLength = 0;
  202291. device->overlapBuffer->startFrame = 0;
  202292. device->overlapBuffer->numFrames = 0;
  202293. device->jitter = false;
  202294. firstFrameInBuffer = 0;
  202295. lastIndex = 0;
  202296. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  202297. readBuffer.wantsIndex = true;
  202298. int i;
  202299. for (i = 5; --i >= 0;)
  202300. {
  202301. readBuffer.startFrame = frameNeeded;
  202302. readBuffer.numFrames = framesPerIndexRead;
  202303. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  202304. break;
  202305. }
  202306. if (i >= 0)
  202307. return readBuffer.index;
  202308. return -1;
  202309. }
  202310. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  202311. {
  202312. Array <int> indexes;
  202313. const int trackStart = getPositionOfTrackStart (trackNumber);
  202314. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  202315. bool needToScan = true;
  202316. if (trackEnd - trackStart > 20 * 44100)
  202317. {
  202318. // check the end of the track for indexes before scanning the whole thing
  202319. needToScan = false;
  202320. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  202321. bool seenAnIndex = false;
  202322. while (pos <= trackEnd - samplesPerFrame)
  202323. {
  202324. const int index = getIndexAt (pos);
  202325. if (index == 0)
  202326. {
  202327. // lead-out, so skip back a bit if we've not found any indexes yet..
  202328. if (seenAnIndex)
  202329. break;
  202330. pos -= 44100 * 5;
  202331. if (pos < trackStart)
  202332. break;
  202333. }
  202334. else
  202335. {
  202336. if (index > 0)
  202337. seenAnIndex = true;
  202338. if (index > 1)
  202339. {
  202340. needToScan = true;
  202341. break;
  202342. }
  202343. pos += samplesPerFrame * framesPerIndexRead;
  202344. }
  202345. }
  202346. }
  202347. if (needToScan)
  202348. {
  202349. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  202350. int pos = trackStart;
  202351. int last = -1;
  202352. while (pos < trackEnd - samplesPerFrame * 10)
  202353. {
  202354. const int frameNeeded = pos / samplesPerFrame;
  202355. device->overlapBuffer->dataLength = 0;
  202356. device->overlapBuffer->startFrame = 0;
  202357. device->overlapBuffer->numFrames = 0;
  202358. device->jitter = false;
  202359. firstFrameInBuffer = 0;
  202360. CDReadBuffer readBuffer (4);
  202361. readBuffer.wantsIndex = true;
  202362. int i;
  202363. for (i = 5; --i >= 0;)
  202364. {
  202365. readBuffer.startFrame = frameNeeded;
  202366. readBuffer.numFrames = framesPerIndexRead;
  202367. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  202368. break;
  202369. }
  202370. if (i < 0)
  202371. break;
  202372. if (readBuffer.index > last && readBuffer.index > 1)
  202373. {
  202374. last = readBuffer.index;
  202375. indexes.add (pos);
  202376. }
  202377. pos += samplesPerFrame * framesPerIndexRead;
  202378. }
  202379. indexes.removeValue (trackStart);
  202380. }
  202381. return indexes;
  202382. }
  202383. int AudioCDReader::getCDDBId()
  202384. {
  202385. refreshTrackLengths();
  202386. if (numTracks > 0)
  202387. {
  202388. TOC toc;
  202389. zerostruct (toc);
  202390. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  202391. {
  202392. int n = 0;
  202393. for (int i = numTracks; --i >= 0;)
  202394. {
  202395. int j = getMSFAddressOf (&toc.tracks[i]);
  202396. while (j > 0)
  202397. {
  202398. n += (j % 10);
  202399. j /= 10;
  202400. }
  202401. }
  202402. if (n != 0)
  202403. {
  202404. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  202405. - getMSFAddressOf (&toc.tracks[0]);
  202406. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  202407. }
  202408. }
  202409. }
  202410. return 0;
  202411. }
  202412. void AudioCDReader::ejectDisk()
  202413. {
  202414. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  202415. }
  202416. #if JUCE_USE_CDBURNER
  202417. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  202418. {
  202419. CoInitialize (0);
  202420. IDiscMaster* dm;
  202421. IDiscRecorder* result = 0;
  202422. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  202423. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  202424. IID_IDiscMaster,
  202425. (void**) &dm)))
  202426. {
  202427. if (SUCCEEDED (dm->Open()))
  202428. {
  202429. IEnumDiscRecorders* drEnum = 0;
  202430. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  202431. {
  202432. IDiscRecorder* dr = 0;
  202433. DWORD dummy;
  202434. int index = 0;
  202435. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  202436. {
  202437. if (indexToOpen == index)
  202438. {
  202439. result = dr;
  202440. break;
  202441. }
  202442. else if (list != 0)
  202443. {
  202444. BSTR path;
  202445. if (SUCCEEDED (dr->GetPath (&path)))
  202446. list->add ((const WCHAR*) path);
  202447. }
  202448. ++index;
  202449. dr->Release();
  202450. }
  202451. drEnum->Release();
  202452. }
  202453. /*if (redbookFormat != 0)
  202454. {
  202455. IEnumDiscMasterFormats* mfEnum;
  202456. if (SUCCEEDED (dm->EnumDiscMasterFormats (&mfEnum)))
  202457. {
  202458. IID formatIID;
  202459. DWORD dummy;
  202460. while (mfEnum->Next (1, &formatIID, &dummy) == S_OK)
  202461. {
  202462. }
  202463. mfEnum->Release();
  202464. }
  202465. redbookFormat
  202466. }*/
  202467. if (master == 0)
  202468. dm->Close();
  202469. }
  202470. if (master != 0)
  202471. *master = dm;
  202472. else
  202473. dm->Release();
  202474. }
  202475. return result;
  202476. }
  202477. const StringArray AudioCDBurner::findAvailableDevices()
  202478. {
  202479. StringArray devs;
  202480. enumCDBurners (&devs, -1, 0);
  202481. return devs;
  202482. }
  202483. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  202484. {
  202485. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  202486. if (b->internal == 0)
  202487. deleteAndZero (b);
  202488. return b;
  202489. }
  202490. class CDBurnerInfo : public IDiscMasterProgressEvents
  202491. {
  202492. public:
  202493. CDBurnerInfo()
  202494. : refCount (1),
  202495. progress (0),
  202496. shouldCancel (false),
  202497. listener (0)
  202498. {
  202499. }
  202500. ~CDBurnerInfo()
  202501. {
  202502. }
  202503. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  202504. {
  202505. if (result == 0)
  202506. return E_POINTER;
  202507. if (id == IID_IUnknown || id == IID_IDiscMasterProgressEvents)
  202508. {
  202509. AddRef();
  202510. *result = this;
  202511. return S_OK;
  202512. }
  202513. *result = 0;
  202514. return E_NOINTERFACE;
  202515. }
  202516. ULONG __stdcall AddRef() { return ++refCount; }
  202517. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  202518. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  202519. {
  202520. if (listener != 0 && ! shouldCancel)
  202521. shouldCancel = listener->audioCDBurnProgress (progress);
  202522. *pbCancel = shouldCancel;
  202523. return S_OK;
  202524. }
  202525. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  202526. {
  202527. progress = nCompleted / (float) nTotal;
  202528. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  202529. return E_NOTIMPL;
  202530. }
  202531. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  202532. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  202533. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  202534. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  202535. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  202536. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  202537. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  202538. IDiscMaster* discMaster;
  202539. IDiscRecorder* discRecorder;
  202540. IRedbookDiscMaster* redbook;
  202541. AudioCDBurner::BurnProgressListener* listener;
  202542. float progress;
  202543. bool shouldCancel;
  202544. private:
  202545. int refCount;
  202546. };
  202547. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  202548. : internal (0)
  202549. {
  202550. IDiscMaster* discMaster;
  202551. IDiscRecorder* dr = enumCDBurners (0, deviceIndex, &discMaster);
  202552. if (dr != 0)
  202553. {
  202554. IRedbookDiscMaster* redbook;
  202555. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  202556. hr = discMaster->SetActiveDiscRecorder (dr);
  202557. CDBurnerInfo* const info = new CDBurnerInfo();
  202558. internal = info;
  202559. info->discMaster = discMaster;
  202560. info->discRecorder = dr;
  202561. info->redbook = redbook;
  202562. }
  202563. }
  202564. AudioCDBurner::~AudioCDBurner()
  202565. {
  202566. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  202567. if (info != 0)
  202568. {
  202569. info->discRecorder->Close();
  202570. info->redbook->Release();
  202571. info->discRecorder->Release();
  202572. info->discMaster->Release();
  202573. info->Release();
  202574. }
  202575. }
  202576. bool AudioCDBurner::isDiskPresent() const
  202577. {
  202578. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  202579. HRESULT hr = info->discRecorder->OpenExclusive();
  202580. long type, flags;
  202581. hr = info->discRecorder->QueryMediaType (&type, &flags);
  202582. info->discRecorder->Close();
  202583. return hr == S_OK && type != 0 && (flags & MEDIA_WRITABLE) != 0;
  202584. }
  202585. int AudioCDBurner::getNumAvailableAudioBlocks() const
  202586. {
  202587. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  202588. long blocksFree = 0;
  202589. info->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  202590. return blocksFree;
  202591. }
  202592. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener,
  202593. const bool ejectDiscAfterwards,
  202594. const bool performFakeBurnForTesting)
  202595. {
  202596. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  202597. info->listener = listener;
  202598. info->progress = 0;
  202599. info->shouldCancel = false;
  202600. UINT_PTR cookie;
  202601. HRESULT hr = info->discMaster->ProgressAdvise (info, &cookie);
  202602. hr = info->discMaster->RecordDisc (performFakeBurnForTesting,
  202603. ejectDiscAfterwards);
  202604. String error;
  202605. if (hr != S_OK)
  202606. {
  202607. const char* e = "Couldn't open or write to the CD device";
  202608. if (hr == IMAPI_E_USERABORT)
  202609. e = "User cancelled the write operation";
  202610. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  202611. e = "No Disk present";
  202612. error = e;
  202613. }
  202614. info->discMaster->ProgressUnadvise (cookie);
  202615. info->listener = 0;
  202616. return error;
  202617. }
  202618. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamples)
  202619. {
  202620. if (source == 0)
  202621. return false;
  202622. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  202623. long bytesPerBlock;
  202624. HRESULT hr = info->redbook->GetAudioBlockSize (&bytesPerBlock);
  202625. const int samplesPerBlock = bytesPerBlock / 4;
  202626. bool ok = true;
  202627. hr = info->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  202628. byte* const buffer = (byte*) juce_malloc (bytesPerBlock);
  202629. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  202630. int samplesDone = 0;
  202631. source->prepareToPlay (samplesPerBlock, 44100.0);
  202632. while (ok)
  202633. {
  202634. {
  202635. AudioSourceChannelInfo info;
  202636. info.buffer = &sourceBuffer;
  202637. info.numSamples = samplesPerBlock;
  202638. info.startSample = 0;
  202639. sourceBuffer.clear();
  202640. source->getNextAudioBlock (info);
  202641. }
  202642. zeromem (buffer, bytesPerBlock);
  202643. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  202644. buffer, samplesPerBlock, 4);
  202645. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  202646. buffer + 2, samplesPerBlock, 4);
  202647. hr = info->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  202648. if (hr != S_OK)
  202649. ok = false;
  202650. samplesDone += samplesPerBlock;
  202651. if (samplesDone >= numSamples)
  202652. break;
  202653. }
  202654. juce_free (buffer);
  202655. hr = info->redbook->CloseAudioTrack();
  202656. delete source;
  202657. return ok && hr == S_OK;
  202658. }
  202659. #endif
  202660. END_JUCE_NAMESPACE
  202661. /********* End of inlined file: juce_win32_AudioCDReader.cpp *********/
  202662. /********* Start of inlined file: juce_win32_DirectSound.cpp *********/
  202663. extern "C"
  202664. {
  202665. // Declare just the minimum number of interfaces for the DSound objects that we need..
  202666. typedef struct typeDSBUFFERDESC
  202667. {
  202668. DWORD dwSize;
  202669. DWORD dwFlags;
  202670. DWORD dwBufferBytes;
  202671. DWORD dwReserved;
  202672. LPWAVEFORMATEX lpwfxFormat;
  202673. GUID guid3DAlgorithm;
  202674. } DSBUFFERDESC;
  202675. struct IDirectSoundBuffer;
  202676. #undef INTERFACE
  202677. #define INTERFACE IDirectSound
  202678. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  202679. {
  202680. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  202681. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  202682. STDMETHOD_(ULONG,Release) (THIS) PURE;
  202683. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  202684. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  202685. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  202686. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  202687. STDMETHOD(Compact) (THIS) PURE;
  202688. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  202689. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  202690. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  202691. };
  202692. #undef INTERFACE
  202693. #define INTERFACE IDirectSoundBuffer
  202694. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  202695. {
  202696. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  202697. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  202698. STDMETHOD_(ULONG,Release) (THIS) PURE;
  202699. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  202700. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  202701. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  202702. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  202703. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  202704. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  202705. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  202706. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  202707. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  202708. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  202709. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  202710. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  202711. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  202712. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  202713. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  202714. STDMETHOD(Stop) (THIS) PURE;
  202715. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  202716. STDMETHOD(Restore) (THIS) PURE;
  202717. };
  202718. typedef struct typeDSCBUFFERDESC
  202719. {
  202720. DWORD dwSize;
  202721. DWORD dwFlags;
  202722. DWORD dwBufferBytes;
  202723. DWORD dwReserved;
  202724. LPWAVEFORMATEX lpwfxFormat;
  202725. } DSCBUFFERDESC;
  202726. struct IDirectSoundCaptureBuffer;
  202727. #undef INTERFACE
  202728. #define INTERFACE IDirectSoundCapture
  202729. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  202730. {
  202731. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  202732. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  202733. STDMETHOD_(ULONG,Release) (THIS) PURE;
  202734. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  202735. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  202736. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  202737. };
  202738. #undef INTERFACE
  202739. #define INTERFACE IDirectSoundCaptureBuffer
  202740. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  202741. {
  202742. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  202743. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  202744. STDMETHOD_(ULONG,Release) (THIS) PURE;
  202745. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  202746. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  202747. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  202748. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  202749. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  202750. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  202751. STDMETHOD(Start) (THIS_ DWORD) PURE;
  202752. STDMETHOD(Stop) (THIS) PURE;
  202753. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  202754. };
  202755. };
  202756. BEGIN_JUCE_NAMESPACE
  202757. static const String getDSErrorMessage (HRESULT hr)
  202758. {
  202759. const char* result = 0;
  202760. switch (hr)
  202761. {
  202762. case MAKE_HRESULT(1, 0x878, 10):
  202763. result = "Device already allocated";
  202764. break;
  202765. case MAKE_HRESULT(1, 0x878, 30):
  202766. result = "Control unavailable";
  202767. break;
  202768. case E_INVALIDARG:
  202769. result = "Invalid parameter";
  202770. break;
  202771. case MAKE_HRESULT(1, 0x878, 50):
  202772. result = "Invalid call";
  202773. break;
  202774. case E_FAIL:
  202775. result = "Generic error";
  202776. break;
  202777. case MAKE_HRESULT(1, 0x878, 70):
  202778. result = "Priority level error";
  202779. break;
  202780. case E_OUTOFMEMORY:
  202781. result = "Out of memory";
  202782. break;
  202783. case MAKE_HRESULT(1, 0x878, 100):
  202784. result = "Bad format";
  202785. break;
  202786. case E_NOTIMPL:
  202787. result = "Unsupported function";
  202788. break;
  202789. case MAKE_HRESULT(1, 0x878, 120):
  202790. result = "No driver";
  202791. break;
  202792. case MAKE_HRESULT(1, 0x878, 130):
  202793. result = "Already initialised";
  202794. break;
  202795. case CLASS_E_NOAGGREGATION:
  202796. result = "No aggregation";
  202797. break;
  202798. case MAKE_HRESULT(1, 0x878, 150):
  202799. result = "Buffer lost";
  202800. break;
  202801. case MAKE_HRESULT(1, 0x878, 160):
  202802. result = "Another app has priority";
  202803. break;
  202804. case MAKE_HRESULT(1, 0x878, 170):
  202805. result = "Uninitialised";
  202806. break;
  202807. case E_NOINTERFACE:
  202808. result = "No interface";
  202809. break;
  202810. case S_OK:
  202811. result = "No error";
  202812. break;
  202813. default:
  202814. return "Unknown error: " + String ((int) hr);
  202815. }
  202816. return result;
  202817. }
  202818. #define DS_DEBUGGING 1
  202819. #ifdef DS_DEBUGGING
  202820. #define CATCH JUCE_CATCH_EXCEPTION
  202821. #undef log
  202822. #define log(a) Logger::writeToLog(a);
  202823. #undef logError
  202824. #define logError(a) logDSError(a, __LINE__);
  202825. static void logDSError (HRESULT hr, int lineNum)
  202826. {
  202827. if (hr != S_OK)
  202828. {
  202829. String error ("DS error at line ");
  202830. error << lineNum << T(" - ") << getDSErrorMessage (hr);
  202831. log (error);
  202832. }
  202833. }
  202834. #else
  202835. #define CATCH JUCE_CATCH_ALL
  202836. #define log(a)
  202837. #define logError(a)
  202838. #endif
  202839. #define DSOUND_FUNCTION(functionName, params) \
  202840. typedef HRESULT (WINAPI *type##functionName) params; \
  202841. static type##functionName ds##functionName = 0;
  202842. #define DSOUND_FUNCTION_LOAD(functionName) \
  202843. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  202844. jassert (ds##functionName != 0);
  202845. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  202846. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  202847. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  202848. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  202849. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  202850. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  202851. static void initialiseDSoundFunctions()
  202852. {
  202853. if (dsDirectSoundCreate == 0)
  202854. {
  202855. HMODULE h = LoadLibraryA ("dsound.dll");
  202856. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  202857. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  202858. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  202859. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  202860. }
  202861. }
  202862. class DSoundInternalOutChannel
  202863. {
  202864. String name;
  202865. LPGUID guid;
  202866. int sampleRate, bufferSizeSamples;
  202867. float* leftBuffer;
  202868. float* rightBuffer;
  202869. IDirectSound* pDirectSound;
  202870. IDirectSoundBuffer* pOutputBuffer;
  202871. DWORD writeOffset;
  202872. int totalBytesPerBuffer;
  202873. int bytesPerBuffer;
  202874. unsigned int lastPlayCursor;
  202875. public:
  202876. int bitDepth;
  202877. bool doneFlag;
  202878. DSoundInternalOutChannel (const String& name_,
  202879. LPGUID guid_,
  202880. int rate,
  202881. int bufferSize,
  202882. float* left,
  202883. float* right)
  202884. : name (name_),
  202885. guid (guid_),
  202886. sampleRate (rate),
  202887. bufferSizeSamples (bufferSize),
  202888. leftBuffer (left),
  202889. rightBuffer (right),
  202890. pDirectSound (0),
  202891. pOutputBuffer (0),
  202892. bitDepth (16)
  202893. {
  202894. }
  202895. ~DSoundInternalOutChannel()
  202896. {
  202897. close();
  202898. }
  202899. void close()
  202900. {
  202901. HRESULT hr;
  202902. if (pOutputBuffer != 0)
  202903. {
  202904. JUCE_TRY
  202905. {
  202906. log (T("closing dsound out: ") + name);
  202907. hr = pOutputBuffer->Stop();
  202908. logError (hr);
  202909. }
  202910. CATCH
  202911. JUCE_TRY
  202912. {
  202913. hr = pOutputBuffer->Release();
  202914. logError (hr);
  202915. }
  202916. CATCH
  202917. pOutputBuffer = 0;
  202918. }
  202919. if (pDirectSound != 0)
  202920. {
  202921. JUCE_TRY
  202922. {
  202923. hr = pDirectSound->Release();
  202924. logError (hr);
  202925. }
  202926. CATCH
  202927. pDirectSound = 0;
  202928. }
  202929. }
  202930. const String open()
  202931. {
  202932. log (T("opening dsound out device: ") + name
  202933. + T(" rate=") + String (sampleRate)
  202934. + T(" bits=") + String (bitDepth)
  202935. + T(" buf=") + String (bufferSizeSamples));
  202936. pDirectSound = 0;
  202937. pOutputBuffer = 0;
  202938. writeOffset = 0;
  202939. String error;
  202940. HRESULT hr = E_NOINTERFACE;
  202941. if (dsDirectSoundCreate != 0)
  202942. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  202943. if (hr == S_OK)
  202944. {
  202945. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  202946. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  202947. const int numChannels = 2;
  202948. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  202949. logError (hr);
  202950. if (hr == S_OK)
  202951. {
  202952. IDirectSoundBuffer* pPrimaryBuffer;
  202953. DSBUFFERDESC primaryDesc;
  202954. zerostruct (primaryDesc);
  202955. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  202956. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  202957. primaryDesc.dwBufferBytes = 0;
  202958. primaryDesc.lpwfxFormat = 0;
  202959. log ("opening dsound out step 2");
  202960. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  202961. logError (hr);
  202962. if (hr == S_OK)
  202963. {
  202964. WAVEFORMATEX wfFormat;
  202965. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  202966. wfFormat.nChannels = (unsigned short) numChannels;
  202967. wfFormat.nSamplesPerSec = sampleRate;
  202968. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  202969. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  202970. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  202971. wfFormat.cbSize = 0;
  202972. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  202973. logError (hr);
  202974. if (hr == S_OK)
  202975. {
  202976. DSBUFFERDESC secondaryDesc;
  202977. zerostruct (secondaryDesc);
  202978. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  202979. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  202980. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  202981. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  202982. secondaryDesc.lpwfxFormat = &wfFormat;
  202983. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  202984. logError (hr);
  202985. if (hr == S_OK)
  202986. {
  202987. log ("opening dsound out step 3");
  202988. DWORD dwDataLen;
  202989. unsigned char* pDSBuffData;
  202990. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  202991. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  202992. logError (hr);
  202993. if (hr == S_OK)
  202994. {
  202995. zeromem (pDSBuffData, dwDataLen);
  202996. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  202997. if (hr == S_OK)
  202998. {
  202999. hr = pOutputBuffer->SetCurrentPosition (0);
  203000. if (hr == S_OK)
  203001. {
  203002. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  203003. if (hr == S_OK)
  203004. return String::empty;
  203005. }
  203006. }
  203007. }
  203008. }
  203009. }
  203010. }
  203011. }
  203012. }
  203013. error = getDSErrorMessage (hr);
  203014. close();
  203015. return error;
  203016. }
  203017. void synchronisePosition()
  203018. {
  203019. if (pOutputBuffer != 0)
  203020. {
  203021. DWORD playCursor;
  203022. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  203023. }
  203024. }
  203025. bool service()
  203026. {
  203027. if (pOutputBuffer == 0)
  203028. return true;
  203029. DWORD playCursor, writeCursor;
  203030. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  203031. if (hr != S_OK)
  203032. {
  203033. logError (hr);
  203034. jassertfalse
  203035. return true;
  203036. }
  203037. int playWriteGap = writeCursor - playCursor;
  203038. if (playWriteGap < 0)
  203039. playWriteGap += totalBytesPerBuffer;
  203040. int bytesEmpty = playCursor - writeOffset;
  203041. if (bytesEmpty < 0)
  203042. bytesEmpty += totalBytesPerBuffer;
  203043. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  203044. {
  203045. writeOffset = writeCursor;
  203046. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  203047. }
  203048. if (bytesEmpty >= bytesPerBuffer)
  203049. {
  203050. LPBYTE lpbuf1 = 0;
  203051. LPBYTE lpbuf2 = 0;
  203052. DWORD dwSize1 = 0;
  203053. DWORD dwSize2 = 0;
  203054. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  203055. bytesPerBuffer,
  203056. (void**) &lpbuf1, &dwSize1,
  203057. (void**) &lpbuf2, &dwSize2, 0);
  203058. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  203059. {
  203060. pOutputBuffer->Restore();
  203061. hr = pOutputBuffer->Lock (writeOffset,
  203062. bytesPerBuffer,
  203063. (void**) &lpbuf1, &dwSize1,
  203064. (void**) &lpbuf2, &dwSize2, 0);
  203065. }
  203066. if (hr == S_OK)
  203067. {
  203068. if (bitDepth == 16)
  203069. {
  203070. const float gainL = 32767.0f;
  203071. const float gainR = 32767.0f;
  203072. int* dest = (int*)lpbuf1;
  203073. const float* left = leftBuffer;
  203074. const float* right = rightBuffer;
  203075. int samples1 = dwSize1 >> 2;
  203076. int samples2 = dwSize2 >> 2;
  203077. if (left == 0)
  203078. {
  203079. while (--samples1 >= 0)
  203080. {
  203081. int r = roundFloatToInt (gainR * *right++);
  203082. if (r < -32768)
  203083. r = -32768;
  203084. else if (r > 32767)
  203085. r = 32767;
  203086. *dest++ = (r << 16);
  203087. }
  203088. dest = (int*)lpbuf2;
  203089. while (--samples2 >= 0)
  203090. {
  203091. int r = roundFloatToInt (gainR * *right++);
  203092. if (r < -32768)
  203093. r = -32768;
  203094. else if (r > 32767)
  203095. r = 32767;
  203096. *dest++ = (r << 16);
  203097. }
  203098. }
  203099. else if (right == 0)
  203100. {
  203101. while (--samples1 >= 0)
  203102. {
  203103. int l = roundFloatToInt (gainL * *left++);
  203104. if (l < -32768)
  203105. l = -32768;
  203106. else if (l > 32767)
  203107. l = 32767;
  203108. l &= 0xffff;
  203109. *dest++ = l;
  203110. }
  203111. dest = (int*)lpbuf2;
  203112. while (--samples2 >= 0)
  203113. {
  203114. int l = roundFloatToInt (gainL * *left++);
  203115. if (l < -32768)
  203116. l = -32768;
  203117. else if (l > 32767)
  203118. l = 32767;
  203119. l &= 0xffff;
  203120. *dest++ = l;
  203121. }
  203122. }
  203123. else
  203124. {
  203125. while (--samples1 >= 0)
  203126. {
  203127. int l = roundFloatToInt (gainL * *left++);
  203128. if (l < -32768)
  203129. l = -32768;
  203130. else if (l > 32767)
  203131. l = 32767;
  203132. l &= 0xffff;
  203133. int r = roundFloatToInt (gainR * *right++);
  203134. if (r < -32768)
  203135. r = -32768;
  203136. else if (r > 32767)
  203137. r = 32767;
  203138. *dest++ = (r << 16) | l;
  203139. }
  203140. dest = (int*)lpbuf2;
  203141. while (--samples2 >= 0)
  203142. {
  203143. int l = roundFloatToInt (gainL * *left++);
  203144. if (l < -32768)
  203145. l = -32768;
  203146. else if (l > 32767)
  203147. l = 32767;
  203148. l &= 0xffff;
  203149. int r = roundFloatToInt (gainR * *right++);
  203150. if (r < -32768)
  203151. r = -32768;
  203152. else if (r > 32767)
  203153. r = 32767;
  203154. *dest++ = (r << 16) | l;
  203155. }
  203156. }
  203157. }
  203158. else
  203159. {
  203160. jassertfalse
  203161. }
  203162. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  203163. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  203164. }
  203165. else
  203166. {
  203167. jassertfalse
  203168. logError (hr);
  203169. }
  203170. bytesEmpty -= bytesPerBuffer;
  203171. return true;
  203172. }
  203173. else
  203174. {
  203175. return false;
  203176. }
  203177. }
  203178. };
  203179. struct DSoundInternalInChannel
  203180. {
  203181. String name;
  203182. LPGUID guid;
  203183. int sampleRate, bufferSizeSamples;
  203184. float* leftBuffer;
  203185. float* rightBuffer;
  203186. IDirectSound* pDirectSound;
  203187. IDirectSoundCapture* pDirectSoundCapture;
  203188. IDirectSoundCaptureBuffer* pInputBuffer;
  203189. public:
  203190. unsigned int readOffset;
  203191. int bytesPerBuffer, totalBytesPerBuffer;
  203192. int bitDepth;
  203193. bool doneFlag;
  203194. DSoundInternalInChannel (const String& name_,
  203195. LPGUID guid_,
  203196. int rate,
  203197. int bufferSize,
  203198. float* left,
  203199. float* right)
  203200. : name (name_),
  203201. guid (guid_),
  203202. sampleRate (rate),
  203203. bufferSizeSamples (bufferSize),
  203204. leftBuffer (left),
  203205. rightBuffer (right),
  203206. pDirectSound (0),
  203207. pDirectSoundCapture (0),
  203208. pInputBuffer (0),
  203209. bitDepth (16)
  203210. {
  203211. }
  203212. ~DSoundInternalInChannel()
  203213. {
  203214. close();
  203215. }
  203216. void close()
  203217. {
  203218. HRESULT hr;
  203219. if (pInputBuffer != 0)
  203220. {
  203221. JUCE_TRY
  203222. {
  203223. log (T("closing dsound in: ") + name);
  203224. hr = pInputBuffer->Stop();
  203225. logError (hr);
  203226. }
  203227. CATCH
  203228. JUCE_TRY
  203229. {
  203230. hr = pInputBuffer->Release();
  203231. logError (hr);
  203232. }
  203233. CATCH
  203234. pInputBuffer = 0;
  203235. }
  203236. if (pDirectSoundCapture != 0)
  203237. {
  203238. JUCE_TRY
  203239. {
  203240. hr = pDirectSoundCapture->Release();
  203241. logError (hr);
  203242. }
  203243. CATCH
  203244. pDirectSoundCapture = 0;
  203245. }
  203246. if (pDirectSound != 0)
  203247. {
  203248. JUCE_TRY
  203249. {
  203250. hr = pDirectSound->Release();
  203251. logError (hr);
  203252. }
  203253. CATCH
  203254. pDirectSound = 0;
  203255. }
  203256. }
  203257. const String open()
  203258. {
  203259. log (T("opening dsound in device: ") + name
  203260. + T(" rate=") + String (sampleRate) + T(" bits=") + String (bitDepth) + T(" buf=") + String (bufferSizeSamples));
  203261. pDirectSound = 0;
  203262. pDirectSoundCapture = 0;
  203263. pInputBuffer = 0;
  203264. readOffset = 0;
  203265. totalBytesPerBuffer = 0;
  203266. String error;
  203267. HRESULT hr = E_NOINTERFACE;
  203268. if (dsDirectSoundCaptureCreate != 0)
  203269. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  203270. logError (hr);
  203271. if (hr == S_OK)
  203272. {
  203273. const int numChannels = 2;
  203274. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  203275. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  203276. WAVEFORMATEX wfFormat;
  203277. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  203278. wfFormat.nChannels = (unsigned short)numChannels;
  203279. wfFormat.nSamplesPerSec = sampleRate;
  203280. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  203281. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  203282. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  203283. wfFormat.cbSize = 0;
  203284. DSCBUFFERDESC captureDesc;
  203285. zerostruct (captureDesc);
  203286. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  203287. captureDesc.dwFlags = 0;
  203288. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  203289. captureDesc.lpwfxFormat = &wfFormat;
  203290. log (T("opening dsound in step 2"));
  203291. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  203292. logError (hr);
  203293. if (hr == S_OK)
  203294. {
  203295. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  203296. logError (hr);
  203297. if (hr == S_OK)
  203298. return String::empty;
  203299. }
  203300. }
  203301. error = getDSErrorMessage (hr);
  203302. close();
  203303. return error;
  203304. }
  203305. void synchronisePosition()
  203306. {
  203307. if (pInputBuffer != 0)
  203308. {
  203309. DWORD capturePos;
  203310. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  203311. }
  203312. }
  203313. bool service()
  203314. {
  203315. if (pInputBuffer == 0)
  203316. return true;
  203317. DWORD capturePos, readPos;
  203318. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  203319. logError (hr);
  203320. if (hr != S_OK)
  203321. return true;
  203322. int bytesFilled = readPos - readOffset;
  203323. if (bytesFilled < 0)
  203324. bytesFilled += totalBytesPerBuffer;
  203325. if (bytesFilled >= bytesPerBuffer)
  203326. {
  203327. LPBYTE lpbuf1 = 0;
  203328. LPBYTE lpbuf2 = 0;
  203329. DWORD dwsize1 = 0;
  203330. DWORD dwsize2 = 0;
  203331. HRESULT hr = pInputBuffer->Lock (readOffset,
  203332. bytesPerBuffer,
  203333. (void**) &lpbuf1, &dwsize1,
  203334. (void**) &lpbuf2, &dwsize2, 0);
  203335. if (hr == S_OK)
  203336. {
  203337. if (bitDepth == 16)
  203338. {
  203339. const float g = 1.0f / 32768.0f;
  203340. float* destL = leftBuffer;
  203341. float* destR = rightBuffer;
  203342. int samples1 = dwsize1 >> 2;
  203343. int samples2 = dwsize2 >> 2;
  203344. const short* src = (const short*)lpbuf1;
  203345. if (destL == 0)
  203346. {
  203347. while (--samples1 >= 0)
  203348. {
  203349. ++src;
  203350. *destR++ = *src++ * g;
  203351. }
  203352. src = (const short*)lpbuf2;
  203353. while (--samples2 >= 0)
  203354. {
  203355. ++src;
  203356. *destR++ = *src++ * g;
  203357. }
  203358. }
  203359. else if (destR == 0)
  203360. {
  203361. while (--samples1 >= 0)
  203362. {
  203363. *destL++ = *src++ * g;
  203364. ++src;
  203365. }
  203366. src = (const short*)lpbuf2;
  203367. while (--samples2 >= 0)
  203368. {
  203369. *destL++ = *src++ * g;
  203370. ++src;
  203371. }
  203372. }
  203373. else
  203374. {
  203375. while (--samples1 >= 0)
  203376. {
  203377. *destL++ = *src++ * g;
  203378. *destR++ = *src++ * g;
  203379. }
  203380. src = (const short*)lpbuf2;
  203381. while (--samples2 >= 0)
  203382. {
  203383. *destL++ = *src++ * g;
  203384. *destR++ = *src++ * g;
  203385. }
  203386. }
  203387. }
  203388. else
  203389. {
  203390. jassertfalse
  203391. }
  203392. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  203393. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  203394. }
  203395. else
  203396. {
  203397. logError (hr);
  203398. jassertfalse
  203399. }
  203400. bytesFilled -= bytesPerBuffer;
  203401. return true;
  203402. }
  203403. else
  203404. {
  203405. return false;
  203406. }
  203407. }
  203408. };
  203409. class DSoundAudioIODevice : public AudioIODevice,
  203410. public Thread
  203411. {
  203412. public:
  203413. DSoundAudioIODevice (const String& deviceName,
  203414. const int outputDeviceIndex_,
  203415. const int inputDeviceIndex_)
  203416. : AudioIODevice (deviceName, "DirectSound"),
  203417. Thread ("Juce DSound"),
  203418. isOpen_ (false),
  203419. isStarted (false),
  203420. outputDeviceIndex (outputDeviceIndex_),
  203421. inputDeviceIndex (inputDeviceIndex_),
  203422. inChans (4),
  203423. outChans (4),
  203424. numInputBuffers (0),
  203425. numOutputBuffers (0),
  203426. totalSamplesOut (0),
  203427. sampleRate (0.0),
  203428. inputBuffers (0),
  203429. outputBuffers (0),
  203430. callback (0),
  203431. bufferSizeSamples (0)
  203432. {
  203433. if (outputDeviceIndex_ >= 0)
  203434. {
  203435. outChannels.add (TRANS("Left"));
  203436. outChannels.add (TRANS("Right"));
  203437. }
  203438. if (inputDeviceIndex_ >= 0)
  203439. {
  203440. inChannels.add (TRANS("Left"));
  203441. inChannels.add (TRANS("Right"));
  203442. }
  203443. }
  203444. ~DSoundAudioIODevice()
  203445. {
  203446. close();
  203447. }
  203448. const StringArray getOutputChannelNames()
  203449. {
  203450. return outChannels;
  203451. }
  203452. const StringArray getInputChannelNames()
  203453. {
  203454. return inChannels;
  203455. }
  203456. int getNumSampleRates()
  203457. {
  203458. return 4;
  203459. }
  203460. double getSampleRate (int index)
  203461. {
  203462. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  203463. return samps [jlimit (0, 3, index)];
  203464. }
  203465. int getNumBufferSizesAvailable()
  203466. {
  203467. return 50;
  203468. }
  203469. int getBufferSizeSamples (int index)
  203470. {
  203471. int n = 64;
  203472. for (int i = 0; i < index; ++i)
  203473. n += (n < 512) ? 32
  203474. : ((n < 1024) ? 64
  203475. : ((n < 2048) ? 128 : 256));
  203476. return n;
  203477. }
  203478. int getDefaultBufferSize()
  203479. {
  203480. return 2560;
  203481. }
  203482. const String open (const BitArray& inputChannels,
  203483. const BitArray& outputChannels,
  203484. double sampleRate,
  203485. int bufferSizeSamples)
  203486. {
  203487. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  203488. isOpen_ = lastError.isEmpty();
  203489. return lastError;
  203490. }
  203491. void close()
  203492. {
  203493. stop();
  203494. if (isOpen_)
  203495. {
  203496. closeDevice();
  203497. isOpen_ = false;
  203498. }
  203499. }
  203500. bool isOpen()
  203501. {
  203502. return isOpen_ && isThreadRunning();
  203503. }
  203504. int getCurrentBufferSizeSamples()
  203505. {
  203506. return bufferSizeSamples;
  203507. }
  203508. double getCurrentSampleRate()
  203509. {
  203510. return sampleRate;
  203511. }
  203512. int getCurrentBitDepth()
  203513. {
  203514. int i, bits = 256;
  203515. for (i = inChans.size(); --i >= 0;)
  203516. bits = jmin (bits, inChans[i]->bitDepth);
  203517. for (i = outChans.size(); --i >= 0;)
  203518. bits = jmin (bits, outChans[i]->bitDepth);
  203519. if (bits > 32)
  203520. bits = 16;
  203521. return bits;
  203522. }
  203523. const BitArray getActiveOutputChannels() const
  203524. {
  203525. return enabledOutputs;
  203526. }
  203527. const BitArray getActiveInputChannels() const
  203528. {
  203529. return enabledInputs;
  203530. }
  203531. int getOutputLatencyInSamples()
  203532. {
  203533. return (int) (getCurrentBufferSizeSamples() * 1.5);
  203534. }
  203535. int getInputLatencyInSamples()
  203536. {
  203537. return getOutputLatencyInSamples();
  203538. }
  203539. void start (AudioIODeviceCallback* call)
  203540. {
  203541. if (isOpen_ && call != 0 && ! isStarted)
  203542. {
  203543. if (! isThreadRunning())
  203544. {
  203545. // something gone wrong and the thread's stopped..
  203546. isOpen_ = false;
  203547. return;
  203548. }
  203549. call->audioDeviceAboutToStart (this);
  203550. const ScopedLock sl (startStopLock);
  203551. callback = call;
  203552. isStarted = true;
  203553. }
  203554. }
  203555. void stop()
  203556. {
  203557. if (isStarted)
  203558. {
  203559. AudioIODeviceCallback* const callbackLocal = callback;
  203560. {
  203561. const ScopedLock sl (startStopLock);
  203562. isStarted = false;
  203563. }
  203564. if (callbackLocal != 0)
  203565. callbackLocal->audioDeviceStopped();
  203566. }
  203567. }
  203568. bool isPlaying()
  203569. {
  203570. return isStarted && isOpen_ && isThreadRunning();
  203571. }
  203572. const String getLastError()
  203573. {
  203574. return lastError;
  203575. }
  203576. juce_UseDebuggingNewOperator
  203577. StringArray inChannels, outChannels;
  203578. int outputDeviceIndex, inputDeviceIndex;
  203579. private:
  203580. bool isOpen_;
  203581. bool isStarted;
  203582. String lastError;
  203583. OwnedArray <DSoundInternalInChannel> inChans;
  203584. OwnedArray <DSoundInternalOutChannel> outChans;
  203585. WaitableEvent startEvent;
  203586. int numInputBuffers, numOutputBuffers, bufferSizeSamples;
  203587. int volatile totalSamplesOut;
  203588. int64 volatile lastBlockTime;
  203589. double sampleRate;
  203590. BitArray enabledInputs, enabledOutputs;
  203591. float** inputBuffers;
  203592. float** outputBuffers;
  203593. AudioIODeviceCallback* callback;
  203594. CriticalSection startStopLock;
  203595. DSoundAudioIODevice (const DSoundAudioIODevice&);
  203596. const DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  203597. const String openDevice (const BitArray& inputChannels,
  203598. const BitArray& outputChannels,
  203599. double sampleRate_,
  203600. int bufferSizeSamples_);
  203601. void closeDevice()
  203602. {
  203603. isStarted = false;
  203604. stopThread (5000);
  203605. inChans.clear();
  203606. outChans.clear();
  203607. int i;
  203608. for (i = 0; i < numInputBuffers; ++i)
  203609. juce_free (inputBuffers[i]);
  203610. delete[] inputBuffers;
  203611. inputBuffers = 0;
  203612. numInputBuffers = 0;
  203613. for (i = 0; i < numOutputBuffers; ++i)
  203614. juce_free (outputBuffers[i]);
  203615. delete[] outputBuffers;
  203616. outputBuffers = 0;
  203617. numOutputBuffers = 0;
  203618. }
  203619. void resync()
  203620. {
  203621. int i;
  203622. for (i = outChans.size(); --i >= 0;)
  203623. outChans.getUnchecked(i)->close();
  203624. for (i = inChans.size(); --i >= 0;)
  203625. inChans.getUnchecked(i)->close();
  203626. if (threadShouldExit())
  203627. return;
  203628. // boost our priority while opening the devices to try to get better sync between them
  203629. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  203630. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  203631. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  203632. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  203633. for (i = outChans.size(); --i >= 0;)
  203634. outChans.getUnchecked(i)->open();
  203635. for (i = inChans.size(); --i >= 0;)
  203636. inChans.getUnchecked(i)->open();
  203637. if (! threadShouldExit())
  203638. {
  203639. sleep (5);
  203640. for (i = 0; i < outChans.size(); ++i)
  203641. outChans.getUnchecked(i)->synchronisePosition();
  203642. for (i = 0; i < inChans.size(); ++i)
  203643. inChans.getUnchecked(i)->synchronisePosition();
  203644. }
  203645. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  203646. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  203647. }
  203648. public:
  203649. void run()
  203650. {
  203651. while (! threadShouldExit())
  203652. {
  203653. if (wait (100))
  203654. break;
  203655. }
  203656. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  203657. const int maxTimeMS = jmax (5, 3 * latencyMs);
  203658. while (! threadShouldExit())
  203659. {
  203660. int numToDo = 0;
  203661. uint32 startTime = Time::getMillisecondCounter();
  203662. int i;
  203663. for (i = inChans.size(); --i >= 0;)
  203664. {
  203665. inChans.getUnchecked(i)->doneFlag = false;
  203666. ++numToDo;
  203667. }
  203668. for (i = outChans.size(); --i >= 0;)
  203669. {
  203670. outChans.getUnchecked(i)->doneFlag = false;
  203671. ++numToDo;
  203672. }
  203673. if (numToDo > 0)
  203674. {
  203675. const int maxCount = 3;
  203676. int count = maxCount;
  203677. for (;;)
  203678. {
  203679. for (i = inChans.size(); --i >= 0;)
  203680. {
  203681. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  203682. if ((! in->doneFlag) && in->service())
  203683. {
  203684. in->doneFlag = true;
  203685. --numToDo;
  203686. }
  203687. }
  203688. for (i = outChans.size(); --i >= 0;)
  203689. {
  203690. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  203691. if ((! out->doneFlag) && out->service())
  203692. {
  203693. out->doneFlag = true;
  203694. --numToDo;
  203695. }
  203696. }
  203697. if (numToDo <= 0)
  203698. break;
  203699. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  203700. {
  203701. resync();
  203702. break;
  203703. }
  203704. if (--count <= 0)
  203705. {
  203706. Sleep (1);
  203707. count = maxCount;
  203708. }
  203709. if (threadShouldExit())
  203710. return;
  203711. }
  203712. }
  203713. else
  203714. {
  203715. sleep (1);
  203716. }
  203717. const ScopedLock sl (startStopLock);
  203718. if (isStarted)
  203719. {
  203720. JUCE_TRY
  203721. {
  203722. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  203723. numInputBuffers,
  203724. outputBuffers,
  203725. numOutputBuffers,
  203726. bufferSizeSamples);
  203727. }
  203728. JUCE_CATCH_EXCEPTION
  203729. totalSamplesOut += bufferSizeSamples;
  203730. }
  203731. else
  203732. {
  203733. for (i = 0; i < numOutputBuffers; ++i)
  203734. if (outputBuffers[i] != 0)
  203735. zeromem (outputBuffers[i], bufferSizeSamples * sizeof (float));
  203736. totalSamplesOut = 0;
  203737. sleep (1);
  203738. }
  203739. }
  203740. }
  203741. };
  203742. class DSoundAudioIODeviceType : public AudioIODeviceType
  203743. {
  203744. public:
  203745. DSoundAudioIODeviceType()
  203746. : AudioIODeviceType (T("DirectSound")),
  203747. hasScanned (false)
  203748. {
  203749. initialiseDSoundFunctions();
  203750. }
  203751. ~DSoundAudioIODeviceType()
  203752. {
  203753. }
  203754. void scanForDevices()
  203755. {
  203756. hasScanned = true;
  203757. outputDeviceNames.clear();
  203758. outputGuids.clear();
  203759. inputDeviceNames.clear();
  203760. inputGuids.clear();
  203761. if (dsDirectSoundEnumerateW != 0)
  203762. {
  203763. dsDirectSoundEnumerateW (outputEnumProcW, this);
  203764. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  203765. }
  203766. }
  203767. const StringArray getDeviceNames (const bool wantInputNames) const
  203768. {
  203769. jassert (hasScanned); // need to call scanForDevices() before doing this
  203770. return wantInputNames ? inputDeviceNames
  203771. : outputDeviceNames;
  203772. }
  203773. int getDefaultDeviceIndex (const bool /*forInput*/) const
  203774. {
  203775. jassert (hasScanned); // need to call scanForDevices() before doing this
  203776. return 0;
  203777. }
  203778. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  203779. {
  203780. jassert (hasScanned); // need to call scanForDevices() before doing this
  203781. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  203782. if (d == 0)
  203783. return -1;
  203784. return asInput ? d->inputDeviceIndex
  203785. : d->outputDeviceIndex;
  203786. }
  203787. bool hasSeparateInputsAndOutputs() const { return true; }
  203788. AudioIODevice* createDevice (const String& outputDeviceName,
  203789. const String& inputDeviceName)
  203790. {
  203791. jassert (hasScanned); // need to call scanForDevices() before doing this
  203792. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  203793. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  203794. if (outputIndex >= 0 || inputIndex >= 0)
  203795. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  203796. : inputDeviceName,
  203797. outputIndex, inputIndex);
  203798. return 0;
  203799. }
  203800. juce_UseDebuggingNewOperator
  203801. StringArray outputDeviceNames;
  203802. OwnedArray <GUID> outputGuids;
  203803. StringArray inputDeviceNames;
  203804. OwnedArray <GUID> inputGuids;
  203805. private:
  203806. bool hasScanned;
  203807. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  203808. {
  203809. desc = desc.trim();
  203810. if (desc.isNotEmpty())
  203811. {
  203812. const String origDesc (desc);
  203813. int n = 2;
  203814. while (outputDeviceNames.contains (desc))
  203815. desc = origDesc + T(" (") + String (n++) + T(")");
  203816. outputDeviceNames.add (desc);
  203817. if (lpGUID != 0)
  203818. outputGuids.add (new GUID (*lpGUID));
  203819. else
  203820. outputGuids.add (0);
  203821. }
  203822. return TRUE;
  203823. }
  203824. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  203825. {
  203826. return ((DSoundAudioIODeviceType*) object)
  203827. ->outputEnumProc (lpGUID, String (description));
  203828. }
  203829. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  203830. {
  203831. return ((DSoundAudioIODeviceType*) object)
  203832. ->outputEnumProc (lpGUID, String (description));
  203833. }
  203834. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  203835. {
  203836. desc = desc.trim();
  203837. if (desc.isNotEmpty())
  203838. {
  203839. const String origDesc (desc);
  203840. int n = 2;
  203841. while (inputDeviceNames.contains (desc))
  203842. desc = origDesc + T(" (") + String (n++) + T(")");
  203843. inputDeviceNames.add (desc);
  203844. if (lpGUID != 0)
  203845. inputGuids.add (new GUID (*lpGUID));
  203846. else
  203847. inputGuids.add (0);
  203848. }
  203849. return TRUE;
  203850. }
  203851. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  203852. {
  203853. return ((DSoundAudioIODeviceType*) object)
  203854. ->inputEnumProc (lpGUID, String (description));
  203855. }
  203856. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  203857. {
  203858. return ((DSoundAudioIODeviceType*) object)
  203859. ->inputEnumProc (lpGUID, String (description));
  203860. }
  203861. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  203862. const DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  203863. };
  203864. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  203865. {
  203866. return new DSoundAudioIODeviceType();
  203867. }
  203868. const String DSoundAudioIODevice::openDevice (const BitArray& inputChannels,
  203869. const BitArray& outputChannels,
  203870. double sampleRate_,
  203871. int bufferSizeSamples_)
  203872. {
  203873. closeDevice();
  203874. totalSamplesOut = 0;
  203875. sampleRate = sampleRate_;
  203876. if (bufferSizeSamples_ <= 0)
  203877. bufferSizeSamples_ = 960; // use as a default size if none is set.
  203878. bufferSizeSamples = bufferSizeSamples_ & ~7;
  203879. DSoundAudioIODeviceType dlh;
  203880. dlh.scanForDevices();
  203881. enabledInputs = inputChannels;
  203882. enabledInputs.setRange (inChannels.size(),
  203883. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  203884. false);
  203885. numInputBuffers = enabledInputs.countNumberOfSetBits();
  203886. inputBuffers = new float* [numInputBuffers + 2];
  203887. zeromem (inputBuffers, sizeof (float*) * numInputBuffers + 2);
  203888. int i, numIns = 0;
  203889. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  203890. {
  203891. float* left = 0;
  203892. float* right = 0;
  203893. if (enabledInputs[i])
  203894. left = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  203895. if (enabledInputs[i + 1])
  203896. right = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  203897. if (left != 0 || right != 0)
  203898. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  203899. dlh.inputGuids [inputDeviceIndex],
  203900. (int) sampleRate, bufferSizeSamples,
  203901. left, right));
  203902. }
  203903. enabledOutputs = outputChannels;
  203904. enabledOutputs.setRange (outChannels.size(),
  203905. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  203906. false);
  203907. numOutputBuffers = enabledOutputs.countNumberOfSetBits();
  203908. outputBuffers = new float* [numOutputBuffers + 2];
  203909. zeromem (outputBuffers, sizeof (float*) * numOutputBuffers + 2);
  203910. int numOuts = 0;
  203911. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  203912. {
  203913. float* left = 0;
  203914. float* right = 0;
  203915. if (enabledOutputs[i])
  203916. left = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  203917. if (enabledOutputs[i + 1])
  203918. right = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  203919. if (left != 0 || right != 0)
  203920. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  203921. dlh.outputGuids [outputDeviceIndex],
  203922. (int) sampleRate, bufferSizeSamples,
  203923. left, right));
  203924. }
  203925. String error;
  203926. // boost our priority while opening the devices to try to get better sync between them
  203927. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  203928. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  203929. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  203930. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  203931. for (i = 0; i < outChans.size(); ++i)
  203932. {
  203933. error = outChans[i]->open();
  203934. if (error.isNotEmpty())
  203935. {
  203936. error = T("Error opening ") + dlh.outputDeviceNames[i]
  203937. + T(": \"") + error + T("\"");
  203938. break;
  203939. }
  203940. }
  203941. if (error.isEmpty())
  203942. {
  203943. for (i = 0; i < inChans.size(); ++i)
  203944. {
  203945. error = inChans[i]->open();
  203946. if (error.isNotEmpty())
  203947. {
  203948. error = T("Error opening ") + dlh.inputDeviceNames[i]
  203949. + T(": \"") + error + T("\"");
  203950. break;
  203951. }
  203952. }
  203953. }
  203954. if (error.isEmpty())
  203955. {
  203956. totalSamplesOut = 0;
  203957. for (i = 0; i < outChans.size(); ++i)
  203958. outChans.getUnchecked(i)->synchronisePosition();
  203959. for (i = 0; i < inChans.size(); ++i)
  203960. inChans.getUnchecked(i)->synchronisePosition();
  203961. startThread (9);
  203962. sleep (10);
  203963. notify();
  203964. }
  203965. else
  203966. {
  203967. log (error);
  203968. }
  203969. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  203970. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  203971. return error;
  203972. }
  203973. #undef log
  203974. END_JUCE_NAMESPACE
  203975. /********* End of inlined file: juce_win32_DirectSound.cpp *********/
  203976. /********* Start of inlined file: juce_win32_FileChooser.cpp *********/
  203977. #ifdef _MSC_VER
  203978. #pragma warning (disable: 4514)
  203979. #pragma warning (push)
  203980. #endif
  203981. #include <shlobj.h>
  203982. BEGIN_JUCE_NAMESPACE
  203983. #ifdef _MSC_VER
  203984. #pragma warning (pop)
  203985. #endif
  203986. static const void* defaultDirPath = 0;
  203987. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  203988. static Component* currentExtraFileWin = 0;
  203989. static bool areThereAnyAlwaysOnTopWindows()
  203990. {
  203991. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  203992. {
  203993. Component* c = Desktop::getInstance().getComponent (i);
  203994. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  203995. return true;
  203996. }
  203997. return false;
  203998. }
  203999. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  204000. {
  204001. if (msg == BFFM_INITIALIZED)
  204002. {
  204003. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  204004. }
  204005. else if (msg == BFFM_VALIDATEFAILEDW)
  204006. {
  204007. returnedString = (LPCWSTR) lParam;
  204008. }
  204009. else if (msg == BFFM_VALIDATEFAILEDA)
  204010. {
  204011. returnedString = (const char*) lParam;
  204012. }
  204013. return 0;
  204014. }
  204015. void juce_setWindowStyleBit (HWND h, int styleType, int feature, bool bitIsSet);
  204016. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  204017. {
  204018. if (currentExtraFileWin != 0)
  204019. {
  204020. if (uiMsg == WM_INITDIALOG)
  204021. {
  204022. HWND dialogH = GetParent (hdlg);
  204023. jassert (dialogH != 0);
  204024. if (dialogH == 0)
  204025. dialogH = hdlg;
  204026. RECT r, cr;
  204027. GetWindowRect (dialogH, &r);
  204028. GetClientRect (dialogH, &cr);
  204029. SetWindowPos (dialogH, 0,
  204030. r.left, r.top,
  204031. currentExtraFileWin->getWidth() + jmax (150, r.right - r.left),
  204032. jmax (150, r.bottom - r.top),
  204033. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  204034. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  204035. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  204036. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  204037. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  204038. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  204039. }
  204040. else if (uiMsg == WM_NOTIFY)
  204041. {
  204042. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  204043. if (ofn->hdr.code == CDN_SELCHANGE)
  204044. {
  204045. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  204046. if (comp != 0)
  204047. {
  204048. TCHAR path [MAX_PATH * 2];
  204049. path[0] = 0;
  204050. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  204051. const String fn ((const WCHAR*) path);
  204052. comp->selectedFileChanged (File (fn));
  204053. }
  204054. }
  204055. }
  204056. }
  204057. return 0;
  204058. }
  204059. class FPComponentHolder : public Component
  204060. {
  204061. public:
  204062. FPComponentHolder()
  204063. {
  204064. setVisible (true);
  204065. setOpaque (true);
  204066. }
  204067. ~FPComponentHolder()
  204068. {
  204069. }
  204070. void paint (Graphics& g)
  204071. {
  204072. g.fillAll (Colours::lightgrey);
  204073. }
  204074. private:
  204075. FPComponentHolder (const FPComponentHolder&);
  204076. const FPComponentHolder& operator= (const FPComponentHolder&);
  204077. };
  204078. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  204079. const String& title,
  204080. const File& currentFileOrDirectory,
  204081. const String& filter,
  204082. bool selectsDirectory,
  204083. bool isSaveDialogue,
  204084. bool warnAboutOverwritingExistingFiles,
  204085. bool selectMultipleFiles,
  204086. FilePreviewComponent* extraInfoComponent)
  204087. {
  204088. const int numCharsAvailable = 32768;
  204089. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  204090. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  204091. int fnameIdx = 0;
  204092. JUCE_TRY
  204093. {
  204094. // use a modal window as the parent for this dialog box
  204095. // to block input from other app windows
  204096. const Rectangle mainMon (Desktop::getInstance().getMainMonitorArea());
  204097. Component w (String::empty);
  204098. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  204099. mainMon.getY() + mainMon.getHeight() / 4,
  204100. 0, 0);
  204101. w.setOpaque (true);
  204102. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  204103. w.addToDesktop (0);
  204104. if (extraInfoComponent == 0)
  204105. w.enterModalState();
  204106. String initialDir;
  204107. if (currentFileOrDirectory.isDirectory())
  204108. {
  204109. initialDir = currentFileOrDirectory.getFullPathName();
  204110. }
  204111. else
  204112. {
  204113. currentFileOrDirectory.getFileName().copyToBuffer (fname, numCharsAvailable);
  204114. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  204115. }
  204116. if (currentExtraFileWin->isValidComponent())
  204117. {
  204118. jassertfalse
  204119. return;
  204120. }
  204121. if (selectsDirectory)
  204122. {
  204123. LPITEMIDLIST list = 0;
  204124. filenameSpace.fillWith (0);
  204125. {
  204126. BROWSEINFO bi;
  204127. zerostruct (bi);
  204128. bi.hwndOwner = (HWND) w.getWindowHandle();
  204129. bi.pszDisplayName = fname;
  204130. bi.lpszTitle = title;
  204131. bi.lpfn = browseCallbackProc;
  204132. #ifdef BIF_USENEWUI
  204133. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  204134. #else
  204135. bi.ulFlags = 0x50;
  204136. #endif
  204137. defaultDirPath = (const WCHAR*) initialDir;
  204138. list = SHBrowseForFolder (&bi);
  204139. if (! SHGetPathFromIDListW (list, fname))
  204140. {
  204141. fname[0] = 0;
  204142. returnedString = String::empty;
  204143. }
  204144. }
  204145. LPMALLOC al;
  204146. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  204147. al->Free (list);
  204148. defaultDirPath = 0;
  204149. if (returnedString.isNotEmpty())
  204150. {
  204151. const String stringFName (fname);
  204152. results.add (new File (File (stringFName).getSiblingFile (returnedString)));
  204153. returnedString = String::empty;
  204154. return;
  204155. }
  204156. }
  204157. else
  204158. {
  204159. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  204160. if (warnAboutOverwritingExistingFiles)
  204161. flags |= OFN_OVERWRITEPROMPT;
  204162. if (selectMultipleFiles)
  204163. flags |= OFN_ALLOWMULTISELECT;
  204164. if (extraInfoComponent != 0)
  204165. {
  204166. flags |= OFN_ENABLEHOOK;
  204167. currentExtraFileWin = new FPComponentHolder();
  204168. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  204169. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  204170. extraInfoComponent->getHeight());
  204171. currentExtraFileWin->addToDesktop (0);
  204172. currentExtraFileWin->enterModalState();
  204173. }
  204174. {
  204175. WCHAR filters [1024];
  204176. zeromem (filters, sizeof (filters));
  204177. filter.copyToBuffer (filters, 1024);
  204178. filter.copyToBuffer (filters + filter.length() + 1,
  204179. 1022 - filter.length());
  204180. OPENFILENAMEW of;
  204181. zerostruct (of);
  204182. #ifdef OPENFILENAME_SIZE_VERSION_400W
  204183. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  204184. #else
  204185. of.lStructSize = sizeof (of);
  204186. #endif
  204187. of.hwndOwner = (HWND) w.getWindowHandle();
  204188. of.lpstrFilter = filters;
  204189. of.nFilterIndex = 1;
  204190. of.lpstrFile = fname;
  204191. of.nMaxFile = numCharsAvailable;
  204192. of.lpstrInitialDir = initialDir;
  204193. of.lpstrTitle = title;
  204194. of.Flags = flags;
  204195. if (extraInfoComponent != 0)
  204196. of.lpfnHook = &openCallback;
  204197. if (isSaveDialogue)
  204198. {
  204199. if (! GetSaveFileName (&of))
  204200. fname[0] = 0;
  204201. else
  204202. fnameIdx = of.nFileOffset;
  204203. }
  204204. else
  204205. {
  204206. if (! GetOpenFileName (&of))
  204207. fname[0] = 0;
  204208. else
  204209. fnameIdx = of.nFileOffset;
  204210. }
  204211. }
  204212. }
  204213. }
  204214. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  204215. catch (...)
  204216. {
  204217. fname[0] = 0;
  204218. }
  204219. #endif
  204220. deleteAndZero (currentExtraFileWin);
  204221. const WCHAR* const files = fname;
  204222. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  204223. {
  204224. const WCHAR* filename = files + fnameIdx;
  204225. while (*filename != 0)
  204226. {
  204227. const String filepath (String (files) + T("\\") + String (filename));
  204228. results.add (new File (filepath));
  204229. filename += CharacterFunctions::length (filename) + 1;
  204230. }
  204231. }
  204232. else if (files[0] != 0)
  204233. {
  204234. results.add (new File (files));
  204235. }
  204236. }
  204237. END_JUCE_NAMESPACE
  204238. /********* End of inlined file: juce_win32_FileChooser.cpp *********/
  204239. /********* Start of inlined file: juce_win32_Fonts.cpp *********/
  204240. BEGIN_JUCE_NAMESPACE
  204241. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  204242. NEWTEXTMETRICEXW*,
  204243. int type,
  204244. LPARAM lParam)
  204245. {
  204246. if (lpelfe != 0 && type == TRUETYPE_FONTTYPE)
  204247. {
  204248. const String fontName (lpelfe->elfLogFont.lfFaceName);
  204249. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters (T("@")));
  204250. }
  204251. return 1;
  204252. }
  204253. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  204254. NEWTEXTMETRICEXW*,
  204255. int type,
  204256. LPARAM lParam)
  204257. {
  204258. if (lpelfe != 0
  204259. && ((type & (DEVICE_FONTTYPE | RASTER_FONTTYPE)) == 0))
  204260. {
  204261. LOGFONTW lf;
  204262. zerostruct (lf);
  204263. lf.lfWeight = FW_DONTCARE;
  204264. lf.lfOutPrecision = OUT_TT_ONLY_PRECIS;
  204265. lf.lfQuality = DEFAULT_QUALITY;
  204266. lf.lfCharSet = DEFAULT_CHARSET;
  204267. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204268. lf.lfPitchAndFamily = FF_DONTCARE;
  204269. const String fontName (lpelfe->elfLogFont.lfFaceName);
  204270. fontName.copyToBuffer (lf.lfFaceName, LF_FACESIZE - 1);
  204271. HDC dc = CreateCompatibleDC (0);
  204272. EnumFontFamiliesEx (dc, &lf,
  204273. (FONTENUMPROCW) &wfontEnum2,
  204274. lParam, 0);
  204275. DeleteDC (dc);
  204276. }
  204277. return 1;
  204278. }
  204279. const StringArray Font::findAllTypefaceNames() throw()
  204280. {
  204281. StringArray results;
  204282. HDC dc = CreateCompatibleDC (0);
  204283. {
  204284. LOGFONTW lf;
  204285. zerostruct (lf);
  204286. lf.lfWeight = FW_DONTCARE;
  204287. lf.lfOutPrecision = OUT_TT_ONLY_PRECIS;
  204288. lf.lfQuality = DEFAULT_QUALITY;
  204289. lf.lfCharSet = DEFAULT_CHARSET;
  204290. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204291. lf.lfPitchAndFamily = FF_DONTCARE;
  204292. lf.lfFaceName[0] = 0;
  204293. EnumFontFamiliesEx (dc, &lf,
  204294. (FONTENUMPROCW) &wfontEnum1,
  204295. (LPARAM) &results, 0);
  204296. }
  204297. DeleteDC (dc);
  204298. results.sort (true);
  204299. return results;
  204300. }
  204301. extern bool juce_IsRunningInWine() throw();
  204302. void Font::getDefaultFontNames (String& defaultSans,
  204303. String& defaultSerif,
  204304. String& defaultFixed) throw()
  204305. {
  204306. if (juce_IsRunningInWine())
  204307. {
  204308. // If we're running in Wine, then use fonts that might be available on Linux..
  204309. defaultSans = "Bitstream Vera Sans";
  204310. defaultSerif = "Bitstream Vera Serif";
  204311. defaultFixed = "Bitstream Vera Sans Mono";
  204312. }
  204313. else
  204314. {
  204315. defaultSans = "Verdana";
  204316. defaultSerif = "Times";
  204317. defaultFixed = "Lucida Console";
  204318. }
  204319. }
  204320. class FontDCHolder : private DeletedAtShutdown
  204321. {
  204322. HDC dc;
  204323. String fontName;
  204324. KERNINGPAIR* kps;
  204325. int numKPs;
  204326. bool bold, italic;
  204327. int size;
  204328. FontDCHolder (const FontDCHolder&);
  204329. const FontDCHolder& operator= (const FontDCHolder&);
  204330. public:
  204331. HFONT fontH;
  204332. FontDCHolder() throw()
  204333. : dc (0),
  204334. kps (0),
  204335. numKPs (0),
  204336. bold (false),
  204337. italic (false),
  204338. size (0)
  204339. {
  204340. }
  204341. ~FontDCHolder() throw()
  204342. {
  204343. if (dc != 0)
  204344. {
  204345. DeleteDC (dc);
  204346. DeleteObject (fontH);
  204347. juce_free (kps);
  204348. }
  204349. clearSingletonInstance();
  204350. }
  204351. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  204352. HDC loadFont (const String& fontName_,
  204353. const bool bold_,
  204354. const bool italic_,
  204355. const int size_) throw()
  204356. {
  204357. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  204358. {
  204359. fontName = fontName_;
  204360. bold = bold_;
  204361. italic = italic_;
  204362. size = size_;
  204363. if (dc != 0)
  204364. {
  204365. DeleteDC (dc);
  204366. DeleteObject (fontH);
  204367. juce_free (kps);
  204368. kps = 0;
  204369. }
  204370. fontH = 0;
  204371. dc = CreateCompatibleDC (0);
  204372. SetMapperFlags (dc, 0);
  204373. SetMapMode (dc, MM_TEXT);
  204374. LOGFONTW lfw;
  204375. zerostruct (lfw);
  204376. lfw.lfCharSet = DEFAULT_CHARSET;
  204377. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204378. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  204379. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  204380. lfw.lfQuality = PROOF_QUALITY;
  204381. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  204382. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  204383. fontName.copyToBuffer (lfw.lfFaceName, LF_FACESIZE - 1);
  204384. lfw.lfHeight = size > 0 ? size : -256;
  204385. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  204386. if (standardSizedFont != 0)
  204387. {
  204388. if (SelectObject (dc, standardSizedFont) != 0)
  204389. {
  204390. fontH = standardSizedFont;
  204391. if (size == 0)
  204392. {
  204393. OUTLINETEXTMETRIC otm;
  204394. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  204395. {
  204396. lfw.lfHeight = -(int) otm.otmEMSquare;
  204397. fontH = CreateFontIndirect (&lfw);
  204398. SelectObject (dc, fontH);
  204399. DeleteObject (standardSizedFont);
  204400. }
  204401. }
  204402. }
  204403. else
  204404. {
  204405. jassertfalse
  204406. }
  204407. }
  204408. else
  204409. {
  204410. jassertfalse
  204411. }
  204412. }
  204413. return dc;
  204414. }
  204415. KERNINGPAIR* getKerningPairs (int& numKPs_) throw()
  204416. {
  204417. if (kps == 0)
  204418. {
  204419. numKPs = GetKerningPairs (dc, 0, 0);
  204420. kps = (KERNINGPAIR*) juce_calloc (sizeof (KERNINGPAIR) * numKPs);
  204421. GetKerningPairs (dc, numKPs, kps);
  204422. }
  204423. numKPs_ = numKPs;
  204424. return kps;
  204425. }
  204426. };
  204427. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  204428. static bool addGlyphToTypeface (HDC dc,
  204429. juce_wchar character,
  204430. Typeface& dest,
  204431. bool addKerning)
  204432. {
  204433. Path destShape;
  204434. GLYPHMETRICS gm;
  204435. float height;
  204436. BOOL ok = false;
  204437. {
  204438. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  204439. WORD index = 0;
  204440. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  204441. && index == 0xffff)
  204442. {
  204443. return false;
  204444. }
  204445. }
  204446. TEXTMETRIC tm;
  204447. ok = GetTextMetrics (dc, &tm);
  204448. height = (float) tm.tmHeight;
  204449. if (! ok)
  204450. {
  204451. dest.addGlyph (character, destShape, 0);
  204452. return true;
  204453. }
  204454. const float scaleX = 1.0f / height;
  204455. const float scaleY = -1.0f / height;
  204456. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  204457. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  204458. &gm, 0, 0, &identityMatrix);
  204459. if (bufSize > 0)
  204460. {
  204461. char* const data = (char*) juce_malloc (bufSize);
  204462. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  204463. bufSize, data, &identityMatrix);
  204464. const TTPOLYGONHEADER* pheader = (TTPOLYGONHEADER*) data;
  204465. while ((char*) pheader < data + bufSize)
  204466. {
  204467. #define remapX(v) (scaleX * (v).x.value)
  204468. #define remapY(v) (scaleY * (v).y.value)
  204469. float x = remapX (pheader->pfxStart);
  204470. float y = remapY (pheader->pfxStart);
  204471. destShape.startNewSubPath (x, y);
  204472. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  204473. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  204474. while ((const char*) curve < curveEnd)
  204475. {
  204476. if (curve->wType == TT_PRIM_LINE)
  204477. {
  204478. for (int i = 0; i < curve->cpfx; ++i)
  204479. {
  204480. x = remapX (curve->apfx [i]);
  204481. y = remapY (curve->apfx [i]);
  204482. destShape.lineTo (x, y);
  204483. }
  204484. }
  204485. else if (curve->wType == TT_PRIM_QSPLINE)
  204486. {
  204487. for (int i = 0; i < curve->cpfx - 1; ++i)
  204488. {
  204489. const float x2 = remapX (curve->apfx [i]);
  204490. const float y2 = remapY (curve->apfx [i]);
  204491. float x3, y3;
  204492. if (i < curve->cpfx - 2)
  204493. {
  204494. x3 = 0.5f * (x2 + remapX (curve->apfx [i + 1]));
  204495. y3 = 0.5f * (y2 + remapY (curve->apfx [i + 1]));
  204496. }
  204497. else
  204498. {
  204499. x3 = remapX (curve->apfx [i + 1]);
  204500. y3 = remapY (curve->apfx [i + 1]);
  204501. }
  204502. destShape.quadraticTo (x2, y2, x3, y3);
  204503. x = x3;
  204504. y = y3;
  204505. }
  204506. }
  204507. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  204508. }
  204509. pheader = (const TTPOLYGONHEADER*) curve;
  204510. destShape.closeSubPath();
  204511. }
  204512. juce_free (data);
  204513. }
  204514. dest.addGlyph (character, destShape, gm.gmCellIncX / height);
  204515. if (addKerning)
  204516. {
  204517. int numKPs;
  204518. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  204519. for (int i = 0; i < numKPs; ++i)
  204520. {
  204521. if (kps[i].wFirst == character)
  204522. {
  204523. dest.addKerningPair (kps[i].wFirst,
  204524. kps[i].wSecond,
  204525. kps[i].iKernAmount / height);
  204526. }
  204527. }
  204528. }
  204529. return true;
  204530. }
  204531. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  204532. {
  204533. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), 0);
  204534. return addGlyphToTypeface (dc, character, *this, true);
  204535. }
  204536. /*Image* Typeface::renderGlyphToImage (juce_wchar character, float& topLeftX, float& topLeftY)
  204537. {
  204538. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), hintingSize);
  204539. int bufSize;
  204540. GLYPHMETRICS gm;
  204541. const UINT format = GGO_GRAY2_BITMAP;
  204542. const int shift = 6;
  204543. if (wGetGlyphOutlineW != 0)
  204544. bufSize = wGetGlyphOutlineW (dc, character, format, &gm, 0, 0, &identityMatrix);
  204545. else
  204546. bufSize = GetGlyphOutline (dc, character, format, &gm, 0, 0, &identityMatrix);
  204547. Image* im = new Image (Image::SingleChannel, jmax (1, gm.gmBlackBoxX), jmax (1, gm.gmBlackBoxY), true);
  204548. if (bufSize > 0)
  204549. {
  204550. topLeftX = (float) gm.gmptGlyphOrigin.x;
  204551. topLeftY = (float) -gm.gmptGlyphOrigin.y;
  204552. uint8* const data = (uint8*) juce_calloc (bufSize);
  204553. if (wGetGlyphOutlineW != 0)
  204554. wGetGlyphOutlineW (dc, character, format, &gm, bufSize, data, &identityMatrix);
  204555. else
  204556. GetGlyphOutline (dc, character, format, &gm, bufSize, data, &identityMatrix);
  204557. const int stride = ((gm.gmBlackBoxX + 3) & ~3);
  204558. for (int y = gm.gmBlackBoxY; --y >= 0;)
  204559. {
  204560. for (int x = gm.gmBlackBoxX; --x >= 0;)
  204561. {
  204562. const int level = data [x + y * stride] << shift;
  204563. if (level > 0)
  204564. im->setPixelAt (x, y, Colour ((uint8) 0xff, (uint8) 0xff, (uint8) 0xff, (uint8) jmin (0xff, level)));
  204565. }
  204566. }
  204567. juce_free (data);
  204568. }
  204569. return im;
  204570. }*/
  204571. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  204572. bool bold,
  204573. bool italic,
  204574. bool addAllGlyphsToFont) throw()
  204575. {
  204576. clear();
  204577. HDC dc = FontDCHolder::getInstance()->loadFont (fontName, bold, italic, 0);
  204578. float height;
  204579. int firstChar, lastChar;
  204580. {
  204581. TEXTMETRIC tm;
  204582. GetTextMetrics (dc, &tm);
  204583. height = (float) tm.tmHeight;
  204584. firstChar = tm.tmFirstChar;
  204585. lastChar = tm.tmLastChar;
  204586. setAscent (tm.tmAscent / height);
  204587. setDefaultCharacter (tm.tmDefaultChar);
  204588. }
  204589. setName (fontName);
  204590. setBold (bold);
  204591. setItalic (italic);
  204592. if (addAllGlyphsToFont)
  204593. {
  204594. for (int character = firstChar; character <= lastChar; ++character)
  204595. addGlyphToTypeface (dc, (juce_wchar) character, *this, false);
  204596. int numKPs;
  204597. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  204598. for (int i = 0; i < numKPs; ++i)
  204599. {
  204600. addKerningPair (kps[i].wFirst,
  204601. kps[i].wSecond,
  204602. kps[i].iKernAmount / height);
  204603. }
  204604. }
  204605. }
  204606. END_JUCE_NAMESPACE
  204607. /********* End of inlined file: juce_win32_Fonts.cpp *********/
  204608. /********* Start of inlined file: juce_win32_Messaging.cpp *********/
  204609. BEGIN_JUCE_NAMESPACE
  204610. static const unsigned int specialId = WM_APP + 0x4400;
  204611. static const unsigned int broadcastId = WM_APP + 0x4403;
  204612. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  204613. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  204614. HWND juce_messageWindowHandle = 0;
  204615. extern long improbableWindowNumber; // defined in windowing.cpp
  204616. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  204617. const UINT message,
  204618. const WPARAM wParam,
  204619. const LPARAM lParam) throw()
  204620. {
  204621. JUCE_TRY
  204622. {
  204623. if (h == juce_messageWindowHandle)
  204624. {
  204625. if (message == specialCallbackId)
  204626. {
  204627. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  204628. return (LRESULT) (*func) ((void*) lParam);
  204629. }
  204630. else if (message == specialId)
  204631. {
  204632. // these are trapped early in the dispatch call, but must also be checked
  204633. // here in case there are windows modal dialog boxes doing their own
  204634. // dispatch loop and not calling our version
  204635. MessageManager::getInstance()->deliverMessage ((void*) lParam);
  204636. return 0;
  204637. }
  204638. else if (message == broadcastId)
  204639. {
  204640. String* const messageString = (String*) lParam;
  204641. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  204642. delete messageString;
  204643. return 0;
  204644. }
  204645. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  204646. {
  204647. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  204648. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  204649. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  204650. return 0;
  204651. }
  204652. }
  204653. }
  204654. JUCE_CATCH_EXCEPTION
  204655. return DefWindowProc (h, message, wParam, lParam);
  204656. }
  204657. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  204658. {
  204659. MSG m;
  204660. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  204661. return false;
  204662. if (GetMessage (&m, (HWND) 0, 0, 0) > 0)
  204663. {
  204664. if (m.message == specialId
  204665. && m.hwnd == juce_messageWindowHandle)
  204666. {
  204667. MessageManager::getInstance()->deliverMessage ((void*) m.lParam);
  204668. }
  204669. else
  204670. {
  204671. if (GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber
  204672. && (m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN))
  204673. {
  204674. // if it's someone else's window being clicked on, and the focus is
  204675. // currently on a juce window, pass the kb focus over..
  204676. HWND currentFocus = GetFocus();
  204677. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  204678. SetFocus (m.hwnd);
  204679. }
  204680. TranslateMessage (&m);
  204681. DispatchMessage (&m);
  204682. }
  204683. }
  204684. return true;
  204685. }
  204686. bool juce_postMessageToSystemQueue (void* message)
  204687. {
  204688. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  204689. }
  204690. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  204691. void* userData)
  204692. {
  204693. if (MessageManager::getInstance()->isThisTheMessageThread())
  204694. {
  204695. return (*callback) (userData);
  204696. }
  204697. else
  204698. {
  204699. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  204700. // deadlock because the message manager is blocked from running, and can't
  204701. // call your function..
  204702. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  204703. return (void*) SendMessage (juce_messageWindowHandle,
  204704. specialCallbackId,
  204705. (WPARAM) callback,
  204706. (LPARAM) userData);
  204707. }
  204708. }
  204709. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  204710. {
  204711. if (hwnd != juce_messageWindowHandle)
  204712. (reinterpret_cast <VoidArray*> (lParam))->add ((void*) hwnd);
  204713. return TRUE;
  204714. }
  204715. void MessageManager::broadcastMessage (const String& value) throw()
  204716. {
  204717. VoidArray windows;
  204718. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  204719. const String localCopy (value);
  204720. COPYDATASTRUCT data;
  204721. data.dwData = broadcastId;
  204722. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  204723. data.lpData = (void*) (const juce_wchar*) localCopy;
  204724. for (int i = windows.size(); --i >= 0;)
  204725. {
  204726. HWND hwnd = (HWND) windows.getUnchecked(i);
  204727. TCHAR windowName [64]; // no need to read longer strings than this
  204728. GetWindowText (hwnd, windowName, 64);
  204729. windowName [63] = 0;
  204730. if (String (windowName) == String (messageWindowName))
  204731. {
  204732. DWORD_PTR result;
  204733. SendMessageTimeout (hwnd, WM_COPYDATA,
  204734. (WPARAM) juce_messageWindowHandle,
  204735. (LPARAM) &data,
  204736. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  204737. 8000,
  204738. &result);
  204739. }
  204740. }
  204741. }
  204742. static const String getMessageWindowClassName()
  204743. {
  204744. // this name has to be different for each app/dll instance because otherwise
  204745. // poor old Win32 can get a bit confused (even despite it not being a process-global
  204746. // window class).
  204747. static int number = 0;
  204748. if (number == 0)
  204749. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  204750. return T("JUCEcs_") + String (number);
  204751. }
  204752. void MessageManager::doPlatformSpecificInitialisation()
  204753. {
  204754. OleInitialize (0);
  204755. const String className (getMessageWindowClassName());
  204756. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204757. WNDCLASSEX wc;
  204758. zerostruct (wc);
  204759. wc.cbSize = sizeof (wc);
  204760. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  204761. wc.cbWndExtra = 4;
  204762. wc.hInstance = hmod;
  204763. wc.lpszClassName = className;
  204764. RegisterClassEx (&wc);
  204765. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  204766. messageWindowName,
  204767. 0, 0, 0, 0, 0, 0, 0,
  204768. hmod, 0);
  204769. }
  204770. void MessageManager::doPlatformSpecificShutdown()
  204771. {
  204772. DestroyWindow (juce_messageWindowHandle);
  204773. UnregisterClass (getMessageWindowClassName(), 0);
  204774. OleUninitialize();
  204775. }
  204776. END_JUCE_NAMESPACE
  204777. /********* End of inlined file: juce_win32_Messaging.cpp *********/
  204778. /********* Start of inlined file: juce_win32_Midi.cpp *********/
  204779. BEGIN_JUCE_NAMESPACE
  204780. #if JUCE_MSVC
  204781. #pragma warning (disable: 4312)
  204782. #endif
  204783. using ::free;
  204784. static const int midiBufferSize = 1024 * 10;
  204785. static const int numInHeaders = 32;
  204786. static const int inBufferSize = 256;
  204787. static Array <void*, CriticalSection> activeMidiThreads;
  204788. class MidiInThread : public Thread
  204789. {
  204790. public:
  204791. MidiInThread (MidiInput* const input_,
  204792. MidiInputCallback* const callback_)
  204793. : Thread ("Juce Midi"),
  204794. hIn (0),
  204795. input (input_),
  204796. callback (callback_),
  204797. isStarted (false),
  204798. startTime (0),
  204799. pendingLength(0)
  204800. {
  204801. for (int i = numInHeaders; --i >= 0;)
  204802. {
  204803. zeromem (&hdr[i], sizeof (MIDIHDR));
  204804. hdr[i].lpData = inData[i];
  204805. hdr[i].dwBufferLength = inBufferSize;
  204806. }
  204807. };
  204808. ~MidiInThread()
  204809. {
  204810. stop();
  204811. if (hIn != 0)
  204812. {
  204813. int count = 5;
  204814. while (--count >= 0)
  204815. {
  204816. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  204817. break;
  204818. Sleep (20);
  204819. }
  204820. }
  204821. }
  204822. void handle (const uint32 message, const uint32 timeStamp) throw()
  204823. {
  204824. const int byte = message & 0xff;
  204825. if (byte < 0x80)
  204826. return;
  204827. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  204828. const double time = timeStampToTime (timeStamp);
  204829. lock.enter();
  204830. if (pendingLength < midiBufferSize - 12)
  204831. {
  204832. char* const p = pending + pendingLength;
  204833. *(double*) p = time;
  204834. *(uint32*) (p + 8) = numBytes;
  204835. *(uint32*) (p + 12) = message;
  204836. pendingLength += 12 + numBytes;
  204837. }
  204838. else
  204839. {
  204840. jassertfalse // midi buffer overflow! You might need to increase the size..
  204841. }
  204842. lock.exit();
  204843. notify();
  204844. }
  204845. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp) throw()
  204846. {
  204847. const int num = hdr->dwBytesRecorded;
  204848. if (num > 0)
  204849. {
  204850. const double time = timeStampToTime (timeStamp);
  204851. lock.enter();
  204852. if (pendingLength < midiBufferSize - (8 + num))
  204853. {
  204854. char* const p = pending + pendingLength;
  204855. *(double*) p = time;
  204856. *(uint32*) (p + 8) = num;
  204857. memcpy (p + 12, hdr->lpData, num);
  204858. pendingLength += 12 + num;
  204859. }
  204860. else
  204861. {
  204862. jassertfalse // midi buffer overflow! You might need to increase the size..
  204863. }
  204864. lock.exit();
  204865. notify();
  204866. }
  204867. }
  204868. void writeBlock (const int i) throw()
  204869. {
  204870. hdr[i].dwBytesRecorded = 0;
  204871. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  204872. jassert (res == MMSYSERR_NOERROR);
  204873. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  204874. jassert (res == MMSYSERR_NOERROR);
  204875. }
  204876. void run()
  204877. {
  204878. MemoryBlock pendingCopy (64);
  204879. while (! threadShouldExit())
  204880. {
  204881. for (int i = 0; i < numInHeaders; ++i)
  204882. {
  204883. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  204884. {
  204885. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  204886. (void) res;
  204887. jassert (res == MMSYSERR_NOERROR);
  204888. writeBlock (i);
  204889. }
  204890. }
  204891. lock.enter();
  204892. int len = pendingLength;
  204893. if (len > 0)
  204894. {
  204895. pendingCopy.ensureSize (len);
  204896. pendingCopy.copyFrom (pending, 0, len);
  204897. pendingLength = 0;
  204898. }
  204899. lock.exit();
  204900. //xxx needs to figure out if blocks are broken up or not
  204901. if (len == 0)
  204902. {
  204903. wait (500);
  204904. }
  204905. else
  204906. {
  204907. const char* p = (const char*) pendingCopy.getData();
  204908. while (len > 0)
  204909. {
  204910. const double time = *(const double*) p;
  204911. const int messageLen = *(const int*) (p + 8);
  204912. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  204913. callback->handleIncomingMidiMessage (input, message);
  204914. p += 12 + messageLen;
  204915. len -= 12 + messageLen;
  204916. }
  204917. }
  204918. }
  204919. }
  204920. void start() throw()
  204921. {
  204922. jassert (hIn != 0);
  204923. if (hIn != 0 && ! isStarted)
  204924. {
  204925. stop();
  204926. activeMidiThreads.addIfNotAlreadyThere (this);
  204927. int i;
  204928. for (i = 0; i < numInHeaders; ++i)
  204929. writeBlock (i);
  204930. startTime = Time::getMillisecondCounter();
  204931. MMRESULT res = midiInStart (hIn);
  204932. jassert (res == MMSYSERR_NOERROR);
  204933. if (res == MMSYSERR_NOERROR)
  204934. {
  204935. isStarted = true;
  204936. pendingLength = 0;
  204937. startThread (6);
  204938. }
  204939. }
  204940. }
  204941. void stop() throw()
  204942. {
  204943. if (isStarted)
  204944. {
  204945. stopThread (5000);
  204946. midiInReset (hIn);
  204947. midiInStop (hIn);
  204948. activeMidiThreads.removeValue (this);
  204949. lock.enter();
  204950. lock.exit();
  204951. for (int i = numInHeaders; --i >= 0;)
  204952. {
  204953. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  204954. {
  204955. int c = 10;
  204956. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  204957. Sleep (20);
  204958. jassert (c >= 0);
  204959. }
  204960. }
  204961. isStarted = false;
  204962. pendingLength = 0;
  204963. }
  204964. }
  204965. juce_UseDebuggingNewOperator
  204966. HMIDIIN hIn;
  204967. private:
  204968. MidiInput* input;
  204969. MidiInputCallback* callback;
  204970. bool isStarted;
  204971. uint32 startTime;
  204972. CriticalSection lock;
  204973. MIDIHDR hdr [numInHeaders];
  204974. char inData [numInHeaders] [inBufferSize];
  204975. int pendingLength;
  204976. char pending [midiBufferSize];
  204977. double timeStampToTime (uint32 timeStamp) throw()
  204978. {
  204979. timeStamp += startTime;
  204980. const uint32 now = Time::getMillisecondCounter();
  204981. if (timeStamp > now)
  204982. {
  204983. if (timeStamp > now + 2)
  204984. --startTime;
  204985. timeStamp = now;
  204986. }
  204987. return 0.001 * timeStamp;
  204988. }
  204989. MidiInThread (const MidiInThread&);
  204990. const MidiInThread& operator= (const MidiInThread&);
  204991. };
  204992. static void CALLBACK midiInCallback (HMIDIIN,
  204993. UINT uMsg,
  204994. DWORD_PTR dwInstance,
  204995. DWORD_PTR midiMessage,
  204996. DWORD_PTR timeStamp)
  204997. {
  204998. MidiInThread* const thread = (MidiInThread*) dwInstance;
  204999. if (thread != 0 && activeMidiThreads.contains (thread))
  205000. {
  205001. if (uMsg == MIM_DATA)
  205002. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  205003. else if (uMsg == MIM_LONGDATA)
  205004. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  205005. }
  205006. }
  205007. const StringArray MidiInput::getDevices()
  205008. {
  205009. StringArray s;
  205010. const int num = midiInGetNumDevs();
  205011. for (int i = 0; i < num; ++i)
  205012. {
  205013. MIDIINCAPS mc;
  205014. zerostruct (mc);
  205015. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  205016. s.add (String (mc.szPname, sizeof (mc.szPname)));
  205017. }
  205018. return s;
  205019. }
  205020. int MidiInput::getDefaultDeviceIndex()
  205021. {
  205022. return 0;
  205023. }
  205024. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  205025. {
  205026. if (callback == 0)
  205027. return 0;
  205028. UINT deviceId = MIDI_MAPPER;
  205029. int n = 0;
  205030. String name;
  205031. const int num = midiInGetNumDevs();
  205032. for (int i = 0; i < num; ++i)
  205033. {
  205034. MIDIINCAPS mc;
  205035. zerostruct (mc);
  205036. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  205037. {
  205038. if (index == n)
  205039. {
  205040. deviceId = i;
  205041. name = String (mc.szPname, sizeof (mc.szPname));
  205042. break;
  205043. }
  205044. ++n;
  205045. }
  205046. }
  205047. MidiInput* const in = new MidiInput (name);
  205048. MidiInThread* const thread = new MidiInThread (in, callback);
  205049. HMIDIIN h;
  205050. HRESULT err = midiInOpen (&h, deviceId,
  205051. (DWORD_PTR) &midiInCallback,
  205052. (DWORD_PTR) thread,
  205053. CALLBACK_FUNCTION);
  205054. if (err == MMSYSERR_NOERROR)
  205055. {
  205056. thread->hIn = h;
  205057. in->internal = (void*) thread;
  205058. return in;
  205059. }
  205060. else
  205061. {
  205062. delete in;
  205063. delete thread;
  205064. return 0;
  205065. }
  205066. }
  205067. MidiInput::MidiInput (const String& name_)
  205068. : name (name_),
  205069. internal (0)
  205070. {
  205071. }
  205072. MidiInput::~MidiInput()
  205073. {
  205074. if (internal != 0)
  205075. {
  205076. MidiInThread* const thread = (MidiInThread*) internal;
  205077. delete thread;
  205078. }
  205079. }
  205080. void MidiInput::start()
  205081. {
  205082. ((MidiInThread*) internal)->start();
  205083. }
  205084. void MidiInput::stop()
  205085. {
  205086. ((MidiInThread*) internal)->stop();
  205087. }
  205088. struct MidiOutHandle
  205089. {
  205090. int refCount;
  205091. UINT deviceId;
  205092. HMIDIOUT handle;
  205093. juce_UseDebuggingNewOperator
  205094. };
  205095. static VoidArray handles (4);
  205096. const StringArray MidiOutput::getDevices()
  205097. {
  205098. StringArray s;
  205099. const int num = midiOutGetNumDevs();
  205100. for (int i = 0; i < num; ++i)
  205101. {
  205102. MIDIOUTCAPS mc;
  205103. zerostruct (mc);
  205104. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  205105. s.add (String (mc.szPname, sizeof (mc.szPname)));
  205106. }
  205107. return s;
  205108. }
  205109. int MidiOutput::getDefaultDeviceIndex()
  205110. {
  205111. const int num = midiOutGetNumDevs();
  205112. int n = 0;
  205113. for (int i = 0; i < num; ++i)
  205114. {
  205115. MIDIOUTCAPS mc;
  205116. zerostruct (mc);
  205117. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  205118. {
  205119. if ((mc.wTechnology & MOD_MAPPER) != 0)
  205120. return n;
  205121. ++n;
  205122. }
  205123. }
  205124. return 0;
  205125. }
  205126. MidiOutput* MidiOutput::openDevice (int index)
  205127. {
  205128. UINT deviceId = MIDI_MAPPER;
  205129. const int num = midiOutGetNumDevs();
  205130. int i, n = 0;
  205131. for (i = 0; i < num; ++i)
  205132. {
  205133. MIDIOUTCAPS mc;
  205134. zerostruct (mc);
  205135. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  205136. {
  205137. // use the microsoft sw synth as a default - best not to allow deviceId
  205138. // to be MIDI_MAPPER, or else device sharing breaks
  205139. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase (T("microsoft")))
  205140. deviceId = i;
  205141. if (index == n)
  205142. {
  205143. deviceId = i;
  205144. break;
  205145. }
  205146. ++n;
  205147. }
  205148. }
  205149. for (i = handles.size(); --i >= 0;)
  205150. {
  205151. MidiOutHandle* const han = (MidiOutHandle*) handles.getUnchecked(i);
  205152. if (han != 0 && han->deviceId == deviceId)
  205153. {
  205154. han->refCount++;
  205155. MidiOutput* const out = new MidiOutput();
  205156. out->internal = (void*) han;
  205157. return out;
  205158. }
  205159. }
  205160. for (i = 4; --i >= 0;)
  205161. {
  205162. HMIDIOUT h = 0;
  205163. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  205164. if (res == MMSYSERR_NOERROR)
  205165. {
  205166. MidiOutHandle* const han = new MidiOutHandle();
  205167. han->deviceId = deviceId;
  205168. han->refCount = 1;
  205169. han->handle = h;
  205170. handles.add (han);
  205171. MidiOutput* const out = new MidiOutput();
  205172. out->internal = (void*) han;
  205173. return out;
  205174. }
  205175. else if (res == MMSYSERR_ALLOCATED)
  205176. {
  205177. Sleep (100);
  205178. }
  205179. else
  205180. {
  205181. break;
  205182. }
  205183. }
  205184. return 0;
  205185. }
  205186. MidiOutput::~MidiOutput()
  205187. {
  205188. MidiOutHandle* const h = (MidiOutHandle*) internal;
  205189. if (handles.contains ((void*) h) && --(h->refCount) == 0)
  205190. {
  205191. midiOutClose (h->handle);
  205192. handles.removeValue ((void*) h);
  205193. delete h;
  205194. }
  205195. }
  205196. void MidiOutput::reset()
  205197. {
  205198. const MidiOutHandle* const h = (MidiOutHandle*) internal;
  205199. midiOutReset (h->handle);
  205200. }
  205201. bool MidiOutput::getVolume (float& leftVol,
  205202. float& rightVol)
  205203. {
  205204. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  205205. DWORD n;
  205206. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  205207. {
  205208. const unsigned short* const nn = (const unsigned short*) &n;
  205209. rightVol = nn[0] / (float) 0xffff;
  205210. leftVol = nn[1] / (float) 0xffff;
  205211. return true;
  205212. }
  205213. else
  205214. {
  205215. rightVol = leftVol = 1.0f;
  205216. return false;
  205217. }
  205218. }
  205219. void MidiOutput::setVolume (float leftVol,
  205220. float rightVol)
  205221. {
  205222. const MidiOutHandle* const handle = (MidiOutHandle*) internal;
  205223. DWORD n;
  205224. unsigned short* const nn = (unsigned short*) &n;
  205225. nn[0] = (unsigned short) jlimit (0, 0xffff, (int)(rightVol * 0xffff));
  205226. nn[1] = (unsigned short) jlimit (0, 0xffff, (int)(leftVol * 0xffff));
  205227. midiOutSetVolume (handle->handle, n);
  205228. }
  205229. void MidiOutput::sendMessageNow (const MidiMessage& message)
  205230. {
  205231. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  205232. if (message.getRawDataSize() > 3
  205233. || message.isSysEx())
  205234. {
  205235. MIDIHDR h;
  205236. zerostruct (h);
  205237. h.lpData = (char*) message.getRawData();
  205238. h.dwBufferLength = message.getRawDataSize();
  205239. h.dwBytesRecorded = message.getRawDataSize();
  205240. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  205241. {
  205242. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  205243. if (res == MMSYSERR_NOERROR)
  205244. {
  205245. while ((h.dwFlags & MHDR_DONE) == 0)
  205246. Sleep (1);
  205247. int count = 500; // 1 sec timeout
  205248. while (--count >= 0)
  205249. {
  205250. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  205251. if (res == MIDIERR_STILLPLAYING)
  205252. Sleep (2);
  205253. else
  205254. break;
  205255. }
  205256. }
  205257. }
  205258. }
  205259. else
  205260. {
  205261. midiOutShortMsg (handle->handle,
  205262. *(unsigned int*) message.getRawData());
  205263. }
  205264. }
  205265. END_JUCE_NAMESPACE
  205266. /********* End of inlined file: juce_win32_Midi.cpp *********/
  205267. /********* Start of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  205268. #ifdef _MSC_VER
  205269. #pragma warning (disable: 4514)
  205270. #pragma warning (push)
  205271. #endif
  205272. #include <comutil.h>
  205273. #include <Exdisp.h>
  205274. #include <exdispid.h>
  205275. #ifdef _MSC_VER
  205276. #pragma warning (pop)
  205277. #pragma warning (disable: 4312 4244)
  205278. #endif
  205279. BEGIN_JUCE_NAMESPACE
  205280. class WebBrowserComponentInternal : public ActiveXControlComponent
  205281. {
  205282. public:
  205283. WebBrowserComponentInternal()
  205284. : browser (0),
  205285. connectionPoint (0),
  205286. adviseCookie (0)
  205287. {
  205288. }
  205289. ~WebBrowserComponentInternal()
  205290. {
  205291. if (connectionPoint != 0)
  205292. connectionPoint->Unadvise (adviseCookie);
  205293. if (browser != 0)
  205294. browser->Release();
  205295. }
  205296. void createBrowser()
  205297. {
  205298. createControl (&CLSID_WebBrowser);
  205299. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  205300. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  205301. if (connectionPointContainer != 0)
  205302. {
  205303. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  205304. &connectionPoint);
  205305. if (connectionPoint != 0)
  205306. {
  205307. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  205308. jassert (owner != 0);
  205309. EventHandler* handler = new EventHandler (owner);
  205310. connectionPoint->Advise (handler, &adviseCookie);
  205311. }
  205312. }
  205313. }
  205314. void goToURL (const String& url,
  205315. const StringArray* headers,
  205316. const MemoryBlock* postData)
  205317. {
  205318. if (browser != 0)
  205319. {
  205320. LPSAFEARRAY sa = 0;
  205321. _variant_t flags, frame, postDataVar, headersVar;
  205322. if (headers != 0)
  205323. headersVar = (const tchar*) headers->joinIntoString ("\r\n");
  205324. if (postData != 0 && postData->getSize() > 0)
  205325. {
  205326. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  205327. if (sa != 0)
  205328. {
  205329. void* data = 0;
  205330. SafeArrayAccessData (sa, &data);
  205331. jassert (data != 0);
  205332. if (data != 0)
  205333. {
  205334. postData->copyTo (data, 0, postData->getSize());
  205335. SafeArrayUnaccessData (sa);
  205336. VARIANT postDataVar2;
  205337. VariantInit (&postDataVar2);
  205338. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  205339. V_ARRAY (&postDataVar2) = sa;
  205340. postDataVar = postDataVar2;
  205341. }
  205342. }
  205343. }
  205344. browser->Navigate ((BSTR) (const OLECHAR*) url,
  205345. &flags, &frame,
  205346. &postDataVar, &headersVar);
  205347. if (sa != 0)
  205348. SafeArrayDestroy (sa);
  205349. }
  205350. }
  205351. IWebBrowser2* browser;
  205352. juce_UseDebuggingNewOperator
  205353. private:
  205354. IConnectionPoint* connectionPoint;
  205355. DWORD adviseCookie;
  205356. class EventHandler : public IDispatch
  205357. {
  205358. public:
  205359. EventHandler (WebBrowserComponent* owner_)
  205360. : owner (owner_),
  205361. refCount (0)
  205362. {
  205363. }
  205364. ~EventHandler()
  205365. {
  205366. }
  205367. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  205368. {
  205369. if (id == IID_IUnknown || id == IID_IDispatch || id == DIID_DWebBrowserEvents2)
  205370. {
  205371. AddRef();
  205372. *result = this;
  205373. return S_OK;
  205374. }
  205375. *result = 0;
  205376. return E_NOINTERFACE;
  205377. }
  205378. ULONG __stdcall AddRef() { return ++refCount; }
  205379. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  205380. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  205381. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  205382. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  205383. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  205384. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  205385. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  205386. UINT __RPC_FAR* /*puArgErr*/)
  205387. {
  205388. switch (dispIdMember)
  205389. {
  205390. case DISPID_BEFORENAVIGATE2:
  205391. {
  205392. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  205393. String url;
  205394. if ((vurl->vt & VT_BYREF) != 0)
  205395. url = *vurl->pbstrVal;
  205396. else
  205397. url = vurl->bstrVal;
  205398. *pDispParams->rgvarg->pboolVal
  205399. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  205400. : VARIANT_TRUE;
  205401. return S_OK;
  205402. }
  205403. default:
  205404. break;
  205405. }
  205406. return E_NOTIMPL;
  205407. }
  205408. juce_UseDebuggingNewOperator
  205409. private:
  205410. WebBrowserComponent* const owner;
  205411. int refCount;
  205412. EventHandler (const EventHandler&);
  205413. const EventHandler& operator= (const EventHandler&);
  205414. };
  205415. };
  205416. WebBrowserComponent::WebBrowserComponent()
  205417. : browser (0),
  205418. blankPageShown (false)
  205419. {
  205420. setOpaque (true);
  205421. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  205422. }
  205423. WebBrowserComponent::~WebBrowserComponent()
  205424. {
  205425. delete browser;
  205426. }
  205427. void WebBrowserComponent::goToURL (const String& url,
  205428. const StringArray* headers,
  205429. const MemoryBlock* postData)
  205430. {
  205431. lastURL = url;
  205432. lastHeaders.clear();
  205433. if (headers != 0)
  205434. lastHeaders = *headers;
  205435. lastPostData.setSize (0);
  205436. if (postData != 0)
  205437. lastPostData = *postData;
  205438. blankPageShown = false;
  205439. browser->goToURL (url, headers, postData);
  205440. }
  205441. void WebBrowserComponent::stop()
  205442. {
  205443. if (browser->browser != 0)
  205444. browser->browser->Stop();
  205445. }
  205446. void WebBrowserComponent::goBack()
  205447. {
  205448. lastURL = String::empty;
  205449. blankPageShown = false;
  205450. if (browser->browser != 0)
  205451. browser->browser->GoBack();
  205452. }
  205453. void WebBrowserComponent::goForward()
  205454. {
  205455. lastURL = String::empty;
  205456. if (browser->browser != 0)
  205457. browser->browser->GoForward();
  205458. }
  205459. void WebBrowserComponent::paint (Graphics& g)
  205460. {
  205461. if (browser->browser == 0)
  205462. g.fillAll (Colours::white);
  205463. }
  205464. void WebBrowserComponent::checkWindowAssociation()
  205465. {
  205466. if (isShowing())
  205467. {
  205468. if (browser->browser == 0 && getPeer() != 0)
  205469. {
  205470. browser->createBrowser();
  205471. reloadLastURL();
  205472. }
  205473. else
  205474. {
  205475. if (blankPageShown)
  205476. goBack();
  205477. }
  205478. }
  205479. else
  205480. {
  205481. if (browser != 0 && ! blankPageShown)
  205482. {
  205483. // when the component becomes invisible, some stuff like flash
  205484. // carries on playing audio, so we need to force it onto a blank
  205485. // page to avoid this..
  205486. blankPageShown = true;
  205487. browser->goToURL ("about:blank", 0, 0);
  205488. }
  205489. }
  205490. }
  205491. void WebBrowserComponent::reloadLastURL()
  205492. {
  205493. if (lastURL.isNotEmpty())
  205494. {
  205495. goToURL (lastURL, &lastHeaders, &lastPostData);
  205496. lastURL = String::empty;
  205497. }
  205498. }
  205499. void WebBrowserComponent::parentHierarchyChanged()
  205500. {
  205501. checkWindowAssociation();
  205502. }
  205503. void WebBrowserComponent::moved()
  205504. {
  205505. }
  205506. void WebBrowserComponent::resized()
  205507. {
  205508. browser->setSize (getWidth(), getHeight());
  205509. }
  205510. void WebBrowserComponent::visibilityChanged()
  205511. {
  205512. checkWindowAssociation();
  205513. }
  205514. bool WebBrowserComponent::pageAboutToLoad (const String&)
  205515. {
  205516. return true;
  205517. }
  205518. END_JUCE_NAMESPACE
  205519. /********* End of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  205520. /********* Start of inlined file: juce_win32_Windowing.cpp *********/
  205521. #ifdef _MSC_VER
  205522. #pragma warning (disable: 4514)
  205523. #pragma warning (push)
  205524. #endif
  205525. #include <float.h>
  205526. #include <windowsx.h>
  205527. #include <shlobj.h>
  205528. #if JUCE_OPENGL
  205529. #include <gl/gl.h>
  205530. #endif
  205531. #ifdef _MSC_VER
  205532. #pragma warning (pop)
  205533. #pragma warning (disable: 4312 4244)
  205534. #endif
  205535. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  205536. // these are in the windows SDK, but need to be repeated here for GCC..
  205537. #ifndef GET_APPCOMMAND_LPARAM
  205538. #define FAPPCOMMAND_MASK 0xF000
  205539. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  205540. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  205541. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  205542. #define APPCOMMAND_MEDIA_STOP 13
  205543. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  205544. #define WM_APPCOMMAND 0x0319
  205545. #endif
  205546. BEGIN_JUCE_NAMESPACE
  205547. extern void juce_repeatLastProcessPriority() throw(); // in juce_win32_Threads.cpp
  205548. extern void juce_CheckCurrentlyFocusedTopLevelWindow() throw(); // in juce_TopLevelWindow.cpp
  205549. extern bool juce_IsRunningInWine() throw();
  205550. #ifndef ULW_ALPHA
  205551. #define ULW_ALPHA 0x00000002
  205552. #endif
  205553. #ifndef AC_SRC_ALPHA
  205554. #define AC_SRC_ALPHA 0x01
  205555. #endif
  205556. #define DEBUG_REPAINT_TIMES 0
  205557. static HPALETTE palette = 0;
  205558. static bool createPaletteIfNeeded = true;
  205559. static bool shouldDeactivateTitleBar = true;
  205560. static bool screenSaverAllowed = true;
  205561. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  205562. #define WM_TRAYNOTIFY WM_USER + 100
  205563. using ::abs;
  205564. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  205565. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  205566. bool Desktop::canUseSemiTransparentWindows() throw()
  205567. {
  205568. if (updateLayeredWindow == 0)
  205569. {
  205570. if (! juce_IsRunningInWine())
  205571. {
  205572. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  205573. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  205574. }
  205575. }
  205576. return updateLayeredWindow != 0;
  205577. }
  205578. #undef DefWindowProc
  205579. #define DefWindowProc DefWindowProcW
  205580. const int extendedKeyModifier = 0x10000;
  205581. const int KeyPress::spaceKey = VK_SPACE;
  205582. const int KeyPress::returnKey = VK_RETURN;
  205583. const int KeyPress::escapeKey = VK_ESCAPE;
  205584. const int KeyPress::backspaceKey = VK_BACK;
  205585. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  205586. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  205587. const int KeyPress::tabKey = VK_TAB;
  205588. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  205589. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  205590. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  205591. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  205592. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  205593. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  205594. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  205595. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  205596. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  205597. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  205598. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  205599. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  205600. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  205601. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  205602. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  205603. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  205604. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  205605. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  205606. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  205607. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  205608. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  205609. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  205610. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  205611. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  205612. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  205613. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  205614. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  205615. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  205616. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  205617. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  205618. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  205619. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  205620. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  205621. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  205622. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  205623. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  205624. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  205625. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  205626. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  205627. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  205628. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  205629. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  205630. const int KeyPress::playKey = 0x30000;
  205631. const int KeyPress::stopKey = 0x30001;
  205632. const int KeyPress::fastForwardKey = 0x30002;
  205633. const int KeyPress::rewindKey = 0x30003;
  205634. class WindowsBitmapImage : public Image
  205635. {
  205636. public:
  205637. HBITMAP hBitmap;
  205638. BITMAPV4HEADER bitmapInfo;
  205639. HDC hdc;
  205640. unsigned char* bitmapData;
  205641. WindowsBitmapImage (const PixelFormat format_,
  205642. const int w, const int h, const bool clearImage)
  205643. : Image (format_, w, h)
  205644. {
  205645. jassert (format_ == RGB || format_ == ARGB);
  205646. pixelStride = (format_ == RGB) ? 3 : 4;
  205647. zerostruct (bitmapInfo);
  205648. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  205649. bitmapInfo.bV4Width = w;
  205650. bitmapInfo.bV4Height = h;
  205651. bitmapInfo.bV4Planes = 1;
  205652. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  205653. if (format_ == ARGB)
  205654. {
  205655. bitmapInfo.bV4AlphaMask = 0xff000000;
  205656. bitmapInfo.bV4RedMask = 0xff0000;
  205657. bitmapInfo.bV4GreenMask = 0xff00;
  205658. bitmapInfo.bV4BlueMask = 0xff;
  205659. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  205660. }
  205661. else
  205662. {
  205663. bitmapInfo.bV4V4Compression = BI_RGB;
  205664. }
  205665. lineStride = -((w * pixelStride + 3) & ~3);
  205666. HDC dc = GetDC (0);
  205667. hdc = CreateCompatibleDC (dc);
  205668. ReleaseDC (0, dc);
  205669. SetMapMode (hdc, MM_TEXT);
  205670. hBitmap = CreateDIBSection (hdc,
  205671. (BITMAPINFO*) &(bitmapInfo),
  205672. DIB_RGB_COLORS,
  205673. (void**) &bitmapData,
  205674. 0, 0);
  205675. SelectObject (hdc, hBitmap);
  205676. if (format_ == ARGB && clearImage)
  205677. zeromem (bitmapData, abs (h * lineStride));
  205678. imageData = bitmapData - (lineStride * (h - 1));
  205679. }
  205680. ~WindowsBitmapImage()
  205681. {
  205682. DeleteDC (hdc);
  205683. DeleteObject (hBitmap);
  205684. imageData = 0; // to stop the base class freeing this
  205685. }
  205686. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  205687. const int x, const int y,
  205688. const RectangleList& maskedRegion) throw()
  205689. {
  205690. static HDRAWDIB hdd = 0;
  205691. static bool needToCreateDrawDib = true;
  205692. if (needToCreateDrawDib)
  205693. {
  205694. needToCreateDrawDib = false;
  205695. HDC dc = GetDC (0);
  205696. const int n = GetDeviceCaps (dc, BITSPIXEL);
  205697. ReleaseDC (0, dc);
  205698. // only open if we're not palettised
  205699. if (n > 8)
  205700. hdd = DrawDibOpen();
  205701. }
  205702. if (createPaletteIfNeeded)
  205703. {
  205704. HDC dc = GetDC (0);
  205705. const int n = GetDeviceCaps (dc, BITSPIXEL);
  205706. ReleaseDC (0, dc);
  205707. if (n <= 8)
  205708. palette = CreateHalftonePalette (dc);
  205709. createPaletteIfNeeded = false;
  205710. }
  205711. if (palette != 0)
  205712. {
  205713. SelectPalette (dc, palette, FALSE);
  205714. RealizePalette (dc);
  205715. SetStretchBltMode (dc, HALFTONE);
  205716. }
  205717. SetMapMode (dc, MM_TEXT);
  205718. if (transparent)
  205719. {
  205720. POINT p, pos;
  205721. SIZE size;
  205722. RECT windowBounds;
  205723. GetWindowRect (hwnd, &windowBounds);
  205724. p.x = -x;
  205725. p.y = -y;
  205726. pos.x = windowBounds.left;
  205727. pos.y = windowBounds.top;
  205728. size.cx = windowBounds.right - windowBounds.left;
  205729. size.cy = windowBounds.bottom - windowBounds.top;
  205730. BLENDFUNCTION bf;
  205731. bf.AlphaFormat = AC_SRC_ALPHA;
  205732. bf.BlendFlags = 0;
  205733. bf.BlendOp = AC_SRC_OVER;
  205734. bf.SourceConstantAlpha = 0xff;
  205735. if (! maskedRegion.isEmpty())
  205736. {
  205737. for (RectangleList::Iterator i (maskedRegion); i.next();)
  205738. {
  205739. const Rectangle& r = *i.getRectangle();
  205740. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  205741. }
  205742. }
  205743. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  205744. }
  205745. else
  205746. {
  205747. int savedDC = 0;
  205748. if (! maskedRegion.isEmpty())
  205749. {
  205750. savedDC = SaveDC (dc);
  205751. for (RectangleList::Iterator i (maskedRegion); i.next();)
  205752. {
  205753. const Rectangle& r = *i.getRectangle();
  205754. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  205755. }
  205756. }
  205757. const int w = getWidth();
  205758. const int h = getHeight();
  205759. if (hdd == 0)
  205760. {
  205761. StretchDIBits (dc,
  205762. x, y, w, h,
  205763. 0, 0, w, h,
  205764. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  205765. DIB_RGB_COLORS, SRCCOPY);
  205766. }
  205767. else
  205768. {
  205769. DrawDibDraw (hdd, dc, x, y, -1, -1,
  205770. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  205771. 0, 0, w, h, 0);
  205772. }
  205773. if (! maskedRegion.isEmpty())
  205774. RestoreDC (dc, savedDC);
  205775. }
  205776. }
  205777. juce_UseDebuggingNewOperator
  205778. private:
  205779. WindowsBitmapImage (const WindowsBitmapImage&);
  205780. const WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  205781. };
  205782. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  205783. static int currentModifiers = 0;
  205784. static int modifiersAtLastCallback = 0;
  205785. static void updateKeyModifiers() throw()
  205786. {
  205787. currentModifiers &= ~(ModifierKeys::shiftModifier
  205788. | ModifierKeys::ctrlModifier
  205789. | ModifierKeys::altModifier);
  205790. if ((GetKeyState (VK_SHIFT) & 0x8000) != 0)
  205791. currentModifiers |= ModifierKeys::shiftModifier;
  205792. if ((GetKeyState (VK_CONTROL) & 0x8000) != 0)
  205793. currentModifiers |= ModifierKeys::ctrlModifier;
  205794. if ((GetKeyState (VK_MENU) & 0x8000) != 0)
  205795. currentModifiers |= ModifierKeys::altModifier;
  205796. if ((GetKeyState (VK_RMENU) & 0x8000) != 0)
  205797. currentModifiers &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  205798. }
  205799. void ModifierKeys::updateCurrentModifiers() throw()
  205800. {
  205801. currentModifierFlags = currentModifiers;
  205802. }
  205803. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  205804. {
  205805. SHORT k = (SHORT) keyCode;
  205806. if ((keyCode & extendedKeyModifier) == 0
  205807. && (k >= (SHORT) T('a') && k <= (SHORT) T('z')))
  205808. k += (SHORT) T('A') - (SHORT) T('a');
  205809. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  205810. (SHORT) '+', VK_OEM_PLUS,
  205811. (SHORT) '-', VK_OEM_MINUS,
  205812. (SHORT) '.', VK_OEM_PERIOD,
  205813. (SHORT) ';', VK_OEM_1,
  205814. (SHORT) ':', VK_OEM_1,
  205815. (SHORT) '/', VK_OEM_2,
  205816. (SHORT) '?', VK_OEM_2,
  205817. (SHORT) '[', VK_OEM_4,
  205818. (SHORT) ']', VK_OEM_6 };
  205819. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  205820. if (k == translatedValues [i])
  205821. k = translatedValues [i + 1];
  205822. return (GetKeyState (k) & 0x8000) != 0;
  205823. }
  205824. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  205825. {
  205826. updateKeyModifiers();
  205827. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  205828. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0)
  205829. currentModifiers |= ModifierKeys::leftButtonModifier;
  205830. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0)
  205831. currentModifiers |= ModifierKeys::rightButtonModifier;
  205832. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0)
  205833. currentModifiers |= ModifierKeys::middleButtonModifier;
  205834. return ModifierKeys (currentModifiers);
  205835. }
  205836. static int64 getMouseEventTime() throw()
  205837. {
  205838. static int64 eventTimeOffset = 0;
  205839. static DWORD lastMessageTime = 0;
  205840. const DWORD thisMessageTime = GetMessageTime();
  205841. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  205842. {
  205843. lastMessageTime = thisMessageTime;
  205844. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  205845. }
  205846. return eventTimeOffset + thisMessageTime;
  205847. }
  205848. class Win32ComponentPeer : public ComponentPeer
  205849. {
  205850. public:
  205851. Win32ComponentPeer (Component* const component,
  205852. const int windowStyleFlags)
  205853. : ComponentPeer (component, windowStyleFlags),
  205854. dontRepaint (false),
  205855. fullScreen (false),
  205856. isDragging (false),
  205857. isMouseOver (false),
  205858. hasCreatedCaret (false),
  205859. currentWindowIcon (0),
  205860. taskBarIcon (0),
  205861. dropTarget (0)
  205862. {
  205863. MessageManager::getInstance()
  205864. ->callFunctionOnMessageThread (&createWindowCallback, (void*) this);
  205865. setTitle (component->getName());
  205866. if ((windowStyleFlags & windowHasDropShadow) != 0
  205867. && Desktop::canUseSemiTransparentWindows())
  205868. {
  205869. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  205870. if (shadower != 0)
  205871. shadower->setOwner (component);
  205872. }
  205873. else
  205874. {
  205875. shadower = 0;
  205876. }
  205877. }
  205878. ~Win32ComponentPeer()
  205879. {
  205880. setTaskBarIcon (0);
  205881. deleteAndZero (shadower);
  205882. // do this before the next bit to avoid messages arriving for this window
  205883. // before it's destroyed
  205884. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  205885. MessageManager::getInstance()
  205886. ->callFunctionOnMessageThread (&destroyWindowCallback, (void*) hwnd);
  205887. if (currentWindowIcon != 0)
  205888. DestroyIcon (currentWindowIcon);
  205889. if (dropTarget != 0)
  205890. {
  205891. dropTarget->Release();
  205892. dropTarget = 0;
  205893. }
  205894. }
  205895. void* getNativeHandle() const
  205896. {
  205897. return (void*) hwnd;
  205898. }
  205899. void setVisible (bool shouldBeVisible)
  205900. {
  205901. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  205902. if (shouldBeVisible)
  205903. InvalidateRect (hwnd, 0, 0);
  205904. else
  205905. lastPaintTime = 0;
  205906. }
  205907. void setTitle (const String& title)
  205908. {
  205909. SetWindowText (hwnd, title);
  205910. }
  205911. void setPosition (int x, int y)
  205912. {
  205913. offsetWithinParent (x, y);
  205914. SetWindowPos (hwnd, 0,
  205915. x - windowBorder.getLeft(),
  205916. y - windowBorder.getTop(),
  205917. 0, 0,
  205918. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205919. }
  205920. void repaintNowIfTransparent()
  205921. {
  205922. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  205923. handlePaintMessage();
  205924. }
  205925. void updateBorderSize()
  205926. {
  205927. WINDOWINFO info;
  205928. info.cbSize = sizeof (info);
  205929. if (GetWindowInfo (hwnd, &info))
  205930. {
  205931. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  205932. info.rcClient.left - info.rcWindow.left,
  205933. info.rcWindow.bottom - info.rcClient.bottom,
  205934. info.rcWindow.right - info.rcClient.right);
  205935. }
  205936. }
  205937. void setSize (int w, int h)
  205938. {
  205939. SetWindowPos (hwnd, 0, 0, 0,
  205940. w + windowBorder.getLeftAndRight(),
  205941. h + windowBorder.getTopAndBottom(),
  205942. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205943. updateBorderSize();
  205944. repaintNowIfTransparent();
  205945. }
  205946. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  205947. {
  205948. fullScreen = isNowFullScreen;
  205949. offsetWithinParent (x, y);
  205950. SetWindowPos (hwnd, 0,
  205951. x - windowBorder.getLeft(),
  205952. y - windowBorder.getTop(),
  205953. w + windowBorder.getLeftAndRight(),
  205954. h + windowBorder.getTopAndBottom(),
  205955. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205956. updateBorderSize();
  205957. repaintNowIfTransparent();
  205958. }
  205959. void getBounds (int& x, int& y, int& w, int& h) const
  205960. {
  205961. RECT r;
  205962. GetWindowRect (hwnd, &r);
  205963. x = r.left;
  205964. y = r.top;
  205965. w = r.right - x;
  205966. h = r.bottom - y;
  205967. HWND parentH = GetParent (hwnd);
  205968. if (parentH != 0)
  205969. {
  205970. GetWindowRect (parentH, &r);
  205971. x -= r.left;
  205972. y -= r.top;
  205973. }
  205974. x += windowBorder.getLeft();
  205975. y += windowBorder.getTop();
  205976. w -= windowBorder.getLeftAndRight();
  205977. h -= windowBorder.getTopAndBottom();
  205978. }
  205979. int getScreenX() const
  205980. {
  205981. RECT r;
  205982. GetWindowRect (hwnd, &r);
  205983. return r.left + windowBorder.getLeft();
  205984. }
  205985. int getScreenY() const
  205986. {
  205987. RECT r;
  205988. GetWindowRect (hwnd, &r);
  205989. return r.top + windowBorder.getTop();
  205990. }
  205991. void relativePositionToGlobal (int& x, int& y)
  205992. {
  205993. RECT r;
  205994. GetWindowRect (hwnd, &r);
  205995. x += r.left + windowBorder.getLeft();
  205996. y += r.top + windowBorder.getTop();
  205997. }
  205998. void globalPositionToRelative (int& x, int& y)
  205999. {
  206000. RECT r;
  206001. GetWindowRect (hwnd, &r);
  206002. x -= r.left + windowBorder.getLeft();
  206003. y -= r.top + windowBorder.getTop();
  206004. }
  206005. void setMinimised (bool shouldBeMinimised)
  206006. {
  206007. if (shouldBeMinimised != isMinimised())
  206008. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  206009. }
  206010. bool isMinimised() const
  206011. {
  206012. WINDOWPLACEMENT wp;
  206013. wp.length = sizeof (WINDOWPLACEMENT);
  206014. GetWindowPlacement (hwnd, &wp);
  206015. return wp.showCmd == SW_SHOWMINIMIZED;
  206016. }
  206017. void setFullScreen (bool shouldBeFullScreen)
  206018. {
  206019. setMinimised (false);
  206020. if (fullScreen != shouldBeFullScreen)
  206021. {
  206022. fullScreen = shouldBeFullScreen;
  206023. const ComponentDeletionWatcher deletionChecker (component);
  206024. if (! fullScreen)
  206025. {
  206026. const Rectangle boundsCopy (lastNonFullscreenBounds);
  206027. if (hasTitleBar())
  206028. ShowWindow (hwnd, SW_SHOWNORMAL);
  206029. if (! boundsCopy.isEmpty())
  206030. {
  206031. setBounds (boundsCopy.getX(),
  206032. boundsCopy.getY(),
  206033. boundsCopy.getWidth(),
  206034. boundsCopy.getHeight(),
  206035. false);
  206036. }
  206037. }
  206038. else
  206039. {
  206040. if (hasTitleBar())
  206041. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  206042. else
  206043. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  206044. }
  206045. if (! deletionChecker.hasBeenDeleted())
  206046. handleMovedOrResized();
  206047. }
  206048. }
  206049. bool isFullScreen() const
  206050. {
  206051. if (! hasTitleBar())
  206052. return fullScreen;
  206053. WINDOWPLACEMENT wp;
  206054. wp.length = sizeof (wp);
  206055. GetWindowPlacement (hwnd, &wp);
  206056. return wp.showCmd == SW_SHOWMAXIMIZED;
  206057. }
  206058. bool contains (int x, int y, bool trueIfInAChildWindow) const
  206059. {
  206060. RECT r;
  206061. GetWindowRect (hwnd, &r);
  206062. POINT p;
  206063. p.x = x + r.left + windowBorder.getLeft();
  206064. p.y = y + r.top + windowBorder.getTop();
  206065. HWND w = WindowFromPoint (p);
  206066. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  206067. }
  206068. const BorderSize getFrameSize() const
  206069. {
  206070. return windowBorder;
  206071. }
  206072. bool setAlwaysOnTop (bool alwaysOnTop)
  206073. {
  206074. const bool oldDeactivate = shouldDeactivateTitleBar;
  206075. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206076. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  206077. 0, 0, 0, 0,
  206078. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206079. shouldDeactivateTitleBar = oldDeactivate;
  206080. if (shadower != 0)
  206081. shadower->componentBroughtToFront (*component);
  206082. return true;
  206083. }
  206084. void toFront (bool makeActive)
  206085. {
  206086. setMinimised (false);
  206087. const bool oldDeactivate = shouldDeactivateTitleBar;
  206088. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206089. MessageManager::getInstance()
  206090. ->callFunctionOnMessageThread (makeActive ? &toFrontCallback1
  206091. : &toFrontCallback2,
  206092. (void*) hwnd);
  206093. shouldDeactivateTitleBar = oldDeactivate;
  206094. if (! makeActive)
  206095. {
  206096. // in this case a broughttofront call won't have occured, so do it now..
  206097. handleBroughtToFront();
  206098. }
  206099. }
  206100. void toBehind (ComponentPeer* other)
  206101. {
  206102. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  206103. jassert (otherPeer != 0); // wrong type of window?
  206104. if (otherPeer != 0)
  206105. {
  206106. setMinimised (false);
  206107. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  206108. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206109. }
  206110. }
  206111. bool isFocused() const
  206112. {
  206113. return MessageManager::getInstance()
  206114. ->callFunctionOnMessageThread (&getFocusCallback, 0) == (void*) hwnd;
  206115. }
  206116. void grabFocus()
  206117. {
  206118. const bool oldDeactivate = shouldDeactivateTitleBar;
  206119. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206120. MessageManager::getInstance()
  206121. ->callFunctionOnMessageThread (&setFocusCallback, (void*) hwnd);
  206122. shouldDeactivateTitleBar = oldDeactivate;
  206123. }
  206124. void textInputRequired (int /*x*/, int /*y*/)
  206125. {
  206126. if (! hasCreatedCaret)
  206127. {
  206128. hasCreatedCaret = true;
  206129. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  206130. }
  206131. ShowCaret (hwnd);
  206132. SetCaretPos (0, 0);
  206133. }
  206134. void repaint (int x, int y, int w, int h)
  206135. {
  206136. const RECT r = { x, y, x + w, y + h };
  206137. InvalidateRect (hwnd, &r, FALSE);
  206138. }
  206139. void performAnyPendingRepaintsNow()
  206140. {
  206141. MSG m;
  206142. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  206143. DispatchMessage (&m);
  206144. }
  206145. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  206146. {
  206147. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  206148. return (Win32ComponentPeer*) GetWindowLongPtr (h, 8);
  206149. return 0;
  206150. }
  206151. void setTaskBarIcon (const Image* const image)
  206152. {
  206153. if (image != 0)
  206154. {
  206155. HICON hicon = createHICONFromImage (*image, TRUE, 0, 0);
  206156. if (taskBarIcon == 0)
  206157. {
  206158. taskBarIcon = new NOTIFYICONDATA();
  206159. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  206160. taskBarIcon->hWnd = (HWND) hwnd;
  206161. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  206162. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  206163. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  206164. taskBarIcon->hIcon = hicon;
  206165. taskBarIcon->szTip[0] = 0;
  206166. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  206167. }
  206168. else
  206169. {
  206170. HICON oldIcon = taskBarIcon->hIcon;
  206171. taskBarIcon->hIcon = hicon;
  206172. taskBarIcon->uFlags = NIF_ICON;
  206173. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206174. DestroyIcon (oldIcon);
  206175. }
  206176. DestroyIcon (hicon);
  206177. }
  206178. else if (taskBarIcon != 0)
  206179. {
  206180. taskBarIcon->uFlags = 0;
  206181. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  206182. DestroyIcon (taskBarIcon->hIcon);
  206183. deleteAndZero (taskBarIcon);
  206184. }
  206185. }
  206186. void setTaskBarIconToolTip (const String& toolTip) const
  206187. {
  206188. if (taskBarIcon != 0)
  206189. {
  206190. taskBarIcon->uFlags = NIF_TIP;
  206191. toolTip.copyToBuffer (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  206192. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206193. }
  206194. }
  206195. juce_UseDebuggingNewOperator
  206196. bool dontRepaint;
  206197. private:
  206198. HWND hwnd;
  206199. DropShadower* shadower;
  206200. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  206201. BorderSize windowBorder;
  206202. HICON currentWindowIcon;
  206203. NOTIFYICONDATA* taskBarIcon;
  206204. IDropTarget* dropTarget;
  206205. class TemporaryImage : public Timer
  206206. {
  206207. public:
  206208. TemporaryImage()
  206209. : image (0)
  206210. {
  206211. }
  206212. ~TemporaryImage()
  206213. {
  206214. delete image;
  206215. }
  206216. WindowsBitmapImage* getImage (const bool transparent, const int w, const int h) throw()
  206217. {
  206218. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  206219. if (image == 0 || image->getWidth() < w || image->getHeight() < h || image->getFormat() != format)
  206220. {
  206221. delete image;
  206222. image = new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false);
  206223. }
  206224. startTimer (3000);
  206225. return image;
  206226. }
  206227. void timerCallback()
  206228. {
  206229. stopTimer();
  206230. deleteAndZero (image);
  206231. }
  206232. private:
  206233. WindowsBitmapImage* image;
  206234. TemporaryImage (const TemporaryImage&);
  206235. const TemporaryImage& operator= (const TemporaryImage&);
  206236. };
  206237. TemporaryImage offscreenImageGenerator;
  206238. class WindowClassHolder : public DeletedAtShutdown
  206239. {
  206240. public:
  206241. WindowClassHolder()
  206242. : windowClassName ("JUCE_")
  206243. {
  206244. // this name has to be different for each app/dll instance because otherwise
  206245. // poor old Win32 can get a bit confused (even despite it not being a process-global
  206246. // window class).
  206247. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  206248. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  206249. TCHAR moduleFile [1024];
  206250. moduleFile[0] = 0;
  206251. GetModuleFileName (moduleHandle, moduleFile, 1024);
  206252. WORD iconNum = 0;
  206253. WNDCLASSEX wcex;
  206254. wcex.cbSize = sizeof (wcex);
  206255. wcex.style = CS_OWNDC;
  206256. wcex.lpfnWndProc = (WNDPROC) windowProc;
  206257. wcex.lpszClassName = windowClassName;
  206258. wcex.cbClsExtra = 0;
  206259. wcex.cbWndExtra = 32;
  206260. wcex.hInstance = moduleHandle;
  206261. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  206262. iconNum = 1;
  206263. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  206264. wcex.hCursor = 0;
  206265. wcex.hbrBackground = 0;
  206266. wcex.lpszMenuName = 0;
  206267. RegisterClassEx (&wcex);
  206268. }
  206269. ~WindowClassHolder()
  206270. {
  206271. if (ComponentPeer::getNumPeers() == 0)
  206272. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  206273. clearSingletonInstance();
  206274. }
  206275. String windowClassName;
  206276. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  206277. };
  206278. static void* createWindowCallback (void* userData)
  206279. {
  206280. ((Win32ComponentPeer*) userData)->createWindow();
  206281. return 0;
  206282. }
  206283. void createWindow()
  206284. {
  206285. DWORD exstyle = WS_EX_ACCEPTFILES;
  206286. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  206287. if (hasTitleBar())
  206288. {
  206289. type |= WS_OVERLAPPED;
  206290. exstyle |= WS_EX_APPWINDOW;
  206291. if ((styleFlags & windowHasCloseButton) != 0)
  206292. {
  206293. type |= WS_SYSMENU;
  206294. }
  206295. else
  206296. {
  206297. // annoyingly, windows won't let you have a min/max button without a close button
  206298. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  206299. }
  206300. if ((styleFlags & windowIsResizable) != 0)
  206301. type |= WS_THICKFRAME;
  206302. }
  206303. else
  206304. {
  206305. type |= WS_POPUP | WS_SYSMENU;
  206306. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  206307. exstyle |= WS_EX_TOOLWINDOW;
  206308. else
  206309. exstyle |= WS_EX_APPWINDOW;
  206310. }
  206311. if ((styleFlags & windowHasMinimiseButton) != 0)
  206312. type |= WS_MINIMIZEBOX;
  206313. if ((styleFlags & windowHasMaximiseButton) != 0)
  206314. type |= WS_MAXIMIZEBOX;
  206315. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  206316. exstyle |= WS_EX_TRANSPARENT;
  206317. if ((styleFlags & windowIsSemiTransparent) != 0
  206318. && Desktop::canUseSemiTransparentWindows())
  206319. exstyle |= WS_EX_LAYERED;
  206320. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  206321. if (hwnd != 0)
  206322. {
  206323. SetWindowLongPtr (hwnd, 0, 0);
  206324. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  206325. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  206326. if (dropTarget == 0)
  206327. dropTarget = new JuceDropTarget (this);
  206328. RegisterDragDrop (hwnd, dropTarget);
  206329. updateBorderSize();
  206330. // Calling this function here is (for some reason) necessary to make Windows
  206331. // correctly enable the menu items that we specify in the wm_initmenu message.
  206332. GetSystemMenu (hwnd, false);
  206333. }
  206334. else
  206335. {
  206336. jassertfalse
  206337. }
  206338. }
  206339. static void* destroyWindowCallback (void* handle)
  206340. {
  206341. RevokeDragDrop ((HWND) handle);
  206342. DestroyWindow ((HWND) handle);
  206343. return 0;
  206344. }
  206345. static void* toFrontCallback1 (void* h)
  206346. {
  206347. SetForegroundWindow ((HWND) h);
  206348. return 0;
  206349. }
  206350. static void* toFrontCallback2 (void* h)
  206351. {
  206352. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206353. return 0;
  206354. }
  206355. static void* setFocusCallback (void* h)
  206356. {
  206357. SetFocus ((HWND) h);
  206358. return 0;
  206359. }
  206360. static void* getFocusCallback (void*)
  206361. {
  206362. return (void*) GetFocus();
  206363. }
  206364. void offsetWithinParent (int& x, int& y) const
  206365. {
  206366. if (isTransparent())
  206367. {
  206368. HWND parentHwnd = GetParent (hwnd);
  206369. if (parentHwnd != 0)
  206370. {
  206371. RECT parentRect;
  206372. GetWindowRect (parentHwnd, &parentRect);
  206373. x += parentRect.left;
  206374. y += parentRect.top;
  206375. }
  206376. }
  206377. }
  206378. bool isTransparent() const
  206379. {
  206380. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  206381. }
  206382. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  206383. void setIcon (const Image& newIcon)
  206384. {
  206385. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  206386. if (hicon != 0)
  206387. {
  206388. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  206389. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  206390. if (currentWindowIcon != 0)
  206391. DestroyIcon (currentWindowIcon);
  206392. currentWindowIcon = hicon;
  206393. }
  206394. }
  206395. void handlePaintMessage()
  206396. {
  206397. #if DEBUG_REPAINT_TIMES
  206398. const double paintStart = Time::getMillisecondCounterHiRes();
  206399. #endif
  206400. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  206401. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  206402. PAINTSTRUCT paintStruct;
  206403. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  206404. // message and become re-entrant, but that's OK
  206405. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  206406. // corrupt the image it's using to paint into, so do a check here.
  206407. static bool reentrant = false;
  206408. if (reentrant)
  206409. {
  206410. DeleteObject (rgn);
  206411. EndPaint (hwnd, &paintStruct);
  206412. return;
  206413. }
  206414. reentrant = true;
  206415. // this is the rectangle to update..
  206416. int x = paintStruct.rcPaint.left;
  206417. int y = paintStruct.rcPaint.top;
  206418. int w = paintStruct.rcPaint.right - x;
  206419. int h = paintStruct.rcPaint.bottom - y;
  206420. const bool transparent = isTransparent();
  206421. if (transparent)
  206422. {
  206423. // it's not possible to have a transparent window with a title bar at the moment!
  206424. jassert (! hasTitleBar());
  206425. RECT r;
  206426. GetWindowRect (hwnd, &r);
  206427. x = y = 0;
  206428. w = r.right - r.left;
  206429. h = r.bottom - r.top;
  206430. }
  206431. if (w > 0 && h > 0)
  206432. {
  206433. clearMaskedRegion();
  206434. WindowsBitmapImage* const offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  206435. LowLevelGraphicsSoftwareRenderer context (*offscreenImage);
  206436. RectangleList* const contextClip = context.getRawClipRegion();
  206437. contextClip->clear();
  206438. context.setOrigin (-x, -y);
  206439. bool needToPaintAll = true;
  206440. if (regionType == COMPLEXREGION && ! transparent)
  206441. {
  206442. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  206443. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  206444. DeleteObject (clipRgn);
  206445. char rgnData [8192];
  206446. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  206447. if (res > 0 && res <= sizeof (rgnData))
  206448. {
  206449. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  206450. if (hdr->iType == RDH_RECTANGLES
  206451. && hdr->rcBound.right - hdr->rcBound.left >= w
  206452. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  206453. {
  206454. needToPaintAll = false;
  206455. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  206456. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  206457. while (--num >= 0)
  206458. {
  206459. // (need to move this one pixel to the left because of a win32 bug)
  206460. const int cx = jmax (x, rects->left - 1);
  206461. const int cy = rects->top;
  206462. const int cw = rects->right - cx;
  206463. const int ch = rects->bottom - rects->top;
  206464. if (cx + cw - x <= w && cy + ch - y <= h)
  206465. {
  206466. contextClip->addWithoutMerging (Rectangle (cx - x, cy - y, cw, ch));
  206467. }
  206468. else
  206469. {
  206470. needToPaintAll = true;
  206471. break;
  206472. }
  206473. ++rects;
  206474. }
  206475. }
  206476. }
  206477. }
  206478. if (needToPaintAll)
  206479. {
  206480. contextClip->clear();
  206481. contextClip->addWithoutMerging (Rectangle (0, 0, w, h));
  206482. }
  206483. if (transparent)
  206484. {
  206485. RectangleList::Iterator i (*contextClip);
  206486. while (i.next())
  206487. {
  206488. const Rectangle& r = *i.getRectangle();
  206489. offscreenImage->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  206490. }
  206491. }
  206492. // if the component's not opaque, this won't draw properly unless the platform can support this
  206493. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  206494. updateCurrentModifiers();
  206495. handlePaint (context);
  206496. if (! dontRepaint)
  206497. offscreenImage->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  206498. }
  206499. DeleteObject (rgn);
  206500. EndPaint (hwnd, &paintStruct);
  206501. reentrant = false;
  206502. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  206503. _fpreset(); // because some graphics cards can unmask FP exceptions
  206504. #endif
  206505. lastPaintTime = Time::getMillisecondCounter();
  206506. #if DEBUG_REPAINT_TIMES
  206507. const double elapsed = Time::getMillisecondCounterHiRes() - paintStart;
  206508. Logger::outputDebugString (T("repaint time: ") + String (elapsed, 2));
  206509. #endif
  206510. }
  206511. void doMouseMove (const int x, const int y)
  206512. {
  206513. static uint32 lastMouseTime = 0;
  206514. // this can be set to throttle the mouse-messages to less than a
  206515. // certain number per second, as things can get unresponsive
  206516. // if each drag or move callback has to do a lot of work.
  206517. const int maxMouseMovesPerSecond = 60;
  206518. const int64 mouseEventTime = getMouseEventTime();
  206519. if (! isMouseOver)
  206520. {
  206521. isMouseOver = true;
  206522. TRACKMOUSEEVENT tme;
  206523. tme.cbSize = sizeof (tme);
  206524. tme.dwFlags = TME_LEAVE;
  206525. tme.hwndTrack = hwnd;
  206526. tme.dwHoverTime = 0;
  206527. if (! TrackMouseEvent (&tme))
  206528. {
  206529. jassertfalse;
  206530. }
  206531. updateKeyModifiers();
  206532. handleMouseEnter (x, y, mouseEventTime);
  206533. }
  206534. else if (! isDragging)
  206535. {
  206536. if (((unsigned int) x) < (unsigned int) component->getWidth()
  206537. && ((unsigned int) y) < (unsigned int) component->getHeight())
  206538. {
  206539. RECT r;
  206540. GetWindowRect (hwnd, &r);
  206541. POINT p;
  206542. p.x = x + r.left + windowBorder.getLeft();
  206543. p.y = y + r.top + windowBorder.getTop();
  206544. if (WindowFromPoint (p) == hwnd)
  206545. {
  206546. const uint32 now = Time::getMillisecondCounter();
  206547. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  206548. {
  206549. lastMouseTime = now;
  206550. handleMouseMove (x, y, mouseEventTime);
  206551. }
  206552. }
  206553. }
  206554. }
  206555. else
  206556. {
  206557. const uint32 now = Time::getMillisecondCounter();
  206558. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  206559. {
  206560. lastMouseTime = now;
  206561. handleMouseDrag (x, y, mouseEventTime);
  206562. }
  206563. }
  206564. }
  206565. void doMouseDown (const int x, const int y, const WPARAM wParam)
  206566. {
  206567. if (GetCapture() != hwnd)
  206568. SetCapture (hwnd);
  206569. doMouseMove (x, y);
  206570. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  206571. if ((wParam & MK_LBUTTON) != 0)
  206572. currentModifiers |= ModifierKeys::leftButtonModifier;
  206573. if ((wParam & MK_RBUTTON) != 0)
  206574. currentModifiers |= ModifierKeys::rightButtonModifier;
  206575. if ((wParam & MK_MBUTTON) != 0)
  206576. currentModifiers |= ModifierKeys::middleButtonModifier;
  206577. updateKeyModifiers();
  206578. isDragging = true;
  206579. handleMouseDown (x, y, getMouseEventTime());
  206580. }
  206581. void doMouseUp (const int x, const int y, const WPARAM wParam)
  206582. {
  206583. int numButtons = 0;
  206584. if ((wParam & MK_LBUTTON) != 0)
  206585. ++numButtons;
  206586. if ((wParam & MK_RBUTTON) != 0)
  206587. ++numButtons;
  206588. if ((wParam & MK_MBUTTON) != 0)
  206589. ++numButtons;
  206590. const int oldModifiers = currentModifiers;
  206591. // update the currentmodifiers only after the callback, so the callback
  206592. // knows which button was released.
  206593. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  206594. if ((wParam & MK_LBUTTON) != 0)
  206595. currentModifiers |= ModifierKeys::leftButtonModifier;
  206596. if ((wParam & MK_RBUTTON) != 0)
  206597. currentModifiers |= ModifierKeys::rightButtonModifier;
  206598. if ((wParam & MK_MBUTTON) != 0)
  206599. currentModifiers |= ModifierKeys::middleButtonModifier;
  206600. updateKeyModifiers();
  206601. isDragging = false;
  206602. // release the mouse capture if the user's not still got a button down
  206603. if (numButtons == 0 && hwnd == GetCapture())
  206604. ReleaseCapture();
  206605. handleMouseUp (oldModifiers, x, y, getMouseEventTime());
  206606. }
  206607. void doCaptureChanged()
  206608. {
  206609. if (isDragging)
  206610. {
  206611. RECT wr;
  206612. GetWindowRect (hwnd, &wr);
  206613. const DWORD mp = GetMessagePos();
  206614. doMouseUp (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  206615. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  206616. getMouseEventTime());
  206617. }
  206618. }
  206619. void doMouseExit()
  206620. {
  206621. if (isMouseOver)
  206622. {
  206623. isMouseOver = false;
  206624. RECT wr;
  206625. GetWindowRect (hwnd, &wr);
  206626. const DWORD mp = GetMessagePos();
  206627. handleMouseExit (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  206628. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  206629. getMouseEventTime());
  206630. }
  206631. }
  206632. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  206633. {
  206634. updateKeyModifiers();
  206635. const int amount = jlimit (-1000, 1000, (int) (0.75f * (short) HIWORD (wParam)));
  206636. handleMouseWheel (isVertical ? 0 : amount,
  206637. isVertical ? amount : 0,
  206638. getMouseEventTime());
  206639. }
  206640. void sendModifierKeyChangeIfNeeded()
  206641. {
  206642. if (modifiersAtLastCallback != currentModifiers)
  206643. {
  206644. modifiersAtLastCallback = currentModifiers;
  206645. handleModifierKeysChange();
  206646. }
  206647. }
  206648. bool doKeyUp (const WPARAM key)
  206649. {
  206650. updateKeyModifiers();
  206651. switch (key)
  206652. {
  206653. case VK_SHIFT:
  206654. case VK_CONTROL:
  206655. case VK_MENU:
  206656. case VK_CAPITAL:
  206657. case VK_LWIN:
  206658. case VK_RWIN:
  206659. case VK_APPS:
  206660. case VK_NUMLOCK:
  206661. case VK_SCROLL:
  206662. case VK_LSHIFT:
  206663. case VK_RSHIFT:
  206664. case VK_LCONTROL:
  206665. case VK_LMENU:
  206666. case VK_RCONTROL:
  206667. case VK_RMENU:
  206668. sendModifierKeyChangeIfNeeded();
  206669. }
  206670. return handleKeyUpOrDown();
  206671. }
  206672. bool doKeyDown (const WPARAM key)
  206673. {
  206674. updateKeyModifiers();
  206675. bool used = false;
  206676. switch (key)
  206677. {
  206678. case VK_SHIFT:
  206679. case VK_LSHIFT:
  206680. case VK_RSHIFT:
  206681. case VK_CONTROL:
  206682. case VK_LCONTROL:
  206683. case VK_RCONTROL:
  206684. case VK_MENU:
  206685. case VK_LMENU:
  206686. case VK_RMENU:
  206687. case VK_LWIN:
  206688. case VK_RWIN:
  206689. case VK_CAPITAL:
  206690. case VK_NUMLOCK:
  206691. case VK_SCROLL:
  206692. case VK_APPS:
  206693. sendModifierKeyChangeIfNeeded();
  206694. break;
  206695. case VK_LEFT:
  206696. case VK_RIGHT:
  206697. case VK_UP:
  206698. case VK_DOWN:
  206699. case VK_PRIOR:
  206700. case VK_NEXT:
  206701. case VK_HOME:
  206702. case VK_END:
  206703. case VK_DELETE:
  206704. case VK_INSERT:
  206705. case VK_F1:
  206706. case VK_F2:
  206707. case VK_F3:
  206708. case VK_F4:
  206709. case VK_F5:
  206710. case VK_F6:
  206711. case VK_F7:
  206712. case VK_F8:
  206713. case VK_F9:
  206714. case VK_F10:
  206715. case VK_F11:
  206716. case VK_F12:
  206717. case VK_F13:
  206718. case VK_F14:
  206719. case VK_F15:
  206720. case VK_F16:
  206721. used = handleKeyUpOrDown();
  206722. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  206723. break;
  206724. case VK_ADD:
  206725. case VK_SUBTRACT:
  206726. case VK_MULTIPLY:
  206727. case VK_DIVIDE:
  206728. case VK_SEPARATOR:
  206729. case VK_DECIMAL:
  206730. used = handleKeyUpOrDown();
  206731. break;
  206732. default:
  206733. used = handleKeyUpOrDown();
  206734. {
  206735. MSG msg;
  206736. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  206737. {
  206738. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  206739. // manually generate the key-press event that matches this key-down.
  206740. const UINT keyChar = MapVirtualKey (key, 2);
  206741. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  206742. }
  206743. }
  206744. break;
  206745. }
  206746. return used;
  206747. }
  206748. bool doKeyChar (int key, const LPARAM flags)
  206749. {
  206750. updateKeyModifiers();
  206751. juce_wchar textChar = (juce_wchar) key;
  206752. const int virtualScanCode = (flags >> 16) & 0xff;
  206753. if (key >= '0' && key <= '9')
  206754. {
  206755. switch (virtualScanCode) // check for a numeric keypad scan-code
  206756. {
  206757. case 0x52:
  206758. case 0x4f:
  206759. case 0x50:
  206760. case 0x51:
  206761. case 0x4b:
  206762. case 0x4c:
  206763. case 0x4d:
  206764. case 0x47:
  206765. case 0x48:
  206766. case 0x49:
  206767. key = (key - '0') + KeyPress::numberPad0;
  206768. break;
  206769. default:
  206770. break;
  206771. }
  206772. }
  206773. else
  206774. {
  206775. // convert the scan code to an unmodified character code..
  206776. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  206777. UINT keyChar = MapVirtualKey (virtualKey, 2);
  206778. keyChar = LOWORD (keyChar);
  206779. if (keyChar != 0)
  206780. key = (int) keyChar;
  206781. // avoid sending junk text characters for some control-key combinations
  206782. if (textChar < ' ' && (currentModifiers & (ModifierKeys::ctrlModifier | ModifierKeys::altModifier)) != 0)
  206783. textChar = 0;
  206784. }
  206785. return handleKeyPress (key, textChar);
  206786. }
  206787. bool doAppCommand (const LPARAM lParam)
  206788. {
  206789. int key = 0;
  206790. switch (GET_APPCOMMAND_LPARAM (lParam))
  206791. {
  206792. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  206793. key = KeyPress::playKey;
  206794. break;
  206795. case APPCOMMAND_MEDIA_STOP:
  206796. key = KeyPress::stopKey;
  206797. break;
  206798. case APPCOMMAND_MEDIA_NEXTTRACK:
  206799. key = KeyPress::fastForwardKey;
  206800. break;
  206801. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  206802. key = KeyPress::rewindKey;
  206803. break;
  206804. }
  206805. if (key != 0)
  206806. {
  206807. updateKeyModifiers();
  206808. if (hwnd == GetActiveWindow())
  206809. {
  206810. handleKeyPress (key, 0);
  206811. return true;
  206812. }
  206813. }
  206814. return false;
  206815. }
  206816. class JuceDropTarget : public IDropTarget
  206817. {
  206818. public:
  206819. JuceDropTarget (Win32ComponentPeer* const owner_)
  206820. : owner (owner_),
  206821. refCount (1)
  206822. {
  206823. }
  206824. virtual ~JuceDropTarget()
  206825. {
  206826. jassert (refCount == 0);
  206827. }
  206828. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  206829. {
  206830. if (id == IID_IUnknown || id == IID_IDropTarget)
  206831. {
  206832. AddRef();
  206833. *result = this;
  206834. return S_OK;
  206835. }
  206836. *result = 0;
  206837. return E_NOINTERFACE;
  206838. }
  206839. ULONG __stdcall AddRef() { return ++refCount; }
  206840. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  206841. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206842. {
  206843. updateFileList (pDataObject);
  206844. int x = mousePos.x, y = mousePos.y;
  206845. owner->globalPositionToRelative (x, y);
  206846. owner->handleFileDragMove (files, x, y);
  206847. *pdwEffect = DROPEFFECT_COPY;
  206848. return S_OK;
  206849. }
  206850. HRESULT __stdcall DragLeave()
  206851. {
  206852. owner->handleFileDragExit (files);
  206853. return S_OK;
  206854. }
  206855. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206856. {
  206857. int x = mousePos.x, y = mousePos.y;
  206858. owner->globalPositionToRelative (x, y);
  206859. owner->handleFileDragMove (files, x, y);
  206860. *pdwEffect = DROPEFFECT_COPY;
  206861. return S_OK;
  206862. }
  206863. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206864. {
  206865. updateFileList (pDataObject);
  206866. int x = mousePos.x, y = mousePos.y;
  206867. owner->globalPositionToRelative (x, y);
  206868. owner->handleFileDragDrop (files, x, y);
  206869. *pdwEffect = DROPEFFECT_COPY;
  206870. return S_OK;
  206871. }
  206872. private:
  206873. Win32ComponentPeer* const owner;
  206874. int refCount;
  206875. StringArray files;
  206876. void updateFileList (IDataObject* const pDataObject)
  206877. {
  206878. files.clear();
  206879. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206880. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206881. if (pDataObject->GetData (&format, &medium) == S_OK)
  206882. {
  206883. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  206884. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  206885. unsigned int i = 0;
  206886. if (pDropFiles->fWide)
  206887. {
  206888. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  206889. for (;;)
  206890. {
  206891. unsigned int len = 0;
  206892. while (i + len < totalLen && fname [i + len] != 0)
  206893. ++len;
  206894. if (len == 0)
  206895. break;
  206896. files.add (String (fname + i, len));
  206897. i += len + 1;
  206898. }
  206899. }
  206900. else
  206901. {
  206902. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  206903. for (;;)
  206904. {
  206905. unsigned int len = 0;
  206906. while (i + len < totalLen && fname [i + len] != 0)
  206907. ++len;
  206908. if (len == 0)
  206909. break;
  206910. files.add (String (fname + i, len));
  206911. i += len + 1;
  206912. }
  206913. }
  206914. GlobalUnlock (medium.hGlobal);
  206915. }
  206916. }
  206917. JuceDropTarget (const JuceDropTarget&);
  206918. const JuceDropTarget& operator= (const JuceDropTarget&);
  206919. };
  206920. void doSettingChange()
  206921. {
  206922. Desktop::getInstance().refreshMonitorSizes();
  206923. if (fullScreen && ! isMinimised())
  206924. {
  206925. const Rectangle r (component->getParentMonitorArea());
  206926. SetWindowPos (hwnd, 0,
  206927. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  206928. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  206929. }
  206930. }
  206931. public:
  206932. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  206933. {
  206934. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  206935. if (peer != 0)
  206936. return peer->peerWindowProc (h, message, wParam, lParam);
  206937. return DefWindowProc (h, message, wParam, lParam);
  206938. }
  206939. private:
  206940. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  206941. {
  206942. {
  206943. const MessageManagerLock messLock;
  206944. if (isValidPeer (this))
  206945. {
  206946. switch (message)
  206947. {
  206948. case WM_NCHITTEST:
  206949. if (hasTitleBar())
  206950. break;
  206951. return HTCLIENT;
  206952. case WM_PAINT:
  206953. handlePaintMessage();
  206954. return 0;
  206955. case WM_NCPAINT:
  206956. if (wParam != 1)
  206957. handlePaintMessage();
  206958. if (hasTitleBar())
  206959. break;
  206960. return 0;
  206961. case WM_ERASEBKGND:
  206962. case WM_NCCALCSIZE:
  206963. if (hasTitleBar())
  206964. break;
  206965. return 1;
  206966. case WM_MOUSEMOVE:
  206967. doMouseMove (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  206968. return 0;
  206969. case WM_MOUSELEAVE:
  206970. doMouseExit();
  206971. return 0;
  206972. case WM_LBUTTONDOWN:
  206973. case WM_MBUTTONDOWN:
  206974. case WM_RBUTTONDOWN:
  206975. doMouseDown (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  206976. return 0;
  206977. case WM_LBUTTONUP:
  206978. case WM_MBUTTONUP:
  206979. case WM_RBUTTONUP:
  206980. doMouseUp (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  206981. return 0;
  206982. case WM_CAPTURECHANGED:
  206983. doCaptureChanged();
  206984. return 0;
  206985. case WM_NCMOUSEMOVE:
  206986. if (hasTitleBar())
  206987. break;
  206988. return 0;
  206989. case 0x020A: /* WM_MOUSEWHEEL */
  206990. doMouseWheel (wParam, true);
  206991. return 0;
  206992. case 0x020E: /* WM_MOUSEHWHEEL */
  206993. doMouseWheel (wParam, false);
  206994. return 0;
  206995. case WM_WINDOWPOSCHANGING:
  206996. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  206997. {
  206998. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  206999. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  207000. {
  207001. if (constrainer != 0)
  207002. {
  207003. const Rectangle current (component->getX() - windowBorder.getLeft(),
  207004. component->getY() - windowBorder.getTop(),
  207005. component->getWidth() + windowBorder.getLeftAndRight(),
  207006. component->getHeight() + windowBorder.getTopAndBottom());
  207007. constrainer->checkBounds (wp->x, wp->y, wp->cx, wp->cy,
  207008. current,
  207009. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207010. wp->y != current.getY() && wp->y + wp->cy == current.getBottom(),
  207011. wp->x != current.getX() && wp->x + wp->cx == current.getRight(),
  207012. wp->y == current.getY() && wp->y + wp->cy != current.getBottom(),
  207013. wp->x == current.getX() && wp->x + wp->cx != current.getRight());
  207014. }
  207015. }
  207016. }
  207017. return 0;
  207018. case WM_WINDOWPOSCHANGED:
  207019. handleMovedOrResized();
  207020. if (dontRepaint)
  207021. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  207022. else
  207023. return 0;
  207024. case WM_KEYDOWN:
  207025. case WM_SYSKEYDOWN:
  207026. if (doKeyDown (wParam))
  207027. return 0;
  207028. break;
  207029. case WM_KEYUP:
  207030. case WM_SYSKEYUP:
  207031. if (doKeyUp (wParam))
  207032. return 0;
  207033. break;
  207034. case WM_CHAR:
  207035. if (doKeyChar ((int) wParam, lParam))
  207036. return 0;
  207037. break;
  207038. case WM_APPCOMMAND:
  207039. if (doAppCommand (lParam))
  207040. return TRUE;
  207041. break;
  207042. case WM_SETFOCUS:
  207043. updateKeyModifiers();
  207044. handleFocusGain();
  207045. break;
  207046. case WM_KILLFOCUS:
  207047. if (hasCreatedCaret)
  207048. {
  207049. hasCreatedCaret = false;
  207050. DestroyCaret();
  207051. }
  207052. handleFocusLoss();
  207053. break;
  207054. case WM_ACTIVATEAPP:
  207055. // Windows does weird things to process priority when you swap apps,
  207056. // so this forces an update when the app is brought to the front
  207057. if (wParam != FALSE)
  207058. juce_repeatLastProcessPriority();
  207059. juce_CheckCurrentlyFocusedTopLevelWindow();
  207060. modifiersAtLastCallback = -1;
  207061. return 0;
  207062. case WM_ACTIVATE:
  207063. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  207064. {
  207065. modifiersAtLastCallback = -1;
  207066. updateKeyModifiers();
  207067. if (isMinimised())
  207068. {
  207069. component->repaint();
  207070. handleMovedOrResized();
  207071. if (! isValidMessageListener())
  207072. return 0;
  207073. }
  207074. if (LOWORD (wParam) == WA_CLICKACTIVE
  207075. && component->isCurrentlyBlockedByAnotherModalComponent())
  207076. {
  207077. int mx, my;
  207078. component->getMouseXYRelative (mx, my);
  207079. Component* const underMouse = component->getComponentAt (mx, my);
  207080. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  207081. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  207082. return 0;
  207083. }
  207084. handleBroughtToFront();
  207085. return 0;
  207086. }
  207087. break;
  207088. case WM_NCACTIVATE:
  207089. // while a temporary window is being shown, prevent Windows from deactivating the
  207090. // title bars of our main windows.
  207091. if (wParam == 0 && ! shouldDeactivateTitleBar)
  207092. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  207093. break;
  207094. case WM_MOUSEACTIVATE:
  207095. if (! component->getMouseClickGrabsKeyboardFocus())
  207096. return MA_NOACTIVATE;
  207097. break;
  207098. case WM_SHOWWINDOW:
  207099. if (wParam != 0)
  207100. handleBroughtToFront();
  207101. break;
  207102. case WM_CLOSE:
  207103. handleUserClosingWindow();
  207104. return 0;
  207105. case WM_QUIT:
  207106. JUCEApplication::quit();
  207107. return 0;
  207108. case WM_TRAYNOTIFY:
  207109. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207110. {
  207111. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  207112. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207113. {
  207114. Component* const current = Component::getCurrentlyModalComponent();
  207115. if (current != 0)
  207116. current->inputAttemptWhenModal();
  207117. }
  207118. }
  207119. else
  207120. {
  207121. const int oldModifiers = currentModifiers;
  207122. MouseEvent e (0, 0, ModifierKeys::getCurrentModifiersRealtime(), component,
  207123. getMouseEventTime(), 0, 0, getMouseEventTime(), 1, false);
  207124. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  207125. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::leftButtonModifier);
  207126. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  207127. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::rightButtonModifier);
  207128. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  207129. {
  207130. SetFocus (hwnd);
  207131. SetForegroundWindow (hwnd);
  207132. component->mouseDown (e);
  207133. }
  207134. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207135. {
  207136. e.mods = ModifierKeys (oldModifiers);
  207137. component->mouseUp (e);
  207138. }
  207139. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207140. {
  207141. e.mods = ModifierKeys (oldModifiers);
  207142. component->mouseDoubleClick (e);
  207143. }
  207144. else if (lParam == WM_MOUSEMOVE)
  207145. {
  207146. component->mouseMove (e);
  207147. }
  207148. }
  207149. break;
  207150. case WM_SYNCPAINT:
  207151. return 0;
  207152. case WM_PALETTECHANGED:
  207153. InvalidateRect (h, 0, 0);
  207154. break;
  207155. case WM_DISPLAYCHANGE:
  207156. InvalidateRect (h, 0, 0);
  207157. createPaletteIfNeeded = true;
  207158. // intentional fall-through...
  207159. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  207160. doSettingChange();
  207161. break;
  207162. case WM_INITMENU:
  207163. if (! hasTitleBar())
  207164. {
  207165. if (isFullScreen())
  207166. {
  207167. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  207168. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  207169. }
  207170. else if (! isMinimised())
  207171. {
  207172. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  207173. }
  207174. }
  207175. break;
  207176. case WM_SYSCOMMAND:
  207177. switch (wParam & 0xfff0)
  207178. {
  207179. case SC_CLOSE:
  207180. if (hasTitleBar())
  207181. {
  207182. PostMessage (h, WM_CLOSE, 0, 0);
  207183. return 0;
  207184. }
  207185. break;
  207186. case SC_KEYMENU:
  207187. if (hasTitleBar() && h == GetCapture())
  207188. ReleaseCapture();
  207189. break;
  207190. case SC_MAXIMIZE:
  207191. setFullScreen (true);
  207192. return 0;
  207193. case SC_MINIMIZE:
  207194. if (! hasTitleBar())
  207195. {
  207196. setMinimised (true);
  207197. return 0;
  207198. }
  207199. break;
  207200. case SC_RESTORE:
  207201. if (hasTitleBar())
  207202. {
  207203. if (isFullScreen())
  207204. {
  207205. setFullScreen (false);
  207206. return 0;
  207207. }
  207208. }
  207209. else
  207210. {
  207211. if (isMinimised())
  207212. setMinimised (false);
  207213. else if (isFullScreen())
  207214. setFullScreen (false);
  207215. return 0;
  207216. }
  207217. break;
  207218. case SC_MONITORPOWER:
  207219. case SC_SCREENSAVE:
  207220. if (! screenSaverAllowed)
  207221. return 0;
  207222. break;
  207223. }
  207224. break;
  207225. case WM_NCLBUTTONDOWN:
  207226. case WM_NCRBUTTONDOWN:
  207227. case WM_NCMBUTTONDOWN:
  207228. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207229. {
  207230. Component* const current = Component::getCurrentlyModalComponent();
  207231. if (current != 0)
  207232. current->inputAttemptWhenModal();
  207233. }
  207234. break;
  207235. //case WM_IME_STARTCOMPOSITION;
  207236. // return 0;
  207237. case WM_GETDLGCODE:
  207238. return DLGC_WANTALLKEYS;
  207239. default:
  207240. break;
  207241. }
  207242. }
  207243. }
  207244. // (the message manager lock exits before calling this, to avoid deadlocks if
  207245. // this calls into non-juce windows)
  207246. return DefWindowProc (h, message, wParam, lParam);
  207247. }
  207248. Win32ComponentPeer (const Win32ComponentPeer&);
  207249. const Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  207250. };
  207251. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  207252. {
  207253. return new Win32ComponentPeer (this, styleFlags);
  207254. }
  207255. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  207256. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  207257. {
  207258. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  207259. if (wp != 0)
  207260. wp->setTaskBarIcon (&newImage);
  207261. }
  207262. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  207263. {
  207264. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  207265. if (wp != 0)
  207266. wp->setTaskBarIconToolTip (tooltip);
  207267. }
  207268. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  207269. {
  207270. DWORD val = GetWindowLong (h, styleType);
  207271. if (bitIsSet)
  207272. val |= feature;
  207273. else
  207274. val &= ~feature;
  207275. SetWindowLongPtr (h, styleType, val);
  207276. SetWindowPos (h, 0, 0, 0, 0, 0,
  207277. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  207278. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  207279. }
  207280. bool Process::isForegroundProcess() throw()
  207281. {
  207282. HWND fg = GetForegroundWindow();
  207283. if (fg == 0)
  207284. return true;
  207285. DWORD processId = 0;
  207286. GetWindowThreadProcessId (fg, &processId);
  207287. return processId == GetCurrentProcessId();
  207288. }
  207289. void Desktop::getMousePosition (int& x, int& y) throw()
  207290. {
  207291. POINT mousePos;
  207292. GetCursorPos (&mousePos);
  207293. x = mousePos.x;
  207294. y = mousePos.y;
  207295. }
  207296. void Desktop::setMousePosition (int x, int y) throw()
  207297. {
  207298. SetCursorPos (x, y);
  207299. }
  207300. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  207301. {
  207302. screenSaverAllowed = isEnabled;
  207303. }
  207304. bool Desktop::isScreenSaverEnabled() throw()
  207305. {
  207306. return screenSaverAllowed;
  207307. }
  207308. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  207309. {
  207310. Array <Rectangle>* const monitorCoords = (Array <Rectangle>*) userInfo;
  207311. monitorCoords->add (Rectangle (r->left, r->top, r->right - r->left, r->bottom - r->top));
  207312. return TRUE;
  207313. }
  207314. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  207315. {
  207316. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  207317. // make sure the first in the list is the main monitor
  207318. for (int i = 1; i < monitorCoords.size(); ++i)
  207319. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  207320. monitorCoords.swap (i, 0);
  207321. if (monitorCoords.size() == 0)
  207322. {
  207323. RECT r;
  207324. GetWindowRect (GetDesktopWindow(), &r);
  207325. monitorCoords.add (Rectangle (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207326. }
  207327. if (clipToWorkArea)
  207328. {
  207329. // clip the main monitor to the active non-taskbar area
  207330. RECT r;
  207331. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  207332. Rectangle& screen = monitorCoords.getReference (0);
  207333. screen.setPosition (jmax (screen.getX(), r.left),
  207334. jmax (screen.getY(), r.top));
  207335. screen.setSize (jmin (screen.getRight(), r.right) - screen.getX(),
  207336. jmin (screen.getBottom(), r.bottom) - screen.getY());
  207337. }
  207338. }
  207339. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  207340. {
  207341. Image* im = 0;
  207342. if (bitmap != 0)
  207343. {
  207344. BITMAP bm;
  207345. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  207346. && bm.bmWidth > 0 && bm.bmHeight > 0)
  207347. {
  207348. HDC tempDC = GetDC (0);
  207349. HDC dc = CreateCompatibleDC (tempDC);
  207350. ReleaseDC (0, tempDC);
  207351. SelectObject (dc, bitmap);
  207352. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  207353. for (int y = bm.bmHeight; --y >= 0;)
  207354. {
  207355. for (int x = bm.bmWidth; --x >= 0;)
  207356. {
  207357. COLORREF col = GetPixel (dc, x, y);
  207358. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  207359. (uint8) GetGValue (col),
  207360. (uint8) GetBValue (col)));
  207361. }
  207362. }
  207363. DeleteDC (dc);
  207364. }
  207365. }
  207366. return im;
  207367. }
  207368. static Image* createImageFromHICON (HICON icon) throw()
  207369. {
  207370. ICONINFO info;
  207371. if (GetIconInfo (icon, &info))
  207372. {
  207373. Image* const mask = createImageFromHBITMAP (info.hbmMask);
  207374. if (mask == 0)
  207375. return 0;
  207376. Image* const image = createImageFromHBITMAP (info.hbmColor);
  207377. if (image == 0)
  207378. return mask;
  207379. for (int y = image->getHeight(); --y >= 0;)
  207380. {
  207381. for (int x = image->getWidth(); --x >= 0;)
  207382. {
  207383. const float brightness = mask->getPixelAt (x, y).getBrightness();
  207384. if (brightness > 0.0f)
  207385. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  207386. }
  207387. }
  207388. delete mask;
  207389. return image;
  207390. }
  207391. return 0;
  207392. }
  207393. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  207394. {
  207395. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  207396. ICONINFO info;
  207397. info.fIcon = isIcon;
  207398. info.xHotspot = hotspotX;
  207399. info.yHotspot = hotspotY;
  207400. info.hbmMask = mask;
  207401. HICON hi = 0;
  207402. if (SystemStats::getOperatingSystemType() >= SystemStats::WinXP)
  207403. {
  207404. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  207405. Graphics g (bitmap);
  207406. g.drawImageAt (&image, 0, 0);
  207407. info.hbmColor = bitmap.hBitmap;
  207408. hi = CreateIconIndirect (&info);
  207409. }
  207410. else
  207411. {
  207412. HBITMAP colour = CreateCompatibleBitmap (GetDC (0), image.getWidth(), image.getHeight());
  207413. HDC colDC = CreateCompatibleDC (GetDC (0));
  207414. HDC alphaDC = CreateCompatibleDC (GetDC (0));
  207415. SelectObject (colDC, colour);
  207416. SelectObject (alphaDC, mask);
  207417. for (int y = image.getHeight(); --y >= 0;)
  207418. {
  207419. for (int x = image.getWidth(); --x >= 0;)
  207420. {
  207421. const Colour c (image.getPixelAt (x, y));
  207422. SetPixel (colDC, x, y, COLORREF (c.getRed() | (c.getGreen() << 8) | (c.getBlue() << 16)));
  207423. SetPixel (alphaDC, x, y, COLORREF (0xffffff - (c.getAlpha() | (c.getAlpha() << 8) | (c.getAlpha() << 16))));
  207424. }
  207425. }
  207426. DeleteDC (colDC);
  207427. DeleteDC (alphaDC);
  207428. info.hbmColor = colour;
  207429. hi = CreateIconIndirect (&info);
  207430. DeleteObject (colour);
  207431. }
  207432. DeleteObject (mask);
  207433. return hi;
  207434. }
  207435. Image* juce_createIconForFile (const File& file)
  207436. {
  207437. Image* image = 0;
  207438. TCHAR filename [1024];
  207439. file.getFullPathName().copyToBuffer (filename, 1023);
  207440. WORD iconNum = 0;
  207441. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  207442. filename, &iconNum);
  207443. if (icon != 0)
  207444. {
  207445. image = createImageFromHICON (icon);
  207446. DestroyIcon (icon);
  207447. }
  207448. return image;
  207449. }
  207450. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  207451. {
  207452. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  207453. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  207454. const Image* im = &image;
  207455. Image* newIm = 0;
  207456. if (image.getWidth() > maxW || image.getHeight() > maxH)
  207457. {
  207458. im = newIm = image.createCopy (maxW, maxH);
  207459. hotspotX = (hotspotX * maxW) / image.getWidth();
  207460. hotspotY = (hotspotY * maxH) / image.getHeight();
  207461. }
  207462. void* cursorH = 0;
  207463. const SystemStats::OperatingSystemType os = SystemStats::getOperatingSystemType();
  207464. if (os == SystemStats::WinXP)
  207465. {
  207466. cursorH = (void*) createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  207467. }
  207468. else
  207469. {
  207470. const int stride = (maxW + 7) >> 3;
  207471. uint8* const andPlane = (uint8*) juce_calloc (stride * maxH);
  207472. uint8* const xorPlane = (uint8*) juce_calloc (stride * maxH);
  207473. int index = 0;
  207474. for (int y = 0; y < maxH; ++y)
  207475. {
  207476. for (int x = 0; x < maxW; ++x)
  207477. {
  207478. const unsigned char bit = (unsigned char) (1 << (7 - (x & 7)));
  207479. const Colour pixelColour (im->getPixelAt (x, y));
  207480. if (pixelColour.getAlpha() < 127)
  207481. andPlane [index + (x >> 3)] |= bit;
  207482. else if (pixelColour.getBrightness() >= 0.5f)
  207483. xorPlane [index + (x >> 3)] |= bit;
  207484. }
  207485. index += stride;
  207486. }
  207487. cursorH = CreateCursor (0, hotspotX, hotspotY, maxW, maxH, andPlane, xorPlane);
  207488. juce_free (andPlane);
  207489. juce_free (xorPlane);
  207490. }
  207491. delete newIm;
  207492. return cursorH;
  207493. }
  207494. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  207495. {
  207496. if (cursorHandle != 0 && ! isStandard)
  207497. DestroyCursor ((HCURSOR) cursorHandle);
  207498. }
  207499. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  207500. {
  207501. LPCTSTR cursorName = IDC_ARROW;
  207502. switch (type)
  207503. {
  207504. case MouseCursor::NormalCursor:
  207505. cursorName = IDC_ARROW;
  207506. break;
  207507. case MouseCursor::NoCursor:
  207508. return 0;
  207509. case MouseCursor::DraggingHandCursor:
  207510. {
  207511. static void* dragHandCursor = 0;
  207512. if (dragHandCursor == 0)
  207513. {
  207514. static const unsigned char dragHandData[] =
  207515. { 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,
  207516. 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,
  207517. 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 };
  207518. Image* const image = ImageFileFormat::loadFrom ((const char*) dragHandData, sizeof (dragHandData));
  207519. dragHandCursor = juce_createMouseCursorFromImage (*image, 8, 7);
  207520. delete image;
  207521. }
  207522. return dragHandCursor;
  207523. }
  207524. case MouseCursor::WaitCursor:
  207525. cursorName = IDC_WAIT;
  207526. break;
  207527. case MouseCursor::IBeamCursor:
  207528. cursorName = IDC_IBEAM;
  207529. break;
  207530. case MouseCursor::PointingHandCursor:
  207531. cursorName = MAKEINTRESOURCE(32649);
  207532. break;
  207533. case MouseCursor::LeftRightResizeCursor:
  207534. case MouseCursor::LeftEdgeResizeCursor:
  207535. case MouseCursor::RightEdgeResizeCursor:
  207536. cursorName = IDC_SIZEWE;
  207537. break;
  207538. case MouseCursor::UpDownResizeCursor:
  207539. case MouseCursor::TopEdgeResizeCursor:
  207540. case MouseCursor::BottomEdgeResizeCursor:
  207541. cursorName = IDC_SIZENS;
  207542. break;
  207543. case MouseCursor::TopLeftCornerResizeCursor:
  207544. case MouseCursor::BottomRightCornerResizeCursor:
  207545. cursorName = IDC_SIZENWSE;
  207546. break;
  207547. case MouseCursor::TopRightCornerResizeCursor:
  207548. case MouseCursor::BottomLeftCornerResizeCursor:
  207549. cursorName = IDC_SIZENESW;
  207550. break;
  207551. case MouseCursor::UpDownLeftRightResizeCursor:
  207552. cursorName = IDC_SIZEALL;
  207553. break;
  207554. case MouseCursor::CrosshairCursor:
  207555. cursorName = IDC_CROSS;
  207556. break;
  207557. case MouseCursor::CopyingCursor:
  207558. // can't seem to find one of these in the win32 list..
  207559. break;
  207560. }
  207561. HCURSOR cursorH = LoadCursor (0, cursorName);
  207562. if (cursorH == 0)
  207563. cursorH = LoadCursor (0, IDC_ARROW);
  207564. return (void*) cursorH;
  207565. }
  207566. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  207567. {
  207568. SetCursor ((HCURSOR) getHandle());
  207569. }
  207570. void MouseCursor::showInAllWindows() const throw()
  207571. {
  207572. showInWindow (0);
  207573. }
  207574. class JuceDropSource : public IDropSource
  207575. {
  207576. int refCount;
  207577. public:
  207578. JuceDropSource()
  207579. : refCount (1)
  207580. {
  207581. }
  207582. virtual ~JuceDropSource()
  207583. {
  207584. jassert (refCount == 0);
  207585. }
  207586. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207587. {
  207588. if (id == IID_IUnknown || id == IID_IDropSource)
  207589. {
  207590. AddRef();
  207591. *result = this;
  207592. return S_OK;
  207593. }
  207594. *result = 0;
  207595. return E_NOINTERFACE;
  207596. }
  207597. ULONG __stdcall AddRef() { return ++refCount; }
  207598. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  207599. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  207600. {
  207601. if (escapePressed)
  207602. return DRAGDROP_S_CANCEL;
  207603. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  207604. return DRAGDROP_S_DROP;
  207605. return S_OK;
  207606. }
  207607. HRESULT __stdcall GiveFeedback (DWORD)
  207608. {
  207609. return DRAGDROP_S_USEDEFAULTCURSORS;
  207610. }
  207611. };
  207612. class JuceEnumFormatEtc : public IEnumFORMATETC
  207613. {
  207614. public:
  207615. JuceEnumFormatEtc (const FORMATETC* const format_)
  207616. : refCount (1),
  207617. format (format_),
  207618. index (0)
  207619. {
  207620. }
  207621. virtual ~JuceEnumFormatEtc()
  207622. {
  207623. jassert (refCount == 0);
  207624. }
  207625. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207626. {
  207627. if (id == IID_IUnknown || id == IID_IEnumFORMATETC)
  207628. {
  207629. AddRef();
  207630. *result = this;
  207631. return S_OK;
  207632. }
  207633. *result = 0;
  207634. return E_NOINTERFACE;
  207635. }
  207636. ULONG __stdcall AddRef() { return ++refCount; }
  207637. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  207638. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  207639. {
  207640. if (result == 0)
  207641. return E_POINTER;
  207642. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  207643. newOne->index = index;
  207644. *result = newOne;
  207645. return S_OK;
  207646. }
  207647. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  207648. {
  207649. if (pceltFetched != 0)
  207650. *pceltFetched = 0;
  207651. else if (celt != 1)
  207652. return S_FALSE;
  207653. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  207654. {
  207655. copyFormatEtc (lpFormatEtc [0], *format);
  207656. ++index;
  207657. if (pceltFetched != 0)
  207658. *pceltFetched = 1;
  207659. return S_OK;
  207660. }
  207661. return S_FALSE;
  207662. }
  207663. HRESULT __stdcall Skip (ULONG celt)
  207664. {
  207665. if (index + (int) celt >= 1)
  207666. return S_FALSE;
  207667. index += celt;
  207668. return S_OK;
  207669. }
  207670. HRESULT __stdcall Reset()
  207671. {
  207672. index = 0;
  207673. return S_OK;
  207674. }
  207675. private:
  207676. int refCount;
  207677. const FORMATETC* const format;
  207678. int index;
  207679. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  207680. {
  207681. dest = source;
  207682. if (source.ptd != 0)
  207683. {
  207684. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  207685. *(dest.ptd) = *(source.ptd);
  207686. }
  207687. }
  207688. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  207689. const JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  207690. };
  207691. class JuceDataObject : public IDataObject
  207692. {
  207693. JuceDropSource* const dropSource;
  207694. const FORMATETC* const format;
  207695. const STGMEDIUM* const medium;
  207696. int refCount;
  207697. JuceDataObject (const JuceDataObject&);
  207698. const JuceDataObject& operator= (const JuceDataObject&);
  207699. public:
  207700. JuceDataObject (JuceDropSource* const dropSource_,
  207701. const FORMATETC* const format_,
  207702. const STGMEDIUM* const medium_)
  207703. : dropSource (dropSource_),
  207704. format (format_),
  207705. medium (medium_),
  207706. refCount (1)
  207707. {
  207708. }
  207709. virtual ~JuceDataObject()
  207710. {
  207711. jassert (refCount == 0);
  207712. }
  207713. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207714. {
  207715. if (id == IID_IUnknown || id == IID_IDataObject)
  207716. {
  207717. AddRef();
  207718. *result = this;
  207719. return S_OK;
  207720. }
  207721. *result = 0;
  207722. return E_NOINTERFACE;
  207723. }
  207724. ULONG __stdcall AddRef() { return ++refCount; }
  207725. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  207726. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  207727. {
  207728. if (pFormatEtc->tymed == format->tymed
  207729. && pFormatEtc->cfFormat == format->cfFormat
  207730. && pFormatEtc->dwAspect == format->dwAspect)
  207731. {
  207732. pMedium->tymed = format->tymed;
  207733. pMedium->pUnkForRelease = 0;
  207734. if (format->tymed == TYMED_HGLOBAL)
  207735. {
  207736. const SIZE_T len = GlobalSize (medium->hGlobal);
  207737. void* const src = GlobalLock (medium->hGlobal);
  207738. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  207739. memcpy (dst, src, len);
  207740. GlobalUnlock (medium->hGlobal);
  207741. pMedium->hGlobal = dst;
  207742. return S_OK;
  207743. }
  207744. }
  207745. return DV_E_FORMATETC;
  207746. }
  207747. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  207748. {
  207749. if (f == 0)
  207750. return E_INVALIDARG;
  207751. if (f->tymed == format->tymed
  207752. && f->cfFormat == format->cfFormat
  207753. && f->dwAspect == format->dwAspect)
  207754. return S_OK;
  207755. return DV_E_FORMATETC;
  207756. }
  207757. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  207758. {
  207759. pFormatEtcOut->ptd = 0;
  207760. return E_NOTIMPL;
  207761. }
  207762. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  207763. {
  207764. if (result == 0)
  207765. return E_POINTER;
  207766. if (direction == DATADIR_GET)
  207767. {
  207768. *result = new JuceEnumFormatEtc (format);
  207769. return S_OK;
  207770. }
  207771. *result = 0;
  207772. return E_NOTIMPL;
  207773. }
  207774. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  207775. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  207776. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  207777. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  207778. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  207779. };
  207780. static HDROP createHDrop (const StringArray& fileNames) throw()
  207781. {
  207782. int totalChars = 0;
  207783. for (int i = fileNames.size(); --i >= 0;)
  207784. totalChars += fileNames[i].length() + 1;
  207785. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  207786. sizeof (DROPFILES)
  207787. + sizeof (WCHAR) * (totalChars + 2));
  207788. if (hDrop != 0)
  207789. {
  207790. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  207791. pDropFiles->pFiles = sizeof (DROPFILES);
  207792. pDropFiles->fWide = true;
  207793. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  207794. for (int i = 0; i < fileNames.size(); ++i)
  207795. {
  207796. fileNames[i].copyToBuffer (fname, 2048);
  207797. fname += fileNames[i].length() + 1;
  207798. }
  207799. *fname = 0;
  207800. GlobalUnlock (hDrop);
  207801. }
  207802. return hDrop;
  207803. }
  207804. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  207805. {
  207806. JuceDropSource* const source = new JuceDropSource();
  207807. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  207808. DWORD effect;
  207809. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  207810. data->Release();
  207811. source->Release();
  207812. return res == DRAGDROP_S_DROP;
  207813. }
  207814. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  207815. {
  207816. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207817. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207818. medium.hGlobal = createHDrop (files);
  207819. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  207820. : DROPEFFECT_COPY);
  207821. }
  207822. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  207823. {
  207824. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207825. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207826. const int numChars = text.length();
  207827. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  207828. char* d = (char*) GlobalLock (medium.hGlobal);
  207829. text.copyToBuffer ((WCHAR*) d, numChars + 1);
  207830. format.cfFormat = CF_UNICODETEXT;
  207831. GlobalUnlock (medium.hGlobal);
  207832. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  207833. }
  207834. #if JUCE_OPENGL
  207835. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  207836. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  207837. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  207838. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  207839. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  207840. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  207841. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  207842. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  207843. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  207844. #define WGL_ACCELERATION_ARB 0x2003
  207845. #define WGL_SWAP_METHOD_ARB 0x2007
  207846. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  207847. #define WGL_PIXEL_TYPE_ARB 0x2013
  207848. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  207849. #define WGL_COLOR_BITS_ARB 0x2014
  207850. #define WGL_RED_BITS_ARB 0x2015
  207851. #define WGL_GREEN_BITS_ARB 0x2017
  207852. #define WGL_BLUE_BITS_ARB 0x2019
  207853. #define WGL_ALPHA_BITS_ARB 0x201B
  207854. #define WGL_DEPTH_BITS_ARB 0x2022
  207855. #define WGL_STENCIL_BITS_ARB 0x2023
  207856. #define WGL_FULL_ACCELERATION_ARB 0x2027
  207857. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  207858. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  207859. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  207860. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  207861. #define WGL_STEREO_ARB 0x2012
  207862. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  207863. #define WGL_SAMPLES_ARB 0x2042
  207864. #define WGL_TYPE_RGBA_ARB 0x202B
  207865. static void getWglExtensions (HDC dc, StringArray& result) throw()
  207866. {
  207867. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  207868. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  207869. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  207870. else
  207871. jassertfalse // If this fails, it may be because you didn't activate the openGL context
  207872. }
  207873. class WindowedGLContext : public OpenGLContext
  207874. {
  207875. public:
  207876. WindowedGLContext (Component* const component_,
  207877. HGLRC contextToShareWith,
  207878. const OpenGLPixelFormat& pixelFormat)
  207879. : renderContext (0),
  207880. nativeWindow (0),
  207881. dc (0),
  207882. component (component_)
  207883. {
  207884. jassert (component != 0);
  207885. createNativeWindow();
  207886. // Use a default pixel format that should be supported everywhere
  207887. PIXELFORMATDESCRIPTOR pfd;
  207888. zerostruct (pfd);
  207889. pfd.nSize = sizeof (pfd);
  207890. pfd.nVersion = 1;
  207891. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  207892. pfd.iPixelType = PFD_TYPE_RGBA;
  207893. pfd.cColorBits = 24;
  207894. pfd.cDepthBits = 16;
  207895. const int format = ChoosePixelFormat (dc, &pfd);
  207896. if (format != 0)
  207897. SetPixelFormat (dc, format, &pfd);
  207898. renderContext = wglCreateContext (dc);
  207899. makeActive();
  207900. setPixelFormat (pixelFormat);
  207901. if (contextToShareWith != 0 && renderContext != 0)
  207902. wglShareLists (contextToShareWith, renderContext);
  207903. }
  207904. ~WindowedGLContext()
  207905. {
  207906. makeInactive();
  207907. wglDeleteContext (renderContext);
  207908. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  207909. delete nativeWindow;
  207910. }
  207911. bool makeActive() const throw()
  207912. {
  207913. jassert (renderContext != 0);
  207914. return wglMakeCurrent (dc, renderContext) != 0;
  207915. }
  207916. bool makeInactive() const throw()
  207917. {
  207918. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  207919. }
  207920. bool isActive() const throw()
  207921. {
  207922. return wglGetCurrentContext() == renderContext;
  207923. }
  207924. const OpenGLPixelFormat getPixelFormat() const
  207925. {
  207926. OpenGLPixelFormat pf;
  207927. makeActive();
  207928. StringArray availableExtensions;
  207929. getWglExtensions (dc, availableExtensions);
  207930. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  207931. return pf;
  207932. }
  207933. void* getRawContext() const throw()
  207934. {
  207935. return renderContext;
  207936. }
  207937. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  207938. {
  207939. makeActive();
  207940. PIXELFORMATDESCRIPTOR pfd;
  207941. zerostruct (pfd);
  207942. pfd.nSize = sizeof (pfd);
  207943. pfd.nVersion = 1;
  207944. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  207945. pfd.iPixelType = PFD_TYPE_RGBA;
  207946. pfd.iLayerType = PFD_MAIN_PLANE;
  207947. pfd.cColorBits = pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits;
  207948. pfd.cRedBits = pixelFormat.redBits;
  207949. pfd.cGreenBits = pixelFormat.greenBits;
  207950. pfd.cBlueBits = pixelFormat.blueBits;
  207951. pfd.cAlphaBits = pixelFormat.alphaBits;
  207952. pfd.cDepthBits = pixelFormat.depthBufferBits;
  207953. pfd.cStencilBits = pixelFormat.stencilBufferBits;
  207954. pfd.cAccumBits = pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  207955. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits;
  207956. pfd.cAccumRedBits = pixelFormat.accumulationBufferRedBits;
  207957. pfd.cAccumGreenBits = pixelFormat.accumulationBufferGreenBits;
  207958. pfd.cAccumBlueBits = pixelFormat.accumulationBufferBlueBits;
  207959. pfd.cAccumAlphaBits = pixelFormat.accumulationBufferAlphaBits;
  207960. int format = 0;
  207961. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  207962. StringArray availableExtensions;
  207963. getWglExtensions (dc, availableExtensions);
  207964. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  207965. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  207966. {
  207967. int attributes[64];
  207968. int n = 0;
  207969. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  207970. attributes[n++] = GL_TRUE;
  207971. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  207972. attributes[n++] = GL_TRUE;
  207973. attributes[n++] = WGL_ACCELERATION_ARB;
  207974. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  207975. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  207976. attributes[n++] = GL_TRUE;
  207977. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  207978. attributes[n++] = WGL_TYPE_RGBA_ARB;
  207979. attributes[n++] = WGL_COLOR_BITS_ARB;
  207980. attributes[n++] = pfd.cColorBits;
  207981. attributes[n++] = WGL_RED_BITS_ARB;
  207982. attributes[n++] = pixelFormat.redBits;
  207983. attributes[n++] = WGL_GREEN_BITS_ARB;
  207984. attributes[n++] = pixelFormat.greenBits;
  207985. attributes[n++] = WGL_BLUE_BITS_ARB;
  207986. attributes[n++] = pixelFormat.blueBits;
  207987. attributes[n++] = WGL_ALPHA_BITS_ARB;
  207988. attributes[n++] = pixelFormat.alphaBits;
  207989. attributes[n++] = WGL_DEPTH_BITS_ARB;
  207990. attributes[n++] = pixelFormat.depthBufferBits;
  207991. if (pixelFormat.stencilBufferBits > 0)
  207992. {
  207993. attributes[n++] = WGL_STENCIL_BITS_ARB;
  207994. attributes[n++] = pixelFormat.stencilBufferBits;
  207995. }
  207996. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  207997. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  207998. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  207999. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  208000. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  208001. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  208002. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208003. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  208004. if (availableExtensions.contains ("WGL_ARB_multisample")
  208005. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  208006. {
  208007. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  208008. attributes[n++] = 1;
  208009. attributes[n++] = WGL_SAMPLES_ARB;
  208010. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  208011. }
  208012. attributes[n++] = 0;
  208013. UINT formatsCount;
  208014. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  208015. (void) ok;
  208016. jassert (ok);
  208017. }
  208018. else
  208019. {
  208020. format = ChoosePixelFormat (dc, &pfd);
  208021. }
  208022. if (format != 0)
  208023. {
  208024. makeInactive();
  208025. // win32 can't change the pixel format of a window, so need to delete the
  208026. // old one and create a new one..
  208027. jassert (nativeWindow != 0);
  208028. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  208029. delete nativeWindow;
  208030. createNativeWindow();
  208031. if (SetPixelFormat (dc, format, &pfd))
  208032. {
  208033. wglDeleteContext (renderContext);
  208034. renderContext = wglCreateContext (dc);
  208035. jassert (renderContext != 0);
  208036. return renderContext != 0;
  208037. }
  208038. }
  208039. return false;
  208040. }
  208041. void updateWindowPosition (int x, int y, int w, int h, int)
  208042. {
  208043. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  208044. x, y, w, h,
  208045. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  208046. }
  208047. void repaint()
  208048. {
  208049. int x, y, w, h;
  208050. nativeWindow->getBounds (x, y, w, h);
  208051. nativeWindow->repaint (0, 0, w, h);
  208052. }
  208053. void swapBuffers()
  208054. {
  208055. SwapBuffers (dc);
  208056. }
  208057. bool setSwapInterval (const int numFramesPerSwap)
  208058. {
  208059. makeActive();
  208060. StringArray availableExtensions;
  208061. getWglExtensions (dc, availableExtensions);
  208062. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  208063. return availableExtensions.contains ("WGL_EXT_swap_control")
  208064. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  208065. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  208066. }
  208067. int getSwapInterval() const
  208068. {
  208069. makeActive();
  208070. StringArray availableExtensions;
  208071. getWglExtensions (dc, availableExtensions);
  208072. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  208073. if (availableExtensions.contains ("WGL_EXT_swap_control")
  208074. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  208075. return wglGetSwapIntervalEXT();
  208076. return 0;
  208077. }
  208078. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  208079. {
  208080. jassert (isActive());
  208081. StringArray availableExtensions;
  208082. getWglExtensions (dc, availableExtensions);
  208083. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208084. int numTypes = 0;
  208085. if (availableExtensions.contains("WGL_ARB_pixel_format")
  208086. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208087. {
  208088. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  208089. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  208090. jassertfalse
  208091. }
  208092. else
  208093. {
  208094. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  208095. }
  208096. OpenGLPixelFormat pf;
  208097. for (int i = 0; i < numTypes; ++i)
  208098. {
  208099. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  208100. {
  208101. bool alreadyListed = false;
  208102. for (int j = results.size(); --j >= 0;)
  208103. if (pf == *results.getUnchecked(j))
  208104. alreadyListed = true;
  208105. if (! alreadyListed)
  208106. results.add (new OpenGLPixelFormat (pf));
  208107. }
  208108. }
  208109. }
  208110. juce_UseDebuggingNewOperator
  208111. HGLRC renderContext;
  208112. private:
  208113. Win32ComponentPeer* nativeWindow;
  208114. Component* const component;
  208115. HDC dc;
  208116. void createNativeWindow()
  208117. {
  208118. nativeWindow = new Win32ComponentPeer (component, 0);
  208119. nativeWindow->dontRepaint = true;
  208120. nativeWindow->setVisible (true);
  208121. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  208122. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  208123. if (peer != 0)
  208124. {
  208125. SetParent (hwnd, (HWND) peer->getNativeHandle());
  208126. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  208127. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  208128. }
  208129. dc = GetDC (hwnd);
  208130. }
  208131. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  208132. OpenGLPixelFormat& result,
  208133. const StringArray& availableExtensions) const throw()
  208134. {
  208135. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208136. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208137. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208138. {
  208139. int attributes[32];
  208140. int numAttributes = 0;
  208141. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  208142. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  208143. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  208144. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  208145. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  208146. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  208147. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  208148. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  208149. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  208150. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  208151. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  208152. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  208153. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  208154. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  208155. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208156. if (availableExtensions.contains ("WGL_ARB_multisample"))
  208157. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  208158. int values[32];
  208159. zeromem (values, sizeof (values));
  208160. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  208161. {
  208162. int n = 0;
  208163. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  208164. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  208165. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  208166. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  208167. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  208168. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  208169. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  208170. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  208171. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  208172. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  208173. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  208174. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  208175. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  208176. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  208177. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  208178. result.fullSceneAntiAliasingNumSamples = values[n++]; // WGL_SAMPLES_ARB
  208179. return isValidFormat;
  208180. }
  208181. else
  208182. {
  208183. jassertfalse
  208184. }
  208185. }
  208186. else
  208187. {
  208188. PIXELFORMATDESCRIPTOR pfd;
  208189. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  208190. {
  208191. result.redBits = pfd.cRedBits;
  208192. result.greenBits = pfd.cGreenBits;
  208193. result.blueBits = pfd.cBlueBits;
  208194. result.alphaBits = pfd.cAlphaBits;
  208195. result.depthBufferBits = pfd.cDepthBits;
  208196. result.stencilBufferBits = pfd.cStencilBits;
  208197. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  208198. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  208199. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  208200. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  208201. result.fullSceneAntiAliasingNumSamples = 0;
  208202. return true;
  208203. }
  208204. else
  208205. {
  208206. jassertfalse
  208207. }
  208208. }
  208209. return false;
  208210. }
  208211. WindowedGLContext (const WindowedGLContext&);
  208212. const WindowedGLContext& operator= (const WindowedGLContext&);
  208213. };
  208214. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  208215. const OpenGLPixelFormat& pixelFormat,
  208216. const OpenGLContext* const contextToShareWith)
  208217. {
  208218. WindowedGLContext* c = new WindowedGLContext (component,
  208219. contextToShareWith != 0 ? (HGLRC) contextToShareWith->getRawContext() : 0,
  208220. pixelFormat);
  208221. if (c->renderContext == 0)
  208222. deleteAndZero (c);
  208223. return c;
  208224. }
  208225. void juce_glViewport (const int w, const int h)
  208226. {
  208227. glViewport (0, 0, w, h);
  208228. }
  208229. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  208230. OwnedArray <OpenGLPixelFormat>& results)
  208231. {
  208232. Component tempComp;
  208233. {
  208234. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  208235. wc.makeActive();
  208236. wc.findAlternativeOpenGLPixelFormats (results);
  208237. }
  208238. }
  208239. #endif
  208240. class JuceIStorage : public IStorage
  208241. {
  208242. int refCount;
  208243. public:
  208244. JuceIStorage() : refCount (1) {}
  208245. virtual ~JuceIStorage()
  208246. {
  208247. jassert (refCount == 0);
  208248. }
  208249. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  208250. {
  208251. if (id == IID_IUnknown || id == IID_IStorage)
  208252. {
  208253. AddRef();
  208254. *result = this;
  208255. return S_OK;
  208256. }
  208257. *result = 0;
  208258. return E_NOINTERFACE;
  208259. }
  208260. ULONG __stdcall AddRef() { return ++refCount; }
  208261. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  208262. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208263. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208264. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  208265. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  208266. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  208267. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  208268. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  208269. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  208270. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  208271. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  208272. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  208273. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  208274. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  208275. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  208276. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  208277. juce_UseDebuggingNewOperator
  208278. };
  208279. class JuceOleInPlaceFrame : public IOleInPlaceFrame
  208280. {
  208281. int refCount;
  208282. HWND window;
  208283. public:
  208284. JuceOleInPlaceFrame (HWND window_)
  208285. : refCount (1),
  208286. window (window_)
  208287. {
  208288. }
  208289. virtual ~JuceOleInPlaceFrame()
  208290. {
  208291. jassert (refCount == 0);
  208292. }
  208293. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  208294. {
  208295. if (id == IID_IUnknown || id == IID_IOleInPlaceFrame)
  208296. {
  208297. AddRef();
  208298. *result = this;
  208299. return S_OK;
  208300. }
  208301. *result = 0;
  208302. return E_NOINTERFACE;
  208303. }
  208304. ULONG __stdcall AddRef() { return ++refCount; }
  208305. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  208306. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208307. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208308. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  208309. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208310. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208311. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  208312. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  208313. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  208314. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  208315. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  208316. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  208317. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  208318. juce_UseDebuggingNewOperator
  208319. };
  208320. class JuceIOleInPlaceSite : public IOleInPlaceSite
  208321. {
  208322. int refCount;
  208323. HWND window;
  208324. JuceOleInPlaceFrame* frame;
  208325. public:
  208326. JuceIOleInPlaceSite (HWND window_)
  208327. : refCount (1),
  208328. window (window_)
  208329. {
  208330. frame = new JuceOleInPlaceFrame (window);
  208331. }
  208332. virtual ~JuceIOleInPlaceSite()
  208333. {
  208334. jassert (refCount == 0);
  208335. frame->Release();
  208336. }
  208337. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  208338. {
  208339. if (id == IID_IUnknown || id == IID_IOleInPlaceSite)
  208340. {
  208341. AddRef();
  208342. *result = this;
  208343. return S_OK;
  208344. }
  208345. *result = 0;
  208346. return E_NOINTERFACE;
  208347. }
  208348. ULONG __stdcall AddRef() { return ++refCount; }
  208349. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  208350. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208351. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208352. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  208353. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  208354. HRESULT __stdcall OnUIActivate() { return S_OK; }
  208355. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  208356. {
  208357. frame->AddRef();
  208358. *lplpFrame = frame;
  208359. *lplpDoc = 0;
  208360. lpFrameInfo->fMDIApp = FALSE;
  208361. lpFrameInfo->hwndFrame = window;
  208362. lpFrameInfo->haccel = 0;
  208363. lpFrameInfo->cAccelEntries = 0;
  208364. return S_OK;
  208365. }
  208366. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  208367. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  208368. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  208369. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  208370. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  208371. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  208372. juce_UseDebuggingNewOperator
  208373. };
  208374. class JuceIOleClientSite : public IOleClientSite
  208375. {
  208376. int refCount;
  208377. JuceIOleInPlaceSite* inplaceSite;
  208378. public:
  208379. JuceIOleClientSite (HWND window)
  208380. : refCount (1)
  208381. {
  208382. inplaceSite = new JuceIOleInPlaceSite (window);
  208383. }
  208384. virtual ~JuceIOleClientSite()
  208385. {
  208386. jassert (refCount == 0);
  208387. inplaceSite->Release();
  208388. }
  208389. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  208390. {
  208391. if (id == IID_IUnknown || id == IID_IOleClientSite)
  208392. {
  208393. AddRef();
  208394. *result = this;
  208395. return S_OK;
  208396. }
  208397. else if (id == IID_IOleInPlaceSite)
  208398. {
  208399. inplaceSite->AddRef();
  208400. *result = inplaceSite;
  208401. return S_OK;
  208402. }
  208403. *result = 0;
  208404. return E_NOINTERFACE;
  208405. }
  208406. ULONG __stdcall AddRef() { return ++refCount; }
  208407. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  208408. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  208409. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  208410. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  208411. HRESULT __stdcall ShowObject() { return S_OK; }
  208412. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  208413. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  208414. juce_UseDebuggingNewOperator
  208415. };
  208416. class ActiveXControlData : public ComponentMovementWatcher
  208417. {
  208418. ActiveXControlComponent* const owner;
  208419. bool wasShowing;
  208420. public:
  208421. HWND controlHWND;
  208422. IStorage* storage;
  208423. IOleClientSite* clientSite;
  208424. IOleObject* control;
  208425. ActiveXControlData (HWND hwnd,
  208426. ActiveXControlComponent* const owner_)
  208427. : ComponentMovementWatcher (owner_),
  208428. owner (owner_),
  208429. wasShowing (owner_ != 0 && owner_->isShowing()),
  208430. controlHWND (0),
  208431. storage (new JuceIStorage()),
  208432. clientSite (new JuceIOleClientSite (hwnd)),
  208433. control (0)
  208434. {
  208435. }
  208436. ~ActiveXControlData()
  208437. {
  208438. if (control != 0)
  208439. {
  208440. control->Close (OLECLOSE_NOSAVE);
  208441. control->Release();
  208442. }
  208443. clientSite->Release();
  208444. storage->Release();
  208445. }
  208446. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  208447. {
  208448. Component* const topComp = owner->getTopLevelComponent();
  208449. if (topComp->getPeer() != 0)
  208450. {
  208451. int x = 0, y = 0;
  208452. owner->relativePositionToOtherComponent (topComp, x, y);
  208453. owner->setControlBounds (Rectangle (x, y, owner->getWidth(), owner->getHeight()));
  208454. }
  208455. }
  208456. void componentPeerChanged()
  208457. {
  208458. const bool isShowingNow = owner->isShowing();
  208459. if (wasShowing != isShowingNow)
  208460. {
  208461. wasShowing = isShowingNow;
  208462. owner->setControlVisible (isShowingNow);
  208463. }
  208464. }
  208465. void componentVisibilityChanged (Component&)
  208466. {
  208467. componentPeerChanged();
  208468. }
  208469. static bool doesWindowMatch (const ActiveXControlComponent* const ax, HWND hwnd)
  208470. {
  208471. return ((ActiveXControlData*) ax->control)->controlHWND == hwnd;
  208472. }
  208473. };
  208474. static VoidArray activeXComps;
  208475. static HWND getHWND (const ActiveXControlComponent* const component)
  208476. {
  208477. HWND hwnd = 0;
  208478. const IID iid = IID_IOleWindow;
  208479. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  208480. if (window != 0)
  208481. {
  208482. window->GetWindow (&hwnd);
  208483. window->Release();
  208484. }
  208485. return hwnd;
  208486. }
  208487. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  208488. {
  208489. RECT activeXRect, peerRect;
  208490. GetWindowRect (hwnd, &activeXRect);
  208491. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  208492. const int mx = GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left;
  208493. const int my = GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top;
  208494. const int64 mouseEventTime = getMouseEventTime();
  208495. const int oldModifiers = currentModifiers;
  208496. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  208497. switch (message)
  208498. {
  208499. case WM_MOUSEMOVE:
  208500. if (ModifierKeys (currentModifiers).isAnyMouseButtonDown())
  208501. peer->handleMouseDrag (mx, my, mouseEventTime);
  208502. else
  208503. peer->handleMouseMove (mx, my, mouseEventTime);
  208504. break;
  208505. case WM_LBUTTONDOWN:
  208506. case WM_MBUTTONDOWN:
  208507. case WM_RBUTTONDOWN:
  208508. peer->handleMouseDown (mx, my, mouseEventTime);
  208509. break;
  208510. case WM_LBUTTONUP:
  208511. case WM_MBUTTONUP:
  208512. case WM_RBUTTONUP:
  208513. peer->handleMouseUp (oldModifiers, mx, my, mouseEventTime);
  208514. break;
  208515. default:
  208516. break;
  208517. }
  208518. }
  208519. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  208520. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  208521. {
  208522. for (int i = activeXComps.size(); --i >= 0;)
  208523. {
  208524. const ActiveXControlComponent* const ax = (const ActiveXControlComponent*) activeXComps.getUnchecked(i);
  208525. if (ActiveXControlData::doesWindowMatch (ax, hwnd))
  208526. {
  208527. switch (message)
  208528. {
  208529. case WM_MOUSEMOVE:
  208530. case WM_LBUTTONDOWN:
  208531. case WM_MBUTTONDOWN:
  208532. case WM_RBUTTONDOWN:
  208533. case WM_LBUTTONUP:
  208534. case WM_MBUTTONUP:
  208535. case WM_RBUTTONUP:
  208536. case WM_LBUTTONDBLCLK:
  208537. case WM_MBUTTONDBLCLK:
  208538. case WM_RBUTTONDBLCLK:
  208539. if (ax->isShowing())
  208540. {
  208541. ComponentPeer* const peer = ax->getPeer();
  208542. if (peer != 0)
  208543. {
  208544. offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  208545. if (! ax->areMouseEventsAllowed())
  208546. return 0;
  208547. }
  208548. }
  208549. break;
  208550. default:
  208551. break;
  208552. }
  208553. return CallWindowProc ((WNDPROC) (ax->originalWndProc), hwnd, message, wParam, lParam);
  208554. }
  208555. }
  208556. return DefWindowProc (hwnd, message, wParam, lParam);
  208557. }
  208558. ActiveXControlComponent::ActiveXControlComponent()
  208559. : originalWndProc (0),
  208560. control (0),
  208561. mouseEventsAllowed (true)
  208562. {
  208563. activeXComps.add (this);
  208564. }
  208565. ActiveXControlComponent::~ActiveXControlComponent()
  208566. {
  208567. deleteControl();
  208568. activeXComps.removeValue (this);
  208569. }
  208570. void ActiveXControlComponent::paint (Graphics& g)
  208571. {
  208572. if (control == 0)
  208573. g.fillAll (Colours::lightgrey);
  208574. }
  208575. bool ActiveXControlComponent::createControl (const void* controlIID)
  208576. {
  208577. deleteControl();
  208578. ComponentPeer* const peer = getPeer();
  208579. // the component must have already been added to a real window when you call this!
  208580. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  208581. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  208582. {
  208583. int x = 0, y = 0;
  208584. relativePositionToOtherComponent (getTopLevelComponent(), x, y);
  208585. HWND hwnd = (HWND) peer->getNativeHandle();
  208586. ActiveXControlData* const info = new ActiveXControlData (hwnd, this);
  208587. HRESULT hr;
  208588. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  208589. info->clientSite, info->storage,
  208590. (void**) &(info->control))) == S_OK)
  208591. {
  208592. info->control->SetHostNames (L"Juce", 0);
  208593. if (OleSetContainedObject (info->control, TRUE) == S_OK)
  208594. {
  208595. RECT rect;
  208596. rect.left = x;
  208597. rect.top = y;
  208598. rect.right = x + getWidth();
  208599. rect.bottom = y + getHeight();
  208600. if (info->control->DoVerb (OLEIVERB_SHOW, 0, info->clientSite, 0, hwnd, &rect) == S_OK)
  208601. {
  208602. control = info;
  208603. setControlBounds (Rectangle (x, y, getWidth(), getHeight()));
  208604. info->controlHWND = getHWND (this);
  208605. if (info->controlHWND != 0)
  208606. {
  208607. originalWndProc = (void*) GetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC);
  208608. SetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC, (LONG_PTR) activeXHookWndProc);
  208609. }
  208610. return true;
  208611. }
  208612. }
  208613. }
  208614. delete info;
  208615. }
  208616. return false;
  208617. }
  208618. void ActiveXControlComponent::deleteControl()
  208619. {
  208620. ActiveXControlData* const info = (ActiveXControlData*) control;
  208621. if (info != 0)
  208622. {
  208623. delete info;
  208624. control = 0;
  208625. originalWndProc = 0;
  208626. }
  208627. }
  208628. void* ActiveXControlComponent::queryInterface (const void* iid) const
  208629. {
  208630. ActiveXControlData* const info = (ActiveXControlData*) control;
  208631. void* result = 0;
  208632. if (info != 0 && info->control != 0
  208633. && info->control->QueryInterface (*(const IID*) iid, &result) == S_OK)
  208634. return result;
  208635. return 0;
  208636. }
  208637. void ActiveXControlComponent::setControlBounds (const Rectangle& newBounds) const
  208638. {
  208639. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  208640. if (hwnd != 0)
  208641. MoveWindow (hwnd, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  208642. }
  208643. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  208644. {
  208645. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  208646. if (hwnd != 0)
  208647. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  208648. }
  208649. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  208650. {
  208651. mouseEventsAllowed = eventsCanReachControl;
  208652. }
  208653. END_JUCE_NAMESPACE
  208654. /********* End of inlined file: juce_win32_Windowing.cpp *********/
  208655. #endif
  208656. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  208657. // Auto-links to various win32 libs that are needed by library calls..
  208658. #pragma comment(lib, "kernel32.lib")
  208659. #pragma comment(lib, "user32.lib")
  208660. #pragma comment(lib, "shell32.lib")
  208661. #pragma comment(lib, "gdi32.lib")
  208662. #pragma comment(lib, "vfw32.lib")
  208663. #pragma comment(lib, "comdlg32.lib")
  208664. #pragma comment(lib, "winmm.lib")
  208665. #pragma comment(lib, "wininet.lib")
  208666. #pragma comment(lib, "ole32.lib")
  208667. #pragma comment(lib, "advapi32.lib")
  208668. #pragma comment(lib, "ws2_32.lib")
  208669. #pragma comment(lib, "comsupp.lib")
  208670. #if JUCE_OPENGL
  208671. #pragma comment(lib, "OpenGL32.Lib")
  208672. #pragma comment(lib, "GlU32.Lib")
  208673. #endif
  208674. #if JUCE_QUICKTIME
  208675. #pragma comment (lib, "QTMLClient.lib")
  208676. #endif
  208677. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  208678. #endif
  208679. //==============================================================================
  208680. #if JUCE_LINUX
  208681. /********* Start of inlined file: juce_linux_Files.cpp *********/
  208682. /********* Start of inlined file: linuxincludes.h *********/
  208683. #ifndef __LINUXINCLUDES_JUCEHEADER__
  208684. #define __LINUXINCLUDES_JUCEHEADER__
  208685. // Linux Header Files:
  208686. #include <unistd.h>
  208687. #include <stdlib.h>
  208688. #include <sched.h>
  208689. #include <pthread.h>
  208690. #include <sys/time.h>
  208691. #include <errno.h>
  208692. /* Remove this macro if you're having problems compiling the cpu affinity
  208693. calls (the API for these has changed about quite a bit in various Linux
  208694. versions, and a lot of distros seem to ship with obsolete versions)
  208695. */
  208696. #ifndef SUPPORT_AFFINITIES
  208697. #define SUPPORT_AFFINITIES 1
  208698. #endif
  208699. #endif // __LINUXINCLUDES_JUCEHEADER__
  208700. /********* End of inlined file: linuxincludes.h *********/
  208701. #include <sys/stat.h>
  208702. #include <sys/dir.h>
  208703. #include <sys/ptrace.h>
  208704. #include <sys/vfs.h> // for statfs
  208705. #include <sys/wait.h>
  208706. #include <unistd.h>
  208707. #include <fnmatch.h>
  208708. #include <utime.h>
  208709. #include <pwd.h>
  208710. #include <fcntl.h>
  208711. #define U_ISOFS_SUPER_MAGIC (short) 0x9660 // linux/iso_fs.h
  208712. #define U_MSDOS_SUPER_MAGIC (short) 0x4d44 // linux/msdos_fs.h
  208713. #define U_NFS_SUPER_MAGIC (short) 0x6969 // linux/nfs_fs.h
  208714. #define U_SMB_SUPER_MAGIC (short) 0x517B // linux/smb_fs.h
  208715. BEGIN_JUCE_NAMESPACE
  208716. /*
  208717. Note that a lot of methods that you'd expect to find in this file actually
  208718. live in juce_posix_SharedCode.cpp!
  208719. */
  208720. /********* Start of inlined file: juce_posix_SharedCode.cpp *********/
  208721. /*
  208722. This file contains posix routines that are common to both the Linux and Mac builds.
  208723. It gets included directly in the cpp files for these platforms.
  208724. */
  208725. CriticalSection::CriticalSection() throw()
  208726. {
  208727. pthread_mutexattr_t atts;
  208728. pthread_mutexattr_init (&atts);
  208729. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  208730. pthread_mutex_init (&internal, &atts);
  208731. }
  208732. CriticalSection::~CriticalSection() throw()
  208733. {
  208734. pthread_mutex_destroy (&internal);
  208735. }
  208736. void CriticalSection::enter() const throw()
  208737. {
  208738. pthread_mutex_lock (&internal);
  208739. }
  208740. bool CriticalSection::tryEnter() const throw()
  208741. {
  208742. return pthread_mutex_trylock (&internal) == 0;
  208743. }
  208744. void CriticalSection::exit() const throw()
  208745. {
  208746. pthread_mutex_unlock (&internal);
  208747. }
  208748. struct EventStruct
  208749. {
  208750. pthread_cond_t condition;
  208751. pthread_mutex_t mutex;
  208752. bool triggered;
  208753. };
  208754. WaitableEvent::WaitableEvent() throw()
  208755. {
  208756. EventStruct* const es = new EventStruct();
  208757. es->triggered = false;
  208758. pthread_cond_init (&es->condition, 0);
  208759. pthread_mutex_init (&es->mutex, 0);
  208760. internal = es;
  208761. }
  208762. WaitableEvent::~WaitableEvent() throw()
  208763. {
  208764. EventStruct* const es = (EventStruct*) internal;
  208765. pthread_cond_destroy (&es->condition);
  208766. pthread_mutex_destroy (&es->mutex);
  208767. delete es;
  208768. }
  208769. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  208770. {
  208771. EventStruct* const es = (EventStruct*) internal;
  208772. bool ok = true;
  208773. pthread_mutex_lock (&es->mutex);
  208774. if (timeOutMillisecs < 0)
  208775. {
  208776. while (! es->triggered)
  208777. pthread_cond_wait (&es->condition, &es->mutex);
  208778. }
  208779. else
  208780. {
  208781. while (! es->triggered)
  208782. {
  208783. struct timeval t;
  208784. gettimeofday (&t, 0);
  208785. struct timespec time;
  208786. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  208787. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  208788. if (time.tv_nsec >= 1000000000)
  208789. {
  208790. time.tv_nsec -= 1000000000;
  208791. time.tv_sec++;
  208792. }
  208793. if (pthread_cond_timedwait (&es->condition, &es->mutex, &time) == ETIMEDOUT)
  208794. {
  208795. ok = false;
  208796. break;
  208797. }
  208798. }
  208799. }
  208800. es->triggered = false;
  208801. pthread_mutex_unlock (&es->mutex);
  208802. return ok;
  208803. }
  208804. void WaitableEvent::signal() const throw()
  208805. {
  208806. EventStruct* const es = (EventStruct*) internal;
  208807. pthread_mutex_lock (&es->mutex);
  208808. es->triggered = true;
  208809. pthread_cond_broadcast (&es->condition);
  208810. pthread_mutex_unlock (&es->mutex);
  208811. }
  208812. void WaitableEvent::reset() const throw()
  208813. {
  208814. EventStruct* const es = (EventStruct*) internal;
  208815. pthread_mutex_lock (&es->mutex);
  208816. es->triggered = false;
  208817. pthread_mutex_unlock (&es->mutex);
  208818. }
  208819. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  208820. {
  208821. struct timespec time;
  208822. time.tv_sec = millisecs / 1000;
  208823. time.tv_nsec = (millisecs % 1000) * 1000000;
  208824. nanosleep (&time, 0);
  208825. }
  208826. const tchar File::separator = T('/');
  208827. const tchar* File::separatorString = T("/");
  208828. bool juce_copyFile (const String& s, const String& d) throw();
  208829. static bool juce_stat (const String& fileName, struct stat& info) throw()
  208830. {
  208831. return fileName.isNotEmpty()
  208832. && (stat (fileName.toUTF8(), &info) == 0);
  208833. }
  208834. bool juce_isDirectory (const String& fileName) throw()
  208835. {
  208836. struct stat info;
  208837. return fileName.isEmpty()
  208838. || (juce_stat (fileName, info)
  208839. && ((info.st_mode & S_IFDIR) != 0));
  208840. }
  208841. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  208842. {
  208843. if (fileName.isEmpty())
  208844. return false;
  208845. const char* const fileNameUTF8 = fileName.toUTF8();
  208846. bool exists = access (fileNameUTF8, F_OK) == 0;
  208847. if (exists && dontCountDirectories)
  208848. {
  208849. struct stat info;
  208850. const int res = stat (fileNameUTF8, &info);
  208851. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  208852. exists = false;
  208853. }
  208854. return exists;
  208855. }
  208856. int64 juce_getFileSize (const String& fileName) throw()
  208857. {
  208858. struct stat info;
  208859. return juce_stat (fileName, info) ? info.st_size : 0;
  208860. }
  208861. bool juce_canWriteToFile (const String& fileName) throw()
  208862. {
  208863. return access (fileName.toUTF8(), W_OK) == 0;
  208864. }
  208865. bool juce_deleteFile (const String& fileName) throw()
  208866. {
  208867. const char* const fileNameUTF8 = fileName.toUTF8();
  208868. if (juce_isDirectory (fileName))
  208869. return rmdir (fileNameUTF8) == 0;
  208870. else
  208871. return remove (fileNameUTF8) == 0;
  208872. }
  208873. bool juce_moveFile (const String& source, const String& dest) throw()
  208874. {
  208875. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  208876. return true;
  208877. if (juce_canWriteToFile (source)
  208878. && juce_copyFile (source, dest))
  208879. {
  208880. if (juce_deleteFile (source))
  208881. return true;
  208882. juce_deleteFile (dest);
  208883. }
  208884. return false;
  208885. }
  208886. void juce_createDirectory (const String& fileName) throw()
  208887. {
  208888. mkdir (fileName.toUTF8(), 0777);
  208889. }
  208890. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  208891. {
  208892. const char* const fileNameUTF8 = fileName.toUTF8();
  208893. int flags = O_RDONLY;
  208894. if (forWriting)
  208895. {
  208896. if (juce_fileExists (fileName, false))
  208897. {
  208898. const int f = open (fileNameUTF8, O_RDWR, 00644);
  208899. if (f != -1)
  208900. lseek (f, 0, SEEK_END);
  208901. return (void*) f;
  208902. }
  208903. else
  208904. {
  208905. flags = O_RDWR + O_CREAT;
  208906. }
  208907. }
  208908. return (void*) open (fileNameUTF8, flags, 00644);
  208909. }
  208910. void juce_fileClose (void* handle) throw()
  208911. {
  208912. if (handle != 0)
  208913. close ((int) (pointer_sized_int) handle);
  208914. }
  208915. int juce_fileRead (void* handle, void* buffer, int size) throw()
  208916. {
  208917. if (handle != 0)
  208918. return read ((int) (pointer_sized_int) handle, buffer, size);
  208919. return 0;
  208920. }
  208921. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  208922. {
  208923. if (handle != 0)
  208924. return write ((int) (pointer_sized_int) handle, buffer, size);
  208925. return 0;
  208926. }
  208927. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  208928. {
  208929. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  208930. return pos;
  208931. return -1;
  208932. }
  208933. int64 juce_fileGetPosition (void* handle) throw()
  208934. {
  208935. if (handle != 0)
  208936. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  208937. else
  208938. return -1;
  208939. }
  208940. void juce_fileFlush (void* handle) throw()
  208941. {
  208942. if (handle != 0)
  208943. fsync ((int) (pointer_sized_int) handle);
  208944. }
  208945. // if this file doesn't exist, find a parent of it that does..
  208946. static bool doStatFS (const File* file, struct statfs& result) throw()
  208947. {
  208948. File f (*file);
  208949. for (int i = 5; --i >= 0;)
  208950. {
  208951. if (f.exists())
  208952. break;
  208953. f = f.getParentDirectory();
  208954. }
  208955. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  208956. }
  208957. int64 File::getBytesFreeOnVolume() const throw()
  208958. {
  208959. int64 free_space = 0;
  208960. struct statfs buf;
  208961. if (doStatFS (this, buf))
  208962. // Note: this returns space available to non-super user
  208963. free_space = (int64) buf.f_bsize * (int64) buf.f_bavail;
  208964. return free_space;
  208965. }
  208966. const String juce_getVolumeLabel (const String& filenameOnVolume,
  208967. int& volumeSerialNumber) throw()
  208968. {
  208969. // There is no equivalent on Linux
  208970. volumeSerialNumber = 0;
  208971. return String::empty;
  208972. }
  208973. #if JUCE_64BIT
  208974. #define filedesc ((long long) internal)
  208975. #else
  208976. #define filedesc ((int) internal)
  208977. #endif
  208978. InterProcessLock::InterProcessLock (const String& name_) throw()
  208979. : internal (0),
  208980. name (name_),
  208981. reentrancyLevel (0)
  208982. {
  208983. #if JUCE_MAC
  208984. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  208985. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  208986. #else
  208987. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  208988. #endif
  208989. temp.create();
  208990. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  208991. }
  208992. InterProcessLock::~InterProcessLock() throw()
  208993. {
  208994. while (reentrancyLevel > 0)
  208995. this->exit();
  208996. close (filedesc);
  208997. }
  208998. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  208999. {
  209000. if (internal == 0)
  209001. return false;
  209002. if (reentrancyLevel != 0)
  209003. return true;
  209004. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  209005. struct flock fl;
  209006. zerostruct (fl);
  209007. fl.l_whence = SEEK_SET;
  209008. fl.l_type = F_WRLCK;
  209009. for (;;)
  209010. {
  209011. const int result = fcntl (filedesc, F_SETLK, &fl);
  209012. if (result >= 0)
  209013. {
  209014. ++reentrancyLevel;
  209015. return true;
  209016. }
  209017. if (errno != EINTR)
  209018. {
  209019. if (timeOutMillisecs == 0
  209020. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  209021. break;
  209022. Thread::sleep (10);
  209023. }
  209024. }
  209025. return false;
  209026. }
  209027. void InterProcessLock::exit() throw()
  209028. {
  209029. if (reentrancyLevel > 0 && internal != 0)
  209030. {
  209031. --reentrancyLevel;
  209032. struct flock fl;
  209033. zerostruct (fl);
  209034. fl.l_whence = SEEK_SET;
  209035. fl.l_type = F_UNLCK;
  209036. for (;;)
  209037. {
  209038. const int result = fcntl (filedesc, F_SETLKW, &fl);
  209039. if (result >= 0 || errno != EINTR)
  209040. break;
  209041. }
  209042. }
  209043. }
  209044. /********* End of inlined file: juce_posix_SharedCode.cpp *********/
  209045. static File executableFile;
  209046. void juce_getFileTimes (const String& fileName,
  209047. int64& modificationTime,
  209048. int64& accessTime,
  209049. int64& creationTime) throw()
  209050. {
  209051. modificationTime = 0;
  209052. accessTime = 0;
  209053. creationTime = 0;
  209054. struct stat info;
  209055. const int res = stat (fileName.toUTF8(), &info);
  209056. if (res == 0)
  209057. {
  209058. modificationTime = (int64) info.st_mtime * 1000;
  209059. accessTime = (int64) info.st_atime * 1000;
  209060. creationTime = (int64) info.st_ctime * 1000;
  209061. }
  209062. }
  209063. bool juce_setFileTimes (const String& fileName,
  209064. int64 modificationTime,
  209065. int64 accessTime,
  209066. int64 creationTime) throw()
  209067. {
  209068. struct utimbuf times;
  209069. times.actime = (time_t) (accessTime / 1000);
  209070. times.modtime = (time_t) (modificationTime / 1000);
  209071. return utime (fileName.toUTF8(), &times) == 0;
  209072. }
  209073. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  209074. {
  209075. struct stat info;
  209076. const int res = stat (fileName.toUTF8(), &info);
  209077. if (res != 0)
  209078. return false;
  209079. info.st_mode &= 0777; // Just permissions
  209080. if( isReadOnly )
  209081. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  209082. else
  209083. // Give everybody write permission?
  209084. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  209085. return chmod (fileName.toUTF8(), info.st_mode) == 0;
  209086. }
  209087. bool juce_copyFile (const String& s, const String& d) throw()
  209088. {
  209089. const File source (s), dest (d);
  209090. FileInputStream* in = source.createInputStream();
  209091. bool ok = false;
  209092. if (in != 0)
  209093. {
  209094. if (dest.deleteFile())
  209095. {
  209096. FileOutputStream* const out = dest.createOutputStream();
  209097. if (out != 0)
  209098. {
  209099. const int bytesCopied = out->writeFromInputStream (*in, -1);
  209100. delete out;
  209101. ok = (bytesCopied == source.getSize());
  209102. if (! ok)
  209103. dest.deleteFile();
  209104. }
  209105. }
  209106. delete in;
  209107. }
  209108. return ok;
  209109. }
  209110. const StringArray juce_getFileSystemRoots() throw()
  209111. {
  209112. StringArray s;
  209113. s.add (T("/"));
  209114. return s;
  209115. }
  209116. bool File::isOnCDRomDrive() const throw()
  209117. {
  209118. struct statfs buf;
  209119. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  209120. return (buf.f_type == U_ISOFS_SUPER_MAGIC);
  209121. // Assume not if this fails for some reason
  209122. return false;
  209123. }
  209124. bool File::isOnHardDisk() const throw()
  209125. {
  209126. struct statfs buf;
  209127. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  209128. {
  209129. switch (buf.f_type)
  209130. {
  209131. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  209132. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  209133. case U_NFS_SUPER_MAGIC: // Network NFS
  209134. case U_SMB_SUPER_MAGIC: // Network Samba
  209135. return false;
  209136. default:
  209137. // Assume anything else is a hard-disk (but note it could
  209138. // be a RAM disk. There isn't a good way of determining
  209139. // this for sure)
  209140. return true;
  209141. }
  209142. }
  209143. // Assume so if this fails for some reason
  209144. return true;
  209145. }
  209146. bool File::isHidden() const throw()
  209147. {
  209148. return getFileName().startsWithChar (T('.'));
  209149. }
  209150. const File File::getSpecialLocation (const SpecialLocationType type)
  209151. {
  209152. switch (type)
  209153. {
  209154. case userHomeDirectory:
  209155. {
  209156. const char* homeDir = getenv ("HOME");
  209157. if (homeDir == 0)
  209158. {
  209159. struct passwd* const pw = getpwuid (getuid());
  209160. if (pw != 0)
  209161. homeDir = pw->pw_dir;
  209162. }
  209163. return File (String::fromUTF8 ((const uint8*) homeDir));
  209164. }
  209165. case userDocumentsDirectory:
  209166. case userMusicDirectory:
  209167. case userMoviesDirectory:
  209168. case userApplicationDataDirectory:
  209169. return File ("~");
  209170. case userDesktopDirectory:
  209171. return File ("~/Desktop");
  209172. case commonApplicationDataDirectory:
  209173. return File ("/var");
  209174. case globalApplicationsDirectory:
  209175. return File ("/usr");
  209176. case tempDirectory:
  209177. {
  209178. File tmp ("/var/tmp");
  209179. if (! tmp.isDirectory())
  209180. {
  209181. tmp = T("/tmp");
  209182. if (! tmp.isDirectory())
  209183. tmp = File::getCurrentWorkingDirectory();
  209184. }
  209185. return tmp;
  209186. }
  209187. case currentExecutableFile:
  209188. case currentApplicationFile:
  209189. // if this fails, it's probably because juce_setCurrentExecutableFileName()
  209190. // was never called to set the filename - this should be done by the juce
  209191. // main() function, so maybe you've hacked it to use your own custom main()?
  209192. jassert (executableFile.exists());
  209193. return executableFile;
  209194. default:
  209195. jassertfalse // unknown type?
  209196. break;
  209197. }
  209198. return File::nonexistent;
  209199. }
  209200. void juce_setCurrentExecutableFileName (const String& filename) throw()
  209201. {
  209202. executableFile = File::getCurrentWorkingDirectory().getChildFile (filename);
  209203. }
  209204. const File File::getCurrentWorkingDirectory() throw()
  209205. {
  209206. char buf [2048];
  209207. getcwd (buf, sizeof(buf));
  209208. return File (String::fromUTF8 ((const uint8*) buf));
  209209. }
  209210. bool File::setAsCurrentWorkingDirectory() const throw()
  209211. {
  209212. return chdir (getFullPathName().toUTF8()) == 0;
  209213. }
  209214. struct FindFileStruct
  209215. {
  209216. String parentDir, wildCard;
  209217. DIR* dir;
  209218. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  209219. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  209220. {
  209221. const char* const wildcardUTF8 = wildCard.toUTF8();
  209222. for (;;)
  209223. {
  209224. struct dirent* const de = readdir (dir);
  209225. if (de == 0)
  209226. break;
  209227. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  209228. {
  209229. result = String::fromUTF8 ((const uint8*) de->d_name);
  209230. const String path (parentDir + result);
  209231. if (isDir != 0 || fileSize != 0)
  209232. {
  209233. struct stat info;
  209234. const bool statOk = (stat (path.toUTF8(), &info) == 0);
  209235. if (isDir != 0)
  209236. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  209237. if (isHidden != 0)
  209238. *isHidden = (de->d_name[0] == '.');
  209239. if (fileSize != 0)
  209240. *fileSize = statOk ? info.st_size : 0;
  209241. }
  209242. if (modTime != 0 || creationTime != 0)
  209243. {
  209244. int64 m, a, c;
  209245. juce_getFileTimes (path, m, a, c);
  209246. if (modTime != 0)
  209247. *modTime = m;
  209248. if (creationTime != 0)
  209249. *creationTime = c;
  209250. }
  209251. if (isReadOnly != 0)
  209252. *isReadOnly = ! juce_canWriteToFile (path);
  209253. return true;
  209254. }
  209255. }
  209256. return false;
  209257. }
  209258. };
  209259. // returns 0 on failure
  209260. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  209261. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  209262. Time* creationTime, bool* isReadOnly) throw()
  209263. {
  209264. DIR* d = opendir (directory.toUTF8());
  209265. if (d != 0)
  209266. {
  209267. FindFileStruct* ff = new FindFileStruct();
  209268. ff->parentDir = directory;
  209269. if (!ff->parentDir.endsWithChar (File::separator))
  209270. ff->parentDir += File::separator;
  209271. ff->wildCard = wildCard;
  209272. if (wildCard == T("*.*"))
  209273. ff->wildCard = T("*");
  209274. ff->dir = d;
  209275. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  209276. {
  209277. return ff;
  209278. }
  209279. else
  209280. {
  209281. firstResultFile = String::empty;
  209282. isDir = false;
  209283. isHidden = false;
  209284. closedir (d);
  209285. delete ff;
  209286. }
  209287. }
  209288. return 0;
  209289. }
  209290. bool juce_findFileNext (void* handle, String& resultFile,
  209291. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  209292. {
  209293. FindFileStruct* const ff = (FindFileStruct*) handle;
  209294. if (ff != 0)
  209295. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  209296. return false;
  209297. }
  209298. void juce_findFileClose (void* handle) throw()
  209299. {
  209300. FindFileStruct* const ff = (FindFileStruct*) handle;
  209301. if (ff != 0)
  209302. {
  209303. closedir (ff->dir);
  209304. delete ff;
  209305. }
  209306. }
  209307. bool juce_launchFile (const String& fileName,
  209308. const String& parameters) throw()
  209309. {
  209310. String cmdString (fileName);
  209311. cmdString << " " << parameters;
  209312. if (URL::isProbablyAWebsiteURL (cmdString) || URL::isProbablyAnEmailAddress (cmdString))
  209313. {
  209314. // create a command that tries to launch a bunch of likely browsers
  209315. const char* const browserNames[] = { "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  209316. StringArray cmdLines;
  209317. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  209318. cmdLines.add (String (browserNames[i]) + T(" ") + cmdString.trim().quoted());
  209319. cmdString = cmdLines.joinIntoString (T(" || "));
  209320. }
  209321. char* const argv[4] = { "/bin/sh", "-c", (char*) cmdString.toUTF8(), 0 };
  209322. const int cpid = fork();
  209323. if (cpid == 0)
  209324. {
  209325. setsid();
  209326. // Child process
  209327. execve (argv[0], argv, environ);
  209328. exit (0);
  209329. }
  209330. return cpid >= 0;
  209331. }
  209332. END_JUCE_NAMESPACE
  209333. /********* End of inlined file: juce_linux_Files.cpp *********/
  209334. /********* Start of inlined file: juce_linux_NamedPipe.cpp *********/
  209335. /********* Start of inlined file: juce_mac_NamedPipe.cpp *********/
  209336. #include <sys/stat.h>
  209337. #include <sys/dir.h>
  209338. #include <fcntl.h>
  209339. // As well as being for the mac, this file is included by the linux build.
  209340. #if ! JUCE_MAC
  209341. #include <sys/wait.h>
  209342. #include <errno.h>
  209343. #include <unistd.h>
  209344. #endif
  209345. BEGIN_JUCE_NAMESPACE
  209346. struct NamedPipeInternal
  209347. {
  209348. String pipeInName, pipeOutName;
  209349. int pipeIn, pipeOut;
  209350. bool volatile createdPipe, blocked, stopReadOperation;
  209351. static void signalHandler (int) {}
  209352. };
  209353. void NamedPipe::cancelPendingReads()
  209354. {
  209355. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  209356. {
  209357. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  209358. intern->stopReadOperation = true;
  209359. char buffer [1] = { 0 };
  209360. ::write (intern->pipeIn, buffer, 1);
  209361. int timeout = 2000;
  209362. while (intern->blocked && --timeout >= 0)
  209363. Thread::sleep (2);
  209364. intern->stopReadOperation = false;
  209365. }
  209366. }
  209367. void NamedPipe::close()
  209368. {
  209369. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  209370. if (intern != 0)
  209371. {
  209372. internal = 0;
  209373. if (intern->pipeIn != -1)
  209374. ::close (intern->pipeIn);
  209375. if (intern->pipeOut != -1)
  209376. ::close (intern->pipeOut);
  209377. if (intern->createdPipe)
  209378. {
  209379. unlink (intern->pipeInName);
  209380. unlink (intern->pipeOutName);
  209381. }
  209382. delete intern;
  209383. }
  209384. }
  209385. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  209386. {
  209387. close();
  209388. NamedPipeInternal* const intern = new NamedPipeInternal();
  209389. internal = intern;
  209390. intern->createdPipe = createPipe;
  209391. intern->blocked = false;
  209392. intern->stopReadOperation = false;
  209393. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  209394. siginterrupt (SIGPIPE, 1);
  209395. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  209396. intern->pipeInName = pipePath + T("_in");
  209397. intern->pipeOutName = pipePath + T("_out");
  209398. intern->pipeIn = -1;
  209399. intern->pipeOut = -1;
  209400. if (createPipe)
  209401. {
  209402. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  209403. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  209404. {
  209405. delete intern;
  209406. internal = 0;
  209407. return false;
  209408. }
  209409. }
  209410. return true;
  209411. }
  209412. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  209413. {
  209414. int bytesRead = -1;
  209415. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  209416. if (intern != 0)
  209417. {
  209418. intern->blocked = true;
  209419. if (intern->pipeIn == -1)
  209420. {
  209421. if (intern->createdPipe)
  209422. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  209423. else
  209424. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  209425. if (intern->pipeIn == -1)
  209426. {
  209427. intern->blocked = false;
  209428. return -1;
  209429. }
  209430. }
  209431. bytesRead = 0;
  209432. char* p = (char*) destBuffer;
  209433. while (bytesRead < maxBytesToRead)
  209434. {
  209435. const int bytesThisTime = maxBytesToRead - bytesRead;
  209436. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  209437. if (numRead <= 0 || intern->stopReadOperation)
  209438. {
  209439. bytesRead = -1;
  209440. break;
  209441. }
  209442. bytesRead += numRead;
  209443. p += bytesRead;
  209444. }
  209445. intern->blocked = false;
  209446. }
  209447. return bytesRead;
  209448. }
  209449. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  209450. {
  209451. int bytesWritten = -1;
  209452. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  209453. if (intern != 0)
  209454. {
  209455. if (intern->pipeOut == -1)
  209456. {
  209457. if (intern->createdPipe)
  209458. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  209459. else
  209460. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  209461. if (intern->pipeOut == -1)
  209462. {
  209463. return -1;
  209464. }
  209465. }
  209466. const char* p = (const char*) sourceBuffer;
  209467. bytesWritten = 0;
  209468. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  209469. while (bytesWritten < numBytesToWrite
  209470. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  209471. {
  209472. const int bytesThisTime = numBytesToWrite - bytesWritten;
  209473. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  209474. if (numWritten <= 0)
  209475. {
  209476. bytesWritten = -1;
  209477. break;
  209478. }
  209479. bytesWritten += numWritten;
  209480. p += bytesWritten;
  209481. }
  209482. }
  209483. return bytesWritten;
  209484. }
  209485. END_JUCE_NAMESPACE
  209486. /********* End of inlined file: juce_mac_NamedPipe.cpp *********/
  209487. /********* End of inlined file: juce_linux_NamedPipe.cpp *********/
  209488. /********* Start of inlined file: juce_linux_Network.cpp *********/
  209489. #include <netdb.h>
  209490. #include <arpa/inet.h>
  209491. #include <netinet/in.h>
  209492. #include <sys/types.h>
  209493. #include <sys/ioctl.h>
  209494. #include <sys/socket.h>
  209495. #include <sys/wait.h>
  209496. #include <linux/if.h>
  209497. BEGIN_JUCE_NAMESPACE
  209498. // we'll borrow the mac's socket-based http streaming code..
  209499. /********* Start of inlined file: juce_mac_HTTPStream.h *********/
  209500. // (This file gets included by the mac + linux networking code)
  209501. /** A HTTP input stream that uses sockets.
  209502. */
  209503. class JUCE_HTTPSocketStream
  209504. {
  209505. public:
  209506. JUCE_HTTPSocketStream()
  209507. : readPosition (0),
  209508. socketHandle (-1),
  209509. levelsOfRedirection (0),
  209510. timeoutSeconds (15)
  209511. {
  209512. }
  209513. ~JUCE_HTTPSocketStream()
  209514. {
  209515. closeSocket();
  209516. }
  209517. bool open (const String& url,
  209518. const String& headers,
  209519. const MemoryBlock& postData,
  209520. const bool isPost,
  209521. URL::OpenStreamProgressCallback* callback,
  209522. void* callbackContext,
  209523. int timeOutMs)
  209524. {
  209525. closeSocket();
  209526. uint32 timeOutTime = Time::getMillisecondCounter();
  209527. if (timeOutMs == 0)
  209528. timeOutTime += 60000;
  209529. else if (timeOutMs < 0)
  209530. timeOutTime = 0xffffffff;
  209531. else
  209532. timeOutTime += timeOutMs;
  209533. String hostName, hostPath;
  209534. int hostPort;
  209535. if (! decomposeURL (url, hostName, hostPath, hostPort))
  209536. return false;
  209537. const struct hostent* host = 0;
  209538. int port = 0;
  209539. String proxyName, proxyPath;
  209540. int proxyPort = 0;
  209541. String proxyURL (getenv ("http_proxy"));
  209542. if (proxyURL.startsWithIgnoreCase (T("http://")))
  209543. {
  209544. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  209545. return false;
  209546. host = gethostbyname ((const char*) proxyName.toUTF8());
  209547. port = proxyPort;
  209548. }
  209549. else
  209550. {
  209551. host = gethostbyname ((const char*) hostName.toUTF8());
  209552. port = hostPort;
  209553. }
  209554. if (host == 0)
  209555. return false;
  209556. struct sockaddr_in address;
  209557. zerostruct (address);
  209558. memcpy ((void*) &address.sin_addr, (const void*) host->h_addr, host->h_length);
  209559. address.sin_family = host->h_addrtype;
  209560. address.sin_port = htons (port);
  209561. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  209562. if (socketHandle == -1)
  209563. return false;
  209564. int receiveBufferSize = 16384;
  209565. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  209566. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  209567. #if JUCE_MAC
  209568. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  209569. #endif
  209570. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  209571. {
  209572. closeSocket();
  209573. return false;
  209574. }
  209575. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  209576. proxyName, proxyPort,
  209577. hostPath, url,
  209578. headers, postData,
  209579. isPost));
  209580. int totalHeaderSent = 0;
  209581. while (totalHeaderSent < requestHeader.getSize())
  209582. {
  209583. if (Time::getMillisecondCounter() > timeOutTime)
  209584. {
  209585. closeSocket();
  209586. return false;
  209587. }
  209588. const int numToSend = jmin (1024, requestHeader.getSize() - totalHeaderSent);
  209589. if (send (socketHandle,
  209590. ((const char*) requestHeader.getData()) + totalHeaderSent,
  209591. numToSend, 0)
  209592. != numToSend)
  209593. {
  209594. closeSocket();
  209595. return false;
  209596. }
  209597. totalHeaderSent += numToSend;
  209598. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  209599. {
  209600. closeSocket();
  209601. return false;
  209602. }
  209603. }
  209604. const String responseHeader (readResponse (timeOutTime));
  209605. if (responseHeader.isNotEmpty())
  209606. {
  209607. //DBG (responseHeader);
  209608. StringArray lines;
  209609. lines.addLines (responseHeader);
  209610. // NB - using charToString() here instead of just T(" "), because that was
  209611. // causing a mysterious gcc internal compiler error...
  209612. const int statusCode = responseHeader.fromFirstOccurrenceOf (String::charToString (T(' ')), false, false)
  209613. .substring (0, 3)
  209614. .getIntValue();
  209615. //int contentLength = findHeaderItem (lines, T("Content-Length:")).getIntValue();
  209616. //bool isChunked = findHeaderItem (lines, T("Transfer-Encoding:")).equalsIgnoreCase ("chunked");
  209617. String location (findHeaderItem (lines, T("Location:")));
  209618. if (statusCode >= 300 && statusCode < 400
  209619. && location.isNotEmpty())
  209620. {
  209621. if (! location.startsWithIgnoreCase (T("http://")))
  209622. location = T("http://") + location;
  209623. if (levelsOfRedirection++ < 3)
  209624. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  209625. }
  209626. else
  209627. {
  209628. levelsOfRedirection = 0;
  209629. return true;
  209630. }
  209631. }
  209632. closeSocket();
  209633. return false;
  209634. }
  209635. int read (void* buffer, int bytesToRead)
  209636. {
  209637. fd_set readbits;
  209638. FD_ZERO (&readbits);
  209639. FD_SET (socketHandle, &readbits);
  209640. struct timeval tv;
  209641. tv.tv_sec = timeoutSeconds;
  209642. tv.tv_usec = 0;
  209643. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  209644. return 0; // (timeout)
  209645. const int bytesRead = jmax (0, recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  209646. readPosition += bytesRead;
  209647. return bytesRead;
  209648. }
  209649. int readPosition;
  209650. juce_UseDebuggingNewOperator
  209651. private:
  209652. int socketHandle, levelsOfRedirection;
  209653. const int timeoutSeconds;
  209654. void closeSocket()
  209655. {
  209656. if (socketHandle >= 0)
  209657. close (socketHandle);
  209658. socketHandle = -1;
  209659. }
  209660. const MemoryBlock createRequestHeader (const String& hostName,
  209661. const int hostPort,
  209662. const String& proxyName,
  209663. const int proxyPort,
  209664. const String& hostPath,
  209665. const String& originalURL,
  209666. const String& headers,
  209667. const MemoryBlock& postData,
  209668. const bool isPost)
  209669. {
  209670. String header (isPost ? "POST " : "GET ");
  209671. if (proxyName.isEmpty())
  209672. {
  209673. header << hostPath << " HTTP/1.0\r\nHost: "
  209674. << hostName << ':' << hostPort;
  209675. }
  209676. else
  209677. {
  209678. header << originalURL << " HTTP/1.0\r\nHost: "
  209679. << proxyName << ':' << proxyPort;
  209680. }
  209681. header << "\r\nUser-Agent: JUCE/"
  209682. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  209683. << "\r\nConnection: Close\r\nContent-Length: "
  209684. << postData.getSize() << "\r\n"
  209685. << headers << "\r\n";
  209686. MemoryBlock mb;
  209687. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  209688. mb.append (postData.getData(), postData.getSize());
  209689. return mb;
  209690. }
  209691. const String readResponse (const uint32 timeOutTime)
  209692. {
  209693. int bytesRead = 0, numConsecutiveLFs = 0;
  209694. MemoryBlock buffer (1024, true);
  209695. while (numConsecutiveLFs < 2 && bytesRead < 32768
  209696. && Time::getMillisecondCounter() <= timeOutTime)
  209697. {
  209698. fd_set readbits;
  209699. FD_ZERO (&readbits);
  209700. FD_SET (socketHandle, &readbits);
  209701. struct timeval tv;
  209702. tv.tv_sec = timeoutSeconds;
  209703. tv.tv_usec = 0;
  209704. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  209705. return String::empty; // (timeout)
  209706. buffer.ensureSize (bytesRead + 8, true);
  209707. char* const dest = (char*) buffer.getData() + bytesRead;
  209708. if (recv (socketHandle, dest, 1, 0) == -1)
  209709. return String::empty;
  209710. const char lastByte = *dest;
  209711. ++bytesRead;
  209712. if (lastByte == '\n')
  209713. ++numConsecutiveLFs;
  209714. else if (lastByte != '\r')
  209715. numConsecutiveLFs = 0;
  209716. }
  209717. const String header (String::fromUTF8 ((const uint8*) buffer.getData()));
  209718. if (header.startsWithIgnoreCase (T("HTTP/")))
  209719. return header.trimEnd();
  209720. return String::empty;
  209721. }
  209722. static bool decomposeURL (const String& url,
  209723. String& host, String& path, int& port)
  209724. {
  209725. if (! url.startsWithIgnoreCase (T("http://")))
  209726. return false;
  209727. const int nextSlash = url.indexOfChar (7, '/');
  209728. int nextColon = url.indexOfChar (7, ':');
  209729. if (nextColon > nextSlash && nextSlash > 0)
  209730. nextColon = -1;
  209731. if (nextColon >= 0)
  209732. {
  209733. host = url.substring (7, nextColon);
  209734. if (nextSlash >= 0)
  209735. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  209736. else
  209737. port = url.substring (nextColon + 1).getIntValue();
  209738. }
  209739. else
  209740. {
  209741. port = 80;
  209742. if (nextSlash >= 0)
  209743. host = url.substring (7, nextSlash);
  209744. else
  209745. host = url.substring (7);
  209746. }
  209747. if (nextSlash >= 0)
  209748. path = url.substring (nextSlash);
  209749. else
  209750. path = T("/");
  209751. return true;
  209752. }
  209753. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  209754. {
  209755. for (int i = 0; i < lines.size(); ++i)
  209756. if (lines[i].startsWithIgnoreCase (itemName))
  209757. return lines[i].substring (itemName.length()).trim();
  209758. return String::empty;
  209759. }
  209760. };
  209761. bool juce_isOnLine()
  209762. {
  209763. return true;
  209764. }
  209765. void* juce_openInternetFile (const String& url,
  209766. const String& headers,
  209767. const MemoryBlock& postData,
  209768. const bool isPost,
  209769. URL::OpenStreamProgressCallback* callback,
  209770. void* callbackContext,
  209771. int timeOutMs)
  209772. {
  209773. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  209774. if (s->open (url, headers, postData, isPost,
  209775. callback, callbackContext, timeOutMs))
  209776. return s;
  209777. delete s;
  209778. return 0;
  209779. }
  209780. void juce_closeInternetFile (void* handle)
  209781. {
  209782. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  209783. if (s != 0)
  209784. delete s;
  209785. }
  209786. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  209787. {
  209788. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  209789. if (s != 0)
  209790. return s->read (buffer, bytesToRead);
  209791. return 0;
  209792. }
  209793. int juce_seekInInternetFile (void* handle, int newPosition)
  209794. {
  209795. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  209796. if (s != 0)
  209797. return s->readPosition;
  209798. return 0;
  209799. }
  209800. /********* End of inlined file: juce_mac_HTTPStream.h *********/
  209801. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  209802. {
  209803. int numResults = 0;
  209804. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  209805. if (s != -1)
  209806. {
  209807. char buf [1024];
  209808. struct ifconf ifc;
  209809. ifc.ifc_len = sizeof (buf);
  209810. ifc.ifc_buf = buf;
  209811. ioctl (s, SIOCGIFCONF, &ifc);
  209812. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  209813. {
  209814. struct ifreq ifr;
  209815. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  209816. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  209817. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  209818. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  209819. && numResults < maxNum)
  209820. {
  209821. int64 a = 0;
  209822. for (int j = 6; --j >= 0;)
  209823. a = (a << 8) | ifr.ifr_hwaddr.sa_data[j];
  209824. *addresses++ = a;
  209825. ++numResults;
  209826. }
  209827. }
  209828. close (s);
  209829. }
  209830. return numResults;
  209831. }
  209832. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  209833. const String& emailSubject,
  209834. const String& bodyText,
  209835. const StringArray& filesToAttach)
  209836. {
  209837. jassertfalse // xxx todo
  209838. return false;
  209839. }
  209840. END_JUCE_NAMESPACE
  209841. /********* End of inlined file: juce_linux_Network.cpp *********/
  209842. /********* Start of inlined file: juce_linux_SystemStats.cpp *********/
  209843. #include <sys/sysinfo.h>
  209844. #include <dlfcn.h>
  209845. #ifndef CPU_ISSET
  209846. #undef SUPPORT_AFFINITIES
  209847. #endif
  209848. BEGIN_JUCE_NAMESPACE
  209849. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel, int* extFeatures) throw()
  209850. {
  209851. unsigned int cpu = 0;
  209852. unsigned int ext = 0;
  209853. unsigned int family = 0;
  209854. unsigned int dummy = 0;
  209855. #if JUCE_64BIT
  209856. __asm__ ("cpuid"
  209857. : "=a" (family), "=b" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  209858. #else
  209859. __asm__ ("push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx"
  209860. : "=a" (family), "=D" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  209861. #endif
  209862. if (familyModel != 0)
  209863. *familyModel = family;
  209864. if (extFeatures != 0)
  209865. *extFeatures = ext;
  209866. return cpu;
  209867. }*/
  209868. void Logger::outputDebugString (const String& text) throw()
  209869. {
  209870. fprintf (stdout, text.toUTF8());
  209871. fprintf (stdout, "\n");
  209872. }
  209873. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  209874. {
  209875. String text;
  209876. va_list args;
  209877. va_start (args, format);
  209878. text.vprintf(format, args);
  209879. outputDebugString(text);
  209880. }
  209881. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  209882. {
  209883. return Linux;
  209884. }
  209885. const String SystemStats::getOperatingSystemName() throw()
  209886. {
  209887. return T("Linux");
  209888. }
  209889. bool SystemStats::isOperatingSystem64Bit() throw()
  209890. {
  209891. #if JUCE_64BIT
  209892. return true;
  209893. #else
  209894. //xxx not sure how to find this out?..
  209895. return false;
  209896. #endif
  209897. }
  209898. static const String getCpuInfo (const char* key, bool lastOne = false) throw()
  209899. {
  209900. String info;
  209901. char buf [256];
  209902. FILE* f = fopen ("/proc/cpuinfo", "r");
  209903. while (f != 0 && fgets (buf, sizeof(buf), f))
  209904. {
  209905. if (strncmp (buf, key, strlen (key)) == 0)
  209906. {
  209907. char* p = buf;
  209908. while (*p && *p != '\n')
  209909. ++p;
  209910. if (*p != 0)
  209911. *p = 0;
  209912. p = buf;
  209913. while (*p != 0 && *p != ':')
  209914. ++p;
  209915. if (*p != 0 && *(p + 1) != 0)
  209916. info = p + 2;
  209917. if (! lastOne)
  209918. break;
  209919. }
  209920. }
  209921. fclose (f);
  209922. return info;
  209923. }
  209924. bool SystemStats::hasMMX() throw()
  209925. {
  209926. return getCpuInfo ("flags").contains (T("mmx"));
  209927. }
  209928. bool SystemStats::hasSSE() throw()
  209929. {
  209930. return getCpuInfo ("flags").contains (T("sse"));
  209931. }
  209932. bool SystemStats::hasSSE2() throw()
  209933. {
  209934. return getCpuInfo ("flags").contains (T("sse2"));
  209935. }
  209936. bool SystemStats::has3DNow() throw()
  209937. {
  209938. return getCpuInfo ("flags").contains (T("3dnow"));
  209939. }
  209940. const String SystemStats::getCpuVendor() throw()
  209941. {
  209942. return getCpuInfo ("vendor_id");
  209943. }
  209944. int SystemStats::getCpuSpeedInMegaherz() throw()
  209945. {
  209946. const String speed (getCpuInfo ("cpu MHz"));
  209947. return (int) (speed.getFloatValue() + 0.5f);
  209948. }
  209949. int SystemStats::getMemorySizeInMegabytes() throw()
  209950. {
  209951. struct sysinfo sysi;
  209952. if (sysinfo (&sysi) == 0)
  209953. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  209954. return 0;
  209955. }
  209956. uint32 juce_millisecondsSinceStartup() throw()
  209957. {
  209958. static unsigned int calibrate = 0;
  209959. static bool calibrated = false;
  209960. timeval t;
  209961. unsigned int ret = 0;
  209962. if (! gettimeofday (&t, 0))
  209963. {
  209964. if (! calibrated)
  209965. {
  209966. struct sysinfo sysi;
  209967. if (sysinfo (&sysi) == 0)
  209968. // Safe to assume system was not brought up earlier than 1970!
  209969. calibrate = t.tv_sec - sysi.uptime;
  209970. calibrated = true;
  209971. }
  209972. ret = 1000 * (t.tv_sec - calibrate) + (t.tv_usec / 1000);
  209973. }
  209974. return ret;
  209975. }
  209976. double Time::getMillisecondCounterHiRes() throw()
  209977. {
  209978. return getHighResolutionTicks() * 0.001;
  209979. }
  209980. int64 Time::getHighResolutionTicks() throw()
  209981. {
  209982. timeval t;
  209983. if (gettimeofday (&t, 0))
  209984. return 0;
  209985. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  209986. }
  209987. int64 Time::getHighResolutionTicksPerSecond() throw()
  209988. {
  209989. // Microseconds
  209990. return 1000000;
  209991. }
  209992. bool Time::setSystemTimeToThisTime() const throw()
  209993. {
  209994. timeval t;
  209995. t.tv_sec = millisSinceEpoch % 1000000;
  209996. t.tv_usec = millisSinceEpoch - t.tv_sec;
  209997. return settimeofday (&t, NULL) ? false : true;
  209998. }
  209999. int SystemStats::getPageSize() throw()
  210000. {
  210001. static int systemPageSize = 0;
  210002. if (systemPageSize == 0)
  210003. systemPageSize = sysconf (_SC_PAGESIZE);
  210004. return systemPageSize;
  210005. }
  210006. int SystemStats::getNumCpus() throw()
  210007. {
  210008. const int lastCpu = getCpuInfo ("processor", true).getIntValue();
  210009. return lastCpu + 1;
  210010. }
  210011. void SystemStats::initialiseStats() throw()
  210012. {
  210013. // Process starts off as root when running suid
  210014. Process::lowerPrivilege();
  210015. String s (SystemStats::getJUCEVersion());
  210016. }
  210017. void PlatformUtilities::fpuReset()
  210018. {
  210019. }
  210020. END_JUCE_NAMESPACE
  210021. /********* End of inlined file: juce_linux_SystemStats.cpp *********/
  210022. /********* Start of inlined file: juce_linux_Threads.cpp *********/
  210023. #include <dlfcn.h>
  210024. #include <sys/file.h>
  210025. #include <sys/types.h>
  210026. #include <sys/ptrace.h>
  210027. BEGIN_JUCE_NAMESPACE
  210028. /*
  210029. Note that a lot of methods that you'd expect to find in this file actually
  210030. live in juce_posix_SharedCode.cpp!
  210031. */
  210032. #ifndef CPU_ISSET
  210033. #undef SUPPORT_AFFINITIES
  210034. #endif
  210035. void JUCE_API juce_threadEntryPoint (void*);
  210036. void* threadEntryProc (void* value) throw()
  210037. {
  210038. // New threads start off as root when running suid
  210039. Process::lowerPrivilege();
  210040. juce_threadEntryPoint (value);
  210041. return 0;
  210042. }
  210043. void* juce_createThread (void* userData) throw()
  210044. {
  210045. pthread_t handle = 0;
  210046. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  210047. {
  210048. pthread_detach (handle);
  210049. return (void*)handle;
  210050. }
  210051. return 0;
  210052. }
  210053. void juce_killThread (void* handle) throw()
  210054. {
  210055. if (handle != 0)
  210056. pthread_cancel ((pthread_t)handle);
  210057. }
  210058. void juce_setCurrentThreadName (const String& /*name*/) throw()
  210059. {
  210060. }
  210061. int Thread::getCurrentThreadId() throw()
  210062. {
  210063. return (int) pthread_self();
  210064. }
  210065. /*
  210066. * This is all a bit non-ideal... the trouble is that on Linux you
  210067. * need to call setpriority to affect the dynamic priority for
  210068. * non-realtime processes, but this requires the pid, which is not
  210069. * accessible from the pthread_t. We could get it by calling getpid
  210070. * once each thread has started, but then we would need a list of
  210071. * running threads etc etc.
  210072. * Also there is no such thing as IDLE priority on Linux.
  210073. * For the moment, map idle, low and normal process priorities to
  210074. * SCHED_OTHER, with the thread priority ignored for these classes.
  210075. * Map high priority processes to the lower half of the SCHED_RR
  210076. * range, and realtime to the upper half
  210077. */
  210078. // priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  210079. // priority of the current thread
  210080. void juce_setThreadPriority (void* handle, int priority) throw()
  210081. {
  210082. struct sched_param param;
  210083. int policy, maxp, minp, pri;
  210084. if (handle == 0)
  210085. handle = (void*) pthread_self();
  210086. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  210087. && policy != SCHED_OTHER)
  210088. {
  210089. minp = sched_get_priority_min(policy);
  210090. maxp = sched_get_priority_max(policy);
  210091. pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  210092. if (param.__sched_priority >= (minp + (maxp - minp) / 2))
  210093. // Realtime process priority
  210094. param.__sched_priority = minp + ((maxp - minp) / 2) + pri;
  210095. else
  210096. // High process priority
  210097. param.__sched_priority = minp + pri;
  210098. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  210099. pthread_setschedparam ((pthread_t) handle, policy, &param);
  210100. }
  210101. }
  210102. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  210103. {
  210104. #if SUPPORT_AFFINITIES
  210105. cpu_set_t affinity;
  210106. CPU_ZERO (&affinity);
  210107. for (int i = 0; i < 32; ++i)
  210108. if ((affinityMask & (1 << i)) != 0)
  210109. CPU_SET (i, &affinity);
  210110. /*
  210111. N.B. If this line causes a compile error, then you've probably not got the latest
  210112. version of glibc installed.
  210113. If you don't want to update your copy of glibc and don't care about cpu affinities,
  210114. then you can just disable all this stuff by removing the SUPPORT_AFFINITIES macro
  210115. from the linuxincludes.h file.
  210116. */
  210117. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  210118. sched_yield();
  210119. #else
  210120. /* affinities aren't supported because either the appropriate header files weren't found,
  210121. or the SUPPORT_AFFINITIES macro was turned off in linuxheaders.h
  210122. */
  210123. jassertfalse
  210124. #endif
  210125. }
  210126. void Thread::yield() throw()
  210127. {
  210128. sched_yield();
  210129. }
  210130. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  210131. void Process::setPriority (ProcessPriority prior)
  210132. {
  210133. struct sched_param param;
  210134. int policy, maxp, minp;
  210135. const int p = (int) prior;
  210136. if (p <= 1)
  210137. policy = SCHED_OTHER;
  210138. else
  210139. policy = SCHED_RR;
  210140. minp = sched_get_priority_min (policy);
  210141. maxp = sched_get_priority_max (policy);
  210142. if (p < 2)
  210143. param.__sched_priority = 0;
  210144. else if (p == 2 )
  210145. // Set to middle of lower realtime priority range
  210146. param.__sched_priority = minp + (maxp - minp) / 4;
  210147. else
  210148. // Set to middle of higher realtime priority range
  210149. param.__sched_priority = minp + (3 * (maxp - minp) / 4);
  210150. pthread_setschedparam (pthread_self(), policy, &param);
  210151. }
  210152. void Process::terminate()
  210153. {
  210154. exit (0);
  210155. }
  210156. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  210157. {
  210158. static char testResult = 0;
  210159. if (testResult == 0)
  210160. {
  210161. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  210162. if (testResult >= 0)
  210163. {
  210164. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  210165. testResult = 1;
  210166. }
  210167. }
  210168. return testResult < 0;
  210169. }
  210170. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  210171. {
  210172. return juce_isRunningUnderDebugger();
  210173. }
  210174. void Process::raisePrivilege()
  210175. {
  210176. // If running suid root, change effective user
  210177. // to root
  210178. if (geteuid() != 0 && getuid() == 0)
  210179. {
  210180. setreuid (geteuid(), getuid());
  210181. setregid (getegid(), getgid());
  210182. }
  210183. }
  210184. void Process::lowerPrivilege()
  210185. {
  210186. // If runing suid root, change effective user
  210187. // back to real user
  210188. if (geteuid() == 0 && getuid() != 0)
  210189. {
  210190. setreuid (geteuid(), getuid());
  210191. setregid (getegid(), getgid());
  210192. }
  210193. }
  210194. #if JUCE_BUILD_GUI_CLASSES
  210195. void* Process::loadDynamicLibrary (const String& name)
  210196. {
  210197. return dlopen ((const char*) name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  210198. }
  210199. void Process::freeDynamicLibrary (void* handle)
  210200. {
  210201. dlclose(handle);
  210202. }
  210203. void* Process::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  210204. {
  210205. return dlsym (libraryHandle, (const char*) procedureName);
  210206. }
  210207. #endif
  210208. END_JUCE_NAMESPACE
  210209. /********* End of inlined file: juce_linux_Threads.cpp *********/
  210210. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  210211. /********* Start of inlined file: juce_linux_Audio.cpp *********/
  210212. #if JUCE_BUILD_GUI_CLASSES
  210213. #if JUCE_ALSA
  210214. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  210215. not got your paths set up correctly to find its header files.
  210216. The package you need to install to get ASLA support is "libasound2-dev".
  210217. If you don't have the ALSA library and don't want to build Juce with audio support,
  210218. just disable the JUCE_ALSA flag in juce_Config.h
  210219. */
  210220. #include <alsa/asoundlib.h>
  210221. BEGIN_JUCE_NAMESPACE
  210222. static const int maxNumChans = 64;
  210223. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  210224. {
  210225. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  210226. snd_pcm_hw_params_t* hwParams;
  210227. snd_pcm_hw_params_alloca (&hwParams);
  210228. for (int i = 0; ratesToTry[i] != 0; ++i)
  210229. {
  210230. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  210231. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  210232. {
  210233. rates.addIfNotAlreadyThere (ratesToTry[i]);
  210234. }
  210235. }
  210236. }
  210237. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  210238. {
  210239. snd_pcm_hw_params_t *params;
  210240. snd_pcm_hw_params_alloca (&params);
  210241. if (snd_pcm_hw_params_any (handle, params) >= 0)
  210242. {
  210243. snd_pcm_hw_params_get_channels_min (params, minChans);
  210244. snd_pcm_hw_params_get_channels_max (params, maxChans);
  210245. }
  210246. }
  210247. static void getDeviceProperties (const String& id,
  210248. unsigned int& minChansOut,
  210249. unsigned int& maxChansOut,
  210250. unsigned int& minChansIn,
  210251. unsigned int& maxChansIn,
  210252. Array <int>& rates)
  210253. {
  210254. if (id.isEmpty())
  210255. return;
  210256. snd_ctl_t* handle;
  210257. if (snd_ctl_open (&handle, id.upToLastOccurrenceOf (T(","), false, false), SND_CTL_NONBLOCK) >= 0)
  210258. {
  210259. snd_pcm_info_t* info;
  210260. snd_pcm_info_alloca (&info);
  210261. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  210262. snd_pcm_info_set_device (info, id.fromLastOccurrenceOf (T(","), false, false).getIntValue());
  210263. snd_pcm_info_set_subdevice (info, 0);
  210264. if (snd_ctl_pcm_info (handle, info) >= 0)
  210265. {
  210266. snd_pcm_t* pcmHandle;
  210267. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  210268. {
  210269. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  210270. getDeviceSampleRates (pcmHandle, rates);
  210271. snd_pcm_close (pcmHandle);
  210272. }
  210273. }
  210274. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  210275. if (snd_ctl_pcm_info (handle, info) >= 0)
  210276. {
  210277. snd_pcm_t* pcmHandle;
  210278. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  210279. {
  210280. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  210281. if (rates.size() == 0)
  210282. getDeviceSampleRates (pcmHandle, rates);
  210283. snd_pcm_close (pcmHandle);
  210284. }
  210285. }
  210286. snd_ctl_close (handle);
  210287. }
  210288. }
  210289. class ALSADevice
  210290. {
  210291. public:
  210292. ALSADevice (const String& id,
  210293. const bool forInput)
  210294. : handle (0),
  210295. bitDepth (16),
  210296. numChannelsRunning (0),
  210297. isInput (forInput),
  210298. sampleFormat (AudioDataConverters::int16LE)
  210299. {
  210300. failed (snd_pcm_open (&handle, id,
  210301. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  210302. SND_PCM_ASYNC));
  210303. }
  210304. ~ALSADevice()
  210305. {
  210306. if (handle != 0)
  210307. snd_pcm_close (handle);
  210308. }
  210309. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  210310. {
  210311. if (handle == 0)
  210312. return false;
  210313. snd_pcm_hw_params_t* hwParams;
  210314. snd_pcm_hw_params_alloca (&hwParams);
  210315. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  210316. return false;
  210317. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  210318. isInterleaved = false;
  210319. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  210320. isInterleaved = true;
  210321. else
  210322. {
  210323. jassertfalse
  210324. return false;
  210325. }
  210326. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  210327. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  210328. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  210329. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  210330. SND_PCM_FORMAT_S24_LE, 24, AudioDataConverters::int24LE,
  210331. SND_PCM_FORMAT_S24_BE, 24, AudioDataConverters::int24BE,
  210332. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  210333. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  210334. bitDepth = 0;
  210335. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  210336. {
  210337. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  210338. {
  210339. bitDepth = formatsToTry [i + 1];
  210340. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  210341. break;
  210342. }
  210343. }
  210344. if (bitDepth == 0)
  210345. {
  210346. error = "device doesn't support a compatible PCM format";
  210347. DBG (T("ALSA error: ") + error + T("\n"));
  210348. return false;
  210349. }
  210350. int dir = 0;
  210351. unsigned int periods = 4;
  210352. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  210353. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  210354. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  210355. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  210356. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  210357. || failed (snd_pcm_hw_params (handle, hwParams)))
  210358. {
  210359. return false;
  210360. }
  210361. snd_pcm_sw_params_t* swParams;
  210362. snd_pcm_sw_params_alloca (&swParams);
  210363. if (failed (snd_pcm_sw_params_current (handle, swParams))
  210364. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  210365. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, 0))
  210366. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  210367. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, INT_MAX))
  210368. || failed (snd_pcm_sw_params (handle, swParams)))
  210369. {
  210370. return false;
  210371. }
  210372. /*
  210373. #ifdef JUCE_DEBUG
  210374. // enable this to dump the config of the devices that get opened
  210375. snd_output_t* out;
  210376. snd_output_stdio_attach (&out, stderr, 0);
  210377. snd_pcm_hw_params_dump (hwParams, out);
  210378. snd_pcm_sw_params_dump (swParams, out);
  210379. #endif
  210380. */
  210381. numChannelsRunning = numChannels;
  210382. return true;
  210383. }
  210384. bool write (float** const data, const int numSamples)
  210385. {
  210386. if (isInterleaved)
  210387. {
  210388. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  210389. float* interleaved = (float*) scratch;
  210390. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  210391. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  210392. snd_pcm_sframes_t num = snd_pcm_writei (handle, (void*) interleaved, numSamples);
  210393. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  210394. return false;
  210395. }
  210396. else
  210397. {
  210398. for (int i = 0; i < numChannelsRunning; ++i)
  210399. if (data[i] != 0)
  210400. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  210401. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  210402. if (failed (num))
  210403. {
  210404. if (num == -EPIPE)
  210405. {
  210406. if (failed (snd_pcm_prepare (handle)))
  210407. return false;
  210408. }
  210409. else if (num != -ESTRPIPE)
  210410. return false;
  210411. }
  210412. }
  210413. return true;
  210414. }
  210415. bool read (float** const data, const int numSamples)
  210416. {
  210417. if (isInterleaved)
  210418. {
  210419. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  210420. float* interleaved = (float*) scratch;
  210421. snd_pcm_sframes_t num = snd_pcm_readi (handle, (void*) interleaved, numSamples);
  210422. if (failed (num))
  210423. {
  210424. if (num == -EPIPE)
  210425. {
  210426. if (failed (snd_pcm_prepare (handle)))
  210427. return false;
  210428. }
  210429. else if (num != -ESTRPIPE)
  210430. return false;
  210431. }
  210432. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  210433. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  210434. }
  210435. else
  210436. {
  210437. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  210438. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  210439. return false;
  210440. for (int i = 0; i < numChannelsRunning; ++i)
  210441. if (data[i] != 0)
  210442. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  210443. }
  210444. return true;
  210445. }
  210446. juce_UseDebuggingNewOperator
  210447. snd_pcm_t* handle;
  210448. String error;
  210449. int bitDepth, numChannelsRunning;
  210450. private:
  210451. const bool isInput;
  210452. bool isInterleaved;
  210453. MemoryBlock scratch;
  210454. AudioDataConverters::DataFormat sampleFormat;
  210455. bool failed (const int errorNum)
  210456. {
  210457. if (errorNum >= 0)
  210458. return false;
  210459. error = snd_strerror (errorNum);
  210460. DBG (T("ALSA error: ") + error + T("\n"));
  210461. return true;
  210462. }
  210463. };
  210464. class ALSAThread : public Thread
  210465. {
  210466. public:
  210467. ALSAThread (const String& inputId_,
  210468. const String& outputId_)
  210469. : Thread ("Juce ALSA"),
  210470. sampleRate (0),
  210471. bufferSize (0),
  210472. callback (0),
  210473. inputId (inputId_),
  210474. outputId (outputId_),
  210475. outputDevice (0),
  210476. inputDevice (0),
  210477. numCallbacks (0),
  210478. totalNumInputChannels (0),
  210479. totalNumOutputChannels (0)
  210480. {
  210481. zeromem (outputChannelData, sizeof (outputChannelData));
  210482. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  210483. zeromem (inputChannelData, sizeof (inputChannelData));
  210484. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  210485. initialiseRatesAndChannels();
  210486. }
  210487. ~ALSAThread()
  210488. {
  210489. close();
  210490. }
  210491. void open (const BitArray& inputChannels,
  210492. const BitArray& outputChannels,
  210493. const double sampleRate_,
  210494. const int bufferSize_)
  210495. {
  210496. close();
  210497. error = String::empty;
  210498. sampleRate = sampleRate_;
  210499. bufferSize = bufferSize_;
  210500. currentInputChans.clear();
  210501. currentOutputChans.clear();
  210502. if (inputChannels.getHighestBit() >= 0)
  210503. {
  210504. for (int i = 0; i <= inputChannels.getHighestBit(); ++i)
  210505. {
  210506. inputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  210507. if (inputChannels[i])
  210508. {
  210509. inputChannelDataForCallback [totalNumInputChannels++] = inputChannelData [i];
  210510. currentInputChans.setBit (i);
  210511. }
  210512. }
  210513. }
  210514. if (outputChannels.getHighestBit() >= 0)
  210515. {
  210516. for (int i = 0; i <= outputChannels.getHighestBit(); ++i)
  210517. {
  210518. outputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  210519. if (outputChannels[i])
  210520. {
  210521. outputChannelDataForCallback [totalNumOutputChannels++] = outputChannelData [i];
  210522. currentOutputChans.setBit (i);
  210523. }
  210524. }
  210525. }
  210526. if (totalNumOutputChannels > 0 && outputId.isNotEmpty())
  210527. {
  210528. outputDevice = new ALSADevice (outputId, false);
  210529. if (outputDevice->error.isNotEmpty())
  210530. {
  210531. error = outputDevice->error;
  210532. deleteAndZero (outputDevice);
  210533. return;
  210534. }
  210535. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  210536. currentOutputChans.getHighestBit() + 1,
  210537. bufferSize))
  210538. {
  210539. error = outputDevice->error;
  210540. deleteAndZero (outputDevice);
  210541. return;
  210542. }
  210543. }
  210544. if (totalNumInputChannels > 0 && inputId.isNotEmpty())
  210545. {
  210546. inputDevice = new ALSADevice (inputId, true);
  210547. if (inputDevice->error.isNotEmpty())
  210548. {
  210549. error = inputDevice->error;
  210550. deleteAndZero (inputDevice);
  210551. return;
  210552. }
  210553. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  210554. currentInputChans.getHighestBit() + 1,
  210555. bufferSize))
  210556. {
  210557. error = inputDevice->error;
  210558. deleteAndZero (inputDevice);
  210559. return;
  210560. }
  210561. }
  210562. if (outputDevice == 0 && inputDevice == 0)
  210563. {
  210564. error = "no channels";
  210565. return;
  210566. }
  210567. if (outputDevice != 0 && inputDevice != 0)
  210568. {
  210569. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  210570. }
  210571. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  210572. return;
  210573. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  210574. return;
  210575. startThread (9);
  210576. int count = 1000;
  210577. while (numCallbacks == 0)
  210578. {
  210579. sleep (5);
  210580. if (--count < 0 || ! isThreadRunning())
  210581. {
  210582. error = "device didn't start";
  210583. break;
  210584. }
  210585. }
  210586. }
  210587. void close()
  210588. {
  210589. stopThread (6000);
  210590. deleteAndZero (inputDevice);
  210591. deleteAndZero (outputDevice);
  210592. for (int i = 0; i < maxNumChans; ++i)
  210593. {
  210594. juce_free (inputChannelData [i]);
  210595. juce_free (outputChannelData [i]);
  210596. }
  210597. zeromem (outputChannelData, sizeof (outputChannelData));
  210598. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  210599. zeromem (inputChannelData, sizeof (inputChannelData));
  210600. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  210601. totalNumOutputChannels = 0;
  210602. totalNumInputChannels = 0;
  210603. numCallbacks = 0;
  210604. }
  210605. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  210606. {
  210607. const ScopedLock sl (callbackLock);
  210608. callback = newCallback;
  210609. }
  210610. void run()
  210611. {
  210612. while (! threadShouldExit())
  210613. {
  210614. if (inputDevice != 0)
  210615. {
  210616. if (! inputDevice->read (inputChannelData, bufferSize))
  210617. {
  210618. DBG ("ALSA: read failure");
  210619. break;
  210620. }
  210621. }
  210622. if (threadShouldExit())
  210623. break;
  210624. {
  210625. const ScopedLock sl (callbackLock);
  210626. ++numCallbacks;
  210627. if (callback != 0)
  210628. {
  210629. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback,
  210630. totalNumInputChannels,
  210631. outputChannelDataForCallback,
  210632. totalNumOutputChannels,
  210633. bufferSize);
  210634. }
  210635. else
  210636. {
  210637. for (int i = 0; i < totalNumOutputChannels; ++i)
  210638. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  210639. }
  210640. }
  210641. if (outputDevice != 0)
  210642. {
  210643. failed (snd_pcm_wait (outputDevice->handle, 2000));
  210644. if (threadShouldExit())
  210645. break;
  210646. failed (snd_pcm_avail_update (outputDevice->handle));
  210647. if (! outputDevice->write (outputChannelData, bufferSize))
  210648. {
  210649. DBG ("ALSA: write failure");
  210650. break;
  210651. }
  210652. }
  210653. }
  210654. }
  210655. int getBitDepth() const throw()
  210656. {
  210657. if (outputDevice != 0)
  210658. return outputDevice->bitDepth;
  210659. if (inputDevice != 0)
  210660. return inputDevice->bitDepth;
  210661. return 16;
  210662. }
  210663. juce_UseDebuggingNewOperator
  210664. String error;
  210665. double sampleRate;
  210666. int bufferSize;
  210667. BitArray currentInputChans, currentOutputChans;
  210668. Array <int> sampleRates;
  210669. StringArray channelNamesOut, channelNamesIn;
  210670. AudioIODeviceCallback* callback;
  210671. private:
  210672. const String inputId, outputId;
  210673. ALSADevice* outputDevice;
  210674. ALSADevice* inputDevice;
  210675. int numCallbacks;
  210676. CriticalSection callbackLock;
  210677. float* outputChannelData [maxNumChans];
  210678. float* outputChannelDataForCallback [maxNumChans];
  210679. int totalNumInputChannels;
  210680. float* inputChannelData [maxNumChans];
  210681. float* inputChannelDataForCallback [maxNumChans];
  210682. int totalNumOutputChannels;
  210683. unsigned int minChansOut, maxChansOut;
  210684. unsigned int minChansIn, maxChansIn;
  210685. bool failed (const int errorNum) throw()
  210686. {
  210687. if (errorNum >= 0)
  210688. return false;
  210689. error = snd_strerror (errorNum);
  210690. DBG (T("ALSA error: ") + error + T("\n"));
  210691. return true;
  210692. }
  210693. void initialiseRatesAndChannels() throw()
  210694. {
  210695. sampleRates.clear();
  210696. channelNamesOut.clear();
  210697. channelNamesIn.clear();
  210698. minChansOut = 0;
  210699. maxChansOut = 0;
  210700. minChansIn = 0;
  210701. maxChansIn = 0;
  210702. unsigned int dummy = 0;
  210703. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  210704. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  210705. unsigned int i;
  210706. for (i = 0; i < maxChansOut; ++i)
  210707. channelNamesOut.add (T("channel ") + String ((int) i + 1));
  210708. for (i = 0; i < maxChansIn; ++i)
  210709. channelNamesIn.add (T("channel ") + String ((int) i + 1));
  210710. }
  210711. };
  210712. class ALSAAudioIODevice : public AudioIODevice
  210713. {
  210714. public:
  210715. ALSAAudioIODevice (const String& deviceName,
  210716. const String& inputId_,
  210717. const String& outputId_)
  210718. : AudioIODevice (deviceName, T("ALSA")),
  210719. inputId (inputId_),
  210720. outputId (outputId_),
  210721. isOpen_ (false),
  210722. isStarted (false),
  210723. internal (0)
  210724. {
  210725. internal = new ALSAThread (inputId, outputId);
  210726. }
  210727. ~ALSAAudioIODevice()
  210728. {
  210729. delete internal;
  210730. }
  210731. const StringArray getOutputChannelNames()
  210732. {
  210733. return internal->channelNamesOut;
  210734. }
  210735. const StringArray getInputChannelNames()
  210736. {
  210737. return internal->channelNamesIn;
  210738. }
  210739. int getNumSampleRates()
  210740. {
  210741. return internal->sampleRates.size();
  210742. }
  210743. double getSampleRate (int index)
  210744. {
  210745. return internal->sampleRates [index];
  210746. }
  210747. int getNumBufferSizesAvailable()
  210748. {
  210749. return 50;
  210750. }
  210751. int getBufferSizeSamples (int index)
  210752. {
  210753. int n = 16;
  210754. for (int i = 0; i < index; ++i)
  210755. n += n < 64 ? 16
  210756. : (n < 512 ? 32
  210757. : (n < 1024 ? 64
  210758. : (n < 2048 ? 128 : 256)));
  210759. return n;
  210760. }
  210761. int getDefaultBufferSize()
  210762. {
  210763. return 512;
  210764. }
  210765. const String open (const BitArray& inputChannels,
  210766. const BitArray& outputChannels,
  210767. double sampleRate,
  210768. int bufferSizeSamples)
  210769. {
  210770. close();
  210771. if (bufferSizeSamples <= 0)
  210772. bufferSizeSamples = getDefaultBufferSize();
  210773. if (sampleRate <= 0)
  210774. {
  210775. for (int i = 0; i < getNumSampleRates(); ++i)
  210776. {
  210777. if (getSampleRate (i) >= 44100)
  210778. {
  210779. sampleRate = getSampleRate (i);
  210780. break;
  210781. }
  210782. }
  210783. }
  210784. internal->open (inputChannels, outputChannels,
  210785. sampleRate, bufferSizeSamples);
  210786. isOpen_ = internal->error.isEmpty();
  210787. return internal->error;
  210788. }
  210789. void close()
  210790. {
  210791. stop();
  210792. internal->close();
  210793. isOpen_ = false;
  210794. }
  210795. bool isOpen()
  210796. {
  210797. return isOpen_;
  210798. }
  210799. int getCurrentBufferSizeSamples()
  210800. {
  210801. return internal->bufferSize;
  210802. }
  210803. double getCurrentSampleRate()
  210804. {
  210805. return internal->sampleRate;
  210806. }
  210807. int getCurrentBitDepth()
  210808. {
  210809. return internal->getBitDepth();
  210810. }
  210811. const BitArray getActiveOutputChannels() const
  210812. {
  210813. return internal->currentOutputChans;
  210814. }
  210815. const BitArray getActiveInputChannels() const
  210816. {
  210817. return internal->currentInputChans;
  210818. }
  210819. int getOutputLatencyInSamples()
  210820. {
  210821. return 0;
  210822. }
  210823. int getInputLatencyInSamples()
  210824. {
  210825. return 0;
  210826. }
  210827. void start (AudioIODeviceCallback* callback)
  210828. {
  210829. if (! isOpen_)
  210830. callback = 0;
  210831. internal->setCallback (callback);
  210832. if (callback != 0)
  210833. callback->audioDeviceAboutToStart (this);
  210834. isStarted = (callback != 0);
  210835. }
  210836. void stop()
  210837. {
  210838. AudioIODeviceCallback* const oldCallback = internal->callback;
  210839. start (0);
  210840. if (oldCallback != 0)
  210841. oldCallback->audioDeviceStopped();
  210842. }
  210843. bool isPlaying()
  210844. {
  210845. return isStarted && internal->error.isEmpty();
  210846. }
  210847. const String getLastError()
  210848. {
  210849. return internal->error;
  210850. }
  210851. String inputId, outputId;
  210852. private:
  210853. bool isOpen_, isStarted;
  210854. ALSAThread* internal;
  210855. };
  210856. class ALSAAudioIODeviceType : public AudioIODeviceType
  210857. {
  210858. public:
  210859. ALSAAudioIODeviceType()
  210860. : AudioIODeviceType (T("ALSA")),
  210861. hasScanned (false)
  210862. {
  210863. }
  210864. ~ALSAAudioIODeviceType()
  210865. {
  210866. }
  210867. void scanForDevices()
  210868. {
  210869. if (hasScanned)
  210870. return;
  210871. hasScanned = true;
  210872. inputNames.clear();
  210873. inputIds.clear();
  210874. outputNames.clear();
  210875. outputIds.clear();
  210876. snd_ctl_t* handle;
  210877. snd_ctl_card_info_t* info;
  210878. snd_ctl_card_info_alloca (&info);
  210879. int cardNum = -1;
  210880. while (outputIds.size() + inputIds.size() <= 32)
  210881. {
  210882. snd_card_next (&cardNum);
  210883. if (cardNum < 0)
  210884. break;
  210885. if (snd_ctl_open (&handle, T("hw:") + String (cardNum), SND_CTL_NONBLOCK) >= 0)
  210886. {
  210887. if (snd_ctl_card_info (handle, info) >= 0)
  210888. {
  210889. String cardId (snd_ctl_card_info_get_id (info));
  210890. if (cardId.removeCharacters (T("0123456789")).isEmpty())
  210891. cardId = String (cardNum);
  210892. int device = -1;
  210893. for (;;)
  210894. {
  210895. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  210896. break;
  210897. String id, name;
  210898. id << "hw:" << cardId << ',' << device;
  210899. bool isInput, isOutput;
  210900. if (testDevice (id, isInput, isOutput))
  210901. {
  210902. name << snd_ctl_card_info_get_name (info);
  210903. if (name.isEmpty())
  210904. name = id;
  210905. if (isInput)
  210906. {
  210907. inputNames.add (name);
  210908. inputIds.add (id);
  210909. }
  210910. if (isOutput)
  210911. {
  210912. outputNames.add (name);
  210913. outputIds.add (id);
  210914. }
  210915. }
  210916. }
  210917. }
  210918. snd_ctl_close (handle);
  210919. }
  210920. }
  210921. inputNames.appendNumbersToDuplicates (false, true);
  210922. outputNames.appendNumbersToDuplicates (false, true);
  210923. }
  210924. const StringArray getDeviceNames (const bool wantInputNames) const
  210925. {
  210926. jassert (hasScanned); // need to call scanForDevices() before doing this
  210927. return wantInputNames ? inputNames : outputNames;
  210928. }
  210929. int getDefaultDeviceIndex (const bool forInput) const
  210930. {
  210931. jassert (hasScanned); // need to call scanForDevices() before doing this
  210932. return 0;
  210933. }
  210934. bool hasSeparateInputsAndOutputs() const { return true; }
  210935. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  210936. {
  210937. jassert (hasScanned); // need to call scanForDevices() before doing this
  210938. ALSAAudioIODevice* const d = dynamic_cast <ALSAAudioIODevice*> (device);
  210939. if (d == 0)
  210940. return -1;
  210941. return asInput ? inputIds.indexOf (d->inputId)
  210942. : outputIds.indexOf (d->outputId);
  210943. }
  210944. AudioIODevice* createDevice (const String& outputDeviceName,
  210945. const String& inputDeviceName)
  210946. {
  210947. jassert (hasScanned); // need to call scanForDevices() before doing this
  210948. const int inputIndex = inputNames.indexOf (inputDeviceName);
  210949. const int outputIndex = outputNames.indexOf (outputDeviceName);
  210950. String deviceName (outputDeviceName);
  210951. if (deviceName.isEmpty())
  210952. deviceName = inputDeviceName;
  210953. if (index >= 0)
  210954. return new ALSAAudioIODevice (deviceName,
  210955. inputIds [inputIndex],
  210956. outputIds [outputIndex]);
  210957. return 0;
  210958. }
  210959. juce_UseDebuggingNewOperator
  210960. private:
  210961. StringArray inputNames, outputNames, inputIds, outputIds;
  210962. bool hasScanned;
  210963. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  210964. {
  210965. unsigned int minChansOut = 0, maxChansOut = 0;
  210966. unsigned int minChansIn = 0, maxChansIn = 0;
  210967. Array <int> rates;
  210968. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  210969. DBG (T("ALSA device: ") + id
  210970. + T(" outs=") + String ((int) minChansOut) + T("-") + String ((int) maxChansOut)
  210971. + T(" ins=") + String ((int) minChansIn) + T("-") + String ((int) maxChansIn)
  210972. + T(" rates=") + String (rates.size()));
  210973. isInput = maxChansIn > 0;
  210974. isOutput = maxChansOut > 0;
  210975. return (isInput || isOutput) && rates.size() > 0;
  210976. }
  210977. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  210978. const ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  210979. };
  210980. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  210981. {
  210982. return new ALSAAudioIODeviceType();
  210983. }
  210984. END_JUCE_NAMESPACE
  210985. #else // if ALSA is turned off..
  210986. BEGIN_JUCE_NAMESPACE
  210987. AudioIODeviceType* juce_createDefaultAudioIODeviceType() { return 0; }
  210988. END_JUCE_NAMESPACE
  210989. #endif
  210990. #endif
  210991. /********* End of inlined file: juce_linux_Audio.cpp *********/
  210992. /********* Start of inlined file: juce_linux_AudioCDReader.cpp *********/
  210993. BEGIN_JUCE_NAMESPACE
  210994. AudioCDReader::AudioCDReader()
  210995. : AudioFormatReader (0, T("CD Audio"))
  210996. {
  210997. }
  210998. const StringArray AudioCDReader::getAvailableCDNames()
  210999. {
  211000. StringArray names;
  211001. return names;
  211002. }
  211003. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  211004. {
  211005. return 0;
  211006. }
  211007. AudioCDReader::~AudioCDReader()
  211008. {
  211009. }
  211010. void AudioCDReader::refreshTrackLengths()
  211011. {
  211012. }
  211013. bool AudioCDReader::read (int** destSamples,
  211014. int64 startSampleInFile,
  211015. int numSamples)
  211016. {
  211017. return false;
  211018. }
  211019. bool AudioCDReader::isCDStillPresent() const
  211020. {
  211021. return false;
  211022. }
  211023. int AudioCDReader::getNumTracks() const
  211024. {
  211025. return 0;
  211026. }
  211027. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  211028. {
  211029. return 0;
  211030. }
  211031. bool AudioCDReader::isTrackAudio (int trackNum) const
  211032. {
  211033. return false;
  211034. }
  211035. void AudioCDReader::enableIndexScanning (bool b)
  211036. {
  211037. }
  211038. int AudioCDReader::getLastIndex() const
  211039. {
  211040. return 0;
  211041. }
  211042. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211043. {
  211044. return Array<int>();
  211045. }
  211046. int AudioCDReader::getCDDBId()
  211047. {
  211048. return 0;
  211049. }
  211050. END_JUCE_NAMESPACE
  211051. /********* End of inlined file: juce_linux_AudioCDReader.cpp *********/
  211052. /********* Start of inlined file: juce_linux_FileChooser.cpp *********/
  211053. #if JUCE_BUILD_GUI_CLASSES
  211054. BEGIN_JUCE_NAMESPACE
  211055. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  211056. const String& title,
  211057. const File& file,
  211058. const String& filters,
  211059. bool isDirectory,
  211060. bool isSave,
  211061. bool warnAboutOverwritingExistingFiles,
  211062. bool selectMultipleFiles,
  211063. FilePreviewComponent* previewComponent)
  211064. {
  211065. //xxx ain't got one!
  211066. jassertfalse
  211067. }
  211068. END_JUCE_NAMESPACE
  211069. #endif
  211070. /********* End of inlined file: juce_linux_FileChooser.cpp *********/
  211071. /********* Start of inlined file: juce_linux_Fonts.cpp *********/
  211072. #if JUCE_BUILD_GUI_CLASSES
  211073. /* Got a build error here? You'll need to install the freetype library...
  211074. The name of the package to install is "libfreetype6-dev".
  211075. */
  211076. #include <ft2build.h>
  211077. #include FT_FREETYPE_H
  211078. BEGIN_JUCE_NAMESPACE
  211079. class FreeTypeFontFace
  211080. {
  211081. public:
  211082. enum FontStyle
  211083. {
  211084. Plain = 0,
  211085. Bold = 1,
  211086. Italic = 2
  211087. };
  211088. struct FontNameIndex
  211089. {
  211090. String fileName;
  211091. int faceIndex;
  211092. };
  211093. FreeTypeFontFace (const String& familyName)
  211094. : hasSerif (false),
  211095. monospaced (false)
  211096. {
  211097. family = familyName;
  211098. }
  211099. void setFileName (const String& name,
  211100. const int faceIndex,
  211101. FontStyle style)
  211102. {
  211103. if (names[(int) style].fileName.isEmpty())
  211104. {
  211105. names[(int) style].fileName = name;
  211106. names[(int) style].faceIndex = faceIndex;
  211107. }
  211108. }
  211109. const String& getFamilyName() const throw()
  211110. {
  211111. return family;
  211112. }
  211113. const String& getFileName (int style, int* faceIndex) const throw()
  211114. {
  211115. *faceIndex = names [style].faceIndex;
  211116. return names[style].fileName;
  211117. }
  211118. void setMonospaced (bool mono) { monospaced = mono; }
  211119. bool getMonospaced () const throw() { return monospaced; }
  211120. void setSerif (const bool serif) { hasSerif = serif; }
  211121. bool getSerif () const throw() { return hasSerif; }
  211122. private:
  211123. String family;
  211124. FontNameIndex names[4];
  211125. bool hasSerif, monospaced;
  211126. };
  211127. class FreeTypeInterface : public DeletedAtShutdown
  211128. {
  211129. public:
  211130. FreeTypeInterface() throw()
  211131. : lastFace (0),
  211132. lastBold (false),
  211133. lastItalic (false)
  211134. {
  211135. if (FT_Init_FreeType (&ftLib) != 0)
  211136. {
  211137. ftLib = 0;
  211138. DBG (T("Failed to initialize FreeType"));
  211139. }
  211140. StringArray fontDirs;
  211141. fontDirs.addTokens (String (getenv ("JUCE_FONT_PATH")), T(";,"), 0);
  211142. fontDirs.removeEmptyStrings (true);
  211143. if (fontDirs.size() == 0)
  211144. {
  211145. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  211146. XmlElement* const fontsInfo = fontsConfig.getDocumentElement();
  211147. if (fontsInfo != 0)
  211148. {
  211149. forEachXmlChildElementWithTagName (*fontsInfo, e, T("dir"))
  211150. {
  211151. fontDirs.add (e->getAllSubText().trim());
  211152. }
  211153. delete fontsInfo;
  211154. }
  211155. }
  211156. if (fontDirs.size() == 0)
  211157. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  211158. for (int i = 0; i < fontDirs.size(); ++i)
  211159. enumerateFaces (fontDirs[i]);
  211160. }
  211161. ~FreeTypeInterface() throw()
  211162. {
  211163. if (lastFace != 0)
  211164. FT_Done_Face (lastFace);
  211165. if (ftLib != 0)
  211166. FT_Done_FreeType (ftLib);
  211167. clearSingletonInstance();
  211168. }
  211169. FreeTypeFontFace* findOrCreate (const String& familyName,
  211170. const bool create = false) throw()
  211171. {
  211172. for (int i = 0; i < faces.size(); i++)
  211173. if (faces[i]->getFamilyName() == familyName)
  211174. return faces[i];
  211175. if (! create)
  211176. return NULL;
  211177. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  211178. faces.add (newFace);
  211179. return newFace;
  211180. }
  211181. // Enumerate all font faces available in a given directory
  211182. void enumerateFaces (const String& path) throw()
  211183. {
  211184. File dirPath (path);
  211185. if (path.isEmpty() || ! dirPath.isDirectory())
  211186. return;
  211187. DirectoryIterator di (dirPath, true);
  211188. while (di.next())
  211189. {
  211190. File possible (di.getFile());
  211191. if (possible.hasFileExtension (T("ttf"))
  211192. || possible.hasFileExtension (T("pfb"))
  211193. || possible.hasFileExtension (T("pcf")))
  211194. {
  211195. FT_Face face;
  211196. int faceIndex = 0;
  211197. int numFaces = 0;
  211198. do
  211199. {
  211200. if (FT_New_Face (ftLib,
  211201. possible.getFullPathName(),
  211202. faceIndex,
  211203. &face) == 0)
  211204. {
  211205. if (faceIndex == 0)
  211206. numFaces = face->num_faces;
  211207. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  211208. {
  211209. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  211210. int style = (int) FreeTypeFontFace::Plain;
  211211. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  211212. style |= (int) FreeTypeFontFace::Bold;
  211213. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  211214. style |= (int) FreeTypeFontFace::Italic;
  211215. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  211216. if ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0)
  211217. newFace->setMonospaced (true);
  211218. else
  211219. newFace->setMonospaced (false);
  211220. // Surely there must be a better way to do this?
  211221. if (String (face->family_name).containsIgnoreCase (T("Sans"))
  211222. || String (face->family_name).containsIgnoreCase (T("Verdana"))
  211223. || String (face->family_name).containsIgnoreCase (T("Arial")))
  211224. {
  211225. newFace->setSerif (false);
  211226. }
  211227. else
  211228. {
  211229. newFace->setSerif (true);
  211230. }
  211231. }
  211232. FT_Done_Face (face);
  211233. }
  211234. ++faceIndex;
  211235. }
  211236. while (faceIndex < numFaces);
  211237. }
  211238. }
  211239. }
  211240. // Create a FreeType face object for a given font
  211241. FT_Face createFT_Face (const String& fontName,
  211242. const bool bold,
  211243. const bool italic) throw()
  211244. {
  211245. FT_Face face = NULL;
  211246. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  211247. {
  211248. face = lastFace;
  211249. }
  211250. else
  211251. {
  211252. if (lastFace)
  211253. {
  211254. FT_Done_Face (lastFace);
  211255. lastFace = NULL;
  211256. }
  211257. lastFontName = fontName;
  211258. lastBold = bold;
  211259. lastItalic = italic;
  211260. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  211261. if (ftFace != 0)
  211262. {
  211263. int style = (int) FreeTypeFontFace::Plain;
  211264. if (bold)
  211265. style |= (int) FreeTypeFontFace::Bold;
  211266. if (italic)
  211267. style |= (int) FreeTypeFontFace::Italic;
  211268. int faceIndex;
  211269. String fileName (ftFace->getFileName (style, &faceIndex));
  211270. if (fileName.isEmpty())
  211271. {
  211272. style ^= (int) FreeTypeFontFace::Bold;
  211273. fileName = ftFace->getFileName (style, &faceIndex);
  211274. if (fileName.isEmpty())
  211275. {
  211276. style ^= (int) FreeTypeFontFace::Bold;
  211277. style ^= (int) FreeTypeFontFace::Italic;
  211278. fileName = ftFace->getFileName (style, &faceIndex);
  211279. if (! fileName.length())
  211280. {
  211281. style ^= (int) FreeTypeFontFace::Bold;
  211282. fileName = ftFace->getFileName (style, &faceIndex);
  211283. }
  211284. }
  211285. }
  211286. if (! FT_New_Face (ftLib, (const char*) fileName, faceIndex, &lastFace))
  211287. {
  211288. face = lastFace;
  211289. // If there isn't a unicode charmap then select the first one.
  211290. if (FT_Select_Charmap (face, ft_encoding_unicode))
  211291. FT_Set_Charmap (face, face->charmaps[0]);
  211292. }
  211293. }
  211294. }
  211295. return face;
  211296. }
  211297. bool addGlyph (FT_Face face, Typeface& dest, uint32 character) throw()
  211298. {
  211299. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  211300. const float height = (float) (face->ascender - face->descender);
  211301. const float scaleX = 1.0f / height;
  211302. const float scaleY = -1.0f / height;
  211303. Path destShape;
  211304. #define CONVERTX(val) (scaleX * (val).x)
  211305. #define CONVERTY(val) (scaleY * (val).y)
  211306. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE
  211307. | FT_LOAD_NO_BITMAP
  211308. | FT_LOAD_IGNORE_TRANSFORM) != 0
  211309. || face->glyph->format != ft_glyph_format_outline)
  211310. {
  211311. return false;
  211312. }
  211313. const FT_Outline* const outline = &face->glyph->outline;
  211314. const short* const contours = outline->contours;
  211315. const char* const tags = outline->tags;
  211316. FT_Vector* const points = outline->points;
  211317. for (int c = 0; c < outline->n_contours; c++)
  211318. {
  211319. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  211320. const int endPoint = contours[c];
  211321. for (int p = startPoint; p <= endPoint; p++)
  211322. {
  211323. const float x = CONVERTX (points[p]);
  211324. const float y = CONVERTY (points[p]);
  211325. if (p == startPoint)
  211326. {
  211327. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  211328. {
  211329. float x2 = CONVERTX (points [endPoint]);
  211330. float y2 = CONVERTY (points [endPoint]);
  211331. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  211332. {
  211333. x2 = (x + x2) * 0.5f;
  211334. y2 = (y + y2) * 0.5f;
  211335. }
  211336. destShape.startNewSubPath (x2, y2);
  211337. }
  211338. else
  211339. {
  211340. destShape.startNewSubPath (x, y);
  211341. }
  211342. }
  211343. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  211344. {
  211345. if (p != startPoint)
  211346. destShape.lineTo (x, y);
  211347. }
  211348. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  211349. {
  211350. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  211351. float x2 = CONVERTX (points [nextIndex]);
  211352. float y2 = CONVERTY (points [nextIndex]);
  211353. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  211354. {
  211355. x2 = (x + x2) * 0.5f;
  211356. y2 = (y + y2) * 0.5f;
  211357. }
  211358. else
  211359. {
  211360. ++p;
  211361. }
  211362. destShape.quadraticTo (x, y, x2, y2);
  211363. }
  211364. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  211365. {
  211366. if (p >= endPoint)
  211367. return false;
  211368. const int next1 = p + 1;
  211369. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  211370. const float x2 = CONVERTX (points [next1]);
  211371. const float y2 = CONVERTY (points [next1]);
  211372. const float x3 = CONVERTX (points [next2]);
  211373. const float y3 = CONVERTY (points [next2]);
  211374. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  211375. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  211376. return false;
  211377. destShape.cubicTo (x, y, x2, y2, x3, y3);
  211378. p += 2;
  211379. }
  211380. }
  211381. destShape.closeSubPath();
  211382. }
  211383. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance/height);
  211384. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  211385. addKerning (face, dest, character, glyphIndex);
  211386. return true;
  211387. }
  211388. void addKerning (FT_Face face, Typeface& dest, const uint32 character, const uint32 glyphIndex) throw()
  211389. {
  211390. const float height = (float) (face->ascender - face->descender);
  211391. uint32 rightGlyphIndex;
  211392. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  211393. while (rightGlyphIndex != 0)
  211394. {
  211395. FT_Vector kerning;
  211396. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  211397. {
  211398. if (kerning.x != 0)
  211399. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  211400. }
  211401. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  211402. }
  211403. }
  211404. // Add a glyph to a font
  211405. bool addGlyphToFont (const uint32 character,
  211406. const tchar* fontName, bool bold, bool italic,
  211407. Typeface& dest) throw()
  211408. {
  211409. FT_Face face = createFT_Face (fontName, bold, italic);
  211410. if (face != 0)
  211411. return addGlyph (face, dest, character);
  211412. return false;
  211413. }
  211414. // Create a Typeface object for given name/style
  211415. bool createTypeface (const String& fontName,
  211416. const bool bold, const bool italic,
  211417. Typeface& dest,
  211418. const bool addAllGlyphs) throw()
  211419. {
  211420. dest.clear();
  211421. dest.setName (fontName);
  211422. dest.setBold (bold);
  211423. dest.setItalic (italic);
  211424. FT_Face face = createFT_Face (fontName, bold, italic);
  211425. if (face == 0)
  211426. {
  211427. #ifdef JUCE_DEBUG
  211428. String msg (T("Failed to create typeface: "));
  211429. msg << fontName << " " << (bold ? 'B' : ' ') << (italic ? 'I' : ' ');
  211430. DBG (msg);
  211431. #endif
  211432. return face;
  211433. }
  211434. const float height = (float) (face->ascender - face->descender);
  211435. dest.setAscent (face->ascender / height);
  211436. dest.setDefaultCharacter (L' ');
  211437. if (addAllGlyphs)
  211438. {
  211439. uint32 glyphIndex;
  211440. uint32 charCode = FT_Get_First_Char (face, &glyphIndex);
  211441. while (glyphIndex != 0)
  211442. {
  211443. addGlyph (face, dest, charCode);
  211444. charCode = FT_Get_Next_Char (face, charCode, &glyphIndex);
  211445. }
  211446. }
  211447. return true;
  211448. }
  211449. void getFamilyNames (StringArray& familyNames) const throw()
  211450. {
  211451. for (int i = 0; i < faces.size(); i++)
  211452. familyNames.add (faces[i]->getFamilyName());
  211453. }
  211454. void getMonospacedNames (StringArray& monoSpaced) const throw()
  211455. {
  211456. for (int i = 0; i < faces.size(); i++)
  211457. if (faces[i]->getMonospaced())
  211458. monoSpaced.add (faces[i]->getFamilyName());
  211459. }
  211460. void getSerifNames (StringArray& serif) const throw()
  211461. {
  211462. for (int i = 0; i < faces.size(); i++)
  211463. if (faces[i]->getSerif())
  211464. serif.add (faces[i]->getFamilyName());
  211465. }
  211466. void getSansSerifNames (StringArray& sansSerif) const throw()
  211467. {
  211468. for (int i = 0; i < faces.size(); i++)
  211469. if (! faces[i]->getSerif())
  211470. sansSerif.add (faces[i]->getFamilyName());
  211471. }
  211472. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  211473. private:
  211474. FT_Library ftLib;
  211475. FT_Face lastFace;
  211476. String lastFontName;
  211477. bool lastBold, lastItalic;
  211478. OwnedArray<FreeTypeFontFace> faces;
  211479. };
  211480. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  211481. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  211482. bool bold, bool italic,
  211483. bool addAllGlyphsToFont) throw()
  211484. {
  211485. FreeTypeInterface::getInstance()
  211486. ->createTypeface (fontName, bold, italic, *this, addAllGlyphsToFont);
  211487. }
  211488. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  211489. {
  211490. return FreeTypeInterface::getInstance()
  211491. ->addGlyphToFont (character, getName(), isBold(), isItalic(), *this);
  211492. }
  211493. const StringArray Font::findAllTypefaceNames() throw()
  211494. {
  211495. StringArray s;
  211496. FreeTypeInterface::getInstance()->getFamilyNames (s);
  211497. s.sort (true);
  211498. return s;
  211499. }
  211500. static const String pickBestFont (const StringArray& names,
  211501. const char* const choicesString)
  211502. {
  211503. StringArray choices;
  211504. choices.addTokens (String (choicesString), T(","), 0);
  211505. choices.trim();
  211506. choices.removeEmptyStrings();
  211507. int i, j;
  211508. for (j = 0; j < choices.size(); ++j)
  211509. if (names.contains (choices[j], true))
  211510. return choices[j];
  211511. for (j = 0; j < choices.size(); ++j)
  211512. for (i = 0; i < names.size(); i++)
  211513. if (names[i].startsWithIgnoreCase (choices[j]))
  211514. return names[i];
  211515. for (j = 0; j < choices.size(); ++j)
  211516. for (i = 0; i < names.size(); i++)
  211517. if (names[i].containsIgnoreCase (choices[j]))
  211518. return names[i];
  211519. return names[0];
  211520. }
  211521. static const String linux_getDefaultSansSerifFontName()
  211522. {
  211523. StringArray allFonts;
  211524. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  211525. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  211526. }
  211527. static const String linux_getDefaultSerifFontName()
  211528. {
  211529. StringArray allFonts;
  211530. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  211531. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  211532. }
  211533. static const String linux_getDefaultMonospacedFontName()
  211534. {
  211535. StringArray allFonts;
  211536. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  211537. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  211538. }
  211539. void Font::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  211540. {
  211541. defaultSans = linux_getDefaultSansSerifFontName();
  211542. defaultSerif = linux_getDefaultSerifFontName();
  211543. defaultFixed = linux_getDefaultMonospacedFontName();
  211544. }
  211545. END_JUCE_NAMESPACE
  211546. #endif
  211547. /********* End of inlined file: juce_linux_Fonts.cpp *********/
  211548. /********* Start of inlined file: juce_linux_Messaging.cpp *********/
  211549. #if JUCE_BUILD_GUI_CLASSES
  211550. #include <stdio.h>
  211551. #include <signal.h>
  211552. #include <X11/Xlib.h>
  211553. #include <X11/Xatom.h>
  211554. #include <X11/Xresource.h>
  211555. #include <X11/Xutil.h>
  211556. BEGIN_JUCE_NAMESPACE
  211557. #ifdef JUCE_DEBUG
  211558. #define JUCE_DEBUG_XERRORS 1
  211559. #endif
  211560. Display* display = 0; // This is also referenced from WindowDriver.cpp
  211561. static Window juce_messageWindowHandle = None;
  211562. #define SpecialAtom "JUCESpecialAtom"
  211563. #define BroadcastAtom "JUCEBroadcastAtom"
  211564. #define SpecialCallbackAtom "JUCESpecialCallbackAtom"
  211565. static Atom specialId;
  211566. static Atom broadcastId;
  211567. static Atom specialCallbackId;
  211568. // This is referenced from WindowDriver.cpp
  211569. XContext improbableNumber;
  211570. // Defined in WindowDriver.cpp
  211571. extern void juce_windowMessageReceive (XEvent* event);
  211572. struct MessageThreadFuncCall
  211573. {
  211574. MessageCallbackFunction* func;
  211575. void* parameter;
  211576. void* result;
  211577. CriticalSection lock;
  211578. WaitableEvent event;
  211579. };
  211580. static bool errorCondition = false;
  211581. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  211582. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  211583. // (defined in another file to avoid problems including certain headers in this one)
  211584. extern bool juce_isRunningAsApplication();
  211585. // Usually happens when client-server connection is broken
  211586. static int ioErrorHandler (Display* display)
  211587. {
  211588. DBG (T("ERROR: connection to X server broken.. terminating."));
  211589. errorCondition = true;
  211590. if (juce_isRunningAsApplication())
  211591. Process::terminate();
  211592. return 0;
  211593. }
  211594. // A protocol error has occurred
  211595. static int errorHandler (Display* display, XErrorEvent* event)
  211596. {
  211597. #ifdef JUCE_DEBUG_XERRORS
  211598. char errorStr[64] = { 0 };
  211599. char requestStr[64] = { 0 };
  211600. XGetErrorText (display, event->error_code, errorStr, 64);
  211601. XGetErrorDatabaseText (display,
  211602. "XRequest",
  211603. (const char*) String (event->request_code),
  211604. "Unknown",
  211605. requestStr,
  211606. 64);
  211607. DBG (T("ERROR: X returned ") + String (errorStr) + T(" for operation ") + String (requestStr));
  211608. #endif
  211609. return 0;
  211610. }
  211611. static bool breakIn = false;
  211612. // Breakin from keyboard
  211613. static void sig_handler (int sig)
  211614. {
  211615. if (sig == SIGINT)
  211616. {
  211617. breakIn = true;
  211618. return;
  211619. }
  211620. static bool reentrant = false;
  211621. if (reentrant == false)
  211622. {
  211623. reentrant = true;
  211624. // Illegal instruction
  211625. fflush (stdout);
  211626. Logger::outputDebugString ("ERROR: Program executed illegal instruction.. terminating");
  211627. errorCondition = true;
  211628. if (juce_isRunningAsApplication())
  211629. Process::terminate();
  211630. }
  211631. else
  211632. {
  211633. if (juce_isRunningAsApplication())
  211634. exit(0);
  211635. }
  211636. }
  211637. void MessageManager::doPlatformSpecificInitialisation()
  211638. {
  211639. // Initialise xlib for multiple thread support
  211640. static bool initThreadCalled = false;
  211641. if (! initThreadCalled)
  211642. {
  211643. if (! XInitThreads())
  211644. {
  211645. // This is fatal! Print error and closedown
  211646. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  211647. if (juce_isRunningAsApplication())
  211648. Process::terminate();
  211649. return;
  211650. }
  211651. initThreadCalled = true;
  211652. }
  211653. // This is called if the client/server connection is broken
  211654. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  211655. // This is called if a protocol error occurs
  211656. oldErrorHandler = XSetErrorHandler (errorHandler);
  211657. // Install signal handler for break-in
  211658. struct sigaction saction;
  211659. sigset_t maskSet;
  211660. sigemptyset (&maskSet);
  211661. saction.sa_handler = sig_handler;
  211662. saction.sa_mask = maskSet;
  211663. saction.sa_flags = 0;
  211664. sigaction (SIGINT, &saction, NULL);
  211665. #ifndef _DEBUG
  211666. // Setup signal handlers for various fatal errors
  211667. sigaction (SIGILL, &saction, NULL);
  211668. sigaction (SIGBUS, &saction, NULL);
  211669. sigaction (SIGFPE, &saction, NULL);
  211670. sigaction (SIGSEGV, &saction, NULL);
  211671. sigaction (SIGSYS, &saction, NULL);
  211672. #endif
  211673. String displayName (getenv ("DISPLAY"));
  211674. if (displayName.isEmpty())
  211675. displayName = T(":0.0");
  211676. display = XOpenDisplay (displayName);
  211677. if (display == 0)
  211678. {
  211679. // This is fatal! Print error and closedown
  211680. Logger::outputDebugString ("Failed to open the X display.");
  211681. if (juce_isRunningAsApplication())
  211682. Process::terminate();
  211683. return;
  211684. }
  211685. // Get defaults for various properties
  211686. int screen = DefaultScreen (display);
  211687. Window root = RootWindow (display, screen);
  211688. Visual* visual = DefaultVisual (display, screen);
  211689. // Create atoms for our ClientMessages (these cannot be deleted)
  211690. specialId = XInternAtom (display, SpecialAtom, false);
  211691. broadcastId = XInternAtom (display, BroadcastAtom, false);
  211692. specialCallbackId = XInternAtom (display, SpecialCallbackAtom, false);
  211693. // Create a context to store user data associated with Windows we
  211694. // create in WindowDriver
  211695. improbableNumber = XUniqueContext();
  211696. // We're only interested in client messages for this window
  211697. // which are always sent
  211698. XSetWindowAttributes swa;
  211699. swa.event_mask = NoEventMask;
  211700. // Create our message window (this will never be mapped)
  211701. juce_messageWindowHandle = XCreateWindow (display, root,
  211702. 0, 0, 1, 1, 0, 0, InputOnly,
  211703. visual, CWEventMask, &swa);
  211704. }
  211705. void MessageManager::doPlatformSpecificShutdown()
  211706. {
  211707. if (errorCondition == false)
  211708. {
  211709. XDestroyWindow (display, juce_messageWindowHandle);
  211710. XCloseDisplay (display);
  211711. // reset pointers
  211712. juce_messageWindowHandle = 0;
  211713. display = 0;
  211714. // Restore original error handlers
  211715. XSetIOErrorHandler (oldIOErrorHandler);
  211716. oldIOErrorHandler = 0;
  211717. XSetErrorHandler (oldErrorHandler);
  211718. oldErrorHandler = 0;
  211719. }
  211720. }
  211721. bool juce_postMessageToSystemQueue (void* message)
  211722. {
  211723. if (errorCondition)
  211724. return false;
  211725. XClientMessageEvent clientMsg;
  211726. clientMsg.display = display;
  211727. clientMsg.window = juce_messageWindowHandle;
  211728. clientMsg.type = ClientMessage;
  211729. clientMsg.format = 32;
  211730. clientMsg.message_type = specialId;
  211731. #if JUCE_64BIT
  211732. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) message) >> 32));
  211733. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (long) message);
  211734. #else
  211735. clientMsg.data.l[0] = (long) message;
  211736. #endif
  211737. XSendEvent (display, juce_messageWindowHandle, false,
  211738. NoEventMask, (XEvent*) &clientMsg);
  211739. XFlush (display); // This is necessary to ensure the event is delivered
  211740. return true;
  211741. }
  211742. void MessageManager::broadcastMessage (const String& value) throw()
  211743. {
  211744. }
  211745. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  211746. void* parameter)
  211747. {
  211748. void* retVal = 0;
  211749. if (! errorCondition)
  211750. {
  211751. if (! isThisTheMessageThread())
  211752. {
  211753. static MessageThreadFuncCall messageFuncCallContext;
  211754. const ScopedLock sl (messageFuncCallContext.lock);
  211755. XClientMessageEvent clientMsg;
  211756. clientMsg.display = display;
  211757. clientMsg.window = juce_messageWindowHandle;
  211758. clientMsg.type = ClientMessage;
  211759. clientMsg.format = 32;
  211760. clientMsg.message_type = specialCallbackId;
  211761. #if JUCE_64BIT
  211762. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) &messageFuncCallContext) >> 32));
  211763. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (uint64) &messageFuncCallContext);
  211764. #else
  211765. clientMsg.data.l[0] = (long) &messageFuncCallContext;
  211766. #endif
  211767. messageFuncCallContext.func = func;
  211768. messageFuncCallContext.parameter = parameter;
  211769. if (XSendEvent (display, juce_messageWindowHandle, false, NoEventMask, (XEvent*) &clientMsg) == 0)
  211770. return 0;
  211771. XFlush (display); // This is necessary to ensure the event is delivered
  211772. // Wait for it to complete before continuing
  211773. messageFuncCallContext.event.wait();
  211774. retVal = messageFuncCallContext.result;
  211775. }
  211776. else
  211777. {
  211778. // Just call the function directly
  211779. retVal = func (parameter);
  211780. }
  211781. }
  211782. return retVal;
  211783. }
  211784. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  211785. {
  211786. if (errorCondition)
  211787. return false;
  211788. if (breakIn)
  211789. {
  211790. errorCondition = true;
  211791. if (juce_isRunningAsApplication())
  211792. Process::terminate();
  211793. return false;
  211794. }
  211795. if (returnIfNoPendingMessages && ! XPending (display))
  211796. return false;
  211797. XEvent evt;
  211798. XNextEvent (display, &evt);
  211799. if (evt.type == ClientMessage && evt.xany.window == juce_messageWindowHandle)
  211800. {
  211801. XClientMessageEvent* const clientMsg = (XClientMessageEvent*) &evt;
  211802. if (clientMsg->format != 32)
  211803. {
  211804. jassertfalse
  211805. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received malformed client message.");
  211806. }
  211807. else
  211808. {
  211809. JUCE_TRY
  211810. {
  211811. #if JUCE_64BIT
  211812. void* const messagePtr
  211813. = (void*) ((0xffffffff00000000 & (((uint64) clientMsg->data.l[0]) << 32))
  211814. | (clientMsg->data.l[1] & 0x00000000ffffffff));
  211815. #else
  211816. void* const messagePtr = (void*) (clientMsg->data.l[0]);
  211817. #endif
  211818. if (clientMsg->message_type == specialId)
  211819. {
  211820. MessageManager::getInstance()->deliverMessage (messagePtr);
  211821. }
  211822. else if (clientMsg->message_type == specialCallbackId)
  211823. {
  211824. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) messagePtr;
  211825. MessageCallbackFunction* func = call->func;
  211826. call->result = (*func) (call->parameter);
  211827. call->event.signal();
  211828. }
  211829. else if (clientMsg->message_type == broadcastId)
  211830. {
  211831. #if 0
  211832. TCHAR buffer[8192];
  211833. zeromem (buffer, sizeof (buffer));
  211834. if (GlobalGetAtomName ((ATOM) lParam, buffer, 8192) != 0)
  211835. mq->deliverBroadcastMessage (String (buffer));
  211836. #endif
  211837. }
  211838. else
  211839. {
  211840. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received unknown client message.");
  211841. }
  211842. }
  211843. JUCE_CATCH_ALL
  211844. }
  211845. }
  211846. else if (evt.xany.window != juce_messageWindowHandle)
  211847. {
  211848. juce_windowMessageReceive (&evt);
  211849. }
  211850. return true;
  211851. }
  211852. END_JUCE_NAMESPACE
  211853. #endif
  211854. /********* End of inlined file: juce_linux_Messaging.cpp *********/
  211855. /********* Start of inlined file: juce_linux_Midi.cpp *********/
  211856. #if JUCE_BUILD_GUI_CLASSES
  211857. #if JUCE_ALSA
  211858. #include <alsa/asoundlib.h>
  211859. BEGIN_JUCE_NAMESPACE
  211860. static snd_seq_t* iterateDevices (const bool forInput,
  211861. StringArray& deviceNamesFound,
  211862. const int deviceIndexToOpen)
  211863. {
  211864. snd_seq_t* returnedHandle = 0;
  211865. snd_seq_t* seqHandle;
  211866. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  211867. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  211868. {
  211869. snd_seq_system_info_t* systemInfo;
  211870. snd_seq_client_info_t* clientInfo;
  211871. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  211872. {
  211873. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  211874. && snd_seq_client_info_malloc (&clientInfo) == 0)
  211875. {
  211876. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  211877. while (--numClients >= 0 && returnedHandle == 0)
  211878. {
  211879. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  211880. {
  211881. snd_seq_port_info_t* portInfo;
  211882. if (snd_seq_port_info_malloc (&portInfo) == 0)
  211883. {
  211884. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  211885. const int client = snd_seq_client_info_get_client (clientInfo);
  211886. snd_seq_port_info_set_client (portInfo, client);
  211887. snd_seq_port_info_set_port (portInfo, -1);
  211888. while (--numPorts >= 0)
  211889. {
  211890. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  211891. && (snd_seq_port_info_get_capability (portInfo)
  211892. & (forInput ? SND_SEQ_PORT_CAP_READ
  211893. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  211894. {
  211895. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  211896. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  211897. {
  211898. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  211899. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  211900. if (sourcePort != -1)
  211901. {
  211902. snd_seq_set_client_name (seqHandle,
  211903. forInput ? "Juce Midi Input"
  211904. : "Juce Midi Output");
  211905. const int portId
  211906. = snd_seq_create_simple_port (seqHandle,
  211907. forInput ? "Juce Midi In Port"
  211908. : "Juce Midi Out Port",
  211909. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  211910. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  211911. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  211912. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  211913. returnedHandle = seqHandle;
  211914. break;
  211915. }
  211916. }
  211917. }
  211918. }
  211919. snd_seq_port_info_free (portInfo);
  211920. }
  211921. }
  211922. }
  211923. snd_seq_client_info_free (clientInfo);
  211924. }
  211925. snd_seq_system_info_free (systemInfo);
  211926. }
  211927. if (returnedHandle == 0)
  211928. snd_seq_close (seqHandle);
  211929. }
  211930. deviceNamesFound.appendNumbersToDuplicates (true, true);
  211931. return returnedHandle;
  211932. }
  211933. static snd_seq_t* createDevice (const bool forInput,
  211934. const String& deviceNameToOpen)
  211935. {
  211936. snd_seq_t* seqHandle = 0;
  211937. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  211938. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  211939. {
  211940. snd_seq_set_client_name (seqHandle,
  211941. (const char*) (forInput ? (deviceNameToOpen + T(" Input"))
  211942. : (deviceNameToOpen + T(" Output"))));
  211943. const int portId
  211944. = snd_seq_create_simple_port (seqHandle,
  211945. forInput ? "in"
  211946. : "out",
  211947. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  211948. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  211949. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  211950. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  211951. if (portId < 0)
  211952. {
  211953. snd_seq_close (seqHandle);
  211954. seqHandle = 0;
  211955. }
  211956. }
  211957. return seqHandle;
  211958. }
  211959. class MidiOutputDevice
  211960. {
  211961. public:
  211962. MidiOutputDevice (MidiOutput* const midiOutput_,
  211963. snd_seq_t* const seqHandle_)
  211964. :
  211965. midiOutput (midiOutput_),
  211966. seqHandle (seqHandle_),
  211967. maxEventSize (16 * 1024)
  211968. {
  211969. jassert (seqHandle != 0 && midiOutput != 0);
  211970. snd_midi_event_new (maxEventSize, &midiParser);
  211971. }
  211972. ~MidiOutputDevice()
  211973. {
  211974. snd_midi_event_free (midiParser);
  211975. snd_seq_close (seqHandle);
  211976. }
  211977. void sendMessageNow (const MidiMessage& message)
  211978. {
  211979. if (message.getRawDataSize() > maxEventSize)
  211980. {
  211981. maxEventSize = message.getRawDataSize();
  211982. snd_midi_event_free (midiParser);
  211983. snd_midi_event_new (maxEventSize, &midiParser);
  211984. }
  211985. snd_seq_event_t event;
  211986. snd_seq_ev_clear (&event);
  211987. snd_midi_event_encode (midiParser,
  211988. message.getRawData(),
  211989. message.getRawDataSize(),
  211990. &event);
  211991. snd_midi_event_reset_encode (midiParser);
  211992. snd_seq_ev_set_source (&event, 0);
  211993. snd_seq_ev_set_subs (&event);
  211994. snd_seq_ev_set_direct (&event);
  211995. snd_seq_event_output_direct (seqHandle, &event);
  211996. }
  211997. juce_UseDebuggingNewOperator
  211998. private:
  211999. MidiOutput* const midiOutput;
  212000. snd_seq_t* const seqHandle;
  212001. snd_midi_event_t* midiParser;
  212002. int maxEventSize;
  212003. };
  212004. const StringArray MidiOutput::getDevices()
  212005. {
  212006. StringArray devices;
  212007. iterateDevices (false, devices, -1);
  212008. return devices;
  212009. }
  212010. int MidiOutput::getDefaultDeviceIndex()
  212011. {
  212012. return 0;
  212013. }
  212014. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  212015. {
  212016. MidiOutput* newDevice = 0;
  212017. StringArray devices;
  212018. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  212019. if (handle != 0)
  212020. {
  212021. newDevice = new MidiOutput();
  212022. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  212023. }
  212024. return newDevice;
  212025. }
  212026. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  212027. {
  212028. MidiOutput* newDevice = 0;
  212029. snd_seq_t* const handle = createDevice (false, deviceName);
  212030. if (handle != 0)
  212031. {
  212032. newDevice = new MidiOutput();
  212033. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  212034. }
  212035. return newDevice;
  212036. }
  212037. MidiOutput::~MidiOutput()
  212038. {
  212039. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  212040. delete device;
  212041. }
  212042. void MidiOutput::reset()
  212043. {
  212044. }
  212045. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212046. {
  212047. return false;
  212048. }
  212049. void MidiOutput::setVolume (float leftVol, float rightVol)
  212050. {
  212051. }
  212052. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212053. {
  212054. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  212055. }
  212056. class MidiInputThread : public Thread
  212057. {
  212058. public:
  212059. MidiInputThread (MidiInput* const midiInput_,
  212060. snd_seq_t* const seqHandle_,
  212061. MidiInputCallback* const callback_)
  212062. : Thread (T("Juce MIDI Input")),
  212063. midiInput (midiInput_),
  212064. seqHandle (seqHandle_),
  212065. callback (callback_)
  212066. {
  212067. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  212068. }
  212069. ~MidiInputThread()
  212070. {
  212071. snd_seq_close (seqHandle);
  212072. }
  212073. void run()
  212074. {
  212075. const int maxEventSize = 16 * 1024;
  212076. snd_midi_event_t* midiParser;
  212077. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  212078. {
  212079. uint8* const buffer = (uint8*) juce_malloc (maxEventSize);
  212080. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  212081. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  212082. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  212083. while (! threadShouldExit())
  212084. {
  212085. if (poll (pfd, numPfds, 500) > 0)
  212086. {
  212087. snd_seq_event_t* inputEvent = 0;
  212088. snd_seq_nonblock (seqHandle, 1);
  212089. do
  212090. {
  212091. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  212092. {
  212093. // xxx what about SYSEXes that are too big for the buffer?
  212094. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  212095. snd_midi_event_reset_decode (midiParser);
  212096. if (numBytes > 0)
  212097. {
  212098. const MidiMessage message ((const uint8*) buffer,
  212099. numBytes,
  212100. Time::getMillisecondCounter() * 0.001);
  212101. callback->handleIncomingMidiMessage (midiInput, message);
  212102. }
  212103. snd_seq_free_event (inputEvent);
  212104. }
  212105. }
  212106. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  212107. snd_seq_free_event (inputEvent);
  212108. }
  212109. }
  212110. snd_midi_event_free (midiParser);
  212111. juce_free (buffer);
  212112. }
  212113. };
  212114. juce_UseDebuggingNewOperator
  212115. private:
  212116. MidiInput* const midiInput;
  212117. snd_seq_t* const seqHandle;
  212118. MidiInputCallback* const callback;
  212119. };
  212120. MidiInput::MidiInput (const String& name_)
  212121. : name (name_),
  212122. internal (0)
  212123. {
  212124. }
  212125. MidiInput::~MidiInput()
  212126. {
  212127. stop();
  212128. MidiInputThread* const thread = (MidiInputThread*) internal;
  212129. delete thread;
  212130. }
  212131. void MidiInput::start()
  212132. {
  212133. ((MidiInputThread*) internal)->startThread();
  212134. }
  212135. void MidiInput::stop()
  212136. {
  212137. ((MidiInputThread*) internal)->stopThread (3000);
  212138. }
  212139. int MidiInput::getDefaultDeviceIndex()
  212140. {
  212141. return 0;
  212142. }
  212143. const StringArray MidiInput::getDevices()
  212144. {
  212145. StringArray devices;
  212146. iterateDevices (true, devices, -1);
  212147. return devices;
  212148. }
  212149. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  212150. {
  212151. MidiInput* newDevice = 0;
  212152. StringArray devices;
  212153. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  212154. if (handle != 0)
  212155. {
  212156. newDevice = new MidiInput (devices [deviceIndex]);
  212157. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  212158. }
  212159. return newDevice;
  212160. }
  212161. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  212162. {
  212163. MidiInput* newDevice = 0;
  212164. snd_seq_t* const handle = createDevice (true, deviceName);
  212165. if (handle != 0)
  212166. {
  212167. newDevice = new MidiInput (deviceName);
  212168. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  212169. }
  212170. return newDevice;
  212171. }
  212172. END_JUCE_NAMESPACE
  212173. #else
  212174. // (These are just stub functions if ALSA is unavailable...)
  212175. BEGIN_JUCE_NAMESPACE
  212176. const StringArray MidiOutput::getDevices() { return StringArray(); }
  212177. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  212178. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  212179. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  212180. MidiOutput::~MidiOutput() {}
  212181. void MidiOutput::reset() {}
  212182. bool MidiOutput::getVolume (float&, float&) { return false; }
  212183. void MidiOutput::setVolume (float, float) {}
  212184. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  212185. MidiInput::MidiInput (const String& name_)
  212186. : name (name_),
  212187. internal (0)
  212188. {}
  212189. MidiInput::~MidiInput() {}
  212190. void MidiInput::start() {}
  212191. void MidiInput::stop() {}
  212192. int MidiInput::getDefaultDeviceIndex() { return 0; }
  212193. const StringArray MidiInput::getDevices() { return StringArray(); }
  212194. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  212195. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  212196. END_JUCE_NAMESPACE
  212197. #endif
  212198. #endif
  212199. /********* End of inlined file: juce_linux_Midi.cpp *********/
  212200. /********* Start of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  212201. BEGIN_JUCE_NAMESPACE
  212202. /*
  212203. Sorry.. This class isn't implemented on Linux!
  212204. */
  212205. WebBrowserComponent::WebBrowserComponent()
  212206. : browser (0),
  212207. blankPageShown (false)
  212208. {
  212209. setOpaque (true);
  212210. }
  212211. WebBrowserComponent::~WebBrowserComponent()
  212212. {
  212213. }
  212214. void WebBrowserComponent::goToURL (const String& url,
  212215. const StringArray* headers,
  212216. const MemoryBlock* postData)
  212217. {
  212218. lastURL = url;
  212219. lastHeaders.clear();
  212220. if (headers != 0)
  212221. lastHeaders = *headers;
  212222. lastPostData.setSize (0);
  212223. if (postData != 0)
  212224. lastPostData = *postData;
  212225. blankPageShown = false;
  212226. }
  212227. void WebBrowserComponent::stop()
  212228. {
  212229. }
  212230. void WebBrowserComponent::goBack()
  212231. {
  212232. lastURL = String::empty;
  212233. blankPageShown = false;
  212234. }
  212235. void WebBrowserComponent::goForward()
  212236. {
  212237. lastURL = String::empty;
  212238. }
  212239. void WebBrowserComponent::paint (Graphics& g)
  212240. {
  212241. g.fillAll (Colours::white);
  212242. }
  212243. void WebBrowserComponent::checkWindowAssociation()
  212244. {
  212245. }
  212246. void WebBrowserComponent::reloadLastURL()
  212247. {
  212248. if (lastURL.isNotEmpty())
  212249. {
  212250. goToURL (lastURL, &lastHeaders, &lastPostData);
  212251. lastURL = String::empty;
  212252. }
  212253. }
  212254. void WebBrowserComponent::parentHierarchyChanged()
  212255. {
  212256. checkWindowAssociation();
  212257. }
  212258. void WebBrowserComponent::moved()
  212259. {
  212260. }
  212261. void WebBrowserComponent::resized()
  212262. {
  212263. }
  212264. void WebBrowserComponent::visibilityChanged()
  212265. {
  212266. checkWindowAssociation();
  212267. }
  212268. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  212269. {
  212270. return true;
  212271. }
  212272. END_JUCE_NAMESPACE
  212273. /********* End of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  212274. /********* Start of inlined file: juce_linux_Windowing.cpp *********/
  212275. #if JUCE_BUILD_GUI_CLASSES
  212276. #include <X11/Xlib.h>
  212277. #include <X11/Xutil.h>
  212278. #include <X11/Xatom.h>
  212279. #include <X11/Xmd.h>
  212280. #include <X11/keysym.h>
  212281. #include <X11/cursorfont.h>
  212282. #include <dlfcn.h>
  212283. #if JUCE_USE_XINERAMA
  212284. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package..
  212285. */
  212286. #include <X11/extensions/Xinerama.h>
  212287. #endif
  212288. #if JUCE_USE_XSHM
  212289. #include <X11/extensions/XShm.h>
  212290. #include <sys/shm.h>
  212291. #include <sys/ipc.h>
  212292. #endif
  212293. #if JUCE_OPENGL
  212294. /* Got an include error here?
  212295. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  212296. and "freeglut3-dev".
  212297. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  212298. want to disable it.
  212299. */
  212300. #include <GL/glx.h>
  212301. #endif
  212302. #undef KeyPress
  212303. BEGIN_JUCE_NAMESPACE
  212304. #define TAKE_FOCUS 0
  212305. #define DELETE_WINDOW 1
  212306. #define SYSTEM_TRAY_REQUEST_DOCK 0
  212307. #define SYSTEM_TRAY_BEGIN_MESSAGE 1
  212308. #define SYSTEM_TRAY_CANCEL_MESSAGE 2
  212309. static const int repaintTimerPeriod = 1000 / 100; // 100 fps maximum
  212310. static Atom wm_ChangeState = None;
  212311. static Atom wm_State = None;
  212312. static Atom wm_Protocols = None;
  212313. static Atom wm_ProtocolList [2] = { None, None };
  212314. static Atom wm_ActiveWin = None;
  212315. #define ourDndVersion 3
  212316. static Atom XA_XdndAware = None;
  212317. static Atom XA_XdndEnter = None;
  212318. static Atom XA_XdndLeave = None;
  212319. static Atom XA_XdndPosition = None;
  212320. static Atom XA_XdndStatus = None;
  212321. static Atom XA_XdndDrop = None;
  212322. static Atom XA_XdndFinished = None;
  212323. static Atom XA_XdndSelection = None;
  212324. static Atom XA_XdndProxy = None;
  212325. static Atom XA_XdndTypeList = None;
  212326. static Atom XA_XdndActionList = None;
  212327. static Atom XA_XdndActionDescription = None;
  212328. static Atom XA_XdndActionCopy = None;
  212329. static Atom XA_XdndActionMove = None;
  212330. static Atom XA_XdndActionLink = None;
  212331. static Atom XA_XdndActionAsk = None;
  212332. static Atom XA_XdndActionPrivate = None;
  212333. static Atom XA_JXSelectionWindowProperty = None;
  212334. static Atom XA_MimeTextPlain = None;
  212335. static Atom XA_MimeTextUriList = None;
  212336. static Atom XA_MimeRootDrop = None;
  212337. static XErrorHandler oldHandler = 0;
  212338. static int trappedErrorCode = 0;
  212339. extern "C" int errorTrapHandler (Display* dpy, XErrorEvent* err)
  212340. {
  212341. trappedErrorCode = err->error_code;
  212342. return 0;
  212343. }
  212344. static void trapErrors()
  212345. {
  212346. trappedErrorCode = 0;
  212347. oldHandler = XSetErrorHandler (errorTrapHandler);
  212348. }
  212349. static bool untrapErrors()
  212350. {
  212351. XSetErrorHandler (oldHandler);
  212352. return (trappedErrorCode == 0);
  212353. }
  212354. static bool isActiveApplication = false;
  212355. bool Process::isForegroundProcess() throw()
  212356. {
  212357. return isActiveApplication;
  212358. }
  212359. // (used in the messaging code, declared here for build reasons)
  212360. bool juce_isRunningAsApplication()
  212361. {
  212362. return JUCEApplication::getInstance() != 0;
  212363. }
  212364. // These are defined in juce_linux_Messaging.cpp
  212365. extern Display* display;
  212366. extern XContext improbableNumber;
  212367. static const int eventMask = NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  212368. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  212369. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  212370. static int pointerMap[5];
  212371. static int lastMousePosX = 0, lastMousePosY = 0;
  212372. enum MouseButtons
  212373. {
  212374. NoButton = 0,
  212375. LeftButton = 1,
  212376. MiddleButton = 2,
  212377. RightButton = 3,
  212378. WheelUp = 4,
  212379. WheelDown = 5
  212380. };
  212381. static void getMousePos (int& x, int& y, int& mouseMods) throw()
  212382. {
  212383. Window root, child;
  212384. int winx, winy;
  212385. unsigned int mask;
  212386. mouseMods = 0;
  212387. if (XQueryPointer (display,
  212388. RootWindow (display, DefaultScreen (display)),
  212389. &root, &child,
  212390. &x, &y, &winx, &winy, &mask) == False)
  212391. {
  212392. // Pointer not on the default screen
  212393. x = y = -1;
  212394. }
  212395. else
  212396. {
  212397. if ((mask & Button1Mask) != 0)
  212398. mouseMods |= ModifierKeys::leftButtonModifier;
  212399. if ((mask & Button2Mask) != 0)
  212400. mouseMods |= ModifierKeys::middleButtonModifier;
  212401. if ((mask & Button3Mask) != 0)
  212402. mouseMods |= ModifierKeys::rightButtonModifier;
  212403. }
  212404. }
  212405. static int AltMask = 0;
  212406. static int NumLockMask = 0;
  212407. static bool numLock = 0;
  212408. static bool capsLock = 0;
  212409. static char keyStates [32];
  212410. static void updateKeyStates (const int keycode, const bool press) throw()
  212411. {
  212412. const int keybyte = keycode >> 3;
  212413. const int keybit = (1 << (keycode & 7));
  212414. if (press)
  212415. keyStates [keybyte] |= keybit;
  212416. else
  212417. keyStates [keybyte] &= ~keybit;
  212418. }
  212419. static bool keyDown (const int keycode) throw()
  212420. {
  212421. const int keybyte = keycode >> 3;
  212422. const int keybit = (1 << (keycode & 7));
  212423. return (keyStates [keybyte] & keybit) != 0;
  212424. }
  212425. static const int extendedKeyModifier = 0x10000000;
  212426. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  212427. {
  212428. int keysym;
  212429. if (keyCode & extendedKeyModifier)
  212430. {
  212431. keysym = 0xff00 | (keyCode & 0xff);
  212432. }
  212433. else
  212434. {
  212435. keysym = keyCode;
  212436. if (keysym == (XK_Tab & 0xff)
  212437. || keysym == (XK_Return & 0xff)
  212438. || keysym == (XK_Escape & 0xff)
  212439. || keysym == (XK_BackSpace & 0xff))
  212440. {
  212441. keysym |= 0xff00;
  212442. }
  212443. }
  212444. return keyDown (XKeysymToKeycode (display, keysym));
  212445. }
  212446. // Alt and Num lock are not defined by standard X
  212447. // modifier constants: check what they're mapped to
  212448. static void getModifierMapping() throw()
  212449. {
  212450. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  212451. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  212452. AltMask = 0;
  212453. NumLockMask = 0;
  212454. XModifierKeymap* mapping = XGetModifierMapping (display);
  212455. if (mapping)
  212456. {
  212457. for (int i = 0; i < 8; i++)
  212458. {
  212459. if (mapping->modifiermap [i << 1] == altLeftCode)
  212460. AltMask = 1 << i;
  212461. else if (mapping->modifiermap [i << 1] == numLockCode)
  212462. NumLockMask = 1 << i;
  212463. }
  212464. XFreeModifiermap (mapping);
  212465. }
  212466. }
  212467. static int currentModifiers = 0;
  212468. void ModifierKeys::updateCurrentModifiers() throw()
  212469. {
  212470. currentModifierFlags = currentModifiers;
  212471. }
  212472. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  212473. {
  212474. int x, y, mouseMods;
  212475. getMousePos (x, y, mouseMods);
  212476. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  212477. currentModifiers |= mouseMods;
  212478. return ModifierKeys (currentModifiers);
  212479. }
  212480. static void updateKeyModifiers (const int status) throw()
  212481. {
  212482. currentModifiers &= ~(ModifierKeys::shiftModifier
  212483. | ModifierKeys::ctrlModifier
  212484. | ModifierKeys::altModifier);
  212485. if (status & ShiftMask)
  212486. currentModifiers |= ModifierKeys::shiftModifier;
  212487. if (status & ControlMask)
  212488. currentModifiers |= ModifierKeys::ctrlModifier;
  212489. if (status & AltMask)
  212490. currentModifiers |= ModifierKeys::altModifier;
  212491. numLock = ((status & NumLockMask) != 0);
  212492. capsLock = ((status & LockMask) != 0);
  212493. }
  212494. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  212495. {
  212496. int modifier = 0;
  212497. bool isModifier = true;
  212498. switch (sym)
  212499. {
  212500. case XK_Shift_L:
  212501. case XK_Shift_R:
  212502. modifier = ModifierKeys::shiftModifier;
  212503. break;
  212504. case XK_Control_L:
  212505. case XK_Control_R:
  212506. modifier = ModifierKeys::ctrlModifier;
  212507. break;
  212508. case XK_Alt_L:
  212509. case XK_Alt_R:
  212510. modifier = ModifierKeys::altModifier;
  212511. break;
  212512. case XK_Num_Lock:
  212513. if (press)
  212514. numLock = ! numLock;
  212515. break;
  212516. case XK_Caps_Lock:
  212517. if (press)
  212518. capsLock = ! capsLock;
  212519. break;
  212520. case XK_Scroll_Lock:
  212521. break;
  212522. default:
  212523. isModifier = false;
  212524. break;
  212525. }
  212526. if (modifier != 0)
  212527. {
  212528. if (press)
  212529. currentModifiers |= modifier;
  212530. else
  212531. currentModifiers &= ~modifier;
  212532. }
  212533. return isModifier;
  212534. }
  212535. #if JUCE_USE_XSHM
  212536. static bool isShmAvailable() throw()
  212537. {
  212538. static bool isChecked = false;
  212539. static bool isAvailable = false;
  212540. if (! isChecked)
  212541. {
  212542. isChecked = true;
  212543. int major, minor;
  212544. Bool pixmaps;
  212545. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  212546. {
  212547. trapErrors();
  212548. XShmSegmentInfo segmentInfo;
  212549. zerostruct (segmentInfo);
  212550. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  212551. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  212552. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  212553. xImage->bytes_per_line * xImage->height,
  212554. IPC_CREAT | 0777)) >= 0)
  212555. {
  212556. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  212557. if (segmentInfo.shmaddr != (void*) -1)
  212558. {
  212559. segmentInfo.readOnly = False;
  212560. xImage->data = segmentInfo.shmaddr;
  212561. XSync (display, False);
  212562. if (XShmAttach (display, &segmentInfo) != 0)
  212563. {
  212564. XSync (display, False);
  212565. XShmDetach (display, &segmentInfo);
  212566. isAvailable = true;
  212567. }
  212568. }
  212569. XFlush (display);
  212570. XDestroyImage (xImage);
  212571. shmdt (segmentInfo.shmaddr);
  212572. }
  212573. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  212574. isAvailable &= untrapErrors();
  212575. }
  212576. }
  212577. return isAvailable;
  212578. }
  212579. #endif
  212580. class XBitmapImage : public Image
  212581. {
  212582. public:
  212583. XBitmapImage (const PixelFormat format_, const int w, const int h,
  212584. const bool clearImage, const bool is16Bit_)
  212585. : Image (format_, w, h),
  212586. is16Bit (is16Bit_)
  212587. {
  212588. jassert (format_ == RGB || format_ == ARGB);
  212589. pixelStride = (format_ == RGB) ? 3 : 4;
  212590. lineStride = ((w * pixelStride + 3) & ~3);
  212591. Visual* const visual = DefaultVisual (display, DefaultScreen (display));
  212592. #if JUCE_USE_XSHM
  212593. usingXShm = false;
  212594. if ((! is16Bit) && isShmAvailable())
  212595. {
  212596. zerostruct (segmentInfo);
  212597. xImage = XShmCreateImage (display, visual, 24, ZPixmap, 0, &segmentInfo, w, h);
  212598. if (xImage != 0)
  212599. {
  212600. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  212601. xImage->bytes_per_line * xImage->height,
  212602. IPC_CREAT | 0777)) >= 0)
  212603. {
  212604. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  212605. if (segmentInfo.shmaddr != (void*) -1)
  212606. {
  212607. segmentInfo.readOnly = False;
  212608. xImage->data = segmentInfo.shmaddr;
  212609. imageData = (uint8*) segmentInfo.shmaddr;
  212610. XSync (display, False);
  212611. if (XShmAttach (display, &segmentInfo) != 0)
  212612. {
  212613. XSync (display, False);
  212614. usingXShm = true;
  212615. }
  212616. else
  212617. {
  212618. jassertfalse
  212619. }
  212620. }
  212621. else
  212622. {
  212623. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  212624. }
  212625. }
  212626. }
  212627. }
  212628. if (! usingXShm)
  212629. #endif
  212630. {
  212631. imageData = (uint8*) juce_malloc (lineStride * h);
  212632. if (format_ == ARGB && clearImage)
  212633. zeromem (imageData, h * lineStride);
  212634. xImage = (XImage*) juce_calloc (sizeof (XImage));
  212635. xImage->width = w;
  212636. xImage->height = h;
  212637. xImage->xoffset = 0;
  212638. xImage->format = ZPixmap;
  212639. xImage->data = (char*) imageData;
  212640. xImage->byte_order = ImageByteOrder (display);
  212641. xImage->bitmap_unit = BitmapUnit (display);
  212642. xImage->bitmap_bit_order = BitmapBitOrder (display);
  212643. xImage->bitmap_pad = 32;
  212644. xImage->depth = pixelStride * 8;
  212645. xImage->bytes_per_line = lineStride;
  212646. xImage->bits_per_pixel = pixelStride * 8;
  212647. xImage->red_mask = 0x00FF0000;
  212648. xImage->green_mask = 0x0000FF00;
  212649. xImage->blue_mask = 0x000000FF;
  212650. if (is16Bit)
  212651. {
  212652. const int pixelStride = 2;
  212653. const int lineStride = ((w * pixelStride + 3) & ~3);
  212654. xImage->data = (char*) juce_malloc (lineStride * h);
  212655. xImage->bitmap_pad = 16;
  212656. xImage->depth = pixelStride * 8;
  212657. xImage->bytes_per_line = lineStride;
  212658. xImage->bits_per_pixel = pixelStride * 8;
  212659. xImage->red_mask = visual->red_mask;
  212660. xImage->green_mask = visual->green_mask;
  212661. xImage->blue_mask = visual->blue_mask;
  212662. }
  212663. if (! XInitImage (xImage))
  212664. {
  212665. jassertfalse
  212666. }
  212667. }
  212668. }
  212669. ~XBitmapImage()
  212670. {
  212671. #if JUCE_USE_XSHM
  212672. if (usingXShm)
  212673. {
  212674. XShmDetach (display, &segmentInfo);
  212675. XFlush (display);
  212676. XDestroyImage (xImage);
  212677. shmdt (segmentInfo.shmaddr);
  212678. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  212679. }
  212680. else
  212681. #endif
  212682. {
  212683. juce_free (xImage->data);
  212684. xImage->data = 0;
  212685. XDestroyImage (xImage);
  212686. }
  212687. if (! is16Bit)
  212688. imageData = 0; // to stop the base class freeing this (for the 16-bit version we want it to free it)
  212689. }
  212690. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  212691. {
  212692. static GC gc = 0;
  212693. if (gc == 0)
  212694. gc = DefaultGC (display, DefaultScreen (display));
  212695. if (is16Bit)
  212696. {
  212697. const uint32 rMask = xImage->red_mask;
  212698. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  212699. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  212700. const uint32 gMask = xImage->green_mask;
  212701. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  212702. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  212703. const uint32 bMask = xImage->blue_mask;
  212704. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  212705. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  212706. int ls, ps;
  212707. const uint8* const pixels = lockPixelDataReadOnly (0, 0, getWidth(), getHeight(), ls, ps);
  212708. jassert (! isARGB())
  212709. for (int y = sy; y < sy + dh; ++y)
  212710. {
  212711. const uint8* p = pixels + y * ls + sx * ps;
  212712. for (int x = sx; x < sx + dw; ++x)
  212713. {
  212714. const PixelRGB* const pixel = (const PixelRGB*) p;
  212715. p += ps;
  212716. XPutPixel (xImage, x, y,
  212717. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  212718. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  212719. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  212720. }
  212721. }
  212722. releasePixelDataReadOnly (pixels);
  212723. }
  212724. // blit results to screen.
  212725. #if JUCE_USE_XSHM
  212726. if (usingXShm)
  212727. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, False);
  212728. else
  212729. #endif
  212730. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  212731. }
  212732. juce_UseDebuggingNewOperator
  212733. private:
  212734. XImage* xImage;
  212735. const bool is16Bit;
  212736. #if JUCE_USE_XSHM
  212737. XShmSegmentInfo segmentInfo;
  212738. bool usingXShm;
  212739. #endif
  212740. static int getShiftNeeded (const uint32 mask) throw()
  212741. {
  212742. for (int i = 32; --i >= 0;)
  212743. if (((mask >> i) & 1) != 0)
  212744. return i - 7;
  212745. jassertfalse
  212746. return 0;
  212747. }
  212748. };
  212749. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  212750. class LinuxComponentPeer : public ComponentPeer
  212751. {
  212752. public:
  212753. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  212754. : ComponentPeer (component, windowStyleFlags),
  212755. windowH (0),
  212756. parentWindow (0),
  212757. wx (0),
  212758. wy (0),
  212759. ww (0),
  212760. wh (0),
  212761. taskbarImage (0),
  212762. fullScreen (false),
  212763. entered (false),
  212764. mapped (false)
  212765. {
  212766. // it's dangerous to create a window on a thread other than the message thread..
  212767. checkMessageManagerIsLocked
  212768. repainter = new LinuxRepaintManager (this);
  212769. createWindow();
  212770. setTitle (component->getName());
  212771. }
  212772. ~LinuxComponentPeer()
  212773. {
  212774. // it's dangerous to delete a window on a thread other than the message thread..
  212775. checkMessageManagerIsLocked
  212776. deleteTaskBarIcon();
  212777. destroyWindow();
  212778. windowH = 0;
  212779. delete repainter;
  212780. }
  212781. void* getNativeHandle() const
  212782. {
  212783. return (void*) windowH;
  212784. }
  212785. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  212786. {
  212787. XPointer peer = 0;
  212788. if (! XFindContext (display, (XID) windowHandle, improbableNumber, &peer))
  212789. {
  212790. if (peer != 0 && ! ((LinuxComponentPeer*) peer)->isValidMessageListener())
  212791. peer = 0;
  212792. }
  212793. return (LinuxComponentPeer*) peer;
  212794. }
  212795. void setVisible (bool shouldBeVisible)
  212796. {
  212797. if (shouldBeVisible)
  212798. XMapWindow (display, windowH);
  212799. else
  212800. XUnmapWindow (display, windowH);
  212801. }
  212802. void setTitle (const String& title)
  212803. {
  212804. setWindowTitle (windowH, title);
  212805. }
  212806. void setPosition (int x, int y)
  212807. {
  212808. setBounds (x, y, ww, wh, false);
  212809. }
  212810. void setSize (int w, int h)
  212811. {
  212812. setBounds (wx, wy, w, h, false);
  212813. }
  212814. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  212815. {
  212816. fullScreen = isNowFullScreen;
  212817. if (windowH != 0)
  212818. {
  212819. const ComponentDeletionWatcher deletionChecker (component);
  212820. wx = x;
  212821. wy = y;
  212822. ww = jmax (1, w);
  212823. wh = jmax (1, h);
  212824. if (! mapped)
  212825. {
  212826. // Make sure the Window manager does what we want
  212827. XSizeHints* hints = XAllocSizeHints();
  212828. hints->flags = USSize | USPosition;
  212829. hints->width = ww + windowBorder.getLeftAndRight();
  212830. hints->height = wh + windowBorder.getTopAndBottom();
  212831. hints->x = wx - windowBorder.getLeft();
  212832. hints->y = wy - windowBorder.getTop();
  212833. XSetWMNormalHints (display, windowH, hints);
  212834. XFree (hints);
  212835. }
  212836. XMoveResizeWindow (display, windowH,
  212837. wx - windowBorder.getLeft(),
  212838. wy - windowBorder.getTop(),
  212839. ww + windowBorder.getLeftAndRight(),
  212840. wh + windowBorder.getTopAndBottom());
  212841. if (! deletionChecker.hasBeenDeleted())
  212842. {
  212843. updateBorderSize();
  212844. handleMovedOrResized();
  212845. }
  212846. }
  212847. }
  212848. void getBounds (int& x, int& y, int& w, int& h) const
  212849. {
  212850. x = wx;
  212851. y = wy;
  212852. w = ww;
  212853. h = wh;
  212854. }
  212855. int getScreenX() const
  212856. {
  212857. return wx;
  212858. }
  212859. int getScreenY() const
  212860. {
  212861. return wy;
  212862. }
  212863. void relativePositionToGlobal (int& x, int& y)
  212864. {
  212865. x += wx;
  212866. y += wy;
  212867. }
  212868. void globalPositionToRelative (int& x, int& y)
  212869. {
  212870. x -= wx;
  212871. y -= wy;
  212872. }
  212873. void setMinimised (bool shouldBeMinimised)
  212874. {
  212875. if (shouldBeMinimised)
  212876. {
  212877. Window root = RootWindow (display, DefaultScreen (display));
  212878. XClientMessageEvent clientMsg;
  212879. clientMsg.display = display;
  212880. clientMsg.window = windowH;
  212881. clientMsg.type = ClientMessage;
  212882. clientMsg.format = 32;
  212883. clientMsg.message_type = wm_ChangeState;
  212884. clientMsg.data.l[0] = IconicState;
  212885. XSendEvent (display, root, false,
  212886. SubstructureRedirectMask | SubstructureNotifyMask,
  212887. (XEvent*) &clientMsg);
  212888. }
  212889. else
  212890. {
  212891. setVisible (true);
  212892. }
  212893. }
  212894. bool isMinimised() const
  212895. {
  212896. bool minimised = false;
  212897. unsigned char* stateProp;
  212898. unsigned long nitems, bytesLeft;
  212899. Atom actualType;
  212900. int actualFormat;
  212901. if (XGetWindowProperty (display, windowH, wm_State, 0, 64, False,
  212902. wm_State, &actualType, &actualFormat, &nitems, &bytesLeft,
  212903. &stateProp) == Success
  212904. && actualType == wm_State
  212905. && actualFormat == 32
  212906. && nitems > 0)
  212907. {
  212908. if (((unsigned long*) stateProp)[0] == IconicState)
  212909. minimised = true;
  212910. XFree (stateProp);
  212911. }
  212912. return minimised;
  212913. }
  212914. void setFullScreen (const bool shouldBeFullScreen)
  212915. {
  212916. Rectangle r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  212917. setMinimised (false);
  212918. if (fullScreen != shouldBeFullScreen)
  212919. {
  212920. if (shouldBeFullScreen)
  212921. r = Desktop::getInstance().getMainMonitorArea();
  212922. if (! r.isEmpty())
  212923. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  212924. getComponent()->repaint();
  212925. }
  212926. }
  212927. bool isFullScreen() const
  212928. {
  212929. return fullScreen;
  212930. }
  212931. bool isChildWindowOf (Window possibleParent) const
  212932. {
  212933. Window* windowList = 0;
  212934. uint32 windowListSize = 0;
  212935. Window parent, root;
  212936. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  212937. {
  212938. if (windowList != 0)
  212939. XFree (windowList);
  212940. return parent == possibleParent;
  212941. }
  212942. return false;
  212943. }
  212944. bool isFrontWindow() const
  212945. {
  212946. Window* windowList = 0;
  212947. uint32 windowListSize = 0;
  212948. bool result = false;
  212949. Window parent, root = RootWindow (display, DefaultScreen (display));
  212950. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  212951. {
  212952. for (int i = windowListSize; --i >= 0;)
  212953. {
  212954. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  212955. if (peer != 0)
  212956. {
  212957. result = (peer == this);
  212958. break;
  212959. }
  212960. }
  212961. }
  212962. if (windowList != 0)
  212963. XFree (windowList);
  212964. return result;
  212965. }
  212966. bool contains (int x, int y, bool trueIfInAChildWindow) const
  212967. {
  212968. jassert (x >= 0 && y >= 0 && x < ww && y < wh); // should only be called for points that are actually inside the bounds
  212969. if (((unsigned int) x) >= (unsigned int) ww
  212970. || ((unsigned int) y) >= (unsigned int) wh)
  212971. return false;
  212972. bool inFront = false;
  212973. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  212974. {
  212975. Component* const c = Desktop::getInstance().getComponent (i);
  212976. if (inFront)
  212977. {
  212978. if (c->contains (x + wx - c->getScreenX(),
  212979. y + wy - c->getScreenY()))
  212980. {
  212981. return false;
  212982. }
  212983. }
  212984. else if (c == getComponent())
  212985. {
  212986. inFront = true;
  212987. }
  212988. }
  212989. if (trueIfInAChildWindow)
  212990. return true;
  212991. ::Window root, child;
  212992. unsigned int bw, depth;
  212993. int wx, wy, w, h;
  212994. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  212995. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  212996. &bw, &depth))
  212997. {
  212998. return false;
  212999. }
  213000. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  213001. return false;
  213002. return child == None;
  213003. }
  213004. const BorderSize getFrameSize() const
  213005. {
  213006. return BorderSize();
  213007. }
  213008. bool setAlwaysOnTop (bool alwaysOnTop)
  213009. {
  213010. if (windowH != 0)
  213011. {
  213012. const bool wasVisible = component->isVisible();
  213013. if (wasVisible)
  213014. setVisible (false); // doesn't always seem to work if the window is visible when this is done..
  213015. XSetWindowAttributes swa;
  213016. swa.override_redirect = alwaysOnTop ? True : False;
  213017. XChangeWindowAttributes (display, windowH, CWOverrideRedirect, &swa);
  213018. if (wasVisible)
  213019. setVisible (true);
  213020. }
  213021. return true;
  213022. }
  213023. void toFront (bool makeActive)
  213024. {
  213025. if (makeActive)
  213026. {
  213027. setVisible (true);
  213028. grabFocus();
  213029. }
  213030. XEvent ev;
  213031. ev.xclient.type = ClientMessage;
  213032. ev.xclient.serial = 0;
  213033. ev.xclient.send_event = True;
  213034. ev.xclient.message_type = wm_ActiveWin;
  213035. ev.xclient.window = windowH;
  213036. ev.xclient.format = 32;
  213037. ev.xclient.data.l[0] = 2;
  213038. ev.xclient.data.l[1] = CurrentTime;
  213039. ev.xclient.data.l[2] = 0;
  213040. ev.xclient.data.l[3] = 0;
  213041. ev.xclient.data.l[4] = 0;
  213042. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  213043. False,
  213044. SubstructureRedirectMask | SubstructureNotifyMask,
  213045. &ev);
  213046. XSync (display, False);
  213047. handleBroughtToFront();
  213048. }
  213049. void toBehind (ComponentPeer* other)
  213050. {
  213051. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  213052. jassert (otherPeer != 0); // wrong type of window?
  213053. if (otherPeer != 0)
  213054. {
  213055. setMinimised (false);
  213056. Window newStack[] = { otherPeer->windowH, windowH };
  213057. XRestackWindows (display, newStack, 2);
  213058. }
  213059. }
  213060. bool isFocused() const
  213061. {
  213062. int revert;
  213063. Window focusedWindow = 0;
  213064. XGetInputFocus (display, &focusedWindow, &revert);
  213065. return focusedWindow == windowH;
  213066. }
  213067. void grabFocus()
  213068. {
  213069. XWindowAttributes atts;
  213070. if (windowH != 0
  213071. && XGetWindowAttributes (display, windowH, &atts)
  213072. && atts.map_state == IsViewable
  213073. && ! isFocused())
  213074. {
  213075. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  213076. isActiveApplication = true;
  213077. }
  213078. }
  213079. void textInputRequired (int /*x*/, int /*y*/)
  213080. {
  213081. }
  213082. void repaint (int x, int y, int w, int h)
  213083. {
  213084. if (Rectangle::intersectRectangles (x, y, w, h,
  213085. 0, 0,
  213086. getComponent()->getWidth(),
  213087. getComponent()->getHeight()))
  213088. {
  213089. repainter->repaint (x, y, w, h);
  213090. }
  213091. }
  213092. void performAnyPendingRepaintsNow()
  213093. {
  213094. repainter->performAnyPendingRepaintsNow();
  213095. }
  213096. void setIcon (const Image& newIcon)
  213097. {
  213098. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  213099. uint32* const data = (uint32*) juce_malloc (dataSize);
  213100. int index = 0;
  213101. data[index++] = newIcon.getWidth();
  213102. data[index++] = newIcon.getHeight();
  213103. for (int y = 0; y < newIcon.getHeight(); ++y)
  213104. for (int x = 0; x < newIcon.getWidth(); ++x)
  213105. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  213106. XChangeProperty (display, windowH,
  213107. XInternAtom (display, "_NET_WM_ICON", False),
  213108. XA_CARDINAL, 32, PropModeReplace,
  213109. (unsigned char*) data, dataSize);
  213110. XSync (display, False);
  213111. juce_free (data);
  213112. }
  213113. void handleWindowMessage (XEvent* event)
  213114. {
  213115. switch (event->xany.type)
  213116. {
  213117. case 2: // 'KeyPress'
  213118. {
  213119. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  213120. updateKeyStates (keyEvent->keycode, true);
  213121. char utf8 [64];
  213122. zeromem (utf8, sizeof (utf8));
  213123. KeySym sym;
  213124. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  213125. const juce_wchar unicodeChar = *(const juce_wchar*) String::fromUTF8 ((const uint8*) utf8, sizeof (utf8) - 1);
  213126. int keyCode = (int) unicodeChar;
  213127. if (keyCode < 0x20)
  213128. keyCode = XKeycodeToKeysym (display, keyEvent->keycode,
  213129. (currentModifiers & ModifierKeys::shiftModifier) != 0 ? 1 : 0);
  213130. const int oldMods = currentModifiers;
  213131. bool keyPressed = false;
  213132. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  213133. if ((sym & 0xff00) == 0xff00)
  213134. {
  213135. // Translate keypad
  213136. if (sym == XK_KP_Divide)
  213137. keyCode = XK_slash;
  213138. else if (sym == XK_KP_Multiply)
  213139. keyCode = XK_asterisk;
  213140. else if (sym == XK_KP_Subtract)
  213141. keyCode = XK_hyphen;
  213142. else if (sym == XK_KP_Add)
  213143. keyCode = XK_plus;
  213144. else if (sym == XK_KP_Enter)
  213145. keyCode = XK_Return;
  213146. else if (sym == XK_KP_Decimal)
  213147. keyCode = numLock ? XK_period : XK_Delete;
  213148. else if (sym == XK_KP_0)
  213149. keyCode = numLock ? XK_0 : XK_Insert;
  213150. else if (sym == XK_KP_1)
  213151. keyCode = numLock ? XK_1 : XK_End;
  213152. else if (sym == XK_KP_2)
  213153. keyCode = numLock ? XK_2 : XK_Down;
  213154. else if (sym == XK_KP_3)
  213155. keyCode = numLock ? XK_3 : XK_Page_Down;
  213156. else if (sym == XK_KP_4)
  213157. keyCode = numLock ? XK_4 : XK_Left;
  213158. else if (sym == XK_KP_5)
  213159. keyCode = XK_5;
  213160. else if (sym == XK_KP_6)
  213161. keyCode = numLock ? XK_6 : XK_Right;
  213162. else if (sym == XK_KP_7)
  213163. keyCode = numLock ? XK_7 : XK_Home;
  213164. else if (sym == XK_KP_8)
  213165. keyCode = numLock ? XK_8 : XK_Up;
  213166. else if (sym == XK_KP_9)
  213167. keyCode = numLock ? XK_9 : XK_Page_Up;
  213168. switch (sym)
  213169. {
  213170. case XK_Left:
  213171. case XK_Right:
  213172. case XK_Up:
  213173. case XK_Down:
  213174. case XK_Page_Up:
  213175. case XK_Page_Down:
  213176. case XK_End:
  213177. case XK_Home:
  213178. case XK_Delete:
  213179. case XK_Insert:
  213180. keyPressed = true;
  213181. keyCode = (sym & 0xff) | extendedKeyModifier;
  213182. break;
  213183. case XK_Tab:
  213184. case XK_Return:
  213185. case XK_Escape:
  213186. case XK_BackSpace:
  213187. keyPressed = true;
  213188. keyCode &= 0xff;
  213189. break;
  213190. default:
  213191. {
  213192. if (sym >= XK_F1 && sym <= XK_F16)
  213193. {
  213194. keyPressed = true;
  213195. keyCode = (sym & 0xff) | extendedKeyModifier;
  213196. }
  213197. break;
  213198. }
  213199. }
  213200. }
  213201. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  213202. keyPressed = true;
  213203. if (oldMods != currentModifiers)
  213204. handleModifierKeysChange();
  213205. if (keyDownChange)
  213206. handleKeyUpOrDown();
  213207. if (keyPressed)
  213208. handleKeyPress (keyCode, unicodeChar);
  213209. break;
  213210. }
  213211. case KeyRelease:
  213212. {
  213213. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  213214. updateKeyStates (keyEvent->keycode, false);
  213215. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  213216. const int oldMods = currentModifiers;
  213217. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  213218. if (oldMods != currentModifiers)
  213219. handleModifierKeysChange();
  213220. if (keyDownChange)
  213221. handleKeyUpOrDown();
  213222. break;
  213223. }
  213224. case ButtonPress:
  213225. {
  213226. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  213227. bool buttonMsg = false;
  213228. bool wheelUpMsg = false;
  213229. bool wheelDownMsg = false;
  213230. const int map = pointerMap [buttonPressEvent->button - Button1];
  213231. if (map == LeftButton)
  213232. {
  213233. currentModifiers |= ModifierKeys::leftButtonModifier;
  213234. buttonMsg = true;
  213235. }
  213236. else if (map == RightButton)
  213237. {
  213238. currentModifiers |= ModifierKeys::rightButtonModifier;
  213239. buttonMsg = true;
  213240. }
  213241. else if (map == MiddleButton)
  213242. {
  213243. currentModifiers |= ModifierKeys::middleButtonModifier;
  213244. buttonMsg = true;
  213245. }
  213246. else if (map == WheelUp)
  213247. {
  213248. wheelUpMsg = true;
  213249. }
  213250. else if (map == WheelDown)
  213251. {
  213252. wheelDownMsg = true;
  213253. }
  213254. updateKeyModifiers (buttonPressEvent->state);
  213255. if (buttonMsg)
  213256. {
  213257. toFront (true);
  213258. handleMouseDown (buttonPressEvent->x, buttonPressEvent->y,
  213259. getEventTime (buttonPressEvent->time));
  213260. }
  213261. else if (wheelUpMsg || wheelDownMsg)
  213262. {
  213263. handleMouseWheel (0, wheelDownMsg ? -84 : 84,
  213264. getEventTime (buttonPressEvent->time));
  213265. }
  213266. lastMousePosX = lastMousePosY = 0x100000;
  213267. break;
  213268. }
  213269. case ButtonRelease:
  213270. {
  213271. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  213272. const int oldModifiers = currentModifiers;
  213273. const int map = pointerMap [buttonRelEvent->button - Button1];
  213274. if (map == LeftButton)
  213275. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  213276. else if (map == RightButton)
  213277. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  213278. else if (map == MiddleButton)
  213279. currentModifiers &= ~ModifierKeys::middleButtonModifier;
  213280. updateKeyModifiers (buttonRelEvent->state);
  213281. handleMouseUp (oldModifiers,
  213282. buttonRelEvent->x, buttonRelEvent->y,
  213283. getEventTime (buttonRelEvent->time));
  213284. lastMousePosX = lastMousePosY = 0x100000;
  213285. break;
  213286. }
  213287. case MotionNotify:
  213288. {
  213289. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  213290. updateKeyModifiers (movedEvent->state);
  213291. int x, y, mouseMods;
  213292. getMousePos (x, y, mouseMods);
  213293. if (lastMousePosX != x || lastMousePosY != y)
  213294. {
  213295. lastMousePosX = x;
  213296. lastMousePosY = y;
  213297. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  213298. {
  213299. Window wRoot = 0, wParent = 0;
  213300. Window* wChild = 0;
  213301. unsigned int numChildren;
  213302. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  213303. if (wParent != 0
  213304. && wParent != windowH
  213305. && wParent != wRoot)
  213306. {
  213307. parentWindow = wParent;
  213308. updateBounds();
  213309. x -= getScreenX();
  213310. y -= getScreenY();
  213311. }
  213312. else
  213313. {
  213314. parentWindow = 0;
  213315. x -= getScreenX();
  213316. y -= getScreenY();
  213317. }
  213318. }
  213319. else
  213320. {
  213321. x -= getScreenX();
  213322. y -= getScreenY();
  213323. }
  213324. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0)
  213325. handleMouseMove (x, y, getEventTime (movedEvent->time));
  213326. else
  213327. handleMouseDrag (x, y, getEventTime (movedEvent->time));
  213328. }
  213329. break;
  213330. }
  213331. case EnterNotify:
  213332. {
  213333. lastMousePosX = lastMousePosY = 0x100000;
  213334. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  213335. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  213336. && ! entered)
  213337. {
  213338. updateKeyModifiers (enterEvent->state);
  213339. handleMouseEnter (enterEvent->x, enterEvent->y, getEventTime (enterEvent->time));
  213340. entered = true;
  213341. }
  213342. break;
  213343. }
  213344. case LeaveNotify:
  213345. {
  213346. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  213347. // Suppress the normal leave if we've got a pointer grab, or if
  213348. // it's a bogus one caused by clicking a mouse button when running
  213349. // in a Window manager
  213350. if (((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  213351. && leaveEvent->mode == NotifyNormal)
  213352. || leaveEvent->mode == NotifyUngrab)
  213353. {
  213354. updateKeyModifiers (leaveEvent->state);
  213355. handleMouseExit (leaveEvent->x, leaveEvent->y, getEventTime (leaveEvent->time));
  213356. entered = false;
  213357. }
  213358. break;
  213359. }
  213360. case FocusIn:
  213361. {
  213362. isActiveApplication = true;
  213363. if (isFocused())
  213364. handleFocusGain();
  213365. break;
  213366. }
  213367. case FocusOut:
  213368. {
  213369. isActiveApplication = false;
  213370. if (! isFocused())
  213371. handleFocusLoss();
  213372. break;
  213373. }
  213374. case Expose:
  213375. {
  213376. // Batch together all pending expose events
  213377. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  213378. XEvent nextEvent;
  213379. if (exposeEvent->window != windowH)
  213380. {
  213381. Window child;
  213382. XTranslateCoordinates (display, exposeEvent->window, windowH,
  213383. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  213384. &child);
  213385. }
  213386. repaint (exposeEvent->x, exposeEvent->y,
  213387. exposeEvent->width, exposeEvent->height);
  213388. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  213389. {
  213390. XPeekEvent (display, (XEvent*) &nextEvent);
  213391. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  213392. break;
  213393. XNextEvent (display, (XEvent*) &nextEvent);
  213394. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  213395. repaint (nextExposeEvent->x, nextExposeEvent->y,
  213396. nextExposeEvent->width, nextExposeEvent->height);
  213397. }
  213398. break;
  213399. }
  213400. case CirculateNotify:
  213401. case CreateNotify:
  213402. case DestroyNotify:
  213403. // Think we can ignore these
  213404. break;
  213405. case ConfigureNotify:
  213406. {
  213407. updateBounds();
  213408. updateBorderSize();
  213409. handleMovedOrResized();
  213410. // if the native title bar is dragged, need to tell any active menus, etc.
  213411. if ((styleFlags & windowHasTitleBar) != 0
  213412. && component->isCurrentlyBlockedByAnotherModalComponent())
  213413. {
  213414. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  213415. if (currentModalComp != 0)
  213416. currentModalComp->inputAttemptWhenModal();
  213417. }
  213418. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  213419. if (confEvent->window == windowH
  213420. && confEvent->above != 0
  213421. && isFrontWindow())
  213422. {
  213423. handleBroughtToFront();
  213424. }
  213425. break;
  213426. }
  213427. case ReparentNotify:
  213428. case GravityNotify:
  213429. {
  213430. parentWindow = 0;
  213431. Window wRoot = 0;
  213432. Window* wChild = 0;
  213433. unsigned int numChildren;
  213434. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  213435. if (parentWindow == windowH || parentWindow == wRoot)
  213436. parentWindow = 0;
  213437. updateBounds();
  213438. updateBorderSize();
  213439. handleMovedOrResized();
  213440. break;
  213441. }
  213442. case MapNotify:
  213443. mapped = true;
  213444. handleBroughtToFront();
  213445. break;
  213446. case UnmapNotify:
  213447. mapped = false;
  213448. break;
  213449. case MappingNotify:
  213450. {
  213451. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  213452. if (mappingEvent->request != MappingPointer)
  213453. {
  213454. // Deal with modifier/keyboard mapping
  213455. XRefreshKeyboardMapping (mappingEvent);
  213456. getModifierMapping();
  213457. }
  213458. break;
  213459. }
  213460. case ClientMessage:
  213461. {
  213462. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  213463. if (clientMsg->message_type == wm_Protocols && clientMsg->format == 32)
  213464. {
  213465. const Atom atom = (Atom) clientMsg->data.l[0];
  213466. if (atom == wm_ProtocolList [TAKE_FOCUS])
  213467. {
  213468. XWindowAttributes atts;
  213469. if (clientMsg->window != 0
  213470. && XGetWindowAttributes (display, clientMsg->window, &atts))
  213471. {
  213472. if (atts.map_state == IsViewable)
  213473. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  213474. }
  213475. }
  213476. else if (atom == wm_ProtocolList [DELETE_WINDOW])
  213477. {
  213478. handleUserClosingWindow();
  213479. }
  213480. }
  213481. else if (clientMsg->message_type == XA_XdndEnter)
  213482. {
  213483. handleDragAndDropEnter (clientMsg);
  213484. }
  213485. else if (clientMsg->message_type == XA_XdndLeave)
  213486. {
  213487. resetDragAndDrop();
  213488. }
  213489. else if (clientMsg->message_type == XA_XdndPosition)
  213490. {
  213491. handleDragAndDropPosition (clientMsg);
  213492. }
  213493. else if (clientMsg->message_type == XA_XdndDrop)
  213494. {
  213495. handleDragAndDropDrop (clientMsg);
  213496. }
  213497. else if (clientMsg->message_type == XA_XdndStatus)
  213498. {
  213499. handleDragAndDropStatus (clientMsg);
  213500. }
  213501. else if (clientMsg->message_type == XA_XdndFinished)
  213502. {
  213503. resetDragAndDrop();
  213504. }
  213505. break;
  213506. }
  213507. case SelectionNotify:
  213508. handleDragAndDropSelection (event);
  213509. break;
  213510. case SelectionClear:
  213511. case SelectionRequest:
  213512. break;
  213513. default:
  213514. break;
  213515. }
  213516. }
  213517. void showMouseCursor (Cursor cursor) throw()
  213518. {
  213519. XDefineCursor (display, windowH, cursor);
  213520. }
  213521. void setTaskBarIcon (const Image& image)
  213522. {
  213523. deleteTaskBarIcon();
  213524. taskbarImage = image.createCopy();
  213525. Screen* const screen = XDefaultScreenOfDisplay (display);
  213526. const int screenNumber = XScreenNumberOfScreen (screen);
  213527. char screenAtom[32];
  213528. snprintf (screenAtom, sizeof (screenAtom), "_NET_SYSTEM_TRAY_S%d", screenNumber);
  213529. Atom selectionAtom = XInternAtom (display, screenAtom, false);
  213530. XGrabServer (display);
  213531. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  213532. if (managerWin != None)
  213533. XSelectInput (display, managerWin, StructureNotifyMask);
  213534. XUngrabServer (display);
  213535. XFlush (display);
  213536. if (managerWin != None)
  213537. {
  213538. XEvent ev;
  213539. zerostruct (ev);
  213540. ev.xclient.type = ClientMessage;
  213541. ev.xclient.window = managerWin;
  213542. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  213543. ev.xclient.format = 32;
  213544. ev.xclient.data.l[0] = CurrentTime;
  213545. ev.xclient.data.l[1] = SYSTEM_TRAY_REQUEST_DOCK;
  213546. ev.xclient.data.l[2] = windowH;
  213547. ev.xclient.data.l[3] = 0;
  213548. ev.xclient.data.l[4] = 0;
  213549. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  213550. XSync (display, False);
  213551. }
  213552. // For older KDE's ...
  213553. long atomData = 1;
  213554. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  213555. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  213556. // For more recent KDE's...
  213557. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  213558. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  213559. }
  213560. void deleteTaskBarIcon()
  213561. {
  213562. deleteAndZero (taskbarImage);
  213563. }
  213564. const Image* getTaskbarIcon() const throw() { return taskbarImage; }
  213565. juce_UseDebuggingNewOperator
  213566. bool dontRepaint;
  213567. private:
  213568. class LinuxRepaintManager : public Timer
  213569. {
  213570. public:
  213571. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  213572. : peer (peer_),
  213573. image (0),
  213574. lastTimeImageUsed (0)
  213575. {
  213576. #if JUCE_USE_XSHM
  213577. useARGBImagesForRendering = isShmAvailable();
  213578. if (useARGBImagesForRendering)
  213579. {
  213580. XShmSegmentInfo segmentinfo;
  213581. XImage* const testImage
  213582. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  213583. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  213584. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  213585. XDestroyImage (testImage);
  213586. }
  213587. #endif
  213588. }
  213589. ~LinuxRepaintManager()
  213590. {
  213591. delete image;
  213592. }
  213593. void timerCallback()
  213594. {
  213595. if (! regionsNeedingRepaint.isEmpty())
  213596. {
  213597. stopTimer();
  213598. performAnyPendingRepaintsNow();
  213599. }
  213600. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  213601. {
  213602. stopTimer();
  213603. deleteAndZero (image);
  213604. }
  213605. }
  213606. void repaint (int x, int y, int w, int h)
  213607. {
  213608. if (! isTimerRunning())
  213609. startTimer (repaintTimerPeriod);
  213610. regionsNeedingRepaint.add (x, y, w, h);
  213611. }
  213612. void performAnyPendingRepaintsNow()
  213613. {
  213614. peer->clearMaskedRegion();
  213615. const Rectangle totalArea (regionsNeedingRepaint.getBounds());
  213616. if (! totalArea.isEmpty())
  213617. {
  213618. if (image == 0 || image->getWidth() < totalArea.getWidth()
  213619. || image->getHeight() < totalArea.getHeight())
  213620. {
  213621. delete image;
  213622. #if JUCE_USE_XSHM
  213623. image = new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  213624. : Image::RGB,
  213625. #else
  213626. image = new XBitmapImage (Image::RGB,
  213627. #endif
  213628. (totalArea.getWidth() + 31) & ~31,
  213629. (totalArea.getHeight() + 31) & ~31,
  213630. false,
  213631. peer->depthIs16Bit);
  213632. }
  213633. startTimer (repaintTimerPeriod);
  213634. LowLevelGraphicsSoftwareRenderer context (*image);
  213635. context.setOrigin (-totalArea.getX(), -totalArea.getY());
  213636. if (context.reduceClipRegion (regionsNeedingRepaint))
  213637. peer->handlePaint (context);
  213638. if (! peer->maskedRegion.isEmpty())
  213639. regionsNeedingRepaint.subtract (peer->maskedRegion);
  213640. for (RectangleList::Iterator i (regionsNeedingRepaint); i.next();)
  213641. {
  213642. const Rectangle& r = *i.getRectangle();
  213643. image->blitToWindow (peer->windowH,
  213644. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  213645. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  213646. }
  213647. }
  213648. regionsNeedingRepaint.clear();
  213649. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  213650. startTimer (repaintTimerPeriod);
  213651. }
  213652. private:
  213653. LinuxComponentPeer* const peer;
  213654. XBitmapImage* image;
  213655. uint32 lastTimeImageUsed;
  213656. RectangleList regionsNeedingRepaint;
  213657. #if JUCE_USE_XSHM
  213658. bool useARGBImagesForRendering;
  213659. #endif
  213660. LinuxRepaintManager (const LinuxRepaintManager&);
  213661. const LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  213662. };
  213663. LinuxRepaintManager* repainter;
  213664. friend class LinuxRepaintManager;
  213665. Window windowH, parentWindow;
  213666. int wx, wy, ww, wh;
  213667. Image* taskbarImage;
  213668. bool fullScreen, entered, mapped, depthIs16Bit;
  213669. BorderSize windowBorder;
  213670. void removeWindowDecorations (Window wndH)
  213671. {
  213672. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  213673. if (hints != None)
  213674. {
  213675. typedef struct
  213676. {
  213677. unsigned long flags;
  213678. unsigned long functions;
  213679. unsigned long decorations;
  213680. long input_mode;
  213681. unsigned long status;
  213682. } MotifWmHints;
  213683. MotifWmHints motifHints;
  213684. zerostruct (motifHints);
  213685. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  213686. motifHints.decorations = 0;
  213687. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  213688. (unsigned char*) &motifHints, 4);
  213689. }
  213690. hints = XInternAtom (display, "_WIN_HINTS", True);
  213691. if (hints != None)
  213692. {
  213693. long gnomeHints = 0;
  213694. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  213695. (unsigned char*) &gnomeHints, 1);
  213696. }
  213697. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  213698. if (hints != None)
  213699. {
  213700. long kwmHints = 2; /*KDE_tinyDecoration*/
  213701. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  213702. (unsigned char*) &kwmHints, 1);
  213703. }
  213704. hints = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  213705. if (hints != None)
  213706. {
  213707. long netHints [2];
  213708. netHints[0] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  213709. if ((styleFlags & windowIsTemporary) != 0)
  213710. netHints[1] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_MENU", True);
  213711. else
  213712. netHints[1] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  213713. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  213714. (unsigned char*) &netHints, 2);
  213715. }
  213716. }
  213717. void addWindowButtons (Window wndH)
  213718. {
  213719. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  213720. if (hints != None)
  213721. {
  213722. typedef struct
  213723. {
  213724. unsigned long flags;
  213725. unsigned long functions;
  213726. unsigned long decorations;
  213727. long input_mode;
  213728. unsigned long status;
  213729. } MotifWmHints;
  213730. MotifWmHints motifHints;
  213731. zerostruct (motifHints);
  213732. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  213733. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  213734. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  213735. if ((styleFlags & windowHasCloseButton) != 0)
  213736. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  213737. if ((styleFlags & windowHasMinimiseButton) != 0)
  213738. {
  213739. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  213740. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  213741. }
  213742. if ((styleFlags & windowHasMaximiseButton) != 0)
  213743. {
  213744. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  213745. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  213746. }
  213747. if ((styleFlags & windowIsResizable) != 0)
  213748. {
  213749. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  213750. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  213751. }
  213752. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  213753. }
  213754. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  213755. if (hints != None)
  213756. {
  213757. long netHints [6];
  213758. int num = 0;
  213759. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", (styleFlags & windowIsResizable) ? True : False);
  213760. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", (styleFlags & windowHasMaximiseButton) ? True : False);
  213761. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", (styleFlags & windowHasMinimiseButton) ? True : False);
  213762. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", (styleFlags & windowHasCloseButton) ? True : False);
  213763. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  213764. (unsigned char*) &netHints, num);
  213765. }
  213766. }
  213767. void createWindow()
  213768. {
  213769. static bool atomsInitialised = false;
  213770. if (! atomsInitialised)
  213771. {
  213772. atomsInitialised = true;
  213773. wm_Protocols = XInternAtom (display, "WM_PROTOCOLS", 1);
  213774. wm_ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", 1);
  213775. wm_ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", 1);
  213776. wm_ChangeState = XInternAtom (display, "WM_CHANGE_STATE", 1);
  213777. wm_State = XInternAtom (display, "WM_STATE", 1);
  213778. wm_ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  213779. XA_XdndAware = XInternAtom (display, "XdndAware", 0);
  213780. XA_XdndEnter = XInternAtom (display, "XdndEnter", 0);
  213781. XA_XdndLeave = XInternAtom (display, "XdndLeave", 0);
  213782. XA_XdndPosition = XInternAtom (display, "XdndPosition", 0);
  213783. XA_XdndStatus = XInternAtom (display, "XdndStatus", 0);
  213784. XA_XdndDrop = XInternAtom (display, "XdndDrop", 0);
  213785. XA_XdndFinished = XInternAtom (display, "XdndFinished", 0);
  213786. XA_XdndSelection = XInternAtom (display, "XdndSelection", 0);
  213787. XA_XdndProxy = XInternAtom (display, "XdndProxy", 0);
  213788. XA_XdndTypeList = XInternAtom (display, "XdndTypeList", 0);
  213789. XA_XdndActionList = XInternAtom (display, "XdndActionList", 0);
  213790. XA_XdndActionCopy = XInternAtom (display, "XdndActionCopy", 0);
  213791. XA_XdndActionMove = XInternAtom (display, "XdndActionMove", 0);
  213792. XA_XdndActionLink = XInternAtom (display, "XdndActionLink", 0);
  213793. XA_XdndActionAsk = XInternAtom (display, "XdndActionAsk", 0);
  213794. XA_XdndActionPrivate = XInternAtom (display, "XdndActionPrivate", 0);
  213795. XA_XdndActionDescription = XInternAtom (display, "XdndActionDescription", 0);
  213796. XA_JXSelectionWindowProperty = XInternAtom (display, "JXSelectionWindowProperty", 0);
  213797. XA_MimeTextPlain = XInternAtom (display, "text/plain", 0);
  213798. XA_MimeTextUriList = XInternAtom (display, "text/uri-list", 0);
  213799. XA_MimeRootDrop = XInternAtom (display, "application/x-rootwindow-drop", 0);
  213800. }
  213801. resetDragAndDrop();
  213802. XA_OtherMime = XA_MimeTextPlain; // xxx why??
  213803. allowedMimeTypeAtoms [0] = XA_MimeTextPlain;
  213804. allowedMimeTypeAtoms [1] = XA_OtherMime;
  213805. allowedMimeTypeAtoms [2] = XA_MimeTextUriList;
  213806. allowedActions [0] = XA_XdndActionMove;
  213807. allowedActions [1] = XA_XdndActionCopy;
  213808. allowedActions [2] = XA_XdndActionLink;
  213809. allowedActions [3] = XA_XdndActionAsk;
  213810. allowedActions [4] = XA_XdndActionPrivate;
  213811. // Get defaults for various properties
  213812. const int screen = DefaultScreen (display);
  213813. Window root = RootWindow (display, screen);
  213814. // Attempt to create a 24-bit window on the default screen. If this is not
  213815. // possible then exit
  213816. XVisualInfo desiredVisual;
  213817. desiredVisual.screen = screen;
  213818. desiredVisual.depth = 24;
  213819. depthIs16Bit = false;
  213820. int numVisuals;
  213821. XVisualInfo* visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  213822. &desiredVisual, &numVisuals);
  213823. if (numVisuals < 1 || visuals == 0)
  213824. {
  213825. XFree (visuals);
  213826. desiredVisual.depth = 16;
  213827. visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  213828. &desiredVisual, &numVisuals);
  213829. if (numVisuals < 1 || visuals == 0)
  213830. {
  213831. Logger::outputDebugString ("ERROR: System doesn't support 24 or 16 bit RGB display.\n");
  213832. Process::terminate();
  213833. }
  213834. depthIs16Bit = true;
  213835. }
  213836. XFree (visuals);
  213837. // Set up the window attributes
  213838. XSetWindowAttributes swa;
  213839. swa.border_pixel = 0;
  213840. swa.background_pixmap = None;
  213841. swa.colormap = DefaultColormap (display, screen);
  213842. swa.override_redirect = getComponent()->isAlwaysOnTop() ? True : False;
  213843. swa.event_mask = eventMask;
  213844. Window wndH = XCreateWindow (display, root,
  213845. 0, 0, 1, 1,
  213846. 0, 0, InputOutput, (Visual*) CopyFromParent,
  213847. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  213848. &swa);
  213849. XGrabButton (display, AnyButton, AnyModifier, wndH, False,
  213850. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  213851. GrabModeAsync, GrabModeAsync, None, None);
  213852. // Set the window context to identify the window handle object
  213853. if (XSaveContext (display, (XID) wndH, improbableNumber, (XPointer) this))
  213854. {
  213855. // Failed
  213856. jassertfalse
  213857. Logger::outputDebugString ("Failed to create context information for window.\n");
  213858. XDestroyWindow (display, wndH);
  213859. wndH = 0;
  213860. }
  213861. // Set window manager hints
  213862. XWMHints* wmHints = XAllocWMHints();
  213863. wmHints->flags = InputHint | StateHint;
  213864. wmHints->input = True; // Locally active input model
  213865. wmHints->initial_state = NormalState;
  213866. XSetWMHints (display, wndH, wmHints);
  213867. XFree (wmHints);
  213868. if ((styleFlags & windowIsSemiTransparent) != 0)
  213869. {
  213870. //xxx
  213871. }
  213872. if ((styleFlags & windowAppearsOnTaskbar) != 0)
  213873. {
  213874. //xxx
  213875. }
  213876. //XSetTransientForHint (display, wndH, RootWindow (display, DefaultScreen (display)));
  213877. if ((styleFlags & windowHasTitleBar) == 0)
  213878. removeWindowDecorations (wndH);
  213879. else
  213880. addWindowButtons (wndH);
  213881. // Set window manager protocols
  213882. XChangeProperty (display, wndH, wm_Protocols, XA_ATOM, 32, PropModeReplace,
  213883. (unsigned char*) wm_ProtocolList, 2);
  213884. // Set drag and drop flags
  213885. XChangeProperty (display, wndH, XA_XdndTypeList, XA_ATOM, 32, PropModeReplace,
  213886. (const unsigned char*) allowedMimeTypeAtoms, numElementsInArray (allowedMimeTypeAtoms));
  213887. XChangeProperty (display, wndH, XA_XdndActionList, XA_ATOM, 32, PropModeReplace,
  213888. (const unsigned char*) allowedActions, numElementsInArray (allowedActions));
  213889. XChangeProperty (display, wndH, XA_XdndActionDescription, XA_STRING, 8, PropModeReplace,
  213890. (const unsigned char*) "", 0);
  213891. unsigned long dndVersion = ourDndVersion;
  213892. XChangeProperty (display, wndH, XA_XdndAware, XA_ATOM, 32, PropModeReplace,
  213893. (const unsigned char*) &dndVersion, 1);
  213894. // Set window name
  213895. setWindowTitle (wndH, getComponent()->getName());
  213896. // Initialise the pointer and keyboard mapping
  213897. // This is not the same as the logical pointer mapping the X server uses:
  213898. // we don't mess with this.
  213899. static bool mappingInitialised = false;
  213900. if (! mappingInitialised)
  213901. {
  213902. mappingInitialised = true;
  213903. const int numButtons = XGetPointerMapping (display, 0, 0);
  213904. if (numButtons == 2)
  213905. {
  213906. pointerMap[0] = LeftButton;
  213907. pointerMap[1] = RightButton;
  213908. pointerMap[2] = pointerMap[3] = pointerMap[4] = NoButton;
  213909. }
  213910. else if (numButtons >= 3)
  213911. {
  213912. pointerMap[0] = LeftButton;
  213913. pointerMap[1] = MiddleButton;
  213914. pointerMap[2] = RightButton;
  213915. if (numButtons >= 5)
  213916. {
  213917. pointerMap[3] = WheelUp;
  213918. pointerMap[4] = WheelDown;
  213919. }
  213920. }
  213921. getModifierMapping();
  213922. }
  213923. windowH = wndH;
  213924. }
  213925. void destroyWindow()
  213926. {
  213927. XPointer handlePointer;
  213928. if (! XFindContext (display, (XID) windowH, improbableNumber, &handlePointer))
  213929. XDeleteContext (display, (XID) windowH, improbableNumber);
  213930. XDestroyWindow (display, windowH);
  213931. // Wait for it to complete and then remove any events for this
  213932. // window from the event queue.
  213933. XSync (display, false);
  213934. XEvent event;
  213935. while (XCheckWindowEvent (display, windowH, eventMask, &event) == True)
  213936. {}
  213937. }
  213938. static int64 getEventTime (::Time t) throw()
  213939. {
  213940. static int64 eventTimeOffset = 0x12345678;
  213941. const int64 thisMessageTime = t;
  213942. if (eventTimeOffset == 0x12345678)
  213943. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  213944. return eventTimeOffset + thisMessageTime;
  213945. }
  213946. static void setWindowTitle (Window xwin, const char* const title) throw()
  213947. {
  213948. XTextProperty nameProperty;
  213949. char* strings[] = { (char*) title };
  213950. if (XStringListToTextProperty (strings, 1, &nameProperty))
  213951. {
  213952. XSetWMName (display, xwin, &nameProperty);
  213953. XSetWMIconName (display, xwin, &nameProperty);
  213954. XFree (nameProperty.value);
  213955. }
  213956. }
  213957. void updateBorderSize()
  213958. {
  213959. if ((styleFlags & windowHasTitleBar) == 0)
  213960. {
  213961. windowBorder = BorderSize (0);
  213962. }
  213963. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  213964. {
  213965. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  213966. if (hints != None)
  213967. {
  213968. unsigned char* data = 0;
  213969. unsigned long nitems, bytesLeft;
  213970. Atom actualType;
  213971. int actualFormat;
  213972. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  213973. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  213974. &data) == Success)
  213975. {
  213976. const unsigned long* const sizes = (const unsigned long*) data;
  213977. if (actualFormat == 32)
  213978. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  213979. (int) sizes[3], (int) sizes[1]);
  213980. XFree (data);
  213981. }
  213982. }
  213983. }
  213984. }
  213985. void updateBounds()
  213986. {
  213987. jassert (windowH != 0);
  213988. if (windowH != 0)
  213989. {
  213990. Window root, child;
  213991. unsigned int bw, depth;
  213992. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  213993. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  213994. &bw, &depth))
  213995. {
  213996. wx = wy = ww = wh = 0;
  213997. }
  213998. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  213999. {
  214000. wx = wy = 0;
  214001. }
  214002. }
  214003. }
  214004. void resetDragAndDrop()
  214005. {
  214006. dragAndDropFiles.clear();
  214007. lastDropX = lastDropY = -1;
  214008. dragAndDropCurrentMimeType = 0;
  214009. dragAndDropSourceWindow = 0;
  214010. srcMimeTypeAtomList.clear();
  214011. }
  214012. void sendDragAndDropMessage (XClientMessageEvent& msg)
  214013. {
  214014. msg.type = ClientMessage;
  214015. msg.display = display;
  214016. msg.window = dragAndDropSourceWindow;
  214017. msg.format = 32;
  214018. msg.data.l[0] = windowH;
  214019. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  214020. }
  214021. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  214022. {
  214023. XClientMessageEvent msg;
  214024. zerostruct (msg);
  214025. msg.message_type = XA_XdndStatus;
  214026. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  214027. msg.data.l[4] = dropAction;
  214028. sendDragAndDropMessage (msg);
  214029. }
  214030. void sendDragAndDropLeave()
  214031. {
  214032. XClientMessageEvent msg;
  214033. zerostruct (msg);
  214034. msg.message_type = XA_XdndLeave;
  214035. sendDragAndDropMessage (msg);
  214036. }
  214037. void sendDragAndDropFinish()
  214038. {
  214039. XClientMessageEvent msg;
  214040. zerostruct (msg);
  214041. msg.message_type = XA_XdndFinished;
  214042. sendDragAndDropMessage (msg);
  214043. }
  214044. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  214045. {
  214046. if ((clientMsg->data.l[1] & 1) == 0)
  214047. {
  214048. sendDragAndDropLeave();
  214049. if (dragAndDropFiles.size() > 0)
  214050. handleFileDragExit (dragAndDropFiles);
  214051. dragAndDropFiles.clear();
  214052. }
  214053. }
  214054. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  214055. {
  214056. if (dragAndDropSourceWindow == 0)
  214057. return;
  214058. dragAndDropSourceWindow = clientMsg->data.l[0];
  214059. const int dropX = ((int) clientMsg->data.l[2] >> 16) - getScreenX();
  214060. const int dropY = ((int) clientMsg->data.l[2] & 0xffff) - getScreenY();
  214061. if (lastDropX != dropX || lastDropY != dropY)
  214062. {
  214063. lastDropX = dropX;
  214064. lastDropY = dropY;
  214065. dragAndDropTimestamp = clientMsg->data.l[3];
  214066. Atom targetAction = XA_XdndActionCopy;
  214067. for (int i = numElementsInArray (allowedActions); --i >= 0;)
  214068. {
  214069. if ((Atom) clientMsg->data.l[4] == allowedActions[i])
  214070. {
  214071. targetAction = allowedActions[i];
  214072. break;
  214073. }
  214074. }
  214075. sendDragAndDropStatus (true, targetAction);
  214076. if (dragAndDropFiles.size() == 0)
  214077. updateDraggedFileList (clientMsg);
  214078. if (dragAndDropFiles.size() > 0)
  214079. handleFileDragMove (dragAndDropFiles, dropX, dropY);
  214080. }
  214081. }
  214082. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  214083. {
  214084. if (dragAndDropFiles.size() == 0)
  214085. updateDraggedFileList (clientMsg);
  214086. const StringArray files (dragAndDropFiles);
  214087. const int lastX = lastDropX, lastY = lastDropY;
  214088. sendDragAndDropFinish();
  214089. resetDragAndDrop();
  214090. if (files.size() > 0)
  214091. handleFileDragDrop (files, lastX, lastY);
  214092. }
  214093. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  214094. {
  214095. dragAndDropFiles.clear();
  214096. srcMimeTypeAtomList.clear();
  214097. dragAndDropCurrentMimeType = 0;
  214098. const int dndCurrentVersion = (int) (clientMsg->data.l[1] & 0xff000000) >> 24;
  214099. if (dndCurrentVersion < 3 || dndCurrentVersion > ourDndVersion)
  214100. {
  214101. dragAndDropSourceWindow = 0;
  214102. return;
  214103. }
  214104. dragAndDropSourceWindow = clientMsg->data.l[0];
  214105. if ((clientMsg->data.l[1] & 1) != 0)
  214106. {
  214107. Atom actual;
  214108. int format;
  214109. unsigned long count = 0, remaining = 0;
  214110. unsigned char* data = 0;
  214111. XGetWindowProperty (display, dragAndDropSourceWindow, XA_XdndTypeList,
  214112. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  214113. &count, &remaining, &data);
  214114. if (data != 0)
  214115. {
  214116. if (actual == XA_ATOM && format == 32 && count != 0)
  214117. {
  214118. const unsigned long* const types = (const unsigned long*) data;
  214119. for (unsigned int i = 0; i < count; ++i)
  214120. if (types[i] != None)
  214121. srcMimeTypeAtomList.add (types[i]);
  214122. }
  214123. XFree (data);
  214124. }
  214125. }
  214126. if (srcMimeTypeAtomList.size() == 0)
  214127. {
  214128. for (int i = 2; i < 5; ++i)
  214129. if (clientMsg->data.l[i] != None)
  214130. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  214131. if (srcMimeTypeAtomList.size() == 0)
  214132. {
  214133. dragAndDropSourceWindow = 0;
  214134. return;
  214135. }
  214136. }
  214137. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  214138. for (int j = 0; j < numElementsInArray (allowedMimeTypeAtoms); ++j)
  214139. if (srcMimeTypeAtomList[i] == allowedMimeTypeAtoms[j])
  214140. dragAndDropCurrentMimeType = allowedMimeTypeAtoms[j];
  214141. handleDragAndDropPosition (clientMsg);
  214142. }
  214143. void handleDragAndDropSelection (const XEvent* const evt)
  214144. {
  214145. dragAndDropFiles.clear();
  214146. if (evt->xselection.property != 0)
  214147. {
  214148. StringArray lines;
  214149. {
  214150. MemoryBlock dropData;
  214151. for (;;)
  214152. {
  214153. Atom actual;
  214154. uint8* data = 0;
  214155. unsigned long count = 0, remaining = 0;
  214156. int format = 0;
  214157. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  214158. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  214159. &format, &count, &remaining, &data) == Success)
  214160. {
  214161. dropData.append (data, count * format / 8);
  214162. XFree (data);
  214163. if (remaining == 0)
  214164. break;
  214165. }
  214166. else
  214167. {
  214168. XFree (data);
  214169. break;
  214170. }
  214171. }
  214172. lines.addLines (dropData.toString());
  214173. }
  214174. for (int i = 0; i < lines.size(); ++i)
  214175. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf (T("file://"), false, true)));
  214176. dragAndDropFiles.trim();
  214177. dragAndDropFiles.removeEmptyStrings();
  214178. }
  214179. }
  214180. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  214181. {
  214182. dragAndDropFiles.clear();
  214183. if (dragAndDropSourceWindow != None
  214184. && dragAndDropCurrentMimeType != 0)
  214185. {
  214186. dragAndDropTimestamp = clientMsg->data.l[2];
  214187. XConvertSelection (display,
  214188. XA_XdndSelection,
  214189. dragAndDropCurrentMimeType,
  214190. XA_JXSelectionWindowProperty,
  214191. windowH,
  214192. dragAndDropTimestamp);
  214193. }
  214194. }
  214195. StringArray dragAndDropFiles;
  214196. int dragAndDropTimestamp, lastDropX, lastDropY;
  214197. Atom XA_OtherMime, dragAndDropCurrentMimeType;
  214198. Window dragAndDropSourceWindow;
  214199. unsigned long allowedActions [5];
  214200. unsigned long allowedMimeTypeAtoms [3];
  214201. Array <Atom> srcMimeTypeAtomList;
  214202. };
  214203. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  214204. {
  214205. return new LinuxComponentPeer (this, styleFlags);
  214206. }
  214207. // (this callback is hooked up in the messaging code)
  214208. void juce_windowMessageReceive (XEvent* event)
  214209. {
  214210. if (event->xany.window != None)
  214211. {
  214212. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  214213. const MessageManagerLock messLock;
  214214. if (ComponentPeer::isValidPeer (peer))
  214215. peer->handleWindowMessage (event);
  214216. }
  214217. else
  214218. {
  214219. switch (event->xany.type)
  214220. {
  214221. case KeymapNotify:
  214222. {
  214223. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  214224. memcpy (keyStates, keymapEvent->key_vector, 32);
  214225. break;
  214226. }
  214227. default:
  214228. break;
  214229. }
  214230. }
  214231. }
  214232. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool /*clipToWorkArea*/) throw()
  214233. {
  214234. #if JUCE_USE_XINERAMA
  214235. int major_opcode, first_event, first_error;
  214236. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error)
  214237. && XineramaIsActive (display))
  214238. {
  214239. int numMonitors = 0;
  214240. XineramaScreenInfo* const screens = XineramaQueryScreens (display, &numMonitors);
  214241. if (screens != 0)
  214242. {
  214243. for (int i = numMonitors; --i >= 0;)
  214244. {
  214245. int index = screens[i].screen_number;
  214246. if (index >= 0)
  214247. {
  214248. while (monitorCoords.size() < index)
  214249. monitorCoords.add (Rectangle (0, 0, 0, 0));
  214250. monitorCoords.set (index, Rectangle (screens[i].x_org,
  214251. screens[i].y_org,
  214252. screens[i].width,
  214253. screens[i].height));
  214254. }
  214255. }
  214256. XFree (screens);
  214257. }
  214258. }
  214259. if (monitorCoords.size() == 0)
  214260. #endif
  214261. {
  214262. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  214263. if (hints != None)
  214264. {
  214265. const int numMonitors = ScreenCount (display);
  214266. for (int i = 0; i < numMonitors; ++i)
  214267. {
  214268. Window root = RootWindow (display, i);
  214269. unsigned long nitems, bytesLeft;
  214270. Atom actualType;
  214271. int actualFormat;
  214272. unsigned char* data = 0;
  214273. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  214274. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  214275. &data) == Success)
  214276. {
  214277. const long* const position = (const long*) data;
  214278. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  214279. monitorCoords.add (Rectangle (position[0], position[1],
  214280. position[2], position[3]));
  214281. XFree (data);
  214282. }
  214283. }
  214284. }
  214285. if (monitorCoords.size() == 0)
  214286. {
  214287. monitorCoords.add (Rectangle (0, 0,
  214288. DisplayWidth (display, DefaultScreen (display)),
  214289. DisplayHeight (display, DefaultScreen (display))));
  214290. }
  214291. }
  214292. }
  214293. bool Desktop::canUseSemiTransparentWindows() throw()
  214294. {
  214295. return false;
  214296. }
  214297. void Desktop::getMousePosition (int& x, int& y) throw()
  214298. {
  214299. int mouseMods;
  214300. getMousePos (x, y, mouseMods);
  214301. }
  214302. void Desktop::setMousePosition (int x, int y) throw()
  214303. {
  214304. Window root = RootWindow (display, DefaultScreen (display));
  214305. XWarpPointer (display, None, root, 0, 0, 0, 0, x, y);
  214306. }
  214307. static bool screenSaverAllowed = true;
  214308. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  214309. {
  214310. if (screenSaverAllowed != isEnabled)
  214311. {
  214312. screenSaverAllowed = isEnabled;
  214313. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  214314. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  214315. if (xScreenSaverSuspend == 0)
  214316. {
  214317. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  214318. if (h != 0)
  214319. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  214320. }
  214321. if (xScreenSaverSuspend != 0)
  214322. xScreenSaverSuspend (display, ! isEnabled);
  214323. }
  214324. }
  214325. bool Desktop::isScreenSaverEnabled() throw()
  214326. {
  214327. return screenSaverAllowed;
  214328. }
  214329. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  214330. {
  214331. Window root = RootWindow (display, DefaultScreen (display));
  214332. const unsigned int imageW = image.getWidth();
  214333. const unsigned int imageH = image.getHeight();
  214334. unsigned int cursorW, cursorH;
  214335. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  214336. return 0;
  214337. Image im (Image::ARGB, cursorW, cursorH, true);
  214338. Graphics g (im);
  214339. if (imageW > cursorW || imageH > cursorH)
  214340. {
  214341. hotspotX = (hotspotX * cursorW) / imageW;
  214342. hotspotY = (hotspotY * cursorH) / imageH;
  214343. g.drawImageWithin (&image, 0, 0, imageW, imageH,
  214344. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  214345. false);
  214346. }
  214347. else
  214348. {
  214349. g.drawImageAt (&image, 0, 0);
  214350. }
  214351. const int stride = (cursorW + 7) >> 3;
  214352. uint8* const maskPlane = (uint8*) juce_calloc (stride * cursorH);
  214353. uint8* const sourcePlane = (uint8*) juce_calloc (stride * cursorH);
  214354. bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  214355. for (int y = cursorH; --y >= 0;)
  214356. {
  214357. for (int x = cursorW; --x >= 0;)
  214358. {
  214359. const uint8 mask = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  214360. const int offset = y * stride + (x >> 3);
  214361. const Colour c (im.getPixelAt (x, y));
  214362. if (c.getAlpha() >= 128)
  214363. maskPlane[offset] |= mask;
  214364. if (c.getBrightness() >= 0.5f)
  214365. sourcePlane[offset] |= mask;
  214366. }
  214367. }
  214368. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, (char*) sourcePlane, cursorW, cursorH, 0xffff, 0, 1);
  214369. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, (char*) maskPlane, cursorW, cursorH, 0xffff, 0, 1);
  214370. juce_free (maskPlane);
  214371. juce_free (sourcePlane);
  214372. XColor white, black;
  214373. black.red = black.green = black.blue = 0;
  214374. white.red = white.green = white.blue = 0xffff;
  214375. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  214376. XFreePixmap (display, sourcePixmap);
  214377. XFreePixmap (display, maskPixmap);
  214378. return result;
  214379. }
  214380. void juce_deleteMouseCursor (void* const cursorHandle, const bool) throw()
  214381. {
  214382. if (cursorHandle != None)
  214383. XFreeCursor (display, (Cursor) cursorHandle);
  214384. }
  214385. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  214386. {
  214387. unsigned int shape;
  214388. switch (type)
  214389. {
  214390. case MouseCursor::NoCursor:
  214391. {
  214392. const Image im (Image::ARGB, 16, 16, true);
  214393. return juce_createMouseCursorFromImage (im, 0, 0);
  214394. }
  214395. case MouseCursor::NormalCursor:
  214396. return (void*) None; // Use parent cursor
  214397. case MouseCursor::DraggingHandCursor:
  214398. {
  214399. static unsigned char dragHandData[] = {71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  214400. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  214401. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  214402. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217,
  214403. 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  214404. const int dragHandDataSize = 99;
  214405. Image* const im = ImageFileFormat::loadFrom ((const char*) dragHandData, dragHandDataSize);
  214406. void* const dragHandCursor = juce_createMouseCursorFromImage (*im, 8, 7);
  214407. delete im;
  214408. return dragHandCursor;
  214409. }
  214410. case MouseCursor::CopyingCursor:
  214411. {
  214412. static unsigned char copyCursorData[] = {71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  214413. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0,
  214414. 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  214415. 78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174,
  214416. 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  214417. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  214418. const int copyCursorSize = 119;
  214419. Image* const im = ImageFileFormat::loadFrom ((const char*) copyCursorData, copyCursorSize);
  214420. void* const copyCursor = juce_createMouseCursorFromImage (*im, 1, 3);
  214421. delete im;
  214422. return copyCursor;
  214423. }
  214424. case MouseCursor::WaitCursor:
  214425. shape = XC_watch;
  214426. break;
  214427. case MouseCursor::IBeamCursor:
  214428. shape = XC_xterm;
  214429. break;
  214430. case MouseCursor::PointingHandCursor:
  214431. shape = XC_hand2;
  214432. break;
  214433. case MouseCursor::LeftRightResizeCursor:
  214434. shape = XC_sb_h_double_arrow;
  214435. break;
  214436. case MouseCursor::UpDownResizeCursor:
  214437. shape = XC_sb_v_double_arrow;
  214438. break;
  214439. case MouseCursor::UpDownLeftRightResizeCursor:
  214440. shape = XC_fleur;
  214441. break;
  214442. case MouseCursor::TopEdgeResizeCursor:
  214443. shape = XC_top_side;
  214444. break;
  214445. case MouseCursor::BottomEdgeResizeCursor:
  214446. shape = XC_bottom_side;
  214447. break;
  214448. case MouseCursor::LeftEdgeResizeCursor:
  214449. shape = XC_left_side;
  214450. break;
  214451. case MouseCursor::RightEdgeResizeCursor:
  214452. shape = XC_right_side;
  214453. break;
  214454. case MouseCursor::TopLeftCornerResizeCursor:
  214455. shape = XC_top_left_corner;
  214456. break;
  214457. case MouseCursor::TopRightCornerResizeCursor:
  214458. shape = XC_top_right_corner;
  214459. break;
  214460. case MouseCursor::BottomLeftCornerResizeCursor:
  214461. shape = XC_bottom_left_corner;
  214462. break;
  214463. case MouseCursor::BottomRightCornerResizeCursor:
  214464. shape = XC_bottom_right_corner;
  214465. break;
  214466. case MouseCursor::CrosshairCursor:
  214467. shape = XC_crosshair;
  214468. break;
  214469. default:
  214470. return (void*) None; // Use parent cursor
  214471. }
  214472. return (void*) XCreateFontCursor (display, shape);
  214473. }
  214474. void MouseCursor::showInWindow (ComponentPeer* peer) const throw()
  214475. {
  214476. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  214477. if (lp != 0)
  214478. lp->showMouseCursor ((Cursor) getHandle());
  214479. }
  214480. void MouseCursor::showInAllWindows() const throw()
  214481. {
  214482. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  214483. showInWindow (ComponentPeer::getPeer (i));
  214484. }
  214485. Image* juce_createIconForFile (const File& file)
  214486. {
  214487. return 0;
  214488. }
  214489. #if JUCE_OPENGL
  214490. class WindowedGLContext : public OpenGLContext
  214491. {
  214492. public:
  214493. WindowedGLContext (Component* const component,
  214494. const OpenGLPixelFormat& pixelFormat_,
  214495. GLXContext sharedContext)
  214496. : renderContext (0),
  214497. embeddedWindow (0),
  214498. pixelFormat (pixelFormat_)
  214499. {
  214500. jassert (component != 0);
  214501. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  214502. if (peer == 0)
  214503. return;
  214504. XSync (display, False);
  214505. GLint attribs [64];
  214506. int n = 0;
  214507. attribs[n++] = GLX_RGBA;
  214508. attribs[n++] = GLX_DOUBLEBUFFER;
  214509. attribs[n++] = GLX_RED_SIZE;
  214510. attribs[n++] = pixelFormat.redBits;
  214511. attribs[n++] = GLX_GREEN_SIZE;
  214512. attribs[n++] = pixelFormat.greenBits;
  214513. attribs[n++] = GLX_BLUE_SIZE;
  214514. attribs[n++] = pixelFormat.blueBits;
  214515. attribs[n++] = GLX_ALPHA_SIZE;
  214516. attribs[n++] = pixelFormat.alphaBits;
  214517. attribs[n++] = GLX_DEPTH_SIZE;
  214518. attribs[n++] = pixelFormat.depthBufferBits;
  214519. attribs[n++] = GLX_STENCIL_SIZE;
  214520. attribs[n++] = pixelFormat.stencilBufferBits;
  214521. attribs[n++] = GLX_ACCUM_RED_SIZE;
  214522. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  214523. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  214524. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  214525. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  214526. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  214527. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  214528. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  214529. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  214530. attribs[n++] = None;
  214531. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  214532. if (bestVisual == 0)
  214533. return;
  214534. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  214535. Window windowH = (Window) peer->getNativeHandle();
  214536. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  214537. XSetWindowAttributes swa;
  214538. swa.colormap = colourMap;
  214539. swa.border_pixel = 0;
  214540. swa.event_mask = ExposureMask | StructureNotifyMask;
  214541. embeddedWindow = XCreateWindow (display, windowH,
  214542. 0, 0, 1, 1, 0,
  214543. bestVisual->depth,
  214544. InputOutput,
  214545. bestVisual->visual,
  214546. CWBorderPixel | CWColormap | CWEventMask,
  214547. &swa);
  214548. XSaveContext (display, (XID) embeddedWindow, improbableNumber, (XPointer) peer);
  214549. XMapWindow (display, embeddedWindow);
  214550. XFreeColormap (display, colourMap);
  214551. XFree (bestVisual);
  214552. XSync (display, False);
  214553. }
  214554. ~WindowedGLContext()
  214555. {
  214556. makeInactive();
  214557. glXDestroyContext (display, renderContext);
  214558. XUnmapWindow (display, embeddedWindow);
  214559. XDestroyWindow (display, embeddedWindow);
  214560. }
  214561. bool makeActive() const throw()
  214562. {
  214563. jassert (renderContext != 0);
  214564. return glXMakeCurrent (display, embeddedWindow, renderContext)
  214565. && XSync (display, False);
  214566. }
  214567. bool makeInactive() const throw()
  214568. {
  214569. return (! isActive()) || glXMakeCurrent (display, None, 0);
  214570. }
  214571. bool isActive() const throw()
  214572. {
  214573. return glXGetCurrentContext() == renderContext;
  214574. }
  214575. const OpenGLPixelFormat getPixelFormat() const
  214576. {
  214577. return pixelFormat;
  214578. }
  214579. void* getRawContext() const throw()
  214580. {
  214581. return renderContext;
  214582. }
  214583. void updateWindowPosition (int x, int y, int w, int h, int)
  214584. {
  214585. XMoveResizeWindow (display, embeddedWindow,
  214586. x, y, jmax (1, w), jmax (1, h));
  214587. }
  214588. void swapBuffers()
  214589. {
  214590. glXSwapBuffers (display, embeddedWindow);
  214591. }
  214592. bool setSwapInterval (const int numFramesPerSwap)
  214593. {
  214594. // xxx needs doing..
  214595. return false;
  214596. }
  214597. int getSwapInterval() const
  214598. {
  214599. // xxx needs doing..
  214600. return 0;
  214601. }
  214602. void repaint()
  214603. {
  214604. }
  214605. juce_UseDebuggingNewOperator
  214606. GLXContext renderContext;
  214607. private:
  214608. Window embeddedWindow;
  214609. OpenGLPixelFormat pixelFormat;
  214610. WindowedGLContext (const WindowedGLContext&);
  214611. const WindowedGLContext& operator= (const WindowedGLContext&);
  214612. };
  214613. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  214614. const OpenGLPixelFormat& pixelFormat,
  214615. const OpenGLContext* const contextToShareWith)
  214616. {
  214617. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  214618. contextToShareWith != 0 ? (GLXContext) contextToShareWith->getRawContext() : 0);
  214619. if (c->renderContext == 0)
  214620. deleteAndZero (c);
  214621. return c;
  214622. }
  214623. void juce_glViewport (const int w, const int h)
  214624. {
  214625. glViewport (0, 0, w, h);
  214626. }
  214627. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  214628. OwnedArray <OpenGLPixelFormat>& results)
  214629. {
  214630. results.add (new OpenGLPixelFormat()); // xxx
  214631. }
  214632. #endif
  214633. static void initClipboard (Window root, Atom* cutBuffers) throw()
  214634. {
  214635. static bool init = false;
  214636. if (! init)
  214637. {
  214638. init = true;
  214639. // Make sure all cut buffers exist before use
  214640. for (int i = 0; i < 8; i++)
  214641. {
  214642. XChangeProperty (display, root, cutBuffers[i],
  214643. XA_STRING, 8, PropModeAppend, NULL, 0);
  214644. }
  214645. }
  214646. }
  214647. // Clipboard implemented currently using cut buffers
  214648. // rather than the more powerful selection method
  214649. void SystemClipboard::copyTextToClipboard (const String& clipText) throw()
  214650. {
  214651. Window root = RootWindow (display, DefaultScreen (display));
  214652. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  214653. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  214654. initClipboard (root, cutBuffers);
  214655. XRotateWindowProperties (display, root, cutBuffers, 8, 1);
  214656. XChangeProperty (display, root, cutBuffers[0],
  214657. XA_STRING, 8, PropModeReplace, (const unsigned char*) (const char*) clipText,
  214658. clipText.length());
  214659. }
  214660. const String SystemClipboard::getTextFromClipboard() throw()
  214661. {
  214662. const int bufSize = 64; // in words
  214663. String returnData;
  214664. int byteOffset = 0;
  214665. Window root = RootWindow (display, DefaultScreen (display));
  214666. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  214667. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  214668. initClipboard (root, cutBuffers);
  214669. for (;;)
  214670. {
  214671. unsigned long bytesLeft = 0, nitems = 0;
  214672. unsigned char* clipData = 0;
  214673. int actualFormat = 0;
  214674. Atom actualType;
  214675. if (XGetWindowProperty (display, root, cutBuffers[0], byteOffset >> 2, bufSize,
  214676. False, XA_STRING, &actualType, &actualFormat, &nitems, &bytesLeft,
  214677. &clipData) == Success)
  214678. {
  214679. if (actualType == XA_STRING && actualFormat == 8)
  214680. {
  214681. byteOffset += nitems;
  214682. returnData += String ((const char*) clipData, nitems);
  214683. }
  214684. else
  214685. {
  214686. bytesLeft = 0;
  214687. }
  214688. if (clipData != 0)
  214689. XFree (clipData);
  214690. }
  214691. if (bytesLeft == 0)
  214692. break;
  214693. }
  214694. return returnData;
  214695. }
  214696. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  214697. {
  214698. jassertfalse // not implemented!
  214699. return false;
  214700. }
  214701. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  214702. {
  214703. jassertfalse // not implemented!
  214704. return false;
  214705. }
  214706. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  214707. {
  214708. if (! isOnDesktop ())
  214709. addToDesktop (0);
  214710. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  214711. if (wp != 0)
  214712. {
  214713. wp->setTaskBarIcon (newImage);
  214714. setVisible (true);
  214715. toFront (false);
  214716. repaint();
  214717. }
  214718. }
  214719. void SystemTrayIconComponent::paint (Graphics& g)
  214720. {
  214721. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  214722. if (wp != 0)
  214723. {
  214724. const Image* const image = wp->getTaskbarIcon();
  214725. if (image != 0)
  214726. g.drawImageAt (image, 0, 0, false);
  214727. }
  214728. }
  214729. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  214730. {
  214731. // xxx not yet implemented!
  214732. }
  214733. void PlatformUtilities::beep()
  214734. {
  214735. fprintf (stdout, "\a");
  214736. fflush (stdout);
  214737. }
  214738. bool AlertWindow::showNativeDialogBox (const String& title,
  214739. const String& bodyText,
  214740. bool isOkCancel)
  214741. {
  214742. // xxx this is supposed to pop up an alert!
  214743. Logger::outputDebugString (title + ": " + bodyText);
  214744. // use a non-native one for the time being..
  214745. if (isOkCancel)
  214746. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  214747. else
  214748. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  214749. return true;
  214750. }
  214751. const int KeyPress::spaceKey = XK_space & 0xff;
  214752. const int KeyPress::returnKey = XK_Return & 0xff;
  214753. const int KeyPress::escapeKey = XK_Escape & 0xff;
  214754. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  214755. const int KeyPress::leftKey = (XK_Left & 0xff) | extendedKeyModifier;
  214756. const int KeyPress::rightKey = (XK_Right & 0xff) | extendedKeyModifier;
  214757. const int KeyPress::upKey = (XK_Up & 0xff) | extendedKeyModifier;
  214758. const int KeyPress::downKey = (XK_Down & 0xff) | extendedKeyModifier;
  214759. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | extendedKeyModifier;
  214760. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | extendedKeyModifier;
  214761. const int KeyPress::endKey = (XK_End & 0xff) | extendedKeyModifier;
  214762. const int KeyPress::homeKey = (XK_Home & 0xff) | extendedKeyModifier;
  214763. const int KeyPress::insertKey = (XK_Insert & 0xff) | extendedKeyModifier;
  214764. const int KeyPress::deleteKey = (XK_Delete & 0xff) | extendedKeyModifier;
  214765. const int KeyPress::tabKey = XK_Tab & 0xff;
  214766. const int KeyPress::F1Key = (XK_F1 & 0xff) | extendedKeyModifier;
  214767. const int KeyPress::F2Key = (XK_F2 & 0xff) | extendedKeyModifier;
  214768. const int KeyPress::F3Key = (XK_F3 & 0xff) | extendedKeyModifier;
  214769. const int KeyPress::F4Key = (XK_F4 & 0xff) | extendedKeyModifier;
  214770. const int KeyPress::F5Key = (XK_F5 & 0xff) | extendedKeyModifier;
  214771. const int KeyPress::F6Key = (XK_F6 & 0xff) | extendedKeyModifier;
  214772. const int KeyPress::F7Key = (XK_F7 & 0xff) | extendedKeyModifier;
  214773. const int KeyPress::F8Key = (XK_F8 & 0xff) | extendedKeyModifier;
  214774. const int KeyPress::F9Key = (XK_F9 & 0xff) | extendedKeyModifier;
  214775. const int KeyPress::F10Key = (XK_F10 & 0xff) | extendedKeyModifier;
  214776. const int KeyPress::F11Key = (XK_F11 & 0xff) | extendedKeyModifier;
  214777. const int KeyPress::F12Key = (XK_F12 & 0xff) | extendedKeyModifier;
  214778. const int KeyPress::F13Key = (XK_F13 & 0xff) | extendedKeyModifier;
  214779. const int KeyPress::F14Key = (XK_F14 & 0xff) | extendedKeyModifier;
  214780. const int KeyPress::F15Key = (XK_F15 & 0xff) | extendedKeyModifier;
  214781. const int KeyPress::F16Key = (XK_F16 & 0xff) | extendedKeyModifier;
  214782. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | extendedKeyModifier;
  214783. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | extendedKeyModifier;
  214784. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | extendedKeyModifier;
  214785. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | extendedKeyModifier;
  214786. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | extendedKeyModifier;
  214787. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | extendedKeyModifier;
  214788. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | extendedKeyModifier;
  214789. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| extendedKeyModifier;
  214790. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| extendedKeyModifier;
  214791. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| extendedKeyModifier;
  214792. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| extendedKeyModifier;
  214793. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| extendedKeyModifier;
  214794. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| extendedKeyModifier;
  214795. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| extendedKeyModifier;
  214796. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| extendedKeyModifier;
  214797. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| extendedKeyModifier;
  214798. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| extendedKeyModifier;
  214799. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| extendedKeyModifier;
  214800. const int KeyPress::playKey = (0xffeeff00) | extendedKeyModifier;
  214801. const int KeyPress::stopKey = (0xffeeff01) | extendedKeyModifier;
  214802. const int KeyPress::fastForwardKey = (0xffeeff02) | extendedKeyModifier;
  214803. const int KeyPress::rewindKey = (0xffeeff03) | extendedKeyModifier;
  214804. END_JUCE_NAMESPACE
  214805. #endif
  214806. /********* End of inlined file: juce_linux_Windowing.cpp *********/
  214807. #endif
  214808. #endif
  214809. //==============================================================================
  214810. #if JUCE_MAC
  214811. /********* Start of inlined file: juce_mac_Files.cpp *********/
  214812. #include <ApplicationServices/ApplicationServices.h>
  214813. #include <sys/stat.h>
  214814. #include <sys/dir.h>
  214815. #include <sys/param.h>
  214816. #include <sys/mount.h>
  214817. #include <unistd.h>
  214818. #include <fnmatch.h>
  214819. #include <utime.h>
  214820. #include <pwd.h>
  214821. #include <fcntl.h>
  214822. BEGIN_JUCE_NAMESPACE
  214823. /*
  214824. Note that a lot of methods that you'd expect to find in this file actually
  214825. live in juce_posix_SharedCode.cpp!
  214826. */
  214827. /********* Start of inlined file: juce_posix_SharedCode.cpp *********/
  214828. /*
  214829. This file contains posix routines that are common to both the Linux and Mac builds.
  214830. It gets included directly in the cpp files for these platforms.
  214831. */
  214832. CriticalSection::CriticalSection() throw()
  214833. {
  214834. pthread_mutexattr_t atts;
  214835. pthread_mutexattr_init (&atts);
  214836. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  214837. pthread_mutex_init (&internal, &atts);
  214838. }
  214839. CriticalSection::~CriticalSection() throw()
  214840. {
  214841. pthread_mutex_destroy (&internal);
  214842. }
  214843. void CriticalSection::enter() const throw()
  214844. {
  214845. pthread_mutex_lock (&internal);
  214846. }
  214847. bool CriticalSection::tryEnter() const throw()
  214848. {
  214849. return pthread_mutex_trylock (&internal) == 0;
  214850. }
  214851. void CriticalSection::exit() const throw()
  214852. {
  214853. pthread_mutex_unlock (&internal);
  214854. }
  214855. struct EventStruct
  214856. {
  214857. pthread_cond_t condition;
  214858. pthread_mutex_t mutex;
  214859. bool triggered;
  214860. };
  214861. WaitableEvent::WaitableEvent() throw()
  214862. {
  214863. EventStruct* const es = new EventStruct();
  214864. es->triggered = false;
  214865. pthread_cond_init (&es->condition, 0);
  214866. pthread_mutex_init (&es->mutex, 0);
  214867. internal = es;
  214868. }
  214869. WaitableEvent::~WaitableEvent() throw()
  214870. {
  214871. EventStruct* const es = (EventStruct*) internal;
  214872. pthread_cond_destroy (&es->condition);
  214873. pthread_mutex_destroy (&es->mutex);
  214874. delete es;
  214875. }
  214876. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  214877. {
  214878. EventStruct* const es = (EventStruct*) internal;
  214879. bool ok = true;
  214880. pthread_mutex_lock (&es->mutex);
  214881. if (timeOutMillisecs < 0)
  214882. {
  214883. while (! es->triggered)
  214884. pthread_cond_wait (&es->condition, &es->mutex);
  214885. }
  214886. else
  214887. {
  214888. while (! es->triggered)
  214889. {
  214890. struct timeval t;
  214891. gettimeofday (&t, 0);
  214892. struct timespec time;
  214893. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  214894. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  214895. if (time.tv_nsec >= 1000000000)
  214896. {
  214897. time.tv_nsec -= 1000000000;
  214898. time.tv_sec++;
  214899. }
  214900. if (pthread_cond_timedwait (&es->condition, &es->mutex, &time) == ETIMEDOUT)
  214901. {
  214902. ok = false;
  214903. break;
  214904. }
  214905. }
  214906. }
  214907. es->triggered = false;
  214908. pthread_mutex_unlock (&es->mutex);
  214909. return ok;
  214910. }
  214911. void WaitableEvent::signal() const throw()
  214912. {
  214913. EventStruct* const es = (EventStruct*) internal;
  214914. pthread_mutex_lock (&es->mutex);
  214915. es->triggered = true;
  214916. pthread_cond_broadcast (&es->condition);
  214917. pthread_mutex_unlock (&es->mutex);
  214918. }
  214919. void WaitableEvent::reset() const throw()
  214920. {
  214921. EventStruct* const es = (EventStruct*) internal;
  214922. pthread_mutex_lock (&es->mutex);
  214923. es->triggered = false;
  214924. pthread_mutex_unlock (&es->mutex);
  214925. }
  214926. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  214927. {
  214928. struct timespec time;
  214929. time.tv_sec = millisecs / 1000;
  214930. time.tv_nsec = (millisecs % 1000) * 1000000;
  214931. nanosleep (&time, 0);
  214932. }
  214933. const tchar File::separator = T('/');
  214934. const tchar* File::separatorString = T("/");
  214935. bool juce_copyFile (const String& s, const String& d) throw();
  214936. static bool juce_stat (const String& fileName, struct stat& info) throw()
  214937. {
  214938. return fileName.isNotEmpty()
  214939. && (stat (fileName.toUTF8(), &info) == 0);
  214940. }
  214941. bool juce_isDirectory (const String& fileName) throw()
  214942. {
  214943. struct stat info;
  214944. return fileName.isEmpty()
  214945. || (juce_stat (fileName, info)
  214946. && ((info.st_mode & S_IFDIR) != 0));
  214947. }
  214948. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  214949. {
  214950. if (fileName.isEmpty())
  214951. return false;
  214952. const char* const fileNameUTF8 = fileName.toUTF8();
  214953. bool exists = access (fileNameUTF8, F_OK) == 0;
  214954. if (exists && dontCountDirectories)
  214955. {
  214956. struct stat info;
  214957. const int res = stat (fileNameUTF8, &info);
  214958. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  214959. exists = false;
  214960. }
  214961. return exists;
  214962. }
  214963. int64 juce_getFileSize (const String& fileName) throw()
  214964. {
  214965. struct stat info;
  214966. return juce_stat (fileName, info) ? info.st_size : 0;
  214967. }
  214968. bool juce_canWriteToFile (const String& fileName) throw()
  214969. {
  214970. return access (fileName.toUTF8(), W_OK) == 0;
  214971. }
  214972. bool juce_deleteFile (const String& fileName) throw()
  214973. {
  214974. const char* const fileNameUTF8 = fileName.toUTF8();
  214975. if (juce_isDirectory (fileName))
  214976. return rmdir (fileNameUTF8) == 0;
  214977. else
  214978. return remove (fileNameUTF8) == 0;
  214979. }
  214980. bool juce_moveFile (const String& source, const String& dest) throw()
  214981. {
  214982. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  214983. return true;
  214984. if (juce_canWriteToFile (source)
  214985. && juce_copyFile (source, dest))
  214986. {
  214987. if (juce_deleteFile (source))
  214988. return true;
  214989. juce_deleteFile (dest);
  214990. }
  214991. return false;
  214992. }
  214993. void juce_createDirectory (const String& fileName) throw()
  214994. {
  214995. mkdir (fileName.toUTF8(), 0777);
  214996. }
  214997. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  214998. {
  214999. const char* const fileNameUTF8 = fileName.toUTF8();
  215000. int flags = O_RDONLY;
  215001. if (forWriting)
  215002. {
  215003. if (juce_fileExists (fileName, false))
  215004. {
  215005. const int f = open (fileNameUTF8, O_RDWR, 00644);
  215006. if (f != -1)
  215007. lseek (f, 0, SEEK_END);
  215008. return (void*) f;
  215009. }
  215010. else
  215011. {
  215012. flags = O_RDWR + O_CREAT;
  215013. }
  215014. }
  215015. return (void*) open (fileNameUTF8, flags, 00644);
  215016. }
  215017. void juce_fileClose (void* handle) throw()
  215018. {
  215019. if (handle != 0)
  215020. close ((int) (pointer_sized_int) handle);
  215021. }
  215022. int juce_fileRead (void* handle, void* buffer, int size) throw()
  215023. {
  215024. if (handle != 0)
  215025. return read ((int) (pointer_sized_int) handle, buffer, size);
  215026. return 0;
  215027. }
  215028. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  215029. {
  215030. if (handle != 0)
  215031. return write ((int) (pointer_sized_int) handle, buffer, size);
  215032. return 0;
  215033. }
  215034. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  215035. {
  215036. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  215037. return pos;
  215038. return -1;
  215039. }
  215040. int64 juce_fileGetPosition (void* handle) throw()
  215041. {
  215042. if (handle != 0)
  215043. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  215044. else
  215045. return -1;
  215046. }
  215047. void juce_fileFlush (void* handle) throw()
  215048. {
  215049. if (handle != 0)
  215050. fsync ((int) (pointer_sized_int) handle);
  215051. }
  215052. // if this file doesn't exist, find a parent of it that does..
  215053. static bool doStatFS (const File* file, struct statfs& result) throw()
  215054. {
  215055. File f (*file);
  215056. for (int i = 5; --i >= 0;)
  215057. {
  215058. if (f.exists())
  215059. break;
  215060. f = f.getParentDirectory();
  215061. }
  215062. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  215063. }
  215064. int64 File::getBytesFreeOnVolume() const throw()
  215065. {
  215066. int64 free_space = 0;
  215067. struct statfs buf;
  215068. if (doStatFS (this, buf))
  215069. // Note: this returns space available to non-super user
  215070. free_space = (int64) buf.f_bsize * (int64) buf.f_bavail;
  215071. return free_space;
  215072. }
  215073. const String juce_getVolumeLabel (const String& filenameOnVolume,
  215074. int& volumeSerialNumber) throw()
  215075. {
  215076. // There is no equivalent on Linux
  215077. volumeSerialNumber = 0;
  215078. return String::empty;
  215079. }
  215080. #if JUCE_64BIT
  215081. #define filedesc ((long long) internal)
  215082. #else
  215083. #define filedesc ((int) internal)
  215084. #endif
  215085. InterProcessLock::InterProcessLock (const String& name_) throw()
  215086. : internal (0),
  215087. name (name_),
  215088. reentrancyLevel (0)
  215089. {
  215090. #if JUCE_MAC
  215091. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  215092. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  215093. #else
  215094. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  215095. #endif
  215096. temp.create();
  215097. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  215098. }
  215099. InterProcessLock::~InterProcessLock() throw()
  215100. {
  215101. while (reentrancyLevel > 0)
  215102. this->exit();
  215103. close (filedesc);
  215104. }
  215105. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  215106. {
  215107. if (internal == 0)
  215108. return false;
  215109. if (reentrancyLevel != 0)
  215110. return true;
  215111. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  215112. struct flock fl;
  215113. zerostruct (fl);
  215114. fl.l_whence = SEEK_SET;
  215115. fl.l_type = F_WRLCK;
  215116. for (;;)
  215117. {
  215118. const int result = fcntl (filedesc, F_SETLK, &fl);
  215119. if (result >= 0)
  215120. {
  215121. ++reentrancyLevel;
  215122. return true;
  215123. }
  215124. if (errno != EINTR)
  215125. {
  215126. if (timeOutMillisecs == 0
  215127. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  215128. break;
  215129. Thread::sleep (10);
  215130. }
  215131. }
  215132. return false;
  215133. }
  215134. void InterProcessLock::exit() throw()
  215135. {
  215136. if (reentrancyLevel > 0 && internal != 0)
  215137. {
  215138. --reentrancyLevel;
  215139. struct flock fl;
  215140. zerostruct (fl);
  215141. fl.l_whence = SEEK_SET;
  215142. fl.l_type = F_UNLCK;
  215143. for (;;)
  215144. {
  215145. const int result = fcntl (filedesc, F_SETLKW, &fl);
  215146. if (result >= 0 || errno != EINTR)
  215147. break;
  215148. }
  215149. }
  215150. }
  215151. /********* End of inlined file: juce_posix_SharedCode.cpp *********/
  215152. static File executableFile;
  215153. void PlatformUtilities::copyToStr255 (Str255& d, const String& s)
  215154. {
  215155. unsigned char* t = (unsigned char*) d;
  215156. t[0] = jmin (254, s.length());
  215157. s.copyToBuffer ((char*) t + 1, 254);
  215158. }
  215159. void PlatformUtilities::copyToStr63 (Str63& d, const String& s)
  215160. {
  215161. unsigned char* t = (unsigned char*) d;
  215162. t[0] = jmin (62, s.length());
  215163. s.copyToBuffer ((char*) t + 1, 62);
  215164. }
  215165. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  215166. {
  215167. String result;
  215168. if (cfString != 0)
  215169. {
  215170. #if JUCE_STRINGS_ARE_UNICODE
  215171. CFRange range = { 0, CFStringGetLength (cfString) };
  215172. UniChar* const u = (UniChar*) juce_malloc (sizeof (UniChar) * (range.length + 1));
  215173. CFStringGetCharacters (cfString, range, u);
  215174. u[range.length] = 0;
  215175. result = convertUTF16ToString (u);
  215176. juce_free (u);
  215177. #else
  215178. const int len = CFStringGetLength (cfString);
  215179. char* buffer = (char*) juce_malloc (len + 1);
  215180. CFStringGetCString (cfString, buffer, len + 1, CFStringGetSystemEncoding());
  215181. result = buffer;
  215182. juce_free (buffer);
  215183. #endif
  215184. }
  215185. return result;
  215186. }
  215187. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  215188. {
  215189. #if JUCE_STRINGS_ARE_UNICODE
  215190. const int len = s.length();
  215191. const juce_wchar* t = (const juce_wchar*) s;
  215192. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  215193. for (int i = 0; i <= len; ++i)
  215194. temp[i] = t[i];
  215195. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  215196. juce_free (temp);
  215197. return result;
  215198. #else
  215199. return CFStringCreateWithCString (kCFAllocatorDefault,
  215200. (const char*) s,
  215201. CFStringGetSystemEncoding());
  215202. #endif
  215203. }
  215204. const String PlatformUtilities::convertUTF16ToString (const UniChar* utf16)
  215205. {
  215206. String s;
  215207. while (*utf16 != 0)
  215208. s += (juce_wchar) *utf16++;
  215209. return s;
  215210. }
  215211. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  215212. {
  215213. UnicodeMapping map;
  215214. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  215215. kUnicodeNoSubset,
  215216. kTextEncodingDefaultFormat);
  215217. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  215218. kUnicodeCanonicalCompVariant,
  215219. kTextEncodingDefaultFormat);
  215220. map.mappingVersion = kUnicodeUseLatestMapping;
  215221. UnicodeToTextInfo conversionInfo = 0;
  215222. String result;
  215223. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  215224. {
  215225. const int len = s.length();
  215226. UniChar* const tempIn = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  215227. UniChar* const tempOut = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  215228. for (int i = 0; i <= len; ++i)
  215229. tempIn[i] = s[i];
  215230. ByteCount bytesRead = 0;
  215231. ByteCount outputBufferSize = 0;
  215232. if (ConvertFromUnicodeToText (conversionInfo,
  215233. len * sizeof (UniChar), tempIn,
  215234. kUnicodeDefaultDirectionMask,
  215235. 0, 0, 0, 0,
  215236. len * sizeof (UniChar), &bytesRead,
  215237. &outputBufferSize, tempOut) == noErr)
  215238. {
  215239. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  215240. tchar* t = const_cast <tchar*> ((const tchar*) result);
  215241. int i;
  215242. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  215243. t[i] = (tchar) tempOut[i];
  215244. t[i] = 0;
  215245. }
  215246. juce_free (tempIn);
  215247. juce_free (tempOut);
  215248. DisposeUnicodeToTextInfo (&conversionInfo);
  215249. }
  215250. return result;
  215251. }
  215252. const unsigned int macTimeToUnixTimeDiff = 0x7c25be90;
  215253. static uint64 utcDateTimeToUnixTime (const UTCDateTime& d) throw()
  215254. {
  215255. if (d.highSeconds == 0 && d.lowSeconds == 0 && d.fraction == 0)
  215256. return 0;
  215257. return (((((uint64) d.highSeconds) << 32) | (uint64) d.lowSeconds) * 1000)
  215258. + ((d.fraction * 1000) >> 16)
  215259. - 2082844800000ll;
  215260. }
  215261. static void unixTimeToUtcDateTime (uint64 t, UTCDateTime& d) throw()
  215262. {
  215263. if (t != 0)
  215264. t += 2082844800000ll;
  215265. d.highSeconds = (t / 1000) >> 32;
  215266. d.lowSeconds = (t / 1000) & (uint64) 0xffffffff;
  215267. d.fraction = ((t % 1000) << 16) / 1000;
  215268. }
  215269. void juce_getFileTimes (const String& fileName,
  215270. int64& modificationTime,
  215271. int64& accessTime,
  215272. int64& creationTime) throw()
  215273. {
  215274. modificationTime = 0;
  215275. accessTime = 0;
  215276. creationTime = 0;
  215277. FSRef fileRef;
  215278. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  215279. {
  215280. FSRefParam info;
  215281. zerostruct (info);
  215282. info.ref = &fileRef;
  215283. info.whichInfo = kFSCatInfoAllDates;
  215284. FSCatalogInfo catInfo;
  215285. info.catInfo = &catInfo;
  215286. if (PBGetCatalogInfoSync (&info) == noErr)
  215287. {
  215288. creationTime = utcDateTimeToUnixTime (catInfo.createDate);
  215289. accessTime = utcDateTimeToUnixTime (catInfo.accessDate);
  215290. modificationTime = utcDateTimeToUnixTime (catInfo.contentModDate);
  215291. }
  215292. }
  215293. }
  215294. bool juce_setFileTimes (const String& fileName,
  215295. int64 modificationTime,
  215296. int64 accessTime,
  215297. int64 creationTime) throw()
  215298. {
  215299. FSRef fileRef;
  215300. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  215301. {
  215302. FSRefParam info;
  215303. zerostruct (info);
  215304. info.ref = &fileRef;
  215305. info.whichInfo = kFSCatInfoAllDates;
  215306. FSCatalogInfo catInfo;
  215307. info.catInfo = &catInfo;
  215308. if (PBGetCatalogInfoSync (&info) == noErr)
  215309. {
  215310. if (creationTime != 0)
  215311. unixTimeToUtcDateTime (creationTime, catInfo.createDate);
  215312. if (modificationTime != 0)
  215313. unixTimeToUtcDateTime (modificationTime, catInfo.contentModDate);
  215314. if (accessTime != 0)
  215315. unixTimeToUtcDateTime (accessTime, catInfo.accessDate);
  215316. return PBSetCatalogInfoSync (&info) == noErr;
  215317. }
  215318. }
  215319. return false;
  215320. }
  215321. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  215322. {
  215323. const char* const fileNameUTF8 = fileName.toUTF8();
  215324. struct stat info;
  215325. const int res = stat (fileNameUTF8, &info);
  215326. bool ok = false;
  215327. if (res == 0)
  215328. {
  215329. info.st_mode &= 0777; // Just permissions
  215330. if (isReadOnly)
  215331. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  215332. else
  215333. // Give everybody write permission?
  215334. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  215335. ok = chmod (fileNameUTF8, info.st_mode) == 0;
  215336. }
  215337. return ok;
  215338. }
  215339. bool juce_copyFile (const String& src, const String& dst) throw()
  215340. {
  215341. const File destFile (dst);
  215342. if (! destFile.create())
  215343. return false;
  215344. FSRef srcRef, dstRef;
  215345. if (! (PlatformUtilities::makeFSRefFromPath (&srcRef, src)
  215346. && PlatformUtilities::makeFSRefFromPath (&dstRef, dst)))
  215347. {
  215348. return false;
  215349. }
  215350. int okForks = 0;
  215351. CatPositionRec iter;
  215352. iter.initialize = 0;
  215353. HFSUniStr255 forkName;
  215354. // can't just copy the data because this is a bloody Mac, so we need to copy each
  215355. // fork separately...
  215356. while (FSIterateForks (&srcRef, &iter, &forkName, 0, 0) == noErr)
  215357. {
  215358. SInt16 srcForkNum = 0, dstForkNum = 0;
  215359. OSErr err = FSOpenFork (&srcRef, forkName.length, forkName.unicode, fsRdPerm, &srcForkNum);
  215360. if (err == noErr)
  215361. {
  215362. err = FSOpenFork (&dstRef, forkName.length, forkName.unicode, fsRdWrPerm, &dstForkNum);
  215363. if (err == noErr)
  215364. {
  215365. MemoryBlock buf (32768);
  215366. SInt64 pos = 0;
  215367. for (;;)
  215368. {
  215369. ByteCount bytesRead = 0;
  215370. err = FSReadFork (srcForkNum, fsFromStart, pos, buf.getSize(), (char*) buf, &bytesRead);
  215371. if (bytesRead > 0)
  215372. {
  215373. err = FSWriteFork (dstForkNum, fsFromStart, pos, bytesRead, (const char*) buf, &bytesRead);
  215374. pos += bytesRead;
  215375. }
  215376. if (err != noErr)
  215377. {
  215378. if (err == eofErr)
  215379. ++okForks;
  215380. break;
  215381. }
  215382. }
  215383. FSFlushFork (dstForkNum);
  215384. FSCloseFork (dstForkNum);
  215385. }
  215386. FSCloseFork (srcForkNum);
  215387. }
  215388. }
  215389. if (okForks > 0) // some files seem to be ok even if not all their forks get copied..
  215390. {
  215391. // copy permissions..
  215392. struct stat info;
  215393. if (juce_stat (src, info))
  215394. chmod (dst.toUTF8(), info.st_mode & 0777);
  215395. return true;
  215396. }
  215397. return false;
  215398. }
  215399. const StringArray juce_getFileSystemRoots() throw()
  215400. {
  215401. StringArray s;
  215402. s.add (T("/"));
  215403. return s;
  215404. }
  215405. static bool isFileOnDriveType (const File* const f, const char** types) throw()
  215406. {
  215407. struct statfs buf;
  215408. if (doStatFS (f, buf))
  215409. {
  215410. const String type (buf.f_fstypename);
  215411. while (*types != 0)
  215412. if (type.equalsIgnoreCase (*types++))
  215413. return true;
  215414. }
  215415. return false;
  215416. }
  215417. bool File::isOnCDRomDrive() const throw()
  215418. {
  215419. static const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  215420. return isFileOnDriveType (this, (const char**) cdTypes);
  215421. }
  215422. bool File::isOnHardDisk() const throw()
  215423. {
  215424. static const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  215425. return ! (isOnCDRomDrive() || isFileOnDriveType (this, (const char**) nonHDTypes));
  215426. }
  215427. static bool juce_isHiddenFile (const String& path) throw()
  215428. {
  215429. FSRef ref;
  215430. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  215431. return false;
  215432. FSCatalogInfo info;
  215433. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  215434. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  215435. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  215436. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  215437. }
  215438. bool File::isHidden() const throw()
  215439. {
  215440. return juce_isHiddenFile (getFullPathName());
  215441. }
  215442. const File File::getSpecialLocation (const SpecialLocationType type)
  215443. {
  215444. const char* resultPath = 0;
  215445. switch (type)
  215446. {
  215447. case userHomeDirectory:
  215448. resultPath = getenv ("HOME");
  215449. if (resultPath == 0)
  215450. {
  215451. struct passwd* const pw = getpwuid (getuid());
  215452. if (pw != 0)
  215453. resultPath = pw->pw_dir;
  215454. }
  215455. break;
  215456. case userDocumentsDirectory:
  215457. resultPath = "~/Documents";
  215458. break;
  215459. case userDesktopDirectory:
  215460. resultPath = "~/Desktop";
  215461. break;
  215462. case userApplicationDataDirectory:
  215463. resultPath = "~/Library";
  215464. break;
  215465. case commonApplicationDataDirectory:
  215466. resultPath = "/Library";
  215467. break;
  215468. case globalApplicationsDirectory:
  215469. resultPath = "/Applications";
  215470. break;
  215471. case userMusicDirectory:
  215472. resultPath = "~/Music";
  215473. break;
  215474. case userMoviesDirectory:
  215475. resultPath = "~/Movies";
  215476. break;
  215477. case tempDirectory:
  215478. {
  215479. File tmp (T("~/Library/Caches/") + executableFile.getFileNameWithoutExtension());
  215480. tmp.createDirectory();
  215481. return tmp.getFullPathName();
  215482. }
  215483. case currentExecutableFile:
  215484. return executableFile;
  215485. case currentApplicationFile:
  215486. {
  215487. const File parent (executableFile.getParentDirectory());
  215488. return parent.getFullPathName().endsWithIgnoreCase (T("Contents/MacOS"))
  215489. ? parent.getParentDirectory().getParentDirectory()
  215490. : executableFile;
  215491. }
  215492. default:
  215493. jassertfalse // unknown type?
  215494. break;
  215495. }
  215496. if (resultPath != 0)
  215497. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  215498. return File::nonexistent;
  215499. }
  215500. void juce_setCurrentExecutableFileName (const String& filename) throw()
  215501. {
  215502. executableFile = File::getCurrentWorkingDirectory()
  215503. .getChildFile (PlatformUtilities::convertToPrecomposedUnicode (filename));
  215504. }
  215505. void juce_setCurrentExecutableFileNameFromBundleId (const String& bundleId) throw()
  215506. {
  215507. CFStringRef bundleIdStringRef = PlatformUtilities::juceStringToCFString (bundleId);
  215508. CFBundleRef bundleRef = CFBundleGetBundleWithIdentifier (bundleIdStringRef);
  215509. CFRelease (bundleIdStringRef);
  215510. if (bundleRef != 0)
  215511. {
  215512. CFURLRef exeURLRef = CFBundleCopyExecutableURL (bundleRef);
  215513. if (exeURLRef != 0)
  215514. {
  215515. CFStringRef pathStringRef = CFURLCopyFileSystemPath (exeURLRef, kCFURLPOSIXPathStyle);
  215516. CFRelease (exeURLRef);
  215517. if (pathStringRef != 0)
  215518. {
  215519. juce_setCurrentExecutableFileName (PlatformUtilities::cfStringToJuceString (pathStringRef));
  215520. CFRelease (pathStringRef);
  215521. }
  215522. }
  215523. }
  215524. }
  215525. const File File::getCurrentWorkingDirectory() throw()
  215526. {
  215527. char buf [2048];
  215528. getcwd (buf, sizeof(buf));
  215529. return File (PlatformUtilities::convertToPrecomposedUnicode (buf));
  215530. }
  215531. bool File::setAsCurrentWorkingDirectory() const throw()
  215532. {
  215533. return chdir (getFullPathName().toUTF8()) == 0;
  215534. }
  215535. struct FindFileStruct
  215536. {
  215537. String parentDir, wildCard;
  215538. DIR* dir;
  215539. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  215540. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  215541. {
  215542. const char* const wildCardUTF8 = wildCard.toUTF8();
  215543. for (;;)
  215544. {
  215545. struct dirent* const de = readdir (dir);
  215546. if (de == 0)
  215547. break;
  215548. if (fnmatch (wildCardUTF8, de->d_name, 0) == 0)
  215549. {
  215550. result = PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 ((const uint8*) de->d_name));
  215551. const String path (parentDir + result);
  215552. if (isDir != 0 || fileSize != 0)
  215553. {
  215554. struct stat info;
  215555. const bool statOk = juce_stat (path, info);
  215556. if (isDir != 0)
  215557. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  215558. if (isHidden != 0)
  215559. *isHidden = (de->d_name[0] == '.')
  215560. || juce_isHiddenFile (path);
  215561. if (fileSize != 0)
  215562. *fileSize = statOk ? info.st_size : 0;
  215563. }
  215564. if (modTime != 0 || creationTime != 0)
  215565. {
  215566. int64 m, a, c;
  215567. juce_getFileTimes (path, m, a, c);
  215568. if (modTime != 0)
  215569. *modTime = m;
  215570. if (creationTime != 0)
  215571. *creationTime = c;
  215572. }
  215573. if (isReadOnly != 0)
  215574. *isReadOnly = ! juce_canWriteToFile (path);
  215575. return true;
  215576. }
  215577. }
  215578. return false;
  215579. }
  215580. };
  215581. // returns 0 on failure
  215582. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  215583. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  215584. Time* creationTime, bool* isReadOnly) throw()
  215585. {
  215586. DIR* const d = opendir (directory.toUTF8());
  215587. if (d != 0)
  215588. {
  215589. FindFileStruct* const ff = new FindFileStruct();
  215590. ff->parentDir = directory;
  215591. if (!ff->parentDir.endsWithChar (File::separator))
  215592. ff->parentDir += File::separator;
  215593. ff->wildCard = wildCard;
  215594. ff->dir = d;
  215595. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  215596. {
  215597. return ff;
  215598. }
  215599. else
  215600. {
  215601. firstResultFile = String::empty;
  215602. isDir = false;
  215603. closedir (d);
  215604. delete ff;
  215605. }
  215606. }
  215607. return 0;
  215608. }
  215609. bool juce_findFileNext (void* handle, String& resultFile,
  215610. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  215611. {
  215612. FindFileStruct* const ff = (FindFileStruct*) handle;
  215613. if (ff != 0)
  215614. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  215615. return false;
  215616. }
  215617. void juce_findFileClose (void* handle) throw()
  215618. {
  215619. FindFileStruct* const ff = (FindFileStruct*)handle;
  215620. if (ff != 0)
  215621. {
  215622. closedir (ff->dir);
  215623. delete ff;
  215624. }
  215625. }
  215626. bool juce_launchExecutable (const String& pathAndArguments) throw()
  215627. {
  215628. char* const argv[4] = { "/bin/sh", "-c", (char*) (const char*) pathAndArguments, 0 };
  215629. const int cpid = fork();
  215630. if (cpid == 0)
  215631. {
  215632. // Child process
  215633. if (execve (argv[0], argv, 0) < 0)
  215634. exit (0);
  215635. }
  215636. else
  215637. {
  215638. if (cpid < 0)
  215639. return false;
  215640. }
  215641. return true;
  215642. }
  215643. bool juce_launchFile (const String& fileName,
  215644. const String& parameters) throw()
  215645. {
  215646. bool ok = false;
  215647. if (fileName.startsWithIgnoreCase (T("http:"))
  215648. || fileName.startsWithIgnoreCase (T("https:"))
  215649. || fileName.startsWithIgnoreCase (T("ftp:"))
  215650. || fileName.startsWithIgnoreCase (T("file:")))
  215651. {
  215652. CFStringRef urlString = PlatformUtilities::juceStringToCFString (fileName);
  215653. if (urlString != 0)
  215654. {
  215655. CFURLRef url = CFURLCreateWithString (kCFAllocatorDefault,
  215656. urlString, 0);
  215657. CFRelease (urlString);
  215658. if (url != 0)
  215659. {
  215660. ok = (LSOpenCFURLRef (url, 0) == noErr);
  215661. CFRelease (url);
  215662. }
  215663. }
  215664. }
  215665. else
  215666. {
  215667. FSRef ref;
  215668. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  215669. {
  215670. if (juce_isDirectory (fileName) && parameters.isNotEmpty())
  215671. {
  215672. // if we're launching a bundled app with a document..
  215673. StringArray docs;
  215674. docs.addTokens (parameters, true);
  215675. FSRef* docRefs = new FSRef [docs.size()];
  215676. for (int i = 0; i < docs.size(); ++i)
  215677. PlatformUtilities::makeFSRefFromPath (docRefs + i, docs[i]);
  215678. LSLaunchFSRefSpec ors;
  215679. ors.appRef = &ref;
  215680. ors.numDocs = docs.size();
  215681. ors.itemRefs = docRefs;
  215682. ors.passThruParams = 0;
  215683. ors.launchFlags = kLSLaunchDefaults;
  215684. ors.asyncRefCon = 0;
  215685. FSRef actual;
  215686. ok = (LSOpenFromRefSpec (&ors, &actual) == noErr);
  215687. delete docRefs;
  215688. }
  215689. else
  215690. {
  215691. if (parameters.isNotEmpty())
  215692. ok = juce_launchExecutable (T("\"") + fileName + T("\" ") + parameters);
  215693. else
  215694. ok = (LSOpenFSRef (&ref, 0) == noErr);
  215695. }
  215696. }
  215697. }
  215698. return ok;
  215699. }
  215700. bool PlatformUtilities::makeFSSpecFromPath (FSSpec* fs, const String& path)
  215701. {
  215702. FSRef ref;
  215703. return makeFSRefFromPath (&ref, path)
  215704. && FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, fs, 0) == noErr;
  215705. }
  215706. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  215707. {
  215708. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  215709. }
  215710. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  215711. {
  215712. uint8 path [2048];
  215713. zeromem (path, sizeof (path));
  215714. String result;
  215715. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  215716. result = String::fromUTF8 (path);
  215717. return PlatformUtilities::convertToPrecomposedUnicode (result);
  215718. }
  215719. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  215720. {
  215721. FSRef fs;
  215722. if (makeFSRefFromPath (&fs, filename))
  215723. {
  215724. LSItemInfoRecord info;
  215725. if (LSCopyItemInfoForRef (&fs, kLSRequestTypeCreator, &info) == noErr)
  215726. return info.filetype;
  215727. }
  215728. return 0;
  215729. }
  215730. bool PlatformUtilities::isBundle (const String& filename)
  215731. {
  215732. FSRef fs;
  215733. if (makeFSRefFromPath (&fs, filename))
  215734. {
  215735. LSItemInfoRecord info;
  215736. if (LSCopyItemInfoForRef (&fs, kLSItemInfoIsPackage, &info) == noErr)
  215737. return (info.flags & kLSItemInfoIsPackage) != 0;
  215738. }
  215739. return false;
  215740. }
  215741. END_JUCE_NAMESPACE
  215742. /********* End of inlined file: juce_mac_Files.cpp *********/
  215743. /********* Start of inlined file: juce_mac_NamedPipe.cpp *********/
  215744. #include <sys/stat.h>
  215745. #include <sys/dir.h>
  215746. #include <fcntl.h>
  215747. // As well as being for the mac, this file is included by the linux build.
  215748. #if ! JUCE_MAC
  215749. #include <sys/wait.h>
  215750. #include <errno.h>
  215751. #include <unistd.h>
  215752. #endif
  215753. BEGIN_JUCE_NAMESPACE
  215754. struct NamedPipeInternal
  215755. {
  215756. String pipeInName, pipeOutName;
  215757. int pipeIn, pipeOut;
  215758. bool volatile createdPipe, blocked, stopReadOperation;
  215759. static void signalHandler (int) {}
  215760. };
  215761. void NamedPipe::cancelPendingReads()
  215762. {
  215763. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  215764. {
  215765. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215766. intern->stopReadOperation = true;
  215767. char buffer [1] = { 0 };
  215768. ::write (intern->pipeIn, buffer, 1);
  215769. int timeout = 2000;
  215770. while (intern->blocked && --timeout >= 0)
  215771. Thread::sleep (2);
  215772. intern->stopReadOperation = false;
  215773. }
  215774. }
  215775. void NamedPipe::close()
  215776. {
  215777. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215778. if (intern != 0)
  215779. {
  215780. internal = 0;
  215781. if (intern->pipeIn != -1)
  215782. ::close (intern->pipeIn);
  215783. if (intern->pipeOut != -1)
  215784. ::close (intern->pipeOut);
  215785. if (intern->createdPipe)
  215786. {
  215787. unlink (intern->pipeInName);
  215788. unlink (intern->pipeOutName);
  215789. }
  215790. delete intern;
  215791. }
  215792. }
  215793. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  215794. {
  215795. close();
  215796. NamedPipeInternal* const intern = new NamedPipeInternal();
  215797. internal = intern;
  215798. intern->createdPipe = createPipe;
  215799. intern->blocked = false;
  215800. intern->stopReadOperation = false;
  215801. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  215802. siginterrupt (SIGPIPE, 1);
  215803. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  215804. intern->pipeInName = pipePath + T("_in");
  215805. intern->pipeOutName = pipePath + T("_out");
  215806. intern->pipeIn = -1;
  215807. intern->pipeOut = -1;
  215808. if (createPipe)
  215809. {
  215810. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  215811. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  215812. {
  215813. delete intern;
  215814. internal = 0;
  215815. return false;
  215816. }
  215817. }
  215818. return true;
  215819. }
  215820. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  215821. {
  215822. int bytesRead = -1;
  215823. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215824. if (intern != 0)
  215825. {
  215826. intern->blocked = true;
  215827. if (intern->pipeIn == -1)
  215828. {
  215829. if (intern->createdPipe)
  215830. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  215831. else
  215832. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  215833. if (intern->pipeIn == -1)
  215834. {
  215835. intern->blocked = false;
  215836. return -1;
  215837. }
  215838. }
  215839. bytesRead = 0;
  215840. char* p = (char*) destBuffer;
  215841. while (bytesRead < maxBytesToRead)
  215842. {
  215843. const int bytesThisTime = maxBytesToRead - bytesRead;
  215844. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  215845. if (numRead <= 0 || intern->stopReadOperation)
  215846. {
  215847. bytesRead = -1;
  215848. break;
  215849. }
  215850. bytesRead += numRead;
  215851. p += bytesRead;
  215852. }
  215853. intern->blocked = false;
  215854. }
  215855. return bytesRead;
  215856. }
  215857. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  215858. {
  215859. int bytesWritten = -1;
  215860. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215861. if (intern != 0)
  215862. {
  215863. if (intern->pipeOut == -1)
  215864. {
  215865. if (intern->createdPipe)
  215866. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  215867. else
  215868. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  215869. if (intern->pipeOut == -1)
  215870. {
  215871. return -1;
  215872. }
  215873. }
  215874. const char* p = (const char*) sourceBuffer;
  215875. bytesWritten = 0;
  215876. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  215877. while (bytesWritten < numBytesToWrite
  215878. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  215879. {
  215880. const int bytesThisTime = numBytesToWrite - bytesWritten;
  215881. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  215882. if (numWritten <= 0)
  215883. {
  215884. bytesWritten = -1;
  215885. break;
  215886. }
  215887. bytesWritten += numWritten;
  215888. p += bytesWritten;
  215889. }
  215890. }
  215891. return bytesWritten;
  215892. }
  215893. END_JUCE_NAMESPACE
  215894. /********* End of inlined file: juce_mac_NamedPipe.cpp *********/
  215895. /********* Start of inlined file: juce_mac_SystemStats.mm *********/
  215896. /********* Start of inlined file: juce_mac_NativeHeaders.h *********/
  215897. #ifndef __JUCE_MAC_NATIVEHEADERS_JUCEHEADER__
  215898. #define __JUCE_MAC_NATIVEHEADERS_JUCEHEADER__
  215899. #include <Cocoa/Cocoa.h>
  215900. BEGIN_JUCE_NAMESPACE
  215901. class AutoPool
  215902. {
  215903. public:
  215904. AutoPool() { pool = [[NSAutoreleasePool alloc] init]; }
  215905. ~AutoPool() { [pool release]; }
  215906. private:
  215907. NSAutoreleasePool* pool;
  215908. };
  215909. END_JUCE_NAMESPACE
  215910. static const JUCE_NAMESPACE::String nsStringToJuce (NSString* s)
  215911. {
  215912. return JUCE_NAMESPACE::String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [s UTF8String]);
  215913. }
  215914. static NSString* juceStringToNS (const JUCE_NAMESPACE::String& s)
  215915. {
  215916. return [NSString stringWithUTF8String: (const char*) s.toUTF8()];
  215917. }
  215918. #endif
  215919. /********* End of inlined file: juce_mac_NativeHeaders.h *********/
  215920. #include <AppKit/AppKit.h>
  215921. #include <CoreAudio/HostTime.h>
  215922. #include <ctime>
  215923. #include <sys/resource.h>
  215924. BEGIN_JUCE_NAMESPACE
  215925. static int64 highResTimerFrequency;
  215926. #if JUCE_INTEL
  215927. static void juce_getCpuVendor (char* const v) throw()
  215928. {
  215929. int vendor[4];
  215930. zerostruct (vendor);
  215931. int dummy = 0;
  215932. asm ("mov %%ebx, %%esi \n\t"
  215933. "cpuid \n\t"
  215934. "xchg %%esi, %%ebx"
  215935. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  215936. memcpy (v, vendor, 16);
  215937. }
  215938. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures) throw()
  215939. {
  215940. unsigned int cpu = 0;
  215941. unsigned int ext = 0;
  215942. unsigned int family = 0;
  215943. unsigned int dummy = 0;
  215944. asm ("mov %%ebx, %%esi \n\t"
  215945. "cpuid \n\t"
  215946. "xchg %%esi, %%ebx"
  215947. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  215948. familyModel = family;
  215949. extFeatures = ext;
  215950. return cpu;
  215951. }
  215952. struct CPUFlags
  215953. {
  215954. bool hasMMX : 1;
  215955. bool hasSSE : 1;
  215956. bool hasSSE2 : 1;
  215957. bool has3DNow : 1;
  215958. };
  215959. static CPUFlags cpuFlags;
  215960. #endif
  215961. void Logger::outputDebugString (const String& text) throw()
  215962. {
  215963. String withLineFeed (text + T("\n"));
  215964. const char* const utf8 = withLineFeed.toUTF8();
  215965. fwrite (utf8, strlen (utf8), 1, stdout);
  215966. }
  215967. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  215968. {
  215969. String text;
  215970. va_list args;
  215971. va_start (args, format);
  215972. text.vprintf(format, args);
  215973. outputDebugString (text);
  215974. }
  215975. int SystemStats::getMemorySizeInMegabytes() throw()
  215976. {
  215977. long bytes;
  215978. if (Gestalt (gestaltPhysicalRAMSize, &bytes) == noErr)
  215979. return (int) (((unsigned long) bytes) / (1024 * 1024));
  215980. return 0;
  215981. }
  215982. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  215983. {
  215984. return MacOSX;
  215985. }
  215986. const String SystemStats::getOperatingSystemName() throw()
  215987. {
  215988. return T("Mac OS X");
  215989. }
  215990. bool SystemStats::isOperatingSystem64Bit() throw()
  215991. {
  215992. #if JUCE_64BIT
  215993. return true;
  215994. #else
  215995. //xxx not sure how to find this out?..
  215996. return false;
  215997. #endif
  215998. }
  215999. void SystemStats::initialiseStats() throw()
  216000. {
  216001. static bool initialised = false;
  216002. if (! initialised)
  216003. {
  216004. initialised = true;
  216005. [NSApplication sharedApplication];
  216006. NSApplicationLoad();
  216007. #if JUCE_INTEL
  216008. {
  216009. unsigned int familyModel, extFeatures;
  216010. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  216011. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  216012. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  216013. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  216014. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  216015. }
  216016. #endif
  216017. highResTimerFrequency = (int64) AudioGetHostClockFrequency();
  216018. String s (SystemStats::getJUCEVersion());
  216019. rlimit lim;
  216020. getrlimit (RLIMIT_NOFILE, &lim);
  216021. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  216022. setrlimit (RLIMIT_NOFILE, &lim);
  216023. }
  216024. }
  216025. bool SystemStats::hasMMX() throw()
  216026. {
  216027. #if JUCE_INTEL
  216028. return cpuFlags.hasMMX;
  216029. #else
  216030. return false;
  216031. #endif
  216032. }
  216033. bool SystemStats::hasSSE() throw()
  216034. {
  216035. #if JUCE_INTEL
  216036. return cpuFlags.hasSSE;
  216037. #else
  216038. return false;
  216039. #endif
  216040. }
  216041. bool SystemStats::hasSSE2() throw()
  216042. {
  216043. #if JUCE_INTEL
  216044. return cpuFlags.hasSSE2;
  216045. #else
  216046. return false;
  216047. #endif
  216048. }
  216049. bool SystemStats::has3DNow() throw()
  216050. {
  216051. #if JUCE_INTEL
  216052. return cpuFlags.has3DNow;
  216053. #else
  216054. return false;
  216055. #endif
  216056. }
  216057. const String SystemStats::getCpuVendor() throw()
  216058. {
  216059. #if JUCE_INTEL
  216060. char v [16];
  216061. juce_getCpuVendor (v);
  216062. return String (v, 16);
  216063. #else
  216064. return String::empty;
  216065. #endif
  216066. }
  216067. int SystemStats::getCpuSpeedInMegaherz() throw()
  216068. {
  216069. return GetCPUSpeed();
  216070. }
  216071. int SystemStats::getNumCpus() throw()
  216072. {
  216073. return MPProcessors();
  216074. }
  216075. static int64 juce_getMicroseconds() throw()
  216076. {
  216077. UnsignedWide t;
  216078. Microseconds (&t);
  216079. return (((int64) t.hi) << 32) | t.lo;
  216080. }
  216081. uint32 juce_millisecondsSinceStartup() throw()
  216082. {
  216083. return (uint32) (juce_getMicroseconds() / 1000);
  216084. }
  216085. double Time::getMillisecondCounterHiRes() throw()
  216086. {
  216087. // xxx might be more accurate to use a scaled AudioGetCurrentHostTime?
  216088. return juce_getMicroseconds() * 0.001;
  216089. }
  216090. int64 Time::getHighResolutionTicks() throw()
  216091. {
  216092. return (int64) AudioGetCurrentHostTime();
  216093. }
  216094. int64 Time::getHighResolutionTicksPerSecond() throw()
  216095. {
  216096. return highResTimerFrequency;
  216097. }
  216098. int64 SystemStats::getClockCycleCounter() throw()
  216099. {
  216100. jassertfalse
  216101. return 0;
  216102. }
  216103. bool Time::setSystemTimeToThisTime() const throw()
  216104. {
  216105. jassertfalse
  216106. return false;
  216107. }
  216108. int SystemStats::getPageSize() throw()
  216109. {
  216110. jassertfalse
  216111. return 512; //xxx
  216112. }
  216113. void PlatformUtilities::fpuReset()
  216114. {
  216115. }
  216116. END_JUCE_NAMESPACE
  216117. /********* End of inlined file: juce_mac_SystemStats.mm *********/
  216118. /********* Start of inlined file: juce_mac_Threads.cpp *********/
  216119. #include <pthread.h>
  216120. #include <sched.h>
  216121. #include <sys/file.h>
  216122. #include <sys/types.h>
  216123. #include <sys/sysctl.h>
  216124. BEGIN_JUCE_NAMESPACE
  216125. /*
  216126. Note that a lot of methods that you'd expect to find in this file actually
  216127. live in juce_posix_SharedCode.cpp!
  216128. */
  216129. void JUCE_API juce_threadEntryPoint (void*);
  216130. void* threadEntryProc (void* userData) throw()
  216131. {
  216132. juce_threadEntryPoint (userData);
  216133. return 0;
  216134. }
  216135. void* juce_createThread (void* userData) throw()
  216136. {
  216137. pthread_t handle = 0;
  216138. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  216139. {
  216140. pthread_detach (handle);
  216141. return (void*) handle;
  216142. }
  216143. return 0;
  216144. }
  216145. void juce_killThread (void* handle) throw()
  216146. {
  216147. if (handle != 0)
  216148. pthread_cancel ((pthread_t) handle);
  216149. }
  216150. void juce_setCurrentThreadName (const String& /*name*/) throw()
  216151. {
  216152. }
  216153. int Thread::getCurrentThreadId() throw()
  216154. {
  216155. return (int) pthread_self();
  216156. }
  216157. void juce_setThreadPriority (void* handle, int priority) throw()
  216158. {
  216159. if (handle == 0)
  216160. handle = (void*) pthread_self();
  216161. struct sched_param param;
  216162. int policy;
  216163. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  216164. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  216165. pthread_setschedparam ((pthread_t) handle, policy, &param);
  216166. }
  216167. void Thread::yield() throw()
  216168. {
  216169. sched_yield();
  216170. }
  216171. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  216172. {
  216173. // xxx
  216174. jassertfalse
  216175. }
  216176. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  216177. {
  216178. static char testResult = 0;
  216179. if (testResult == 0)
  216180. {
  216181. struct kinfo_proc info;
  216182. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  216183. size_t sz = sizeof (info);
  216184. sysctl (m, 4, &info, &sz, 0, 0);
  216185. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  216186. }
  216187. return testResult > 0;
  216188. }
  216189. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  216190. {
  216191. return juce_isRunningUnderDebugger();
  216192. }
  216193. void Process::raisePrivilege()
  216194. {
  216195. jassertfalse
  216196. }
  216197. void Process::lowerPrivilege()
  216198. {
  216199. jassertfalse
  216200. }
  216201. void Process::terminate()
  216202. {
  216203. exit (0);
  216204. }
  216205. void Process::setPriority (ProcessPriority p)
  216206. {
  216207. // xxx
  216208. }
  216209. void* Process::loadDynamicLibrary (const String& name)
  216210. {
  216211. // xxx needs to use bundles
  216212. FSSpec fs;
  216213. if (PlatformUtilities::makeFSSpecFromPath (&fs, name))
  216214. {
  216215. CFragConnectionID connID;
  216216. Ptr mainPtr;
  216217. Str255 errorMessage;
  216218. Str63 nm;
  216219. PlatformUtilities::copyToStr63 (nm, name);
  216220. const OSErr err = GetDiskFragment (&fs, 0, kCFragGoesToEOF, nm, kReferenceCFrag, &connID, &mainPtr, errorMessage);
  216221. if (err == noErr)
  216222. return (void*)connID;
  216223. }
  216224. return 0;
  216225. }
  216226. void Process::freeDynamicLibrary (void* handle)
  216227. {
  216228. if (handle != 0)
  216229. CloseConnection ((CFragConnectionID*)&handle);
  216230. }
  216231. void* Process::getProcedureEntryPoint (void* h, const String& procedureName)
  216232. {
  216233. if (h != 0)
  216234. {
  216235. CFragSymbolClass cl;
  216236. Ptr ptr;
  216237. Str255 name;
  216238. PlatformUtilities::copyToStr255 (name, procedureName);
  216239. if (FindSymbol ((CFragConnectionID) h, name, &ptr, &cl) == noErr)
  216240. {
  216241. return ptr;
  216242. }
  216243. }
  216244. return 0;
  216245. }
  216246. END_JUCE_NAMESPACE
  216247. /********* End of inlined file: juce_mac_Threads.cpp *********/
  216248. /********* Start of inlined file: juce_mac_Network.mm *********/
  216249. #include <IOKit/IOKitLib.h>
  216250. #include <IOKit/network/IOEthernetInterface.h>
  216251. #include <IOKit/network/IONetworkInterface.h>
  216252. #include <IOKit/network/IOEthernetController.h>
  216253. #include <netdb.h>
  216254. #include <arpa/inet.h>
  216255. #include <netinet/in.h>
  216256. #include <sys/types.h>
  216257. #include <sys/socket.h>
  216258. #include <sys/wait.h>
  216259. BEGIN_JUCE_NAMESPACE
  216260. /********* Start of inlined file: juce_mac_HTTPStream.h *********/
  216261. // (This file gets included by the mac + linux networking code)
  216262. /** A HTTP input stream that uses sockets.
  216263. */
  216264. class JUCE_HTTPSocketStream
  216265. {
  216266. public:
  216267. JUCE_HTTPSocketStream()
  216268. : readPosition (0),
  216269. socketHandle (-1),
  216270. levelsOfRedirection (0),
  216271. timeoutSeconds (15)
  216272. {
  216273. }
  216274. ~JUCE_HTTPSocketStream()
  216275. {
  216276. closeSocket();
  216277. }
  216278. bool open (const String& url,
  216279. const String& headers,
  216280. const MemoryBlock& postData,
  216281. const bool isPost,
  216282. URL::OpenStreamProgressCallback* callback,
  216283. void* callbackContext,
  216284. int timeOutMs)
  216285. {
  216286. closeSocket();
  216287. uint32 timeOutTime = Time::getMillisecondCounter();
  216288. if (timeOutMs == 0)
  216289. timeOutTime += 60000;
  216290. else if (timeOutMs < 0)
  216291. timeOutTime = 0xffffffff;
  216292. else
  216293. timeOutTime += timeOutMs;
  216294. String hostName, hostPath;
  216295. int hostPort;
  216296. if (! decomposeURL (url, hostName, hostPath, hostPort))
  216297. return false;
  216298. const struct hostent* host = 0;
  216299. int port = 0;
  216300. String proxyName, proxyPath;
  216301. int proxyPort = 0;
  216302. String proxyURL (getenv ("http_proxy"));
  216303. if (proxyURL.startsWithIgnoreCase (T("http://")))
  216304. {
  216305. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  216306. return false;
  216307. host = gethostbyname ((const char*) proxyName.toUTF8());
  216308. port = proxyPort;
  216309. }
  216310. else
  216311. {
  216312. host = gethostbyname ((const char*) hostName.toUTF8());
  216313. port = hostPort;
  216314. }
  216315. if (host == 0)
  216316. return false;
  216317. struct sockaddr_in address;
  216318. zerostruct (address);
  216319. memcpy ((void*) &address.sin_addr, (const void*) host->h_addr, host->h_length);
  216320. address.sin_family = host->h_addrtype;
  216321. address.sin_port = htons (port);
  216322. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  216323. if (socketHandle == -1)
  216324. return false;
  216325. int receiveBufferSize = 16384;
  216326. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  216327. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  216328. #if JUCE_MAC
  216329. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  216330. #endif
  216331. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  216332. {
  216333. closeSocket();
  216334. return false;
  216335. }
  216336. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  216337. proxyName, proxyPort,
  216338. hostPath, url,
  216339. headers, postData,
  216340. isPost));
  216341. int totalHeaderSent = 0;
  216342. while (totalHeaderSent < requestHeader.getSize())
  216343. {
  216344. if (Time::getMillisecondCounter() > timeOutTime)
  216345. {
  216346. closeSocket();
  216347. return false;
  216348. }
  216349. const int numToSend = jmin (1024, requestHeader.getSize() - totalHeaderSent);
  216350. if (send (socketHandle,
  216351. ((const char*) requestHeader.getData()) + totalHeaderSent,
  216352. numToSend, 0)
  216353. != numToSend)
  216354. {
  216355. closeSocket();
  216356. return false;
  216357. }
  216358. totalHeaderSent += numToSend;
  216359. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  216360. {
  216361. closeSocket();
  216362. return false;
  216363. }
  216364. }
  216365. const String responseHeader (readResponse (timeOutTime));
  216366. if (responseHeader.isNotEmpty())
  216367. {
  216368. //DBG (responseHeader);
  216369. StringArray lines;
  216370. lines.addLines (responseHeader);
  216371. // NB - using charToString() here instead of just T(" "), because that was
  216372. // causing a mysterious gcc internal compiler error...
  216373. const int statusCode = responseHeader.fromFirstOccurrenceOf (String::charToString (T(' ')), false, false)
  216374. .substring (0, 3)
  216375. .getIntValue();
  216376. //int contentLength = findHeaderItem (lines, T("Content-Length:")).getIntValue();
  216377. //bool isChunked = findHeaderItem (lines, T("Transfer-Encoding:")).equalsIgnoreCase ("chunked");
  216378. String location (findHeaderItem (lines, T("Location:")));
  216379. if (statusCode >= 300 && statusCode < 400
  216380. && location.isNotEmpty())
  216381. {
  216382. if (! location.startsWithIgnoreCase (T("http://")))
  216383. location = T("http://") + location;
  216384. if (levelsOfRedirection++ < 3)
  216385. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  216386. }
  216387. else
  216388. {
  216389. levelsOfRedirection = 0;
  216390. return true;
  216391. }
  216392. }
  216393. closeSocket();
  216394. return false;
  216395. }
  216396. int read (void* buffer, int bytesToRead)
  216397. {
  216398. fd_set readbits;
  216399. FD_ZERO (&readbits);
  216400. FD_SET (socketHandle, &readbits);
  216401. struct timeval tv;
  216402. tv.tv_sec = timeoutSeconds;
  216403. tv.tv_usec = 0;
  216404. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216405. return 0; // (timeout)
  216406. const int bytesRead = jmax (0, recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  216407. readPosition += bytesRead;
  216408. return bytesRead;
  216409. }
  216410. int readPosition;
  216411. juce_UseDebuggingNewOperator
  216412. private:
  216413. int socketHandle, levelsOfRedirection;
  216414. const int timeoutSeconds;
  216415. void closeSocket()
  216416. {
  216417. if (socketHandle >= 0)
  216418. close (socketHandle);
  216419. socketHandle = -1;
  216420. }
  216421. const MemoryBlock createRequestHeader (const String& hostName,
  216422. const int hostPort,
  216423. const String& proxyName,
  216424. const int proxyPort,
  216425. const String& hostPath,
  216426. const String& originalURL,
  216427. const String& headers,
  216428. const MemoryBlock& postData,
  216429. const bool isPost)
  216430. {
  216431. String header (isPost ? "POST " : "GET ");
  216432. if (proxyName.isEmpty())
  216433. {
  216434. header << hostPath << " HTTP/1.0\r\nHost: "
  216435. << hostName << ':' << hostPort;
  216436. }
  216437. else
  216438. {
  216439. header << originalURL << " HTTP/1.0\r\nHost: "
  216440. << proxyName << ':' << proxyPort;
  216441. }
  216442. header << "\r\nUser-Agent: JUCE/"
  216443. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  216444. << "\r\nConnection: Close\r\nContent-Length: "
  216445. << postData.getSize() << "\r\n"
  216446. << headers << "\r\n";
  216447. MemoryBlock mb;
  216448. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  216449. mb.append (postData.getData(), postData.getSize());
  216450. return mb;
  216451. }
  216452. const String readResponse (const uint32 timeOutTime)
  216453. {
  216454. int bytesRead = 0, numConsecutiveLFs = 0;
  216455. MemoryBlock buffer (1024, true);
  216456. while (numConsecutiveLFs < 2 && bytesRead < 32768
  216457. && Time::getMillisecondCounter() <= timeOutTime)
  216458. {
  216459. fd_set readbits;
  216460. FD_ZERO (&readbits);
  216461. FD_SET (socketHandle, &readbits);
  216462. struct timeval tv;
  216463. tv.tv_sec = timeoutSeconds;
  216464. tv.tv_usec = 0;
  216465. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216466. return String::empty; // (timeout)
  216467. buffer.ensureSize (bytesRead + 8, true);
  216468. char* const dest = (char*) buffer.getData() + bytesRead;
  216469. if (recv (socketHandle, dest, 1, 0) == -1)
  216470. return String::empty;
  216471. const char lastByte = *dest;
  216472. ++bytesRead;
  216473. if (lastByte == '\n')
  216474. ++numConsecutiveLFs;
  216475. else if (lastByte != '\r')
  216476. numConsecutiveLFs = 0;
  216477. }
  216478. const String header (String::fromUTF8 ((const uint8*) buffer.getData()));
  216479. if (header.startsWithIgnoreCase (T("HTTP/")))
  216480. return header.trimEnd();
  216481. return String::empty;
  216482. }
  216483. static bool decomposeURL (const String& url,
  216484. String& host, String& path, int& port)
  216485. {
  216486. if (! url.startsWithIgnoreCase (T("http://")))
  216487. return false;
  216488. const int nextSlash = url.indexOfChar (7, '/');
  216489. int nextColon = url.indexOfChar (7, ':');
  216490. if (nextColon > nextSlash && nextSlash > 0)
  216491. nextColon = -1;
  216492. if (nextColon >= 0)
  216493. {
  216494. host = url.substring (7, nextColon);
  216495. if (nextSlash >= 0)
  216496. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  216497. else
  216498. port = url.substring (nextColon + 1).getIntValue();
  216499. }
  216500. else
  216501. {
  216502. port = 80;
  216503. if (nextSlash >= 0)
  216504. host = url.substring (7, nextSlash);
  216505. else
  216506. host = url.substring (7);
  216507. }
  216508. if (nextSlash >= 0)
  216509. path = url.substring (nextSlash);
  216510. else
  216511. path = T("/");
  216512. return true;
  216513. }
  216514. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  216515. {
  216516. for (int i = 0; i < lines.size(); ++i)
  216517. if (lines[i].startsWithIgnoreCase (itemName))
  216518. return lines[i].substring (itemName.length()).trim();
  216519. return String::empty;
  216520. }
  216521. };
  216522. bool juce_isOnLine()
  216523. {
  216524. return true;
  216525. }
  216526. void* juce_openInternetFile (const String& url,
  216527. const String& headers,
  216528. const MemoryBlock& postData,
  216529. const bool isPost,
  216530. URL::OpenStreamProgressCallback* callback,
  216531. void* callbackContext,
  216532. int timeOutMs)
  216533. {
  216534. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  216535. if (s->open (url, headers, postData, isPost,
  216536. callback, callbackContext, timeOutMs))
  216537. return s;
  216538. delete s;
  216539. return 0;
  216540. }
  216541. void juce_closeInternetFile (void* handle)
  216542. {
  216543. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  216544. if (s != 0)
  216545. delete s;
  216546. }
  216547. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  216548. {
  216549. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  216550. if (s != 0)
  216551. return s->read (buffer, bytesToRead);
  216552. return 0;
  216553. }
  216554. int juce_seekInInternetFile (void* handle, int newPosition)
  216555. {
  216556. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  216557. if (s != 0)
  216558. return s->readPosition;
  216559. return 0;
  216560. }
  216561. /********* End of inlined file: juce_mac_HTTPStream.h *********/
  216562. static bool GetEthernetIterator (io_iterator_t* matchingServices) throw()
  216563. {
  216564. mach_port_t masterPort;
  216565. if (IOMasterPort (MACH_PORT_NULL, &masterPort) == KERN_SUCCESS)
  216566. {
  216567. CFMutableDictionaryRef dict = IOServiceMatching (kIOEthernetInterfaceClass);
  216568. if (dict != 0)
  216569. {
  216570. CFMutableDictionaryRef propDict = CFDictionaryCreateMutable (kCFAllocatorDefault,
  216571. 0,
  216572. &kCFTypeDictionaryKeyCallBacks,
  216573. &kCFTypeDictionaryValueCallBacks);
  216574. if (propDict != 0)
  216575. {
  216576. CFDictionarySetValue (propDict, CFSTR (kIOPrimaryInterface), kCFBooleanTrue);
  216577. CFDictionarySetValue (dict, CFSTR (kIOPropertyMatchKey), propDict);
  216578. CFRelease (propDict);
  216579. }
  216580. }
  216581. return IOServiceGetMatchingServices (masterPort, dict, matchingServices) == KERN_SUCCESS;
  216582. }
  216583. return false;
  216584. }
  216585. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  216586. {
  216587. int numResults = 0;
  216588. io_iterator_t it;
  216589. if (GetEthernetIterator (&it))
  216590. {
  216591. io_object_t i;
  216592. while ((i = IOIteratorNext (it)) != 0)
  216593. {
  216594. io_object_t controller;
  216595. if (IORegistryEntryGetParentEntry (i, kIOServicePlane, &controller) == KERN_SUCCESS)
  216596. {
  216597. CFTypeRef data = IORegistryEntryCreateCFProperty (controller,
  216598. CFSTR (kIOMACAddress),
  216599. kCFAllocatorDefault,
  216600. 0);
  216601. if (data != 0)
  216602. {
  216603. UInt8 addr [kIOEthernetAddressSize];
  216604. zeromem (addr, sizeof (addr));
  216605. CFDataGetBytes ((CFDataRef) data, CFRangeMake (0, sizeof (addr)), addr);
  216606. CFRelease (data);
  216607. int64 a = 0;
  216608. for (int i = 6; --i >= 0;)
  216609. a = (a << 8) | addr[i];
  216610. if (! littleEndian)
  216611. a = (int64) swapByteOrder ((uint64) a);
  216612. if (numResults < maxNum)
  216613. {
  216614. *addresses++ = a;
  216615. ++numResults;
  216616. }
  216617. }
  216618. IOObjectRelease (controller);
  216619. }
  216620. IOObjectRelease (i);
  216621. }
  216622. IOObjectRelease (it);
  216623. }
  216624. return numResults;
  216625. }
  216626. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  216627. const String& emailSubject,
  216628. const String& bodyText,
  216629. const StringArray& filesToAttach)
  216630. {
  216631. const AutoPool pool;
  216632. String script;
  216633. script << "tell application \"Mail\"\r\n"
  216634. "set newMessage to make new outgoing message with properties {subject:\""
  216635. << emailSubject.replace (T("\""), T("\\\""))
  216636. << "\", content:\""
  216637. << bodyText.replace (T("\""), T("\\\""))
  216638. << "\" & return & return}\r\n"
  216639. "tell newMessage\r\n"
  216640. "set visible to true\r\n"
  216641. "set sender to \"sdfsdfsdfewf\"\r\n"
  216642. "make new to recipient at end of to recipients with properties {address:\""
  216643. << targetEmailAddress
  216644. << "\"}\r\n";
  216645. for (int i = 0; i < filesToAttach.size(); ++i)
  216646. {
  216647. script << "tell content\r\n"
  216648. "make new attachment with properties {file name:\""
  216649. << filesToAttach[i].replace (T("\""), T("\\\""))
  216650. << "\"} at after the last paragraph\r\n"
  216651. "end tell\r\n";
  216652. }
  216653. script << "end tell\r\n"
  216654. "end tell\r\n";
  216655. NSAppleScript* s = [[NSAppleScript alloc]
  216656. initWithSource: [NSString stringWithUTF8String: (const char*) script.toUTF8()]];
  216657. NSDictionary* error = 0;
  216658. const bool ok = [s executeAndReturnError: &error] != nil;
  216659. [s release];
  216660. return ok;
  216661. }
  216662. END_JUCE_NAMESPACE
  216663. /********* End of inlined file: juce_mac_Network.mm *********/
  216664. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  216665. /********* Start of inlined file: juce_mac_AudioCDBurner.mm *********/
  216666. #if JUCE_USE_CDBURNER
  216667. #import <DiscRecording/DiscRecording.h>
  216668. BEGIN_JUCE_NAMESPACE
  216669. END_JUCE_NAMESPACE
  216670. @interface OpenDiskDevice : NSObject
  216671. {
  216672. DRDevice* device;
  216673. NSMutableArray* tracks;
  216674. }
  216675. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device;
  216676. - (void) dealloc;
  216677. - (bool) isDiskPresent;
  216678. - (int) getNumAvailableAudioBlocks;
  216679. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  216680. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  216681. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting;
  216682. @end
  216683. @interface AudioTrackProducer : NSObject
  216684. {
  216685. JUCE_NAMESPACE::AudioSource* source;
  216686. int readPosition, lengthInFrames;
  216687. }
  216688. - (AudioTrackProducer*) init: (int) lengthInFrames;
  216689. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  216690. - (void) dealloc;
  216691. - (void) setupTrackProperties: (DRTrack*) track;
  216692. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  216693. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  216694. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  216695. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  216696. toMedia:(NSDictionary*)mediaInfo;
  216697. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  216698. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  216699. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  216700. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  216701. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  216702. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  216703. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  216704. ioFlags:(uint32_t*)flags;
  216705. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  216706. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  216707. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  216708. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  216709. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  216710. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  216711. ioFlags:(uint32_t*)flags;
  216712. @end
  216713. @implementation OpenDiskDevice
  216714. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device_
  216715. {
  216716. [super init];
  216717. device = device_;
  216718. tracks = [[NSMutableArray alloc] init];
  216719. return self;
  216720. }
  216721. - (void) dealloc
  216722. {
  216723. [tracks release];
  216724. [super dealloc];
  216725. }
  216726. - (bool) isDiskPresent
  216727. {
  216728. return [device isValid]
  216729. && [[[device status] objectForKey: DRDeviceMediaStateKey]
  216730. isEqualTo: DRDeviceMediaStateMediaPresent];
  216731. }
  216732. - (int) getNumAvailableAudioBlocks
  216733. {
  216734. return [[[[device status] objectForKey: DRDeviceMediaInfoKey]
  216735. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  216736. }
  216737. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  216738. {
  216739. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  216740. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  216741. [p setupTrackProperties: t];
  216742. [tracks addObject: t];
  216743. [t release];
  216744. [p release];
  216745. }
  216746. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  216747. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting
  216748. {
  216749. DRBurn* burn = [DRBurn burnForDevice: device];
  216750. if (! [device acquireExclusiveAccess])
  216751. {
  216752. *error = "Couldn't open or write to the CD device";
  216753. return;
  216754. }
  216755. [device acquireMediaReservation];
  216756. NSMutableDictionary* d = [[burn properties] mutableCopy];
  216757. [d autorelease];
  216758. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  216759. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  216760. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount)
  216761. forKey: DRBurnCompletionActionKey];
  216762. [burn setProperties: d];
  216763. [burn writeLayout: tracks];
  216764. for (;;)
  216765. {
  216766. JUCE_NAMESPACE::Thread::sleep (300);
  216767. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  216768. NSLog ([[burn status] description]);
  216769. if (listener != 0 && listener->audioCDBurnProgress (progress))
  216770. {
  216771. [burn abort];
  216772. *error = "User cancelled the write operation";
  216773. break;
  216774. }
  216775. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  216776. {
  216777. *error = "Write operation failed";
  216778. break;
  216779. }
  216780. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  216781. {
  216782. break;
  216783. }
  216784. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  216785. objectForKey: DRErrorStatusErrorStringKey];
  216786. if ([err length] > 0)
  216787. {
  216788. *error = JUCE_NAMESPACE::String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [err UTF8String]);
  216789. break;
  216790. }
  216791. }
  216792. [device releaseMediaReservation];
  216793. [device releaseExclusiveAccess];
  216794. }
  216795. @end
  216796. @implementation AudioTrackProducer
  216797. - (AudioTrackProducer*) init: (int) lengthInFrames_
  216798. {
  216799. lengthInFrames = lengthInFrames_;
  216800. readPosition = 0;
  216801. return self;
  216802. }
  216803. - (void) setupTrackProperties: (DRTrack*) track
  216804. {
  216805. NSMutableDictionary* p = [[track properties] mutableCopy];
  216806. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  216807. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  216808. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  216809. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  216810. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  216811. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  216812. [track setProperties: p];
  216813. [p release];
  216814. }
  216815. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  216816. {
  216817. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  216818. if (s != nil)
  216819. s->source = source_;
  216820. return s;
  216821. }
  216822. - (void) dealloc
  216823. {
  216824. if (source != 0)
  216825. {
  216826. source->releaseResources();
  216827. delete source;
  216828. }
  216829. [super dealloc];
  216830. }
  216831. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  216832. {
  216833. }
  216834. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track
  216835. {
  216836. return true;
  216837. }
  216838. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track
  216839. {
  216840. return lengthInFrames;
  216841. }
  216842. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  216843. toMedia:(NSDictionary*)mediaInfo
  216844. {
  216845. if (source != 0)
  216846. source->prepareToPlay (44100 / 75, 44100);
  216847. readPosition = 0;
  216848. return true;
  216849. }
  216850. - (BOOL) prepareTrackForVerification:(DRTrack*)track
  216851. {
  216852. if (source != 0)
  216853. source->prepareToPlay (44100 / 75, 44100);
  216854. return true;
  216855. }
  216856. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  216857. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  216858. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags
  216859. {
  216860. if (source != 0)
  216861. {
  216862. const int numSamples = JUCE_NAMESPACE::jmin (bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  216863. if (numSamples > 0)
  216864. {
  216865. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  216866. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  216867. info.buffer = &tempBuffer;
  216868. info.startSample = 0;
  216869. info.numSamples = numSamples;
  216870. source->getNextAudioBlock (info);
  216871. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  216872. buffer, numSamples, 4);
  216873. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  216874. buffer + 2, numSamples, 4);
  216875. readPosition += numSamples;
  216876. }
  216877. return numSamples * 4;
  216878. }
  216879. return 0;
  216880. }
  216881. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  216882. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  216883. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  216884. ioFlags:(uint32_t*)flags
  216885. {
  216886. zeromem (buffer, bufferLength);
  216887. return bufferLength;
  216888. }
  216889. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  216890. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  216891. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags
  216892. {
  216893. return true;
  216894. }
  216895. @end
  216896. BEGIN_JUCE_NAMESPACE
  216897. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  216898. : internal (0)
  216899. {
  216900. const AutoPool pool;
  216901. OpenDiskDevice* dev = [[OpenDiskDevice alloc] initWithDevice: [[DRDevice devices] objectAtIndex: deviceIndex]];
  216902. internal = (void*) dev;
  216903. }
  216904. AudioCDBurner::~AudioCDBurner()
  216905. {
  216906. const AutoPool pool;
  216907. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216908. if (dev != 0)
  216909. [dev release];
  216910. }
  216911. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  216912. {
  216913. const AutoPool pool;
  216914. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  216915. if (b->internal == 0)
  216916. deleteAndZero (b);
  216917. return b;
  216918. }
  216919. static NSArray* findDiskBurnerDevices()
  216920. {
  216921. NSMutableArray* results = [NSMutableArray array];
  216922. NSArray* devs = [DRDevice devices];
  216923. if (devs != 0)
  216924. {
  216925. int num = [devs count];
  216926. int i;
  216927. for (i = 0; i < num; ++i)
  216928. {
  216929. NSDictionary* dic = [[devs objectAtIndex: i] info];
  216930. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  216931. if (name != nil)
  216932. [results addObject: name];
  216933. }
  216934. }
  216935. return results;
  216936. }
  216937. const StringArray AudioCDBurner::findAvailableDevices()
  216938. {
  216939. const AutoPool pool;
  216940. NSArray* names = findDiskBurnerDevices();
  216941. StringArray s;
  216942. for (int i = 0; i < [names count]; ++i)
  216943. s.add (String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [[names objectAtIndex: i] UTF8String]));
  216944. return s;
  216945. }
  216946. bool AudioCDBurner::isDiskPresent() const
  216947. {
  216948. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216949. return dev != 0 && [dev isDiskPresent];
  216950. }
  216951. int AudioCDBurner::getNumAvailableAudioBlocks() const
  216952. {
  216953. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216954. return [dev getNumAvailableAudioBlocks];
  216955. }
  216956. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  216957. {
  216958. const AutoPool pool;
  216959. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216960. if (dev != 0)
  216961. {
  216962. [dev addSourceTrack: source numSamples: numSamps];
  216963. return true;
  216964. }
  216965. return false;
  216966. }
  216967. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  216968. const bool ejectDiscAfterwards,
  216969. const bool peformFakeBurnForTesting)
  216970. {
  216971. const AutoPool pool;
  216972. JUCE_NAMESPACE::String error ("Couldn't open or write to the CD device");
  216973. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216974. if (dev != 0)
  216975. {
  216976. error = JUCE_NAMESPACE::String::empty;
  216977. [dev burn: listener
  216978. errorString: &error
  216979. ejectAfterwards: ejectDiscAfterwards
  216980. isFake: peformFakeBurnForTesting];
  216981. }
  216982. return error;
  216983. }
  216984. END_JUCE_NAMESPACE
  216985. #endif
  216986. /********* End of inlined file: juce_mac_AudioCDBurner.mm *********/
  216987. /********* Start of inlined file: juce_mac_CoreAudio.cpp *********/
  216988. #include <CoreAudio/AudioHardware.h>
  216989. BEGIN_JUCE_NAMESPACE
  216990. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  216991. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  216992. #endif
  216993. #undef log
  216994. #if JUCE_COREAUDIO_LOGGING_ENABLED
  216995. #define log(a) Logger::writeToLog (a)
  216996. #else
  216997. #define log(a)
  216998. #endif
  216999. #undef OK
  217000. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  217001. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  217002. {
  217003. if (err == noErr)
  217004. return true;
  217005. Logger::writeToLog (T("CoreAudio error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  217006. jassertfalse
  217007. return false;
  217008. }
  217009. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  217010. #else
  217011. #define OK(a) (a == noErr)
  217012. #endif
  217013. static const int maxNumChans = 96;
  217014. class CoreAudioInternal : public Timer
  217015. {
  217016. public:
  217017. CoreAudioInternal (AudioDeviceID id)
  217018. : deviceID (id),
  217019. started (false),
  217020. audioBuffer (0),
  217021. numInputChans (0),
  217022. numOutputChans (0),
  217023. callbacksAllowed (true),
  217024. numInputChannelInfos (0),
  217025. numOutputChannelInfos (0),
  217026. inputLatency (0),
  217027. outputLatency (0),
  217028. callback (0),
  217029. inputDevice (0),
  217030. isSlaveDevice (false)
  217031. {
  217032. sampleRate = 0;
  217033. bufferSize = 512;
  217034. if (deviceID == 0)
  217035. {
  217036. error = TRANS("can't open device");
  217037. }
  217038. else
  217039. {
  217040. updateDetailsFromDevice();
  217041. AudioDeviceAddPropertyListener (deviceID,
  217042. kAudioPropertyWildcardChannel,
  217043. kAudioPropertyWildcardSection,
  217044. kAudioPropertyWildcardPropertyID,
  217045. deviceListenerProc, this);
  217046. }
  217047. }
  217048. ~CoreAudioInternal()
  217049. {
  217050. AudioDeviceRemovePropertyListener (deviceID,
  217051. kAudioPropertyWildcardChannel,
  217052. kAudioPropertyWildcardSection,
  217053. kAudioPropertyWildcardPropertyID,
  217054. deviceListenerProc);
  217055. stop (false);
  217056. juce_free (audioBuffer);
  217057. delete inputDevice;
  217058. }
  217059. void setTempBufferSize (const int numChannels, const int numSamples)
  217060. {
  217061. juce_free (audioBuffer);
  217062. audioBuffer = (float*) juce_calloc (32 + numChannels * numSamples * sizeof (float));
  217063. zeromem (tempInputBuffers, sizeof (tempInputBuffers));
  217064. zeromem (tempOutputBuffers, sizeof (tempOutputBuffers));
  217065. int count = 0;
  217066. int i;
  217067. for (i = 0; i < numInputChans; ++i)
  217068. tempInputBuffers[i] = audioBuffer + count++ * numSamples;
  217069. for (i = 0; i < numOutputChans; ++i)
  217070. tempOutputBuffers[i] = audioBuffer + count++ * numSamples;
  217071. }
  217072. // returns the number of actual available channels
  217073. void fillInChannelInfo (bool input)
  217074. {
  217075. int chanNum = 0, activeChans = 0;
  217076. UInt32 size;
  217077. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, 0)))
  217078. {
  217079. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  217080. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, bufList)))
  217081. {
  217082. const int numStreams = bufList->mNumberBuffers;
  217083. for (int i = 0; i < numStreams; ++i)
  217084. {
  217085. const AudioBuffer& b = bufList->mBuffers[i];
  217086. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  217087. {
  217088. if (input)
  217089. {
  217090. if (activeInputChans[chanNum])
  217091. {
  217092. inputChannelInfo [activeChans].sourceChannelNum = chanNum;
  217093. inputChannelInfo [activeChans].streamNum = i;
  217094. inputChannelInfo [activeChans].dataOffsetSamples = j;
  217095. inputChannelInfo [activeChans].dataStrideSamples = b.mNumberChannels;
  217096. ++activeChans;
  217097. numInputChannelInfos = activeChans;
  217098. }
  217099. inChanNames.add (T("input ") + String (chanNum + 1));
  217100. }
  217101. else
  217102. {
  217103. if (activeOutputChans[chanNum])
  217104. {
  217105. outputChannelInfo [activeChans].sourceChannelNum = chanNum;
  217106. outputChannelInfo [activeChans].streamNum = i;
  217107. outputChannelInfo [activeChans].dataOffsetSamples = j;
  217108. outputChannelInfo [activeChans].dataStrideSamples = b.mNumberChannels;
  217109. ++activeChans;
  217110. numOutputChannelInfos = activeChans;
  217111. }
  217112. outChanNames.add (T("output ") + String (chanNum + 1));
  217113. }
  217114. ++chanNum;
  217115. }
  217116. }
  217117. }
  217118. juce_free (bufList);
  217119. }
  217120. }
  217121. void updateDetailsFromDevice()
  217122. {
  217123. stopTimer();
  217124. if (deviceID == 0)
  217125. return;
  217126. const ScopedLock sl (callbackLock);
  217127. Float64 sr;
  217128. UInt32 size = sizeof (Float64);
  217129. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyNominalSampleRate, &size, &sr)))
  217130. sampleRate = sr;
  217131. UInt32 framesPerBuf;
  217132. size = sizeof (framesPerBuf);
  217133. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyBufferFrameSize, &size, &framesPerBuf)))
  217134. {
  217135. bufferSize = framesPerBuf;
  217136. if (bufferSize > 0)
  217137. setTempBufferSize (numInputChans + numOutputChans, bufferSize);
  217138. }
  217139. bufferSizes.clear();
  217140. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyBufferFrameSizeRange, &size, 0)))
  217141. {
  217142. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  217143. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyBufferFrameSizeRange, &size, ranges)))
  217144. {
  217145. bufferSizes.add ((int) ranges[0].mMinimum);
  217146. for (int i = 32; i < 8192; i += 32)
  217147. {
  217148. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  217149. {
  217150. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  217151. {
  217152. bufferSizes.addIfNotAlreadyThere (i);
  217153. break;
  217154. }
  217155. }
  217156. }
  217157. if (bufferSize > 0)
  217158. bufferSizes.addIfNotAlreadyThere (bufferSize);
  217159. }
  217160. juce_free (ranges);
  217161. }
  217162. if (bufferSizes.size() == 0 && bufferSize > 0)
  217163. bufferSizes.add (bufferSize);
  217164. sampleRates.clear();
  217165. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  217166. String rates;
  217167. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyAvailableNominalSampleRates, &size, 0)))
  217168. {
  217169. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  217170. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyAvailableNominalSampleRates, &size, ranges)))
  217171. {
  217172. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  217173. {
  217174. bool ok = false;
  217175. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  217176. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  217177. ok = true;
  217178. if (ok)
  217179. {
  217180. sampleRates.add (possibleRates[i]);
  217181. rates << possibleRates[i] << T(" ");
  217182. }
  217183. }
  217184. }
  217185. juce_free (ranges);
  217186. }
  217187. if (sampleRates.size() == 0 && sampleRate > 0)
  217188. {
  217189. sampleRates.add (sampleRate);
  217190. rates << sampleRate;
  217191. }
  217192. log (T("sr: ") + rates);
  217193. inputLatency = 0;
  217194. outputLatency = 0;
  217195. UInt32 lat;
  217196. size = sizeof (UInt32);
  217197. if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  217198. inputLatency = (int) lat;
  217199. if (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  217200. outputLatency = (int) lat;
  217201. log (T("lat: ") + String (inputLatency) + T(" ") + String (outputLatency));
  217202. inChanNames.clear();
  217203. outChanNames.clear();
  217204. zeromem (inputChannelInfo, sizeof (inputChannelInfo));
  217205. zeromem (outputChannelInfo, sizeof (outputChannelInfo));
  217206. fillInChannelInfo (true);
  217207. fillInChannelInfo (false);
  217208. }
  217209. const StringArray getSources (bool input)
  217210. {
  217211. StringArray s;
  217212. int num = 0;
  217213. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  217214. if (types != 0)
  217215. {
  217216. for (int i = 0; i < num; ++i)
  217217. {
  217218. AudioValueTranslation avt;
  217219. char buffer[256];
  217220. avt.mInputData = (void*) &(types[i]);
  217221. avt.mInputDataSize = sizeof (UInt32);
  217222. avt.mOutputData = buffer;
  217223. avt.mOutputDataSize = 256;
  217224. UInt32 transSize = sizeof (avt);
  217225. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSourceNameForID, &transSize, &avt)))
  217226. {
  217227. DBG (buffer);
  217228. s.add (buffer);
  217229. }
  217230. }
  217231. juce_free (types);
  217232. }
  217233. return s;
  217234. }
  217235. int getCurrentSourceIndex (bool input) const
  217236. {
  217237. OSType currentSourceID = 0;
  217238. UInt32 size = 0;
  217239. int result = -1;
  217240. if (deviceID != 0
  217241. && OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyDataSource, &size, 0)))
  217242. {
  217243. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSource, &size, &currentSourceID)))
  217244. {
  217245. int num = 0;
  217246. OSType* const types = getAllDataSourcesForDevice (deviceID, input, num);
  217247. if (types != 0)
  217248. {
  217249. for (int i = 0; i < num; ++i)
  217250. {
  217251. if (types[num] == currentSourceID)
  217252. {
  217253. result = i;
  217254. break;
  217255. }
  217256. }
  217257. juce_free (types);
  217258. }
  217259. }
  217260. }
  217261. return result;
  217262. }
  217263. void setCurrentSourceIndex (int index, bool input)
  217264. {
  217265. if (deviceID != 0)
  217266. {
  217267. int num = 0;
  217268. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  217269. if (types != 0)
  217270. {
  217271. if (((unsigned int) index) < num)
  217272. {
  217273. OSType typeId = types[index];
  217274. AudioDeviceSetProperty (deviceID, 0, 0, input, kAudioDevicePropertyDataSource, sizeof (typeId), &typeId);
  217275. }
  217276. juce_free (types);
  217277. }
  217278. }
  217279. }
  217280. const String reopen (const BitArray& inputChannels,
  217281. const BitArray& outputChannels,
  217282. double newSampleRate,
  217283. int bufferSizeSamples)
  217284. {
  217285. error = String::empty;
  217286. log ("CoreAudio reopen");
  217287. callbacksAllowed = false;
  217288. stopTimer();
  217289. stop (false);
  217290. activeInputChans = inputChannels;
  217291. activeOutputChans = outputChannels;
  217292. activeInputChans.setRange (inChanNames.size(),
  217293. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  217294. false);
  217295. activeOutputChans.setRange (outChanNames.size(),
  217296. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  217297. false);
  217298. numInputChans = activeInputChans.countNumberOfSetBits();
  217299. numOutputChans = activeOutputChans.countNumberOfSetBits();
  217300. // set sample rate
  217301. Float64 sr = newSampleRate;
  217302. UInt32 size = sizeof (sr);
  217303. OK (AudioDeviceSetProperty (deviceID, 0, 0, false, kAudioDevicePropertyNominalSampleRate, size, &sr));
  217304. OK (AudioDeviceSetProperty (deviceID, 0, 0, true, kAudioDevicePropertyNominalSampleRate, size, &sr));
  217305. // change buffer size
  217306. UInt32 framesPerBuf = bufferSizeSamples;
  217307. size = sizeof (framesPerBuf);
  217308. OK (AudioDeviceSetProperty (deviceID, 0, 0, false, kAudioDevicePropertyBufferFrameSize, size, &framesPerBuf));
  217309. OK (AudioDeviceSetProperty (deviceID, 0, 0, true, kAudioDevicePropertyBufferFrameSize, size, &framesPerBuf));
  217310. // wait for the changes to happen (on some devices)
  217311. int i = 30;
  217312. while (--i >= 0)
  217313. {
  217314. updateDetailsFromDevice();
  217315. if (sampleRate == newSampleRate && bufferSizeSamples == bufferSize)
  217316. break;
  217317. Thread::sleep (100);
  217318. }
  217319. if (i < 0)
  217320. error = "Couldn't change sample rate/buffer size";
  217321. if (sampleRates.size() == 0)
  217322. error = "Device has no available sample-rates";
  217323. if (bufferSizes.size() == 0)
  217324. error = "Device has no available buffer-sizes";
  217325. if (inputDevice != 0 && error.isEmpty())
  217326. error = inputDevice->reopen (inputChannels,
  217327. outputChannels,
  217328. newSampleRate,
  217329. bufferSizeSamples);
  217330. callbacksAllowed = true;
  217331. return error;
  217332. }
  217333. bool start (AudioIODeviceCallback* cb)
  217334. {
  217335. if (! started)
  217336. {
  217337. callback = 0;
  217338. if (deviceID != 0)
  217339. {
  217340. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, (void*) this)))
  217341. {
  217342. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  217343. {
  217344. started = true;
  217345. }
  217346. else
  217347. {
  217348. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  217349. }
  217350. }
  217351. }
  217352. }
  217353. if (started)
  217354. {
  217355. const ScopedLock sl (callbackLock);
  217356. callback = cb;
  217357. }
  217358. if (inputDevice != 0)
  217359. return started && inputDevice->start (cb);
  217360. else
  217361. return started;
  217362. }
  217363. void stop (bool leaveInterruptRunning)
  217364. {
  217365. callbackLock.enter();
  217366. callback = 0;
  217367. callbackLock.exit();
  217368. if (started
  217369. && (deviceID != 0)
  217370. && ! leaveInterruptRunning)
  217371. {
  217372. OK (AudioDeviceStop (deviceID, audioIOProc));
  217373. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  217374. started = false;
  217375. callbackLock.enter();
  217376. callbackLock.exit();
  217377. // wait until it's definately stopped calling back..
  217378. for (int i = 40; --i >= 0;)
  217379. {
  217380. Thread::sleep (50);
  217381. UInt32 running = 0;
  217382. UInt32 size = sizeof (running);
  217383. OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyDeviceIsRunning, &size, &running));
  217384. if (running == 0)
  217385. break;
  217386. }
  217387. callbackLock.enter();
  217388. callbackLock.exit();
  217389. }
  217390. if (inputDevice != 0)
  217391. inputDevice->stop (leaveInterruptRunning);
  217392. }
  217393. double getSampleRate() const
  217394. {
  217395. return sampleRate;
  217396. }
  217397. int getBufferSize() const
  217398. {
  217399. return bufferSize;
  217400. }
  217401. void audioCallback (const AudioBufferList* inInputData,
  217402. AudioBufferList* outOutputData)
  217403. {
  217404. int i;
  217405. const ScopedLock sl (callbackLock);
  217406. if (callback != 0)
  217407. {
  217408. if (inputDevice == 0)
  217409. {
  217410. for (i = numInputChans; --i >= 0;)
  217411. {
  217412. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  217413. float* dest = tempInputBuffers [info.sourceChannelNum];
  217414. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  217415. + info.dataOffsetSamples;
  217416. const int stride = info.dataStrideSamples;
  217417. if (stride != 0) // if this is zero, info is invalid
  217418. {
  217419. for (int j = bufferSize; --j >= 0;)
  217420. {
  217421. *dest++ = *src;
  217422. src += stride;
  217423. }
  217424. }
  217425. }
  217426. }
  217427. if (! isSlaveDevice)
  217428. {
  217429. if (inputDevice == 0)
  217430. {
  217431. callback->audioDeviceIOCallback ((const float**) tempInputBuffers,
  217432. numInputChans,
  217433. tempOutputBuffers,
  217434. numOutputChans,
  217435. bufferSize);
  217436. }
  217437. else
  217438. {
  217439. jassert (inputDevice->bufferSize == bufferSize);
  217440. callback->audioDeviceIOCallback ((const float**) inputDevice->tempInputBuffers,
  217441. inputDevice->numInputChans,
  217442. tempOutputBuffers,
  217443. numOutputChans,
  217444. bufferSize);
  217445. }
  217446. for (i = numOutputChans; --i >= 0;)
  217447. {
  217448. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  217449. const float* src = tempOutputBuffers [i];
  217450. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  217451. + info.dataOffsetSamples;
  217452. const int stride = info.dataStrideSamples;
  217453. if (stride != 0) // if this is zero, info is invalid
  217454. {
  217455. for (int j = bufferSize; --j >= 0;)
  217456. {
  217457. *dest = *src++;
  217458. dest += stride;
  217459. }
  217460. }
  217461. }
  217462. }
  217463. }
  217464. else
  217465. {
  217466. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  217467. {
  217468. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  217469. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  217470. + info.dataOffsetSamples;
  217471. const int stride = info.dataStrideSamples;
  217472. if (stride != 0) // if this is zero, info is invalid
  217473. {
  217474. for (int j = bufferSize; --j >= 0;)
  217475. {
  217476. *dest = 0.0f;
  217477. dest += stride;
  217478. }
  217479. }
  217480. }
  217481. }
  217482. }
  217483. // called by callbacks
  217484. void deviceDetailsChanged()
  217485. {
  217486. if (callbacksAllowed)
  217487. startTimer (100);
  217488. }
  217489. void timerCallback()
  217490. {
  217491. stopTimer();
  217492. log ("CoreAudio device changed callback");
  217493. const double oldSampleRate = sampleRate;
  217494. const int oldBufferSize = bufferSize;
  217495. updateDetailsFromDevice();
  217496. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  217497. {
  217498. callbacksAllowed = false;
  217499. stop (false);
  217500. updateDetailsFromDevice();
  217501. callbacksAllowed = true;
  217502. }
  217503. }
  217504. CoreAudioInternal* getRelatedDevice() const
  217505. {
  217506. UInt32 size = 0;
  217507. CoreAudioInternal* result = 0;
  217508. if (deviceID != 0
  217509. && AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyRelatedDevices, &size, 0) == noErr
  217510. && size > 0)
  217511. {
  217512. AudioDeviceID* devs = (AudioDeviceID*) juce_calloc (size);
  217513. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyRelatedDevices, &size, devs)))
  217514. {
  217515. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  217516. {
  217517. if (devs[i] != deviceID && devs[i] != 0)
  217518. {
  217519. result = new CoreAudioInternal (devs[i]);
  217520. if (result->error.isEmpty())
  217521. {
  217522. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  217523. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  217524. if (thisIsInput != otherIsInput
  217525. || (inChanNames.size() + outChanNames.size() == 0)
  217526. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  217527. break;
  217528. }
  217529. deleteAndZero (result);
  217530. }
  217531. }
  217532. }
  217533. juce_free (devs);
  217534. }
  217535. return result;
  217536. }
  217537. juce_UseDebuggingNewOperator
  217538. String error;
  217539. int inputLatency, outputLatency;
  217540. BitArray activeInputChans, activeOutputChans;
  217541. StringArray inChanNames, outChanNames;
  217542. Array <double> sampleRates;
  217543. Array <int> bufferSizes;
  217544. AudioIODeviceCallback* callback;
  217545. CoreAudioInternal* inputDevice;
  217546. bool isSlaveDevice;
  217547. private:
  217548. CriticalSection callbackLock;
  217549. AudioDeviceID deviceID;
  217550. bool started;
  217551. double sampleRate;
  217552. int bufferSize;
  217553. float* audioBuffer;
  217554. int numInputChans, numOutputChans;
  217555. bool callbacksAllowed;
  217556. struct CallbackDetailsForChannel
  217557. {
  217558. int sourceChannelNum;
  217559. int streamNum;
  217560. int dataOffsetSamples;
  217561. int dataStrideSamples;
  217562. };
  217563. int numInputChannelInfos, numOutputChannelInfos;
  217564. CallbackDetailsForChannel inputChannelInfo [maxNumChans];
  217565. CallbackDetailsForChannel outputChannelInfo [maxNumChans];
  217566. float* tempInputBuffers [maxNumChans];
  217567. float* tempOutputBuffers [maxNumChans];
  217568. CoreAudioInternal (const CoreAudioInternal&);
  217569. const CoreAudioInternal& operator= (const CoreAudioInternal&);
  217570. static OSStatus audioIOProc (AudioDeviceID inDevice,
  217571. const AudioTimeStamp* inNow,
  217572. const AudioBufferList* inInputData,
  217573. const AudioTimeStamp* inInputTime,
  217574. AudioBufferList* outOutputData,
  217575. const AudioTimeStamp* inOutputTime,
  217576. void* device)
  217577. {
  217578. ((CoreAudioInternal*) device)->audioCallback (inInputData, outOutputData);
  217579. return noErr;
  217580. }
  217581. static OSStatus deviceListenerProc (AudioDeviceID inDevice,
  217582. UInt32 inLine,
  217583. Boolean isInput,
  217584. AudioDevicePropertyID inPropertyID,
  217585. void* inClientData)
  217586. {
  217587. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  217588. switch (inPropertyID)
  217589. {
  217590. case kAudioDevicePropertyBufferSize:
  217591. case kAudioDevicePropertyBufferFrameSize:
  217592. case kAudioDevicePropertyNominalSampleRate:
  217593. case kAudioDevicePropertyStreamFormat:
  217594. case kAudioDevicePropertyDeviceIsAlive:
  217595. intern->deviceDetailsChanged();
  217596. break;
  217597. case kAudioDevicePropertyBufferSizeRange:
  217598. case kAudioDevicePropertyVolumeScalar:
  217599. case kAudioDevicePropertyMute:
  217600. case kAudioDevicePropertyPlayThru:
  217601. case kAudioDevicePropertyDataSource:
  217602. case kAudioDevicePropertyDeviceIsRunning:
  217603. break;
  217604. }
  217605. return noErr;
  217606. }
  217607. static OSType* getAllDataSourcesForDevice (AudioDeviceID deviceID, const bool input, int& num)
  217608. {
  217609. OSType* types = 0;
  217610. UInt32 size = 0;
  217611. num = 0;
  217612. if (deviceID != 0
  217613. && OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyDataSources, &size, 0)))
  217614. {
  217615. types = (OSType*) juce_calloc (size);
  217616. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSources, &size, types)))
  217617. {
  217618. num = size / sizeof (OSType);
  217619. }
  217620. else
  217621. {
  217622. juce_free (types);
  217623. types = 0;
  217624. }
  217625. }
  217626. return types;
  217627. }
  217628. };
  217629. class CoreAudioIODevice : public AudioIODevice
  217630. {
  217631. public:
  217632. CoreAudioIODevice (const String& deviceName,
  217633. AudioDeviceID inputDeviceId,
  217634. const int inputIndex_,
  217635. AudioDeviceID outputDeviceId,
  217636. const int outputIndex_)
  217637. : AudioIODevice (deviceName, "CoreAudio"),
  217638. inputIndex (inputIndex_),
  217639. outputIndex (outputIndex_),
  217640. isOpen_ (false),
  217641. isStarted (false)
  217642. {
  217643. internal = 0;
  217644. CoreAudioInternal* device = 0;
  217645. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  217646. {
  217647. jassert (inputDeviceId != 0);
  217648. device = new CoreAudioInternal (inputDeviceId);
  217649. lastError = device->error;
  217650. if (lastError.isNotEmpty())
  217651. deleteAndZero (device);
  217652. }
  217653. else
  217654. {
  217655. device = new CoreAudioInternal (outputDeviceId);
  217656. lastError = device->error;
  217657. if (lastError.isNotEmpty())
  217658. {
  217659. deleteAndZero (device);
  217660. }
  217661. else if (inputDeviceId != 0)
  217662. {
  217663. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  217664. lastError = device->error;
  217665. if (lastError.isNotEmpty())
  217666. {
  217667. delete secondDevice;
  217668. }
  217669. else
  217670. {
  217671. device->inputDevice = secondDevice;
  217672. secondDevice->isSlaveDevice = true;
  217673. }
  217674. }
  217675. }
  217676. internal = device;
  217677. AudioHardwareAddPropertyListener (kAudioPropertyWildcardPropertyID,
  217678. hardwareListenerProc, internal);
  217679. }
  217680. ~CoreAudioIODevice()
  217681. {
  217682. AudioHardwareRemovePropertyListener (kAudioPropertyWildcardPropertyID,
  217683. hardwareListenerProc);
  217684. delete internal;
  217685. }
  217686. const StringArray getOutputChannelNames()
  217687. {
  217688. return internal->outChanNames;
  217689. }
  217690. const StringArray getInputChannelNames()
  217691. {
  217692. if (internal->inputDevice != 0)
  217693. return internal->inputDevice->inChanNames;
  217694. else
  217695. return internal->inChanNames;
  217696. }
  217697. int getNumSampleRates()
  217698. {
  217699. return internal->sampleRates.size();
  217700. }
  217701. double getSampleRate (int index)
  217702. {
  217703. return internal->sampleRates [index];
  217704. }
  217705. int getNumBufferSizesAvailable()
  217706. {
  217707. return internal->bufferSizes.size();
  217708. }
  217709. int getBufferSizeSamples (int index)
  217710. {
  217711. return internal->bufferSizes [index];
  217712. }
  217713. int getDefaultBufferSize()
  217714. {
  217715. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  217716. if (getBufferSizeSamples(i) >= 512)
  217717. return getBufferSizeSamples(i);
  217718. return 512;
  217719. }
  217720. const String open (const BitArray& inputChannels,
  217721. const BitArray& outputChannels,
  217722. double sampleRate,
  217723. int bufferSizeSamples)
  217724. {
  217725. isOpen_ = true;
  217726. if (bufferSizeSamples <= 0)
  217727. bufferSizeSamples = getDefaultBufferSize();
  217728. internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  217729. lastError = internal->error;
  217730. return lastError;
  217731. }
  217732. void close()
  217733. {
  217734. isOpen_ = false;
  217735. }
  217736. bool isOpen()
  217737. {
  217738. return isOpen_;
  217739. }
  217740. int getCurrentBufferSizeSamples()
  217741. {
  217742. return internal != 0 ? internal->getBufferSize() : 512;
  217743. }
  217744. double getCurrentSampleRate()
  217745. {
  217746. return internal != 0 ? internal->getSampleRate() : 0;
  217747. }
  217748. int getCurrentBitDepth()
  217749. {
  217750. return 32; // no way to find out, so just assume it's high..
  217751. }
  217752. const BitArray getActiveOutputChannels() const
  217753. {
  217754. return internal != 0 ? internal->activeOutputChans : BitArray();
  217755. }
  217756. const BitArray getActiveInputChannels() const
  217757. {
  217758. BitArray chans;
  217759. if (internal != 0)
  217760. {
  217761. chans = internal->activeInputChans;
  217762. if (internal->inputDevice != 0)
  217763. chans.orWith (internal->inputDevice->activeInputChans);
  217764. }
  217765. return chans;
  217766. }
  217767. int getOutputLatencyInSamples()
  217768. {
  217769. if (internal == 0)
  217770. return 0;
  217771. // this seems like a good guess at getting the latency right - comparing
  217772. // this with a round-trip measurement, it gets it to within a few millisecs
  217773. // for the built-in mac soundcard
  217774. return internal->outputLatency + internal->getBufferSize() * 2;
  217775. }
  217776. int getInputLatencyInSamples()
  217777. {
  217778. if (internal == 0)
  217779. return 0;
  217780. return internal->inputLatency + internal->getBufferSize() * 2;
  217781. }
  217782. void start (AudioIODeviceCallback* callback)
  217783. {
  217784. if (internal != 0 && ! isStarted)
  217785. {
  217786. if (callback != 0)
  217787. callback->audioDeviceAboutToStart (this);
  217788. isStarted = true;
  217789. internal->start (callback);
  217790. }
  217791. }
  217792. void stop()
  217793. {
  217794. if (isStarted && internal != 0)
  217795. {
  217796. AudioIODeviceCallback* const lastCallback = internal->callback;
  217797. isStarted = false;
  217798. internal->stop (true);
  217799. if (lastCallback != 0)
  217800. lastCallback->audioDeviceStopped();
  217801. }
  217802. }
  217803. bool isPlaying()
  217804. {
  217805. if (internal->callback == 0)
  217806. isStarted = false;
  217807. return isStarted;
  217808. }
  217809. const String getLastError()
  217810. {
  217811. return lastError;
  217812. }
  217813. int inputIndex, outputIndex;
  217814. juce_UseDebuggingNewOperator
  217815. private:
  217816. CoreAudioInternal* internal;
  217817. bool isOpen_, isStarted;
  217818. String lastError;
  217819. static OSStatus hardwareListenerProc (AudioHardwarePropertyID inPropertyID, void* inClientData)
  217820. {
  217821. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  217822. switch (inPropertyID)
  217823. {
  217824. case kAudioHardwarePropertyDevices:
  217825. intern->deviceDetailsChanged();
  217826. break;
  217827. case kAudioHardwarePropertyDefaultOutputDevice:
  217828. case kAudioHardwarePropertyDefaultInputDevice:
  217829. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  217830. break;
  217831. }
  217832. return noErr;
  217833. }
  217834. CoreAudioIODevice (const CoreAudioIODevice&);
  217835. const CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  217836. };
  217837. class CoreAudioIODeviceType : public AudioIODeviceType
  217838. {
  217839. public:
  217840. CoreAudioIODeviceType()
  217841. : AudioIODeviceType (T("CoreAudio")),
  217842. hasScanned (false)
  217843. {
  217844. }
  217845. ~CoreAudioIODeviceType()
  217846. {
  217847. }
  217848. void scanForDevices()
  217849. {
  217850. hasScanned = true;
  217851. inputDeviceNames.clear();
  217852. outputDeviceNames.clear();
  217853. inputIds.clear();
  217854. outputIds.clear();
  217855. UInt32 size;
  217856. if (OK (AudioHardwareGetPropertyInfo (kAudioHardwarePropertyDevices, &size, 0)))
  217857. {
  217858. AudioDeviceID* const devs = (AudioDeviceID*) juce_calloc (size);
  217859. if (OK (AudioHardwareGetProperty (kAudioHardwarePropertyDevices, &size, devs)))
  217860. {
  217861. static bool alreadyLogged = false;
  217862. const int num = size / sizeof (AudioDeviceID);
  217863. for (int i = 0; i < num; ++i)
  217864. {
  217865. char name[1024];
  217866. size = sizeof (name);
  217867. if (OK (AudioDeviceGetProperty (devs[i], 0, false, kAudioDevicePropertyDeviceName, &size, name)))
  217868. {
  217869. const String nameString (String::fromUTF8 ((const uint8*) name, strlen (name)));
  217870. if (! alreadyLogged)
  217871. log (T("CoreAudio device: ") + nameString);
  217872. const int numIns = getNumChannels (devs[i], true);
  217873. const int numOuts = getNumChannels (devs[i], false);
  217874. if (numIns > 0)
  217875. {
  217876. inputDeviceNames.add (nameString);
  217877. inputIds.add (devs[i]);
  217878. }
  217879. if (numOuts > 0)
  217880. {
  217881. outputDeviceNames.add (nameString);
  217882. outputIds.add (devs[i]);
  217883. }
  217884. }
  217885. }
  217886. alreadyLogged = true;
  217887. }
  217888. juce_free (devs);
  217889. }
  217890. inputDeviceNames.appendNumbersToDuplicates (false, true);
  217891. outputDeviceNames.appendNumbersToDuplicates (false, true);
  217892. }
  217893. const StringArray getDeviceNames (const bool wantInputNames) const
  217894. {
  217895. jassert (hasScanned); // need to call scanForDevices() before doing this
  217896. if (wantInputNames)
  217897. return inputDeviceNames;
  217898. else
  217899. return outputDeviceNames;
  217900. }
  217901. int getDefaultDeviceIndex (const bool forInput) const
  217902. {
  217903. jassert (hasScanned); // need to call scanForDevices() before doing this
  217904. AudioDeviceID deviceID;
  217905. UInt32 size = sizeof (deviceID);
  217906. // if they're asking for any input channels at all, use the default input, so we
  217907. // get the built-in mic rather than the built-in output with no inputs..
  217908. if (AudioHardwareGetProperty (forInput ? kAudioHardwarePropertyDefaultInputDevice
  217909. : kAudioHardwarePropertyDefaultOutputDevice,
  217910. &size, &deviceID) == noErr)
  217911. {
  217912. if (forInput)
  217913. {
  217914. for (int i = inputIds.size(); --i >= 0;)
  217915. if (inputIds[i] == deviceID)
  217916. return i;
  217917. }
  217918. else
  217919. {
  217920. for (int i = outputIds.size(); --i >= 0;)
  217921. if (outputIds[i] == deviceID)
  217922. return i;
  217923. }
  217924. }
  217925. return 0;
  217926. }
  217927. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  217928. {
  217929. jassert (hasScanned); // need to call scanForDevices() before doing this
  217930. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  217931. if (d == 0)
  217932. return -1;
  217933. return asInput ? d->inputIndex
  217934. : d->outputIndex;
  217935. }
  217936. bool hasSeparateInputsAndOutputs() const { return true; }
  217937. AudioIODevice* createDevice (const String& outputDeviceName,
  217938. const String& inputDeviceName)
  217939. {
  217940. jassert (hasScanned); // need to call scanForDevices() before doing this
  217941. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  217942. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  217943. String deviceName (outputDeviceName);
  217944. if (deviceName.isEmpty())
  217945. deviceName = inputDeviceName;
  217946. if (index >= 0)
  217947. return new CoreAudioIODevice (deviceName,
  217948. inputIds [inputIndex],
  217949. inputIndex,
  217950. outputIds [outputIndex],
  217951. outputIndex);
  217952. return 0;
  217953. }
  217954. juce_UseDebuggingNewOperator
  217955. private:
  217956. StringArray inputDeviceNames, outputDeviceNames;
  217957. Array <AudioDeviceID> inputIds, outputIds;
  217958. bool hasScanned;
  217959. static int getNumChannels (AudioDeviceID deviceID, bool input)
  217960. {
  217961. int total = 0;
  217962. UInt32 size;
  217963. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, 0)))
  217964. {
  217965. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  217966. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, bufList)))
  217967. {
  217968. const int numStreams = bufList->mNumberBuffers;
  217969. for (int i = 0; i < numStreams; ++i)
  217970. {
  217971. const AudioBuffer& b = bufList->mBuffers[i];
  217972. total += b.mNumberChannels;
  217973. }
  217974. }
  217975. juce_free (bufList);
  217976. }
  217977. return total;
  217978. }
  217979. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  217980. const CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  217981. };
  217982. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  217983. {
  217984. return new CoreAudioIODeviceType();
  217985. }
  217986. #undef log
  217987. END_JUCE_NAMESPACE
  217988. /********* End of inlined file: juce_mac_CoreAudio.cpp *********/
  217989. /********* Start of inlined file: juce_mac_CoreMidi.cpp *********/
  217990. #include <CoreMIDI/MIDIServices.h>
  217991. BEGIN_JUCE_NAMESPACE
  217992. #undef log
  217993. #define log(a) Logger::writeToLog(a)
  217994. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  217995. {
  217996. if (err == noErr)
  217997. return true;
  217998. log (T("CoreMidi error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  217999. jassertfalse
  218000. return false;
  218001. }
  218002. #undef OK
  218003. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  218004. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  218005. {
  218006. String result;
  218007. CFStringRef str = 0;
  218008. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  218009. if (str != 0)
  218010. {
  218011. result = PlatformUtilities::cfStringToJuceString (str);
  218012. CFRelease (str);
  218013. str = 0;
  218014. }
  218015. MIDIEntityRef entity = 0;
  218016. MIDIEndpointGetEntity (endpoint, &entity);
  218017. if (entity == 0)
  218018. return result; // probably virtual
  218019. if (result.isEmpty())
  218020. {
  218021. // endpoint name has zero length - try the entity
  218022. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  218023. if (str != 0)
  218024. {
  218025. result += PlatformUtilities::cfStringToJuceString (str);
  218026. CFRelease (str);
  218027. str = 0;
  218028. }
  218029. }
  218030. // now consider the device's name
  218031. MIDIDeviceRef device = 0;
  218032. MIDIEntityGetDevice (entity, &device);
  218033. if (device == 0)
  218034. return result;
  218035. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  218036. if (str != 0)
  218037. {
  218038. const String s (PlatformUtilities::cfStringToJuceString (str));
  218039. CFRelease (str);
  218040. // if an external device has only one entity, throw away
  218041. // the endpoint name and just use the device name
  218042. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  218043. {
  218044. result = s;
  218045. }
  218046. else if (! result.startsWithIgnoreCase (s))
  218047. {
  218048. // prepend the device name to the entity name
  218049. result = (s + T(" ") + result).trimEnd();
  218050. }
  218051. }
  218052. return result;
  218053. }
  218054. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  218055. {
  218056. String result;
  218057. // Does the endpoint have connections?
  218058. CFDataRef connections = 0;
  218059. int numConnections = 0;
  218060. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  218061. if (connections != 0)
  218062. {
  218063. numConnections = CFDataGetLength (connections) / sizeof (MIDIUniqueID);
  218064. if (numConnections > 0)
  218065. {
  218066. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  218067. for (int i = 0; i < numConnections; ++i, ++pid)
  218068. {
  218069. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  218070. MIDIObjectRef connObject;
  218071. MIDIObjectType connObjectType;
  218072. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  218073. if (err == noErr)
  218074. {
  218075. String s;
  218076. if (connObjectType == kMIDIObjectType_ExternalSource
  218077. || connObjectType == kMIDIObjectType_ExternalDestination)
  218078. {
  218079. // Connected to an external device's endpoint (10.3 and later).
  218080. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  218081. }
  218082. else
  218083. {
  218084. // Connected to an external device (10.2) (or something else, catch-all)
  218085. CFStringRef str = 0;
  218086. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  218087. if (str != 0)
  218088. {
  218089. s = PlatformUtilities::cfStringToJuceString (str);
  218090. CFRelease (str);
  218091. }
  218092. }
  218093. if (s.isNotEmpty())
  218094. {
  218095. if (result.isNotEmpty())
  218096. result += (", ");
  218097. result += s;
  218098. }
  218099. }
  218100. }
  218101. }
  218102. CFRelease (connections);
  218103. }
  218104. if (result.isNotEmpty())
  218105. return result;
  218106. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  218107. return getEndpointName (endpoint, false);
  218108. }
  218109. const StringArray MidiOutput::getDevices()
  218110. {
  218111. StringArray s;
  218112. const ItemCount num = MIDIGetNumberOfDestinations();
  218113. for (ItemCount i = 0; i < num; ++i)
  218114. {
  218115. MIDIEndpointRef dest = MIDIGetDestination (i);
  218116. if (dest != 0)
  218117. {
  218118. String name (getConnectedEndpointName (dest));
  218119. if (name.isEmpty())
  218120. name = "<error>";
  218121. s.add (name);
  218122. }
  218123. else
  218124. {
  218125. s.add ("<error>");
  218126. }
  218127. }
  218128. return s;
  218129. }
  218130. int MidiOutput::getDefaultDeviceIndex()
  218131. {
  218132. return 0;
  218133. }
  218134. static MIDIClientRef globalMidiClient;
  218135. static bool hasGlobalClientBeenCreated = false;
  218136. static bool makeSureClientExists()
  218137. {
  218138. if (! hasGlobalClientBeenCreated)
  218139. {
  218140. String name (T("JUCE"));
  218141. if (JUCEApplication::getInstance() != 0)
  218142. name = JUCEApplication::getInstance()->getApplicationName();
  218143. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  218144. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  218145. CFRelease (appName);
  218146. }
  218147. return hasGlobalClientBeenCreated;
  218148. }
  218149. struct MidiPortAndEndpoint
  218150. {
  218151. MIDIPortRef port;
  218152. MIDIEndpointRef endPoint;
  218153. };
  218154. MidiOutput* MidiOutput::openDevice (int index)
  218155. {
  218156. MidiOutput* mo = 0;
  218157. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  218158. {
  218159. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  218160. CFStringRef pname;
  218161. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  218162. {
  218163. log (T("CoreMidi - opening out: ") + PlatformUtilities::cfStringToJuceString (pname));
  218164. if (makeSureClientExists())
  218165. {
  218166. MIDIPortRef port;
  218167. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  218168. {
  218169. MidiPortAndEndpoint* mpe = new MidiPortAndEndpoint();
  218170. mpe->port = port;
  218171. mpe->endPoint = endPoint;
  218172. mo = new MidiOutput();
  218173. mo->internal = (void*)mpe;
  218174. }
  218175. }
  218176. CFRelease (pname);
  218177. }
  218178. }
  218179. return mo;
  218180. }
  218181. MidiOutput::~MidiOutput()
  218182. {
  218183. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  218184. MIDIPortDispose (mpe->port);
  218185. delete mpe;
  218186. }
  218187. void MidiOutput::reset()
  218188. {
  218189. }
  218190. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  218191. {
  218192. return false;
  218193. }
  218194. void MidiOutput::setVolume (float leftVol, float rightVol)
  218195. {
  218196. }
  218197. void MidiOutput::sendMessageNow (const MidiMessage& message)
  218198. {
  218199. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  218200. if (message.isSysEx())
  218201. {
  218202. MIDIPacketList* const packets = (MIDIPacketList*) juce_malloc (32 + message.getRawDataSize());
  218203. packets->numPackets = 1;
  218204. packets->packet[0].timeStamp = 0;
  218205. packets->packet[0].length = message.getRawDataSize();
  218206. memcpy (packets->packet[0].data, message.getRawData(), message.getRawDataSize());
  218207. MIDISend (mpe->port, mpe->endPoint, packets);
  218208. juce_free (packets);
  218209. }
  218210. else
  218211. {
  218212. MIDIPacketList packets;
  218213. packets.numPackets = 1;
  218214. packets.packet[0].timeStamp = 0;
  218215. packets.packet[0].length = message.getRawDataSize();
  218216. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  218217. MIDISend (mpe->port, mpe->endPoint, &packets);
  218218. }
  218219. }
  218220. const StringArray MidiInput::getDevices()
  218221. {
  218222. StringArray s;
  218223. const ItemCount num = MIDIGetNumberOfSources();
  218224. for (ItemCount i = 0; i < num; ++i)
  218225. {
  218226. MIDIEndpointRef source = MIDIGetSource (i);
  218227. if (source != 0)
  218228. {
  218229. String name (getConnectedEndpointName (source));
  218230. if (name.isEmpty())
  218231. name = "<error>";
  218232. s.add (name);
  218233. }
  218234. else
  218235. {
  218236. s.add ("<error>");
  218237. }
  218238. }
  218239. return s;
  218240. }
  218241. int MidiInput::getDefaultDeviceIndex()
  218242. {
  218243. return 0;
  218244. }
  218245. struct MidiPortAndCallback
  218246. {
  218247. MidiInput* input;
  218248. MIDIPortRef port;
  218249. MIDIEndpointRef endPoint;
  218250. MidiInputCallback* callback;
  218251. MemoryBlock pendingData;
  218252. int pendingBytes;
  218253. double pendingDataTime;
  218254. bool active;
  218255. };
  218256. static CriticalSection callbackLock;
  218257. static VoidArray activeCallbacks;
  218258. static void processSysex (MidiPortAndCallback* const mpe, const uint8*& d, int& size, const double time)
  218259. {
  218260. if (*d == 0xf0)
  218261. {
  218262. mpe->pendingBytes = 0;
  218263. mpe->pendingDataTime = time;
  218264. }
  218265. mpe->pendingData.ensureSize (mpe->pendingBytes + size, false);
  218266. uint8* totalMessage = (uint8*) mpe->pendingData.getData();
  218267. uint8* dest = totalMessage + mpe->pendingBytes;
  218268. while (size > 0)
  218269. {
  218270. if (mpe->pendingBytes > 0 && *d >= 0x80)
  218271. {
  218272. if (*d >= 0xfa || *d == 0xf8)
  218273. {
  218274. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (*d, time));
  218275. ++d;
  218276. --size;
  218277. }
  218278. else
  218279. {
  218280. if (*d == 0xf7)
  218281. {
  218282. *dest++ = *d++;
  218283. mpe->pendingBytes++;
  218284. --size;
  218285. }
  218286. break;
  218287. }
  218288. }
  218289. else
  218290. {
  218291. *dest++ = *d++;
  218292. mpe->pendingBytes++;
  218293. --size;
  218294. }
  218295. }
  218296. if (totalMessage [mpe->pendingBytes - 1] == 0xf7)
  218297. {
  218298. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (totalMessage,
  218299. mpe->pendingBytes,
  218300. mpe->pendingDataTime));
  218301. mpe->pendingBytes = 0;
  218302. }
  218303. else
  218304. {
  218305. mpe->callback->handlePartialSysexMessage (mpe->input,
  218306. totalMessage,
  218307. mpe->pendingBytes,
  218308. mpe->pendingDataTime);
  218309. }
  218310. }
  218311. static void midiInputProc (const MIDIPacketList* pktlist,
  218312. void* readProcRefCon,
  218313. void* srcConnRefCon)
  218314. {
  218315. double time = Time::getMillisecondCounterHiRes() * 0.001;
  218316. const double originalTime = time;
  218317. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) readProcRefCon;
  218318. const ScopedLock sl (callbackLock);
  218319. if (activeCallbacks.contains (mpe) && mpe->active)
  218320. {
  218321. const MIDIPacket* packet = &pktlist->packet[0];
  218322. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  218323. {
  218324. const uint8* d = (const uint8*) (packet->data);
  218325. int size = packet->length;
  218326. while (size > 0)
  218327. {
  218328. time = originalTime;
  218329. if (mpe->pendingBytes > 0 || d[0] == 0xf0)
  218330. {
  218331. processSysex (mpe, d, size, time);
  218332. }
  218333. else
  218334. {
  218335. int used = 0;
  218336. const MidiMessage m (d, size, used, 0, time);
  218337. if (used <= 0)
  218338. {
  218339. jassertfalse // malformed midi message
  218340. break;
  218341. }
  218342. else
  218343. {
  218344. mpe->callback->handleIncomingMidiMessage (mpe->input, m);
  218345. }
  218346. size -= used;
  218347. d += used;
  218348. }
  218349. }
  218350. packet = MIDIPacketNext (packet);
  218351. }
  218352. }
  218353. }
  218354. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  218355. {
  218356. MidiInput* mi = 0;
  218357. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  218358. {
  218359. MIDIEndpointRef endPoint = MIDIGetSource (index);
  218360. if (endPoint != 0)
  218361. {
  218362. CFStringRef pname;
  218363. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  218364. {
  218365. log (T("CoreMidi - opening inp: ") + PlatformUtilities::cfStringToJuceString (pname));
  218366. if (makeSureClientExists())
  218367. {
  218368. MIDIPortRef port;
  218369. MidiPortAndCallback* const mpe = new MidiPortAndCallback();
  218370. mpe->active = false;
  218371. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpe, &port)))
  218372. {
  218373. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  218374. {
  218375. mpe->port = port;
  218376. mpe->endPoint = endPoint;
  218377. mpe->callback = callback;
  218378. mpe->pendingBytes = 0;
  218379. mpe->pendingData.ensureSize (128);
  218380. mi = new MidiInput (getDevices() [index]);
  218381. mpe->input = mi;
  218382. mi->internal = (void*) mpe;
  218383. const ScopedLock sl (callbackLock);
  218384. activeCallbacks.add (mpe);
  218385. }
  218386. else
  218387. {
  218388. OK (MIDIPortDispose (port));
  218389. delete mpe;
  218390. }
  218391. }
  218392. else
  218393. {
  218394. delete mpe;
  218395. }
  218396. }
  218397. }
  218398. CFRelease (pname);
  218399. }
  218400. }
  218401. return mi;
  218402. }
  218403. MidiInput::MidiInput (const String& name_)
  218404. : name (name_)
  218405. {
  218406. }
  218407. MidiInput::~MidiInput()
  218408. {
  218409. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  218410. mpe->active = false;
  218411. callbackLock.enter();
  218412. activeCallbacks.removeValue (mpe);
  218413. callbackLock.exit();
  218414. OK (MIDIPortDisconnectSource (mpe->port, mpe->endPoint));
  218415. OK (MIDIPortDispose (mpe->port));
  218416. delete mpe;
  218417. }
  218418. void MidiInput::start()
  218419. {
  218420. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  218421. const ScopedLock sl (callbackLock);
  218422. mpe->active = true;
  218423. }
  218424. void MidiInput::stop()
  218425. {
  218426. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  218427. const ScopedLock sl (callbackLock);
  218428. mpe->active = false;
  218429. }
  218430. #undef log
  218431. END_JUCE_NAMESPACE
  218432. /********* End of inlined file: juce_mac_CoreMidi.cpp *********/
  218433. /********* Start of inlined file: juce_mac_FileChooser.mm *********/
  218434. #include <fnmatch.h>
  218435. BEGIN_JUCE_NAMESPACE
  218436. END_JUCE_NAMESPACE
  218437. @interface JuceFileChooserDelegate : NSObject
  218438. {
  218439. JUCE_NAMESPACE::StringArray* filters;
  218440. }
  218441. - (JuceFileChooserDelegate*) initWithFilters: (JUCE_NAMESPACE::StringArray*) filters_;
  218442. - (void) dealloc;
  218443. - (BOOL) panel:(id) sender shouldShowFilename: (NSString*) filename;
  218444. @end
  218445. @implementation JuceFileChooserDelegate
  218446. - (JuceFileChooserDelegate*) initWithFilters: (JUCE_NAMESPACE::StringArray*) filters_
  218447. {
  218448. [super init];
  218449. filters = filters_;
  218450. return self;
  218451. }
  218452. - (void) dealloc
  218453. {
  218454. delete filters;
  218455. [super dealloc];
  218456. }
  218457. - (BOOL) panel:(id) sender shouldShowFilename: (NSString*) filename
  218458. {
  218459. const char* filenameUTF8 = (const char*) [filename UTF8String];
  218460. for (int i = filters->size(); --i >= 0;)
  218461. {
  218462. const JUCE_NAMESPACE::String wildcard ((*filters)[i].toLowerCase());
  218463. if (fnmatch (wildcard.toUTF8(), filenameUTF8, 0) == 0)
  218464. return true;
  218465. }
  218466. return JUCE_NAMESPACE::File (nsStringToJuce (filename)).isDirectory();
  218467. }
  218468. @end
  218469. BEGIN_JUCE_NAMESPACE
  218470. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  218471. const String& title,
  218472. const File& currentFileOrDirectory,
  218473. const String& filter,
  218474. bool selectsDirectory,
  218475. bool isSaveDialogue,
  218476. bool warnAboutOverwritingExistingFiles,
  218477. bool selectMultipleFiles,
  218478. FilePreviewComponent* extraInfoComponent)
  218479. {
  218480. const AutoPool pool;
  218481. StringArray* filters = new StringArray();
  218482. filters->addTokens (filter.replaceCharacters (T(",:"), T(";;")), T(";"), 0);
  218483. filters->trim();
  218484. filters->removeEmptyStrings();
  218485. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  218486. [delegate autorelease];
  218487. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  218488. : [NSOpenPanel openPanel];
  218489. [panel setTitle: juceStringToNS (title)];
  218490. if (! isSaveDialogue)
  218491. {
  218492. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  218493. [openPanel setCanChooseDirectories: selectsDirectory];
  218494. [openPanel setCanChooseFiles: ! selectsDirectory];
  218495. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  218496. }
  218497. [panel setDelegate: delegate];
  218498. String directory, filename;
  218499. if (currentFileOrDirectory.isDirectory())
  218500. {
  218501. directory = currentFileOrDirectory.getFullPathName();
  218502. }
  218503. else
  218504. {
  218505. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  218506. filename = currentFileOrDirectory.getFileName();
  218507. }
  218508. if ([panel runModalForDirectory: juceStringToNS (directory)
  218509. file: juceStringToNS (filename)]
  218510. == NSOKButton)
  218511. {
  218512. if (isSaveDialogue)
  218513. {
  218514. results.add (new File (nsStringToJuce ([panel filename])));
  218515. }
  218516. else
  218517. {
  218518. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  218519. NSArray* urls = [openPanel filenames];
  218520. for (int i = 0; i < [urls count]; ++i)
  218521. {
  218522. NSString* f = [urls objectAtIndex: i];
  218523. results.add (new File (nsStringToJuce (f)));
  218524. }
  218525. }
  218526. }
  218527. }
  218528. END_JUCE_NAMESPACE
  218529. /********* End of inlined file: juce_mac_FileChooser.mm *********/
  218530. /********* Start of inlined file: juce_mac_Fonts.mm *********/
  218531. #include <ApplicationServices/ApplicationServices.h>
  218532. BEGIN_JUCE_NAMESPACE
  218533. static OSStatus pascal CubicMoveTo (const Float32Point *pt,
  218534. void* callBackDataPtr)
  218535. {
  218536. Path* const p = (Path*) callBackDataPtr;
  218537. p->startNewSubPath (pt->x, pt->y);
  218538. return noErr;
  218539. }
  218540. static OSStatus pascal CubicLineTo (const Float32Point *pt,
  218541. void* callBackDataPtr)
  218542. {
  218543. Path* const p = (Path*) callBackDataPtr;
  218544. p->lineTo (pt->x, pt->y);
  218545. return noErr;
  218546. }
  218547. static OSStatus pascal CubicCurveTo (const Float32Point *pt1,
  218548. const Float32Point *pt2,
  218549. const Float32Point *pt3,
  218550. void* callBackDataPtr)
  218551. {
  218552. Path* const p = (Path*) callBackDataPtr;
  218553. p->cubicTo (pt1->x, pt1->y,
  218554. pt2->x, pt2->y,
  218555. pt3->x, pt3->y);
  218556. return noErr;
  218557. }
  218558. static OSStatus pascal CubicClosePath (void* callBackDataPtr)
  218559. {
  218560. Path* const p = (Path*) callBackDataPtr;
  218561. p->closeSubPath();
  218562. return noErr;
  218563. }
  218564. class ATSFontHelper
  218565. {
  218566. ATSUFontID fontId;
  218567. ATSUStyle style;
  218568. ATSCubicMoveToUPP moveToProc;
  218569. ATSCubicLineToUPP lineToProc;
  218570. ATSCubicCurveToUPP curveToProc;
  218571. ATSCubicClosePathUPP closePathProc;
  218572. float totalSize, ascent;
  218573. TextToUnicodeInfo encodingInfo;
  218574. public:
  218575. String name;
  218576. bool isBold, isItalic;
  218577. float fontSize;
  218578. int refCount;
  218579. ATSFontHelper (const String& name_,
  218580. const bool bold_,
  218581. const bool italic_,
  218582. const float size_)
  218583. : fontId (0),
  218584. name (name_),
  218585. isBold (bold_),
  218586. isItalic (italic_),
  218587. fontSize (size_),
  218588. refCount (1)
  218589. {
  218590. const char* const nameUtf8 = name_.toUTF8();
  218591. ATSUFindFontFromName (const_cast <char*> (nameUtf8),
  218592. strlen (nameUtf8),
  218593. kFontFullName,
  218594. kFontNoPlatformCode,
  218595. kFontNoScriptCode,
  218596. kFontNoLanguageCode,
  218597. &fontId);
  218598. ATSUCreateStyle (&style);
  218599. ATSUAttributeTag attTypes[] = { kATSUFontTag,
  218600. kATSUQDBoldfaceTag,
  218601. kATSUQDItalicTag,
  218602. kATSUSizeTag };
  218603. ByteCount attSizes[] = { sizeof (ATSUFontID),
  218604. sizeof (Boolean),
  218605. sizeof (Boolean),
  218606. sizeof (Fixed) };
  218607. Boolean bold = bold_, italic = italic_;
  218608. Fixed size = X2Fix (size_);
  218609. ATSUAttributeValuePtr attValues[] = { &fontId,
  218610. &bold,
  218611. &italic,
  218612. &size };
  218613. ATSUSetAttributes (style, 4, attTypes, attSizes, attValues);
  218614. moveToProc = NewATSCubicMoveToUPP (CubicMoveTo);
  218615. lineToProc = NewATSCubicLineToUPP (CubicLineTo);
  218616. curveToProc = NewATSCubicCurveToUPP (CubicCurveTo);
  218617. closePathProc = NewATSCubicClosePathUPP (CubicClosePath);
  218618. ascent = 0.0f;
  218619. float kern, descent = 0.0f;
  218620. getPathAndKerning (T('N'), T('O'), 0, kern, &ascent, &descent);
  218621. totalSize = ascent + descent;
  218622. }
  218623. ~ATSFontHelper()
  218624. {
  218625. ATSUDisposeStyle (style);
  218626. DisposeATSCubicMoveToUPP (moveToProc);
  218627. DisposeATSCubicLineToUPP (lineToProc);
  218628. DisposeATSCubicCurveToUPP (curveToProc);
  218629. DisposeATSCubicClosePathUPP (closePathProc);
  218630. }
  218631. bool getPathAndKerning (const juce_wchar char1,
  218632. const juce_wchar char2,
  218633. Path* path,
  218634. float& kerning,
  218635. float* ascent,
  218636. float* descent)
  218637. {
  218638. bool ok = false;
  218639. UniChar buffer[4];
  218640. buffer[0] = T(' ');
  218641. buffer[1] = char1;
  218642. buffer[2] = char2;
  218643. buffer[3] = 0;
  218644. UniCharCount count = kATSUToTextEnd;
  218645. ATSUTextLayout layout;
  218646. OSStatus err = ATSUCreateTextLayoutWithTextPtr (buffer,
  218647. 0,
  218648. 2,
  218649. 2,
  218650. 1,
  218651. &count,
  218652. &style,
  218653. &layout);
  218654. if (err == noErr)
  218655. {
  218656. ATSUSetTransientFontMatching (layout, true);
  218657. ATSLayoutRecord* layoutRecords;
  218658. ItemCount numRecords;
  218659. Fixed* deltaYs;
  218660. ItemCount numDeltaYs;
  218661. ATSUDirectGetLayoutDataArrayPtrFromTextLayout (layout,
  218662. 0,
  218663. kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
  218664. (void**) &layoutRecords,
  218665. &numRecords);
  218666. ATSUDirectGetLayoutDataArrayPtrFromTextLayout (layout,
  218667. 0,
  218668. kATSUDirectDataBaselineDeltaFixedArray,
  218669. (void**) &deltaYs,
  218670. &numDeltaYs);
  218671. if (numRecords > 2)
  218672. {
  218673. kerning = (float) (Fix2X (layoutRecords[2].realPos)
  218674. - Fix2X (layoutRecords[1].realPos));
  218675. if (ascent != 0)
  218676. {
  218677. ATSUTextMeasurement asc;
  218678. ByteCount actualSize;
  218679. ATSUGetLineControl (layout,
  218680. 0,
  218681. kATSULineAscentTag,
  218682. sizeof (ATSUTextMeasurement),
  218683. &asc,
  218684. &actualSize);
  218685. *ascent = (float) Fix2X (asc);
  218686. }
  218687. if (descent != 0)
  218688. {
  218689. ATSUTextMeasurement desc;
  218690. ByteCount actualSize;
  218691. ATSUGetLineControl (layout,
  218692. 0,
  218693. kATSULineDescentTag,
  218694. sizeof (ATSUTextMeasurement),
  218695. &desc,
  218696. &actualSize);
  218697. *descent = (float) Fix2X (desc);
  218698. }
  218699. if (path != 0)
  218700. {
  218701. OSStatus callbackResult;
  218702. ok = (ATSUGlyphGetCubicPaths (style,
  218703. layoutRecords[1].glyphID,
  218704. moveToProc,
  218705. lineToProc,
  218706. curveToProc,
  218707. closePathProc,
  218708. (void*) path,
  218709. &callbackResult) == noErr);
  218710. if (numDeltaYs > 0 && ok)
  218711. {
  218712. const float dy = (float) Fix2X (deltaYs[1]);
  218713. path->applyTransform (AffineTransform::translation (0.0f, dy));
  218714. }
  218715. }
  218716. else
  218717. {
  218718. ok = true;
  218719. }
  218720. }
  218721. if (deltaYs != 0)
  218722. ATSUDirectReleaseLayoutDataArrayPtr (0, kATSUDirectDataBaselineDeltaFixedArray,
  218723. (void**) &deltaYs);
  218724. if (layoutRecords != 0)
  218725. ATSUDirectReleaseLayoutDataArrayPtr (0, kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
  218726. (void**) &layoutRecords);
  218727. ATSUDisposeTextLayout (layout);
  218728. }
  218729. return kerning;
  218730. }
  218731. float getAscent()
  218732. {
  218733. return ascent;
  218734. }
  218735. float getTotalHeight()
  218736. {
  218737. return totalSize;
  218738. }
  218739. juce_wchar getDefaultChar()
  218740. {
  218741. return 0;
  218742. }
  218743. };
  218744. class ATSFontHelperCache : public Timer,
  218745. public DeletedAtShutdown
  218746. {
  218747. VoidArray cache;
  218748. public:
  218749. ATSFontHelperCache()
  218750. {
  218751. }
  218752. ~ATSFontHelperCache()
  218753. {
  218754. for (int i = cache.size(); --i >= 0;)
  218755. {
  218756. ATSFontHelper* const f = (ATSFontHelper*) cache.getUnchecked(i);
  218757. delete f;
  218758. }
  218759. clearSingletonInstance();
  218760. }
  218761. ATSFontHelper* getFont (const String& name,
  218762. const bool bold,
  218763. const bool italic,
  218764. const float size = 1024)
  218765. {
  218766. for (int i = cache.size(); --i >= 0;)
  218767. {
  218768. ATSFontHelper* const f = (ATSFontHelper*) cache.getUnchecked(i);
  218769. if (f->name == name
  218770. && f->isBold == bold
  218771. && f->isItalic == italic
  218772. && f->fontSize == size)
  218773. {
  218774. f->refCount++;
  218775. return f;
  218776. }
  218777. }
  218778. ATSFontHelper* const f = new ATSFontHelper (name, bold, italic, size);
  218779. cache.add (f);
  218780. return f;
  218781. }
  218782. void releaseFont (ATSFontHelper* f)
  218783. {
  218784. for (int i = cache.size(); --i >= 0;)
  218785. {
  218786. ATSFontHelper* const f2 = (ATSFontHelper*) cache.getUnchecked(i);
  218787. if (f == f2)
  218788. {
  218789. f->refCount--;
  218790. if (f->refCount == 0)
  218791. startTimer (5000);
  218792. break;
  218793. }
  218794. }
  218795. }
  218796. void timerCallback()
  218797. {
  218798. stopTimer();
  218799. for (int i = cache.size(); --i >= 0;)
  218800. {
  218801. ATSFontHelper* const f = (ATSFontHelper*) cache.getUnchecked(i);
  218802. if (f->refCount == 0)
  218803. {
  218804. cache.remove (i);
  218805. delete f;
  218806. }
  218807. }
  218808. if (cache.size() == 0)
  218809. delete this;
  218810. }
  218811. juce_DeclareSingleton_SingleThreaded_Minimal (ATSFontHelperCache)
  218812. };
  218813. juce_ImplementSingleton_SingleThreaded (ATSFontHelperCache)
  218814. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  218815. bool bold,
  218816. bool italic,
  218817. bool addAllGlyphsToFont) throw()
  218818. {
  218819. // This method is only safe to be called from the normal UI thread..
  218820. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  218821. ATSFontHelper* const helper = ATSFontHelperCache::getInstance()
  218822. ->getFont (fontName, bold, italic);
  218823. clear();
  218824. setAscent (helper->getAscent() / helper->getTotalHeight());
  218825. setName (fontName);
  218826. setDefaultCharacter (helper->getDefaultChar());
  218827. setBold (bold);
  218828. setItalic (italic);
  218829. if (addAllGlyphsToFont)
  218830. {
  218831. //xxx
  218832. jassertfalse
  218833. }
  218834. ATSFontHelperCache::getInstance()->releaseFont (helper);
  218835. }
  218836. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  218837. {
  218838. // This method is only safe to be called from the normal UI thread..
  218839. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  218840. ATSFontHelper* const helper = ATSFontHelperCache::getInstance()
  218841. ->getFont (getName(), isBold(), isItalic());
  218842. Path path;
  218843. float width;
  218844. bool foundOne = false;
  218845. if (helper->getPathAndKerning (character, T('I'), &path, width, 0, 0))
  218846. {
  218847. path.applyTransform (AffineTransform::scale (1.0f / helper->getTotalHeight(),
  218848. 1.0f / helper->getTotalHeight()));
  218849. addGlyph (character, path, width / helper->getTotalHeight());
  218850. for (int i = 0; i < glyphs.size(); ++i)
  218851. {
  218852. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  218853. float kerning;
  218854. if (helper->getPathAndKerning (character, g->getCharacter(), 0, kerning, 0, 0))
  218855. {
  218856. kerning = (kerning - width) / helper->getTotalHeight();
  218857. if (kerning != 0)
  218858. addKerningPair (character, g->getCharacter(), kerning);
  218859. }
  218860. if (helper->getPathAndKerning (g->getCharacter(), character, 0, kerning, 0, 0))
  218861. {
  218862. kerning = kerning / helper->getTotalHeight() - g->width;
  218863. if (kerning != 0)
  218864. addKerningPair (g->getCharacter(), character, kerning);
  218865. }
  218866. }
  218867. foundOne = true;
  218868. }
  218869. ATSFontHelperCache::getInstance()->releaseFont (helper);
  218870. return foundOne;
  218871. }
  218872. const StringArray Font::findAllTypefaceNames() throw()
  218873. {
  218874. StringArray names;
  218875. ATSFontIterator iter;
  218876. if (ATSFontIteratorCreate (kATSFontContextGlobal,
  218877. 0,
  218878. 0,
  218879. kATSOptionFlagsRestrictedScope,
  218880. &iter) == noErr)
  218881. {
  218882. ATSFontRef font;
  218883. while (ATSFontIteratorNext (iter, &font) == noErr)
  218884. {
  218885. CFStringRef name;
  218886. if (ATSFontGetName (font,
  218887. kATSOptionFlagsDefault,
  218888. &name) == noErr)
  218889. {
  218890. const String nm (PlatformUtilities::cfStringToJuceString (name));
  218891. if (nm.isNotEmpty())
  218892. names.add (nm);
  218893. CFRelease (name);
  218894. }
  218895. }
  218896. ATSFontIteratorRelease (&iter);
  218897. }
  218898. // Use some totuous logic to eliminate bold/italic versions of fonts that we've already got
  218899. // a plain version of. This is only necessary because of Carbon's total lack of support
  218900. // for dealing with font families...
  218901. for (int j = names.size(); --j >= 0;)
  218902. {
  218903. const char* const endings[] = { " bold", " italic", " bold italic", " bolditalic",
  218904. " oblque", " bold oblique", " boldoblique" };
  218905. for (int i = 0; i < numElementsInArray (endings); ++i)
  218906. {
  218907. const String ending (endings[i]);
  218908. if (names[j].endsWithIgnoreCase (ending))
  218909. {
  218910. const String root (names[j].dropLastCharacters (ending.length()).trimEnd());
  218911. if (names.contains (root)
  218912. || names.contains (root + T(" plain"), true))
  218913. {
  218914. names.remove (j);
  218915. break;
  218916. }
  218917. }
  218918. }
  218919. }
  218920. names.sort (true);
  218921. return names;
  218922. }
  218923. void Font::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  218924. {
  218925. defaultSans = "Lucida Grande";
  218926. defaultSerif = "Times New Roman";
  218927. defaultFixed = "Monaco";
  218928. }
  218929. END_JUCE_NAMESPACE
  218930. /********* End of inlined file: juce_mac_Fonts.mm *********/
  218931. /********* Start of inlined file: juce_mac_Messaging.mm *********/
  218932. #include <Carbon/Carbon.h>
  218933. BEGIN_JUCE_NAMESPACE
  218934. #undef Point
  218935. extern void juce_HandleProcessFocusChange();
  218936. extern void juce_maximiseAllMinimisedWindows();
  218937. extern void juce_InvokeMainMenuCommand (const HICommand& command);
  218938. extern void juce_MainMenuAboutToBeUsed();
  218939. struct CallbackMessagePayload
  218940. {
  218941. MessageCallbackFunction* function;
  218942. void* parameter;
  218943. void* volatile result;
  218944. bool volatile hasBeenExecuted;
  218945. };
  218946. END_JUCE_NAMESPACE
  218947. #if JUCE_COCOA
  218948. NSString* juceMessageName = 0;
  218949. @interface JuceAppDelegate : NSObject
  218950. id oldDelegate;
  218951. - (JuceAppDelegate*) init;
  218952. - (void) dealloc;
  218953. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  218954. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  218955. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  218956. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  218957. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  218958. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  218959. - (void) customEvent: (NSNotification*) aNotification;
  218960. - (void) performCallback: (id) info;
  218961. @end
  218962. @implementation JuceAppDelegate
  218963. - (JuceAppDelegate*) init
  218964. {
  218965. [super init];
  218966. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  218967. if (JUCE_NAMESPACE::JUCEApplication::getInstance() != 0)
  218968. {
  218969. oldDelegate = [NSApp delegate];
  218970. [NSApp setDelegate: self];
  218971. }
  218972. else
  218973. {
  218974. oldDelegate = 0;
  218975. [center addObserver: self selector: @selector (applicationDidResignActive:)
  218976. name: NSApplicationDidResignActiveNotification object: NSApp];
  218977. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  218978. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  218979. [center addObserver: self selector: @selector (applicationWillUnhide:)
  218980. name: NSApplicationWillUnhideNotification object: NSApp];
  218981. }
  218982. [center addObserver: self selector: @selector (customEvent:)
  218983. name: juceMessageName object: nil];
  218984. return self;
  218985. }
  218986. - (void) dealloc
  218987. {
  218988. if (oldDelegate != 0)
  218989. [NSApp setDelegate: oldDelegate];
  218990. [[NSNotificationCenter defaultCenter] removeObserver: self];
  218991. [super dealloc];
  218992. }
  218993. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  218994. {
  218995. if (JUCE_NAMESPACE::JUCEApplication::getInstance() != 0)
  218996. JUCE_NAMESPACE::JUCEApplication::getInstance()->systemRequestedQuit();
  218997. return NSTerminateLater;
  218998. }
  218999. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  219000. {
  219001. if (JUCE_NAMESPACE::JUCEApplication::getInstance() != 0)
  219002. {
  219003. JUCE_NAMESPACE::JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  219004. return YES;
  219005. }
  219006. return NO;
  219007. }
  219008. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  219009. {
  219010. JUCE_NAMESPACE::StringArray files;
  219011. for (int i = 0; i < [filenames count]; ++i)
  219012. files.add (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  219013. if (files.size() > 0 && JUCE_NAMESPACE::JUCEApplication::getInstance() != 0)
  219014. JUCE_NAMESPACE::JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (T(" ")));
  219015. }
  219016. - (void) applicationDidBecomeActive: (NSNotification*) aNotification
  219017. {
  219018. JUCE_NAMESPACE::juce_HandleProcessFocusChange();
  219019. }
  219020. - (void) applicationDidResignActive: (NSNotification*) aNotification
  219021. {
  219022. JUCE_NAMESPACE::juce_HandleProcessFocusChange();
  219023. }
  219024. - (void) applicationWillUnhide: (NSNotification*) aNotification
  219025. {
  219026. JUCE_NAMESPACE::juce_maximiseAllMinimisedWindows();
  219027. }
  219028. - (void) customEvent: (NSNotification*) n
  219029. {
  219030. void* message = 0;
  219031. [((NSData*) [n object]) getBytes: &message length: sizeof (message)];
  219032. if (message != 0)
  219033. JUCE_NAMESPACE::MessageManager::getInstance()->deliverMessage (message);
  219034. }
  219035. - (void) performCallback: (id) info
  219036. {
  219037. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) info;
  219038. if (pl != 0)
  219039. {
  219040. pl->result = (*pl->function) (pl->parameter);
  219041. pl->hasBeenExecuted = true;
  219042. }
  219043. }
  219044. @end
  219045. #endif
  219046. BEGIN_JUCE_NAMESPACE
  219047. #if JUCE_COCOA
  219048. static JuceAppDelegate* juceAppDelegate = 0;
  219049. #else
  219050. static int kJUCEClass = FOUR_CHAR_CODE ('JUCE');
  219051. const int kJUCEKind = 1;
  219052. const int kCallbackKind = 2;
  219053. static pascal OSStatus EventHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  219054. {
  219055. void* event = 0;
  219056. GetEventParameter (theEvent, 'mess', typeVoidPtr, 0, sizeof (void*), 0, &event);
  219057. if (event != 0)
  219058. MessageManager::getInstance()->deliverMessage (event);
  219059. return noErr;
  219060. }
  219061. static pascal OSStatus CallbackHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  219062. {
  219063. CallbackMessagePayload* pl = 0;
  219064. GetEventParameter (theEvent, 'mess', typeVoidPtr, 0, sizeof(pl), 0, &pl);
  219065. if (pl != 0)
  219066. {
  219067. pl->result = (*pl->function) (pl->parameter);
  219068. pl->hasBeenExecuted = true;
  219069. }
  219070. return noErr;
  219071. }
  219072. static pascal OSStatus MouseClickHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  219073. {
  219074. ::Point where;
  219075. GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, 0, sizeof(::Point), 0, &where);
  219076. WindowRef window;
  219077. if (FindWindow (where, &window) == inMenuBar)
  219078. {
  219079. // turn off the wait cursor before going in here..
  219080. const int oldTimeBeforeWaitCursor = MessageManager::getInstance()->getTimeBeforeShowingWaitCursor();
  219081. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (0);
  219082. if (Component::getCurrentlyModalComponent() != 0)
  219083. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  219084. juce_MainMenuAboutToBeUsed();
  219085. MenuSelect (where);
  219086. HiliteMenu (0);
  219087. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (oldTimeBeforeWaitCursor);
  219088. return noErr;
  219089. }
  219090. return eventNotHandledErr;
  219091. }
  219092. static pascal OSErr QuitAppleEventHandler (const AppleEvent *appleEvt, AppleEvent* reply, long refcon)
  219093. {
  219094. if (JUCEApplication::getInstance() != 0)
  219095. JUCEApplication::getInstance()->systemRequestedQuit();
  219096. return noErr;
  219097. }
  219098. static pascal OSErr OpenDocEventHandler (const AppleEvent *appleEvt, AppleEvent* reply, long refcon)
  219099. {
  219100. AEDescList docs;
  219101. StringArray files;
  219102. if (AEGetParamDesc (appleEvt, keyDirectObject, typeAEList, &docs) == noErr)
  219103. {
  219104. long num;
  219105. if (AECountItems (&docs, &num) == noErr)
  219106. {
  219107. for (int i = 1; i <= num; ++i)
  219108. {
  219109. FSRef file;
  219110. AEKeyword keyword;
  219111. DescType type;
  219112. Size size;
  219113. if (AEGetNthPtr (&docs, i, typeFSRef, &keyword, &type,
  219114. &file, sizeof (file), &size) == noErr)
  219115. {
  219116. const String path (PlatformUtilities::makePathFromFSRef (&file));
  219117. if (path.isNotEmpty())
  219118. files.add (path.quoted());
  219119. }
  219120. }
  219121. if (files.size() > 0
  219122. && JUCEApplication::getInstance() != 0)
  219123. {
  219124. JUCE_TRY
  219125. {
  219126. JUCEApplication::getInstance()
  219127. ->anotherInstanceStarted (files.joinIntoString (T(" ")));
  219128. }
  219129. JUCE_CATCH_ALL
  219130. }
  219131. }
  219132. AEDisposeDesc (&docs);
  219133. };
  219134. return noErr;
  219135. }
  219136. static pascal OSStatus AppEventHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  219137. {
  219138. const UInt32 eventClass = GetEventClass (theEvent);
  219139. if (eventClass == kEventClassCommand)
  219140. {
  219141. HICommand command;
  219142. if (GetEventParameter (theEvent, kEventParamHICommand, typeHICommand, 0, sizeof (command), 0, &command) == noErr
  219143. || GetEventParameter (theEvent, kEventParamDirectObject, typeHICommand, 0, sizeof (command), 0, &command) == noErr)
  219144. {
  219145. if (command.commandID == kHICommandQuit)
  219146. {
  219147. if (JUCEApplication::getInstance() != 0)
  219148. JUCEApplication::getInstance()->systemRequestedQuit();
  219149. return noErr;
  219150. }
  219151. else if (command.commandID == kHICommandMaximizeAll
  219152. || command.commandID == kHICommandMaximizeWindow
  219153. || command.commandID == kHICommandBringAllToFront)
  219154. {
  219155. juce_maximiseAllMinimisedWindows();
  219156. return noErr;
  219157. }
  219158. else
  219159. {
  219160. juce_InvokeMainMenuCommand (command);
  219161. }
  219162. }
  219163. }
  219164. else if (eventClass == kEventClassApplication)
  219165. {
  219166. if (GetEventKind (theEvent) == kEventAppFrontSwitched)
  219167. {
  219168. juce_HandleProcessFocusChange();
  219169. }
  219170. else if (GetEventKind (theEvent) == kEventAppShown)
  219171. {
  219172. // this seems to blank the windows, so we need to do a repaint..
  219173. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  219174. {
  219175. Component* const c = Desktop::getInstance().getComponent (i);
  219176. if (c != 0)
  219177. c->repaint();
  219178. }
  219179. }
  219180. }
  219181. return eventNotHandledErr;
  219182. }
  219183. static EventQueueRef mainQueue;
  219184. static EventHandlerRef juceEventHandler = 0;
  219185. static EventHandlerRef callbackEventHandler = 0;
  219186. #endif
  219187. void MessageManager::doPlatformSpecificInitialisation()
  219188. {
  219189. static bool initialised = false;
  219190. if (! initialised)
  219191. {
  219192. initialised = true;
  219193. #if JUCE_COCOA
  219194. // if we're linking a Juce app to one or more dynamic libraries, we'll need different values
  219195. // for this so each module doesn't interfere with the others.
  219196. UnsignedWide t;
  219197. Microseconds (&t);
  219198. kJUCEClass ^= t.lo;
  219199. juceMessageName = juceStringToNS ("juce_" + String::toHexString ((int) t.lo));
  219200. juceAppDelegate = [[JuceAppDelegate alloc] init];
  219201. #else
  219202. mainQueue = GetMainEventQueue();
  219203. #endif
  219204. }
  219205. #if ! JUCE_COCOA
  219206. const EventTypeSpec type1 = { kJUCEClass, kJUCEKind };
  219207. InstallApplicationEventHandler (NewEventHandlerUPP (EventHandlerProc), 1, &type1, 0, &juceEventHandler);
  219208. const EventTypeSpec type2 = { kJUCEClass, kCallbackKind };
  219209. InstallApplicationEventHandler (NewEventHandlerUPP (CallbackHandlerProc), 1, &type2, 0, &callbackEventHandler);
  219210. // only do this stuff if we're running as an application rather than a library..
  219211. if (JUCEApplication::getInstance() != 0)
  219212. {
  219213. const EventTypeSpec type3 = { kEventClassMouse, kEventMouseDown };
  219214. InstallApplicationEventHandler (NewEventHandlerUPP (MouseClickHandlerProc), 1, &type3, 0, 0);
  219215. const EventTypeSpec type4[] = { { kEventClassApplication, kEventAppShown },
  219216. { kEventClassApplication, kEventAppFrontSwitched },
  219217. { kEventClassCommand, kEventProcessCommand } };
  219218. InstallApplicationEventHandler (NewEventHandlerUPP (AppEventHandlerProc), 3, type4, 0, 0);
  219219. AEInstallEventHandler (kCoreEventClass, kAEQuitApplication,
  219220. NewAEEventHandlerUPP (QuitAppleEventHandler), 0, false);
  219221. AEInstallEventHandler (kCoreEventClass, kAEOpenDocuments,
  219222. NewAEEventHandlerUPP (OpenDocEventHandler), 0, false);
  219223. }
  219224. #endif
  219225. }
  219226. void MessageManager::doPlatformSpecificShutdown()
  219227. {
  219228. if (juceEventHandler != 0)
  219229. {
  219230. RemoveEventHandler (juceEventHandler);
  219231. juceEventHandler = 0;
  219232. }
  219233. if (callbackEventHandler != 0)
  219234. {
  219235. RemoveEventHandler (callbackEventHandler);
  219236. callbackEventHandler = 0;
  219237. }
  219238. }
  219239. bool juce_postMessageToSystemQueue (void* message)
  219240. {
  219241. #if JUCE_COCOA
  219242. [[NSNotificationCenter defaultCenter] postNotificationName: juceMessageName
  219243. object: [NSData dataWithBytes: &message
  219244. length: (int) sizeof (message)]];
  219245. return true;
  219246. #else
  219247. jassert (mainQueue == GetMainEventQueue());
  219248. EventRef event;
  219249. if (CreateEvent (0, kJUCEClass, kJUCEKind, 0, kEventAttributeUserEvent, &event) == noErr)
  219250. {
  219251. SetEventParameter (event, 'mess', typeVoidPtr, sizeof (void*), &message);
  219252. const bool ok = PostEventToQueue (mainQueue, event, kEventPriorityStandard) == noErr;
  219253. ReleaseEvent (event);
  219254. return ok;
  219255. }
  219256. return false;
  219257. #endif
  219258. }
  219259. void MessageManager::broadcastMessage (const String& value) throw()
  219260. {
  219261. }
  219262. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  219263. void* data)
  219264. {
  219265. if (isThisTheMessageThread())
  219266. {
  219267. return (*callback) (data);
  219268. }
  219269. else
  219270. {
  219271. CallbackMessagePayload cmp;
  219272. cmp.function = callback;
  219273. cmp.parameter = data;
  219274. cmp.result = 0;
  219275. cmp.hasBeenExecuted = false;
  219276. #if JUCE_COCOA
  219277. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  219278. withObject: (id) &cmp
  219279. waitUntilDone: YES];
  219280. return cmp.result;
  219281. #else
  219282. jassert (mainQueue == GetMainEventQueue());
  219283. EventRef event;
  219284. if (CreateEvent (0, kJUCEClass, kCallbackKind, 0, kEventAttributeUserEvent, &event) == noErr)
  219285. {
  219286. void* v = &cmp;
  219287. SetEventParameter (event, 'mess', typeVoidPtr, sizeof (void*), &v);
  219288. if (PostEventToQueue (mainQueue, event, kEventPriorityStandard) == noErr)
  219289. {
  219290. while (! cmp.hasBeenExecuted)
  219291. Thread::yield();
  219292. return cmp.result;
  219293. }
  219294. }
  219295. return 0;
  219296. #endif
  219297. }
  219298. }
  219299. END_JUCE_NAMESPACE
  219300. /********* End of inlined file: juce_mac_Messaging.mm *********/
  219301. /********* Start of inlined file: juce_mac_WebBrowserComponent.mm *********/
  219302. #include <Cocoa/Cocoa.h>
  219303. #include <WebKit/WebKit.h>
  219304. #include <WebKit/HIWebView.h>
  219305. #include <WebKit/WebPolicyDelegate.h>
  219306. #include <WebKit/CarbonUtils.h>
  219307. BEGIN_JUCE_NAMESPACE
  219308. END_JUCE_NAMESPACE
  219309. @interface DownloadClickDetector : NSObject
  219310. {
  219311. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  219312. }
  219313. - (DownloadClickDetector*) initWithOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  219314. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  219315. request: (NSURLRequest*) request
  219316. frame: (WebFrame*) frame
  219317. decisionListener: (id<WebPolicyDecisionListener>) listener;
  219318. @end
  219319. @implementation DownloadClickDetector
  219320. - (DownloadClickDetector*) initWithOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  219321. {
  219322. [super init];
  219323. ownerComponent = ownerComponent_;
  219324. return self;
  219325. }
  219326. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id < WebPolicyDecisionListener >)listener
  219327. {
  219328. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  219329. if (ownerComponent->pageAboutToLoad (JUCE_NAMESPACE::String::fromUTF8 ((const JUCE_NAMESPACE::uint8*) [[url absoluteString] UTF8String])))
  219330. [listener use];
  219331. else
  219332. [listener ignore];
  219333. }
  219334. @end
  219335. BEGIN_JUCE_NAMESPACE
  219336. class WebBrowserComponentInternal : public Timer
  219337. {
  219338. public:
  219339. WebBrowserComponentInternal (WebBrowserComponent* owner_)
  219340. : owner (owner_),
  219341. view (0),
  219342. webView (0)
  219343. {
  219344. HIWebViewCreate (&view);
  219345. ComponentPeer* const peer = owner_->getPeer();
  219346. jassert (peer != 0);
  219347. if (view != 0 && peer != 0)
  219348. {
  219349. WindowRef parentWindow = (WindowRef) peer->getNativeHandle();
  219350. WindowAttributes attributes;
  219351. GetWindowAttributes (parentWindow, &attributes);
  219352. HIViewRef parentView = 0;
  219353. if ((attributes & kWindowCompositingAttribute) != 0)
  219354. {
  219355. HIViewRef root = HIViewGetRoot (parentWindow);
  219356. HIViewFindByID (root, kHIViewWindowContentID, &parentView);
  219357. if (parentView == 0)
  219358. parentView = root;
  219359. }
  219360. else
  219361. {
  219362. GetRootControl (parentWindow, (ControlRef*) &parentView);
  219363. if (parentView == 0)
  219364. CreateRootControl (parentWindow, (ControlRef*) &parentView);
  219365. }
  219366. HIViewAddSubview (parentView, view);
  219367. updateBounds();
  219368. show();
  219369. webView = HIWebViewGetWebView (view);
  219370. clickListener = [[DownloadClickDetector alloc] initWithOwner: owner_];
  219371. [webView setPolicyDelegate: clickListener];
  219372. }
  219373. startTimer (500);
  219374. }
  219375. ~WebBrowserComponentInternal()
  219376. {
  219377. [webView setPolicyDelegate: nil];
  219378. [clickListener release];
  219379. if (view != 0)
  219380. CFRelease (view);
  219381. }
  219382. // Horrific bodge-workaround for the fact that the webview somehow hangs onto key
  219383. // focus when you pop up a new window, no matter what that window does to
  219384. // try to grab focus for itself. This catches such a situation and forces
  219385. // focus away from the webview, then back to the place it should be..
  219386. void timerCallback()
  219387. {
  219388. WindowRef viewWindow = HIViewGetWindow (view);
  219389. WindowRef focusedWindow = GetUserFocusWindow();
  219390. if (focusedWindow != viewWindow)
  219391. {
  219392. if (HIViewSubtreeContainsFocus (view))
  219393. {
  219394. HIViewAdvanceFocus (HIViewGetRoot (viewWindow), 0);
  219395. HIViewAdvanceFocus (HIViewGetRoot (focusedWindow), 0);
  219396. }
  219397. }
  219398. }
  219399. void show()
  219400. {
  219401. HIViewSetVisible (view, true);
  219402. }
  219403. void hide()
  219404. {
  219405. HIViewSetVisible (view, false);
  219406. }
  219407. void goToURL (const String& url,
  219408. const StringArray* headers,
  219409. const MemoryBlock* postData)
  219410. {
  219411. char** headerNamesAsChars = 0;
  219412. char** headerValuesAsChars = 0;
  219413. int numHeaders = 0;
  219414. if (headers != 0)
  219415. {
  219416. numHeaders = headers->size();
  219417. headerNamesAsChars = (char**) juce_malloc (sizeof (char*) * numHeaders);
  219418. headerValuesAsChars = (char**) juce_malloc (sizeof (char*) * numHeaders);
  219419. int i;
  219420. for (i = 0; i < numHeaders; ++i)
  219421. {
  219422. const String headerName ((*headers)[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  219423. headerNamesAsChars[i] = (char*) juce_calloc (headerName.copyToUTF8 (0));
  219424. headerName.copyToUTF8 ((JUCE_NAMESPACE::uint8*) headerNamesAsChars[i]);
  219425. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  219426. headerValuesAsChars[i] = (char*) juce_calloc (headerValue.copyToUTF8 (0));
  219427. headerValue.copyToUTF8 ((JUCE_NAMESPACE::uint8*) headerValuesAsChars[i]);
  219428. }
  219429. }
  219430. sendWebViewToURL ((const char*) url.toUTF8(),
  219431. (const char**) headerNamesAsChars,
  219432. (const char**) headerValuesAsChars,
  219433. numHeaders,
  219434. postData != 0 ? (const char*) postData->getData() : 0,
  219435. postData != 0 ? postData->getSize() : 0);
  219436. for (int i = 0; i < numHeaders; ++i)
  219437. {
  219438. juce_free (headerNamesAsChars[i]);
  219439. juce_free (headerValuesAsChars[i]);
  219440. }
  219441. juce_free (headerNamesAsChars);
  219442. juce_free (headerValuesAsChars);
  219443. }
  219444. void goBack()
  219445. {
  219446. [webView goBack];
  219447. }
  219448. void goForward()
  219449. {
  219450. [webView goForward];
  219451. }
  219452. void stop()
  219453. {
  219454. [webView stopLoading: nil];
  219455. }
  219456. void updateBounds()
  219457. {
  219458. HIRect r;
  219459. r.origin.x = (float) owner->getScreenX() - owner->getTopLevelComponent()->getScreenX();
  219460. r.origin.y = (float) owner->getScreenY() - owner->getTopLevelComponent()->getScreenY();
  219461. r.size.width = (float) owner->getWidth();
  219462. r.size.height = (float) owner->getHeight();
  219463. HIViewSetFrame (view, &r);
  219464. }
  219465. private:
  219466. WebBrowserComponent* const owner;
  219467. HIViewRef view;
  219468. WebView* webView;
  219469. DownloadClickDetector* clickListener;
  219470. void sendWebViewToURL (const char* utf8URL,
  219471. const char** headerNames,
  219472. const char** headerValues,
  219473. int numHeaders,
  219474. const char* postData,
  219475. int postDataSize)
  219476. {
  219477. NSMutableURLRequest* r = [NSMutableURLRequest
  219478. requestWithURL: [NSURL URLWithString: [NSString stringWithUTF8String: utf8URL]]
  219479. cachePolicy: NSURLRequestUseProtocolCachePolicy
  219480. timeoutInterval: 30.0];
  219481. if (postDataSize > 0)
  219482. {
  219483. [ r setHTTPMethod: @"POST"];
  219484. [ r setHTTPBody: [NSData dataWithBytes: postData length: postDataSize]];
  219485. }
  219486. int i;
  219487. for (i = 0; i < numHeaders; ++i)
  219488. {
  219489. [ r setValue: [NSString stringWithUTF8String: headerValues[i]]
  219490. forHTTPHeaderField: [NSString stringWithUTF8String: headerNames[i]]];
  219491. }
  219492. [[webView mainFrame] stopLoading ];
  219493. [[webView mainFrame] loadRequest: r];
  219494. }
  219495. WebBrowserComponentInternal (const WebBrowserComponentInternal&);
  219496. const WebBrowserComponentInternal& operator= (const WebBrowserComponentInternal&);
  219497. };
  219498. WebBrowserComponent::WebBrowserComponent()
  219499. : browser (0),
  219500. associatedWindow (0),
  219501. blankPageShown (false)
  219502. {
  219503. setOpaque (true);
  219504. }
  219505. WebBrowserComponent::~WebBrowserComponent()
  219506. {
  219507. deleteBrowser();
  219508. }
  219509. void WebBrowserComponent::goToURL (const String& url,
  219510. const StringArray* headers,
  219511. const MemoryBlock* postData)
  219512. {
  219513. lastURL = url;
  219514. lastHeaders.clear();
  219515. if (headers != 0)
  219516. lastHeaders = *headers;
  219517. lastPostData.setSize (0);
  219518. if (postData != 0)
  219519. lastPostData = *postData;
  219520. blankPageShown = false;
  219521. if (browser != 0)
  219522. browser->goToURL (url, headers, postData);
  219523. }
  219524. void WebBrowserComponent::stop()
  219525. {
  219526. if (browser != 0)
  219527. browser->stop();
  219528. }
  219529. void WebBrowserComponent::goBack()
  219530. {
  219531. lastURL = String::empty;
  219532. blankPageShown = false;
  219533. if (browser != 0)
  219534. browser->goBack();
  219535. }
  219536. void WebBrowserComponent::goForward()
  219537. {
  219538. lastURL = String::empty;
  219539. if (browser != 0)
  219540. browser->goForward();
  219541. }
  219542. void WebBrowserComponent::paint (Graphics& g)
  219543. {
  219544. if (browser == 0)
  219545. g.fillAll (Colours::white);
  219546. }
  219547. void WebBrowserComponent::checkWindowAssociation()
  219548. {
  219549. void* const window = getWindowHandle();
  219550. if (window != associatedWindow
  219551. || (browser == 0 && window != 0))
  219552. {
  219553. associatedWindow = window;
  219554. deleteBrowser();
  219555. createBrowser();
  219556. }
  219557. if (browser != 0)
  219558. {
  219559. if (associatedWindow != 0 && isShowing())
  219560. {
  219561. browser->show();
  219562. if (blankPageShown)
  219563. goBack();
  219564. }
  219565. else
  219566. {
  219567. if (! blankPageShown)
  219568. {
  219569. // when the component becomes invisible, some stuff like flash
  219570. // carries on playing audio, so we need to force it onto a blank
  219571. // page to avoid this..
  219572. blankPageShown = true;
  219573. browser->goToURL ("about:blank", 0, 0);
  219574. }
  219575. browser->hide();
  219576. }
  219577. }
  219578. }
  219579. void WebBrowserComponent::createBrowser()
  219580. {
  219581. deleteBrowser();
  219582. if (isShowing())
  219583. {
  219584. WebInitForCarbon();
  219585. browser = new WebBrowserComponentInternal (this);
  219586. reloadLastURL();
  219587. }
  219588. }
  219589. void WebBrowserComponent::deleteBrowser()
  219590. {
  219591. deleteAndZero (browser);
  219592. }
  219593. void WebBrowserComponent::reloadLastURL()
  219594. {
  219595. if (lastURL.isNotEmpty())
  219596. {
  219597. goToURL (lastURL, &lastHeaders, &lastPostData);
  219598. lastURL = String::empty;
  219599. }
  219600. }
  219601. void WebBrowserComponent::updateBrowserPosition()
  219602. {
  219603. if (getPeer() != 0 && browser != 0)
  219604. browser->updateBounds();
  219605. }
  219606. void WebBrowserComponent::parentHierarchyChanged()
  219607. {
  219608. checkWindowAssociation();
  219609. }
  219610. void WebBrowserComponent::moved()
  219611. {
  219612. updateBrowserPosition();
  219613. }
  219614. void WebBrowserComponent::resized()
  219615. {
  219616. updateBrowserPosition();
  219617. }
  219618. void WebBrowserComponent::visibilityChanged()
  219619. {
  219620. checkWindowAssociation();
  219621. }
  219622. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  219623. {
  219624. return true;
  219625. }
  219626. END_JUCE_NAMESPACE
  219627. /********* End of inlined file: juce_mac_WebBrowserComponent.mm *********/
  219628. /********* Start of inlined file: juce_mac_Windowing.mm *********/
  219629. #include <Carbon/Carbon.h>
  219630. #include <IOKit/IOKitLib.h>
  219631. #include <IOKit/IOCFPlugIn.h>
  219632. #include <IOKit/hid/IOHIDLib.h>
  219633. #include <IOKit/hid/IOHIDKeys.h>
  219634. #include <fnmatch.h>
  219635. #if JUCE_OPENGL
  219636. #include <AGL/agl.h>
  219637. #endif
  219638. BEGIN_JUCE_NAMESPACE
  219639. #undef Point
  219640. const WindowRegionCode windowRegionToUse = kWindowContentRgn;
  219641. static HIObjectClassRef viewClassRef = 0;
  219642. static CFStringRef juceHiViewClassNameCFString = 0;
  219643. static ComponentPeer* juce_currentMouseTrackingPeer = 0;
  219644. static VoidArray keysCurrentlyDown;
  219645. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  219646. {
  219647. if (keysCurrentlyDown.contains ((void*) keyCode))
  219648. return true;
  219649. if (keyCode >= 'A' && keyCode <= 'Z'
  219650. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toLowerCase ((tchar) keyCode)))
  219651. return true;
  219652. if (keyCode >= 'a' && keyCode <= 'z'
  219653. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toUpperCase ((tchar) keyCode)))
  219654. return true;
  219655. return false;
  219656. }
  219657. static VoidArray minimisedWindows;
  219658. static void setWindowMinimised (WindowRef ref, const bool isMinimised)
  219659. {
  219660. if (isMinimised != minimisedWindows.contains (ref))
  219661. CollapseWindow (ref, isMinimised);
  219662. }
  219663. void juce_maximiseAllMinimisedWindows()
  219664. {
  219665. const VoidArray minWin (minimisedWindows);
  219666. for (int i = minWin.size(); --i >= 0;)
  219667. setWindowMinimised ((WindowRef) (minWin[i]), false);
  219668. }
  219669. class HIViewComponentPeer;
  219670. static HIViewComponentPeer* currentlyFocusedPeer = 0;
  219671. static int currentModifiers = 0;
  219672. static void updateModifiers (EventRef theEvent)
  219673. {
  219674. currentModifiers &= ~ (ModifierKeys::shiftModifier | ModifierKeys::ctrlModifier
  219675. | ModifierKeys::altModifier | ModifierKeys::commandModifier);
  219676. UInt32 m;
  219677. if (theEvent != 0)
  219678. GetEventParameter (theEvent, kEventParamKeyModifiers, typeUInt32, 0, sizeof(m), 0, &m);
  219679. else
  219680. m = GetCurrentEventKeyModifiers();
  219681. if ((m & (shiftKey | rightShiftKey)) != 0)
  219682. currentModifiers |= ModifierKeys::shiftModifier;
  219683. if ((m & (controlKey | rightControlKey)) != 0)
  219684. currentModifiers |= ModifierKeys::ctrlModifier;
  219685. if ((m & (optionKey | rightOptionKey)) != 0)
  219686. currentModifiers |= ModifierKeys::altModifier;
  219687. if ((m & cmdKey) != 0)
  219688. currentModifiers |= ModifierKeys::commandModifier;
  219689. }
  219690. void ModifierKeys::updateCurrentModifiers() throw()
  219691. {
  219692. currentModifierFlags = currentModifiers;
  219693. }
  219694. static int64 getEventTime (EventRef event)
  219695. {
  219696. const int64 millis = (int64) (1000.0 * (event != 0 ? GetEventTime (event)
  219697. : GetCurrentEventTime()));
  219698. static int64 offset = 0;
  219699. if (offset == 0)
  219700. offset = Time::currentTimeMillis() - millis;
  219701. return offset + millis;
  219702. }
  219703. class MacBitmapImage : public Image
  219704. {
  219705. public:
  219706. CGColorSpaceRef colourspace;
  219707. CGDataProviderRef provider;
  219708. MacBitmapImage (const PixelFormat format_,
  219709. const int w, const int h, const bool clearImage)
  219710. : Image (format_, w, h)
  219711. {
  219712. jassert (format_ == RGB || format_ == ARGB);
  219713. pixelStride = (format_ == RGB) ? 3 : 4;
  219714. lineStride = (w * pixelStride + 3) & ~3;
  219715. const int imageSize = lineStride * h;
  219716. if (clearImage)
  219717. imageData = (uint8*) juce_calloc (imageSize);
  219718. else
  219719. imageData = (uint8*) juce_malloc (imageSize);
  219720. //colourspace = CGColorSpaceCreateWithName (kCGColorSpaceUserRGB);
  219721. CMProfileRef prof;
  219722. CMGetSystemProfile (&prof);
  219723. colourspace = CGColorSpaceCreateWithPlatformColorSpace (prof);
  219724. provider = CGDataProviderCreateWithData (0, imageData, h * lineStride, 0);
  219725. CMCloseProfile (prof);
  219726. }
  219727. MacBitmapImage::~MacBitmapImage()
  219728. {
  219729. CGDataProviderRelease (provider);
  219730. CGColorSpaceRelease (colourspace);
  219731. juce_free (imageData);
  219732. imageData = 0; // to stop the base class freeing this
  219733. }
  219734. void blitToContext (CGContextRef context, const float dx, const float dy)
  219735. {
  219736. CGImageRef tempImage = CGImageCreate (getWidth(), getHeight(),
  219737. 8, pixelStride << 3, lineStride, colourspace,
  219738. #if MACOS_10_3_OR_EARLIER || JUCE_BIG_ENDIAN
  219739. hasAlphaChannel() ? kCGImageAlphaPremultipliedFirst
  219740. : kCGImageAlphaNone,
  219741. #else
  219742. hasAlphaChannel() ? kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst
  219743. : kCGImageAlphaNone,
  219744. #endif
  219745. provider, 0, false,
  219746. kCGRenderingIntentDefault);
  219747. HIRect r;
  219748. r.origin.x = dx;
  219749. r.origin.y = dy;
  219750. r.size.width = (float) getWidth();
  219751. r.size.height = (float) getHeight();
  219752. HIViewDrawCGImage (context, &r, tempImage);
  219753. CGImageRelease (tempImage);
  219754. }
  219755. juce_UseDebuggingNewOperator
  219756. };
  219757. class MouseCheckTimer : private Timer,
  219758. private DeletedAtShutdown
  219759. {
  219760. public:
  219761. MouseCheckTimer()
  219762. : lastX (0),
  219763. lastY (0)
  219764. {
  219765. lastPeerUnderMouse = 0;
  219766. resetMouseMoveChecker();
  219767. #if ! MACOS_10_2_OR_EARLIER
  219768. // Just putting this in here because it's a convenient object that'll get deleted at shutdown
  219769. CGDisplayRegisterReconfigurationCallback (&displayChangeCallback, 0);
  219770. #endif
  219771. }
  219772. ~MouseCheckTimer()
  219773. {
  219774. #if ! MACOS_10_2_OR_EARLIER
  219775. CGDisplayRemoveReconfigurationCallback (&displayChangeCallback, 0);
  219776. #endif
  219777. clearSingletonInstance();
  219778. }
  219779. juce_DeclareSingleton_SingleThreaded_Minimal (MouseCheckTimer)
  219780. bool hasEverHadAMouseMove;
  219781. void moved (HIViewComponentPeer* const peer)
  219782. {
  219783. if (hasEverHadAMouseMove)
  219784. startTimer (200);
  219785. lastPeerUnderMouse = peer;
  219786. }
  219787. void resetMouseMoveChecker()
  219788. {
  219789. hasEverHadAMouseMove = false;
  219790. startTimer (1000 / 16);
  219791. }
  219792. void timerCallback();
  219793. private:
  219794. HIViewComponentPeer* lastPeerUnderMouse;
  219795. int lastX, lastY;
  219796. #if ! MACOS_10_2_OR_EARLIER
  219797. static void displayChangeCallback (CGDirectDisplayID, CGDisplayChangeSummaryFlags flags, void*)
  219798. {
  219799. Desktop::getInstance().refreshMonitorSizes();
  219800. }
  219801. #endif
  219802. };
  219803. juce_ImplementSingleton_SingleThreaded (MouseCheckTimer)
  219804. #if JUCE_QUICKTIME
  219805. extern void OfferMouseClickToQuickTime (WindowRef window, ::Point where, long when, long modifiers,
  219806. Component* topLevelComp);
  219807. #endif
  219808. class HIViewComponentPeer : public ComponentPeer,
  219809. private Timer
  219810. {
  219811. public:
  219812. HIViewComponentPeer (Component* const component,
  219813. const int windowStyleFlags,
  219814. HIViewRef viewToAttachTo)
  219815. : ComponentPeer (component, windowStyleFlags),
  219816. fullScreen (false),
  219817. isCompositingWindow (false),
  219818. windowRef (0),
  219819. viewRef (0)
  219820. {
  219821. repainter = new RepaintManager (this);
  219822. eventHandlerRef = 0;
  219823. if (viewToAttachTo != 0)
  219824. {
  219825. isSharedWindow = true;
  219826. }
  219827. else
  219828. {
  219829. isSharedWindow = false;
  219830. WindowRef newWindow = createNewWindow (windowStyleFlags);
  219831. GetRootControl (newWindow, (ControlRef*) &viewToAttachTo);
  219832. jassert (viewToAttachTo != 0);
  219833. HIViewRef growBox = 0;
  219834. HIViewFindByID (HIViewGetRoot (newWindow), kHIViewWindowGrowBoxID, &growBox);
  219835. if (growBox != 0)
  219836. HIGrowBoxViewSetTransparent (growBox, true);
  219837. }
  219838. createNewHIView();
  219839. HIViewAddSubview (viewToAttachTo, viewRef);
  219840. HIViewSetVisible (viewRef, component->isVisible());
  219841. setTitle (component->getName());
  219842. if (component->isVisible() && ! isSharedWindow)
  219843. {
  219844. ShowWindow (windowRef);
  219845. ActivateWindow (windowRef, component->getWantsKeyboardFocus());
  219846. }
  219847. }
  219848. ~HIViewComponentPeer()
  219849. {
  219850. minimisedWindows.removeValue (windowRef);
  219851. if (IsValidWindowPtr (windowRef))
  219852. {
  219853. if (! isSharedWindow)
  219854. {
  219855. CFRelease (viewRef);
  219856. viewRef = 0;
  219857. DisposeWindow (windowRef);
  219858. }
  219859. else
  219860. {
  219861. if (eventHandlerRef != 0)
  219862. RemoveEventHandler (eventHandlerRef);
  219863. CFRelease (viewRef);
  219864. viewRef = 0;
  219865. }
  219866. windowRef = 0;
  219867. }
  219868. if (currentlyFocusedPeer == this)
  219869. currentlyFocusedPeer = 0;
  219870. delete repainter;
  219871. }
  219872. void* getNativeHandle() const
  219873. {
  219874. return windowRef;
  219875. }
  219876. void setVisible (bool shouldBeVisible)
  219877. {
  219878. HIViewSetVisible (viewRef, shouldBeVisible);
  219879. if ((! isSharedWindow) && IsValidWindowPtr (windowRef))
  219880. {
  219881. if (shouldBeVisible)
  219882. ShowWindow (windowRef);
  219883. else
  219884. HideWindow (windowRef);
  219885. resizeViewToFitWindow();
  219886. // If nothing else is focused, then grab the focus too
  219887. if (shouldBeVisible
  219888. && Component::getCurrentlyFocusedComponent() == 0
  219889. && Process::isForegroundProcess())
  219890. {
  219891. component->toFront (true);
  219892. }
  219893. }
  219894. }
  219895. void setTitle (const String& title)
  219896. {
  219897. if ((! isSharedWindow) && IsValidWindowPtr (windowRef))
  219898. {
  219899. CFStringRef t = PlatformUtilities::juceStringToCFString (title);
  219900. SetWindowTitleWithCFString (windowRef, t);
  219901. CFRelease (t);
  219902. }
  219903. }
  219904. void setPosition (int x, int y)
  219905. {
  219906. if (isSharedWindow)
  219907. {
  219908. HIViewPlaceInSuperviewAt (viewRef, x, y);
  219909. }
  219910. else if (IsValidWindowPtr (windowRef))
  219911. {
  219912. Rect r;
  219913. GetWindowBounds (windowRef, windowRegionToUse, &r);
  219914. r.right += x - r.left;
  219915. r.bottom += y - r.top;
  219916. r.left = x;
  219917. r.top = y;
  219918. SetWindowBounds (windowRef, windowRegionToUse, &r);
  219919. }
  219920. }
  219921. void setSize (int w, int h)
  219922. {
  219923. w = jmax (0, w);
  219924. h = jmax (0, h);
  219925. if (w != getComponent()->getWidth()
  219926. || h != getComponent()->getHeight())
  219927. {
  219928. repainter->repaint (0, 0, w, h);
  219929. }
  219930. if (isSharedWindow)
  219931. {
  219932. HIRect r;
  219933. HIViewGetFrame (viewRef, &r);
  219934. r.size.width = (float) w;
  219935. r.size.height = (float) h;
  219936. HIViewSetFrame (viewRef, &r);
  219937. }
  219938. else if (IsValidWindowPtr (windowRef))
  219939. {
  219940. Rect r;
  219941. GetWindowBounds (windowRef, windowRegionToUse, &r);
  219942. r.right = r.left + w;
  219943. r.bottom = r.top + h;
  219944. SetWindowBounds (windowRef, windowRegionToUse, &r);
  219945. }
  219946. }
  219947. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  219948. {
  219949. fullScreen = isNowFullScreen;
  219950. w = jmax (0, w);
  219951. h = jmax (0, h);
  219952. if (w != getComponent()->getWidth()
  219953. || h != getComponent()->getHeight())
  219954. {
  219955. repainter->repaint (0, 0, w, h);
  219956. }
  219957. if (isSharedWindow)
  219958. {
  219959. HIRect r;
  219960. r.origin.x = (float) x;
  219961. r.origin.y = (float) y;
  219962. r.size.width = (float) w;
  219963. r.size.height = (float) h;
  219964. HIViewSetFrame (viewRef, &r);
  219965. }
  219966. else if (IsValidWindowPtr (windowRef))
  219967. {
  219968. Rect r;
  219969. r.left = x;
  219970. r.top = y;
  219971. r.right = x + w;
  219972. r.bottom = y + h;
  219973. SetWindowBounds (windowRef, windowRegionToUse, &r);
  219974. }
  219975. }
  219976. void getBounds (int& x, int& y, int& w, int& h, const bool global) const
  219977. {
  219978. HIRect hiViewPos;
  219979. HIViewGetFrame (viewRef, &hiViewPos);
  219980. if (global)
  219981. {
  219982. HIViewRef content = 0;
  219983. HIViewFindByID (HIViewGetRoot (windowRef), kHIViewWindowContentID, &content);
  219984. HIPoint p = { 0.0f, 0.0f };
  219985. HIViewConvertPoint (&p, viewRef, content);
  219986. x = (int) p.x;
  219987. y = (int) p.y;
  219988. if (IsValidWindowPtr (windowRef))
  219989. {
  219990. Rect windowPos;
  219991. GetWindowBounds (windowRef, kWindowContentRgn, &windowPos);
  219992. x += windowPos.left;
  219993. y += windowPos.top;
  219994. }
  219995. }
  219996. else
  219997. {
  219998. x = (int) hiViewPos.origin.x;
  219999. y = (int) hiViewPos.origin.y;
  220000. }
  220001. w = (int) hiViewPos.size.width;
  220002. h = (int) hiViewPos.size.height;
  220003. }
  220004. void getBounds (int& x, int& y, int& w, int& h) const
  220005. {
  220006. getBounds (x, y, w, h, ! isSharedWindow);
  220007. }
  220008. int getScreenX() const
  220009. {
  220010. int x, y, w, h;
  220011. getBounds (x, y, w, h, true);
  220012. return x;
  220013. }
  220014. int getScreenY() const
  220015. {
  220016. int x, y, w, h;
  220017. getBounds (x, y, w, h, true);
  220018. return y;
  220019. }
  220020. void relativePositionToGlobal (int& x, int& y)
  220021. {
  220022. int wx, wy, ww, wh;
  220023. getBounds (wx, wy, ww, wh, true);
  220024. x += wx;
  220025. y += wy;
  220026. }
  220027. void globalPositionToRelative (int& x, int& y)
  220028. {
  220029. int wx, wy, ww, wh;
  220030. getBounds (wx, wy, ww, wh, true);
  220031. x -= wx;
  220032. y -= wy;
  220033. }
  220034. void setMinimised (bool shouldBeMinimised)
  220035. {
  220036. if (! isSharedWindow)
  220037. setWindowMinimised (windowRef, shouldBeMinimised);
  220038. }
  220039. bool isMinimised() const
  220040. {
  220041. return minimisedWindows.contains (windowRef);
  220042. }
  220043. void setFullScreen (bool shouldBeFullScreen)
  220044. {
  220045. if (! isSharedWindow)
  220046. {
  220047. Rectangle r (lastNonFullscreenBounds);
  220048. setMinimised (false);
  220049. if (fullScreen != shouldBeFullScreen)
  220050. {
  220051. if (shouldBeFullScreen)
  220052. r = Desktop::getInstance().getMainMonitorArea();
  220053. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  220054. if (r != getComponent()->getBounds() && ! r.isEmpty())
  220055. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  220056. }
  220057. }
  220058. }
  220059. bool isFullScreen() const
  220060. {
  220061. return fullScreen;
  220062. }
  220063. bool contains (int x, int y, bool trueIfInAChildWindow) const
  220064. {
  220065. if (((unsigned int) x) >= (unsigned int) component->getWidth()
  220066. || ((unsigned int) y) >= (unsigned int) component->getHeight()
  220067. || ! IsValidWindowPtr (windowRef))
  220068. return false;
  220069. Rect r;
  220070. GetWindowBounds (windowRef, windowRegionToUse, &r);
  220071. ::Point p;
  220072. p.h = r.left + x;
  220073. p.v = r.top + y;
  220074. WindowRef ref2 = 0;
  220075. FindWindow (p, &ref2);
  220076. if (windowRef != ref2)
  220077. return false;
  220078. if (trueIfInAChildWindow)
  220079. return true;
  220080. HIPoint p2;
  220081. p2.x = (float) x;
  220082. p2.y = (float) y;
  220083. HIViewRef hit;
  220084. HIViewGetSubviewHit (viewRef, &p2, true, &hit);
  220085. return hit == 0 || hit == viewRef;
  220086. }
  220087. const BorderSize getFrameSize() const
  220088. {
  220089. return BorderSize();
  220090. }
  220091. bool setAlwaysOnTop (bool alwaysOnTop)
  220092. {
  220093. // can't do this so return false and let the component create a new window
  220094. return false;
  220095. }
  220096. void toFront (bool makeActiveWindow)
  220097. {
  220098. makeActiveWindow = makeActiveWindow
  220099. && component->isValidComponent()
  220100. && (component->getWantsKeyboardFocus()
  220101. || component->isCurrentlyModal());
  220102. if (windowRef != FrontWindow()
  220103. || (makeActiveWindow && ! IsWindowActive (windowRef))
  220104. || ! Process::isForegroundProcess())
  220105. {
  220106. if (! Process::isForegroundProcess())
  220107. {
  220108. ProcessSerialNumber psn;
  220109. GetCurrentProcess (&psn);
  220110. SetFrontProcessWithOptions (&psn, kSetFrontProcessFrontWindowOnly);
  220111. }
  220112. if (IsValidWindowPtr (windowRef))
  220113. {
  220114. if (makeActiveWindow)
  220115. {
  220116. SelectWindow (windowRef);
  220117. SetUserFocusWindow (windowRef);
  220118. HIViewAdvanceFocus (viewRef, 0);
  220119. }
  220120. else
  220121. {
  220122. BringToFront (windowRef);
  220123. }
  220124. handleBroughtToFront();
  220125. }
  220126. }
  220127. }
  220128. void toBehind (ComponentPeer* other)
  220129. {
  220130. HIViewComponentPeer* const otherWindow = dynamic_cast <HIViewComponentPeer*> (other);
  220131. if (other != 0 && windowRef != 0 && otherWindow->windowRef != 0)
  220132. {
  220133. if (windowRef == otherWindow->windowRef)
  220134. {
  220135. HIViewSetZOrder (viewRef, kHIViewZOrderBelow, otherWindow->viewRef);
  220136. }
  220137. else
  220138. {
  220139. SendBehind (windowRef, otherWindow->windowRef);
  220140. }
  220141. }
  220142. }
  220143. void setIcon (const Image& /*newIcon*/)
  220144. {
  220145. // to do..
  220146. }
  220147. void viewFocusGain()
  220148. {
  220149. const MessageManagerLock messLock;
  220150. if (currentlyFocusedPeer != this)
  220151. {
  220152. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  220153. currentlyFocusedPeer->handleFocusLoss();
  220154. currentlyFocusedPeer = this;
  220155. handleFocusGain();
  220156. }
  220157. }
  220158. void viewFocusLoss()
  220159. {
  220160. if (currentlyFocusedPeer == this)
  220161. {
  220162. currentlyFocusedPeer = 0;
  220163. handleFocusLoss();
  220164. }
  220165. }
  220166. bool isFocused() const
  220167. {
  220168. return windowRef == GetUserFocusWindow()
  220169. && HIViewSubtreeContainsFocus (viewRef);
  220170. }
  220171. void grabFocus()
  220172. {
  220173. if ((! isFocused()) && IsValidWindowPtr (windowRef))
  220174. {
  220175. SetUserFocusWindow (windowRef);
  220176. HIViewAdvanceFocus (viewRef, 0);
  220177. }
  220178. }
  220179. void textInputRequired (int /*x*/, int /*y*/)
  220180. {
  220181. }
  220182. void repaint (int x, int y, int w, int h)
  220183. {
  220184. if (Rectangle::intersectRectangles (x, y, w, h,
  220185. 0, 0,
  220186. getComponent()->getWidth(),
  220187. getComponent()->getHeight()))
  220188. {
  220189. if ((getStyleFlags() & windowRepaintedExplictly) == 0)
  220190. {
  220191. if (isCompositingWindow)
  220192. {
  220193. #if MACOS_10_3_OR_EARLIER
  220194. RgnHandle rgn = NewRgn();
  220195. SetRectRgn (rgn, x, y, x + w, y + h);
  220196. HIViewSetNeedsDisplayInRegion (viewRef, rgn, true);
  220197. DisposeRgn (rgn);
  220198. #else
  220199. HIRect r;
  220200. r.origin.x = x;
  220201. r.origin.y = y;
  220202. r.size.width = w;
  220203. r.size.height = h;
  220204. HIViewSetNeedsDisplayInRect (viewRef, &r, true);
  220205. #endif
  220206. }
  220207. else
  220208. {
  220209. if (! isTimerRunning())
  220210. startTimer (20);
  220211. }
  220212. }
  220213. repainter->repaint (x, y, w, h);
  220214. }
  220215. }
  220216. void timerCallback()
  220217. {
  220218. performAnyPendingRepaintsNow();
  220219. }
  220220. void performAnyPendingRepaintsNow()
  220221. {
  220222. stopTimer();
  220223. if (component->isVisible())
  220224. {
  220225. #if MACOS_10_2_OR_EARLIER
  220226. if (! isCompositingWindow)
  220227. {
  220228. Rect w;
  220229. GetWindowBounds (windowRef, windowRegionToUse, &w);
  220230. const int offsetInWindowX = component->getScreenX() - getScreenX();
  220231. const int offsetInWindowY = component->getScreenY() - getScreenY();
  220232. for (RectangleList::Iterator i (repainter->getRegionsNeedingRepaint()); i.next();)
  220233. {
  220234. const Rectangle& r = *i.getRectangle();
  220235. w.left = offsetInWindowX + r.getX();
  220236. w.top = offsetInWindowY + r.getY();
  220237. w.right = offsetInWindowX + r.getRight();
  220238. w.bottom = offsetInWindowY + r.getBottom();
  220239. InvalWindowRect (windowRef, &w);
  220240. }
  220241. }
  220242. else
  220243. {
  220244. EventRef theEvent;
  220245. EventTypeSpec eventTypes[1];
  220246. eventTypes[0].eventClass = kEventClassControl;
  220247. eventTypes[0].eventKind = kEventControlDraw;
  220248. int n = 3;
  220249. while (--n >= 0
  220250. && ReceiveNextEvent (1, eventTypes, kEventDurationNoWait, true, &theEvent) == noErr)
  220251. {
  220252. if (GetEventClass (theEvent) == kEventClassAppleEvent)
  220253. {
  220254. EventRecord eventRec;
  220255. if (ConvertEventRefToEventRecord (theEvent, &eventRec))
  220256. AEProcessAppleEvent (&eventRec);
  220257. }
  220258. else
  220259. {
  220260. EventTargetRef theTarget = GetEventDispatcherTarget();
  220261. SendEventToEventTarget (theEvent, theTarget);
  220262. }
  220263. ReleaseEvent (theEvent);
  220264. }
  220265. }
  220266. #else
  220267. if (HIViewGetNeedsDisplay (viewRef) || repainter->isRepaintNeeded())
  220268. HIViewRender (viewRef);
  220269. #endif
  220270. }
  220271. }
  220272. juce_UseDebuggingNewOperator
  220273. WindowRef windowRef;
  220274. HIViewRef viewRef;
  220275. private:
  220276. EventHandlerRef eventHandlerRef;
  220277. bool fullScreen, isSharedWindow, isCompositingWindow;
  220278. StringArray dragAndDropFiles;
  220279. class RepaintManager : public Timer
  220280. {
  220281. public:
  220282. RepaintManager (HIViewComponentPeer* const peer_)
  220283. : peer (peer_),
  220284. image (0)
  220285. {
  220286. }
  220287. ~RepaintManager()
  220288. {
  220289. delete image;
  220290. }
  220291. void timerCallback()
  220292. {
  220293. stopTimer();
  220294. deleteAndZero (image);
  220295. }
  220296. void repaint (int x, int y, int w, int h)
  220297. {
  220298. regionsNeedingRepaint.add (x, y, w, h);
  220299. }
  220300. bool isRepaintNeeded() const throw()
  220301. {
  220302. return ! regionsNeedingRepaint.isEmpty();
  220303. }
  220304. void repaintAnyRemainingRegions()
  220305. {
  220306. // if any regions have been invaldated during the paint callback,
  220307. // we need to repaint them explicitly because the mac throws this
  220308. // stuff away
  220309. for (RectangleList::Iterator i (regionsNeedingRepaint); i.next();)
  220310. {
  220311. const Rectangle& r = *i.getRectangle();
  220312. peer->repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  220313. }
  220314. }
  220315. void paint (CGContextRef cgContext, int x, int y, int w, int h)
  220316. {
  220317. if (w > 0 && h > 0)
  220318. {
  220319. bool refresh = false;
  220320. int imW = image != 0 ? image->getWidth() : 0;
  220321. int imH = image != 0 ? image->getHeight() : 0;
  220322. if (imW < w || imH < h)
  220323. {
  220324. imW = jmin (peer->getComponent()->getWidth(), (w + 31) & ~31);
  220325. imH = jmin (peer->getComponent()->getHeight(), (h + 31) & ~31);
  220326. delete image;
  220327. image = new MacBitmapImage (peer->getComponent()->isOpaque() ? Image::RGB
  220328. : Image::ARGB,
  220329. imW, imH, false);
  220330. refresh = true;
  220331. }
  220332. else if (imageX > x || imageY > y
  220333. || imageX + imW < x + w
  220334. || imageY + imH < y + h)
  220335. {
  220336. refresh = true;
  220337. }
  220338. if (refresh)
  220339. {
  220340. regionsNeedingRepaint.clear();
  220341. regionsNeedingRepaint.addWithoutMerging (Rectangle (x, y, imW, imH));
  220342. imageX = x;
  220343. imageY = y;
  220344. }
  220345. LowLevelGraphicsSoftwareRenderer context (*image);
  220346. context.setOrigin (-imageX, -imageY);
  220347. if (context.reduceClipRegion (regionsNeedingRepaint))
  220348. {
  220349. regionsNeedingRepaint.clear();
  220350. if (! peer->getComponent()->isOpaque())
  220351. {
  220352. for (RectangleList::Iterator i (*context.getRawClipRegion()); i.next();)
  220353. {
  220354. const Rectangle& r = *i.getRectangle();
  220355. image->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  220356. }
  220357. }
  220358. regionsNeedingRepaint.clear();
  220359. peer->clearMaskedRegion();
  220360. peer->handlePaint (context);
  220361. }
  220362. else
  220363. {
  220364. regionsNeedingRepaint.clear();
  220365. }
  220366. if (! peer->maskedRegion.isEmpty())
  220367. {
  220368. RectangleList total (Rectangle (x, y, w, h));
  220369. total.subtract (peer->maskedRegion);
  220370. CGRect* rects = (CGRect*) juce_malloc (sizeof (CGRect) * total.getNumRectangles());
  220371. int n = 0;
  220372. for (RectangleList::Iterator i (total); i.next();)
  220373. {
  220374. const Rectangle& r = *i.getRectangle();
  220375. rects[n].origin.x = (int) r.getX();
  220376. rects[n].origin.y = (int) r.getY();
  220377. rects[n].size.width = roundFloatToInt (r.getWidth());
  220378. rects[n++].size.height = roundFloatToInt (r.getHeight());
  220379. }
  220380. CGContextClipToRects (cgContext, rects, n);
  220381. juce_free (rects);
  220382. }
  220383. if (peer->isSharedWindow)
  220384. {
  220385. CGRect clip;
  220386. clip.origin.x = x;
  220387. clip.origin.y = y;
  220388. clip.size.width = jmin (w, peer->getComponent()->getWidth() - x);
  220389. clip.size.height = jmin (h, peer->getComponent()->getHeight() - y);
  220390. CGContextClipToRect (cgContext, clip);
  220391. }
  220392. image->blitToContext (cgContext, imageX, imageY);
  220393. }
  220394. startTimer (3000);
  220395. }
  220396. private:
  220397. HIViewComponentPeer* const peer;
  220398. MacBitmapImage* image;
  220399. int imageX, imageY;
  220400. RectangleList regionsNeedingRepaint;
  220401. RepaintManager (const RepaintManager&);
  220402. const RepaintManager& operator= (const RepaintManager&);
  220403. };
  220404. RepaintManager* repainter;
  220405. friend class RepaintManager;
  220406. static OSStatus handleFrameRepaintEvent (EventHandlerCallRef myHandler,
  220407. EventRef theEvent,
  220408. void* userData)
  220409. {
  220410. // don't draw the frame..
  220411. return noErr;
  220412. }
  220413. OSStatus handleKeyEvent (EventRef theEvent, juce_wchar textCharacter)
  220414. {
  220415. updateModifiers (theEvent);
  220416. UniChar unicodeChars [4];
  220417. zeromem (unicodeChars, sizeof (unicodeChars));
  220418. GetEventParameter (theEvent, kEventParamKeyUnicodes, typeUnicodeText, 0, sizeof (unicodeChars), 0, unicodeChars);
  220419. int keyCode = (int) (unsigned int) unicodeChars[0];
  220420. UInt32 rawKey = 0;
  220421. GetEventParameter (theEvent, kEventParamKeyCode, typeUInt32, 0, sizeof (UInt32), 0, &rawKey);
  220422. if ((currentModifiers & ModifierKeys::ctrlModifier) != 0
  220423. && keyCode >= 1 && keyCode <= 26)
  220424. {
  220425. keyCode += ('A' - 1);
  220426. }
  220427. else
  220428. {
  220429. static const int keyTranslations[] =
  220430. {
  220431. 0, 's', 'd', 'f', 'h', 'g', 'z', 'x', 'c', 'v', 0xa7, 'b',
  220432. 'q', 'w', 'e', 'r', 'y', 't', '1', '2', '3', '4', '6', '5',
  220433. '=', '9', '7', '-', '8', '0', ']', 'o', 'u', '[', 'i', 'p',
  220434. KeyPress::returnKey, 'l', 'j', '\'', 'k', ';', '\\', ',', '/',
  220435. 'n', 'm', '.', 0, KeyPress::spaceKey, '`', KeyPress::backspaceKey, 0, 0, 0, 0,
  220436. 0, 0, 0, 0, 0, 0, 0, 0, 0, KeyPress::numberPadDecimalPoint,
  220437. 0, KeyPress::numberPadMultiply, 0, KeyPress::numberPadAdd,
  220438. 0, KeyPress::numberPadDelete, 0, 0, 0, KeyPress::numberPadDivide, KeyPress::returnKey,
  220439. 0, KeyPress::numberPadSubtract, 0, 0, KeyPress::numberPadEquals, KeyPress::numberPad0,
  220440. KeyPress::numberPad1, KeyPress::numberPad2, KeyPress::numberPad3,
  220441. KeyPress::numberPad4, KeyPress::numberPad5, KeyPress::numberPad6,
  220442. KeyPress::numberPad7, 0, KeyPress::numberPad8, KeyPress::numberPad9,
  220443. 0, 0, 0, KeyPress::F5Key, KeyPress::F6Key, KeyPress::F7Key, KeyPress::F3Key,
  220444. KeyPress::F8Key, KeyPress::F9Key, 0, KeyPress::F11Key, 0, KeyPress::F13Key,
  220445. KeyPress::F16Key, KeyPress::F14Key, 0, KeyPress::F10Key, 0, KeyPress::F12Key,
  220446. 0, KeyPress::F15Key, 0, KeyPress::homeKey, KeyPress::pageUpKey, 0, KeyPress::F4Key,
  220447. KeyPress::endKey, KeyPress::F2Key, KeyPress::pageDownKey, KeyPress::F1Key,
  220448. KeyPress::leftKey, KeyPress::rightKey, KeyPress::downKey, KeyPress::upKey, 0
  220449. };
  220450. if (((unsigned int) rawKey) < (unsigned int) numElementsInArray (keyTranslations)
  220451. && keyTranslations [rawKey] != 0)
  220452. {
  220453. keyCode = keyTranslations [rawKey];
  220454. }
  220455. if ((rawKey == 0 && textCharacter != 0)
  220456. || (CharacterFunctions::isLetterOrDigit ((juce_wchar) keyCode)
  220457. && CharacterFunctions::isLetterOrDigit (textCharacter))) // correction for azerty-type layouts..
  220458. {
  220459. keyCode = CharacterFunctions::toLowerCase (textCharacter);
  220460. }
  220461. }
  220462. if ((currentModifiers & (ModifierKeys::commandModifier | ModifierKeys::ctrlModifier)) != 0)
  220463. textCharacter = 0;
  220464. static juce_wchar lastTextCharacter = 0;
  220465. switch (GetEventKind (theEvent))
  220466. {
  220467. case kEventRawKeyDown:
  220468. {
  220469. keysCurrentlyDown.addIfNotAlreadyThere ((void*) keyCode);
  220470. lastTextCharacter = textCharacter;
  220471. const bool used1 = handleKeyUpOrDown();
  220472. const bool used2 = handleKeyPress (keyCode, textCharacter);
  220473. if (used1 || used2)
  220474. return noErr;
  220475. break;
  220476. }
  220477. case kEventRawKeyUp:
  220478. keysCurrentlyDown.removeValue ((void*) keyCode);
  220479. lastTextCharacter = 0;
  220480. if (handleKeyUpOrDown())
  220481. return noErr;
  220482. break;
  220483. case kEventRawKeyRepeat:
  220484. if (handleKeyPress (keyCode, lastTextCharacter))
  220485. return noErr;
  220486. break;
  220487. case kEventRawKeyModifiersChanged:
  220488. handleModifierKeysChange();
  220489. break;
  220490. default:
  220491. jassertfalse
  220492. break;
  220493. }
  220494. return eventNotHandledErr;
  220495. }
  220496. OSStatus handleTextInputEvent (EventRef theEvent)
  220497. {
  220498. UInt32 numBytesRequired = 0;
  220499. GetEventParameter (theEvent, kEventParamTextInputSendText, typeUnicodeText, 0, 0, &numBytesRequired, 0);
  220500. MemoryBlock buffer (numBytesRequired, true);
  220501. UniChar* const uc = (UniChar*) buffer.getData();
  220502. GetEventParameter (theEvent, kEventParamTextInputSendText, typeUnicodeText, 0, numBytesRequired, &numBytesRequired, uc);
  220503. EventRef originalEvent;
  220504. GetEventParameter (theEvent, kEventParamTextInputSendKeyboardEvent, typeEventRef, 0, sizeof (originalEvent), 0, &originalEvent);
  220505. OSStatus res = noErr;
  220506. for (int i = 0; i < numBytesRequired / sizeof (UniChar); ++i)
  220507. res = handleKeyEvent (originalEvent, (juce_wchar) uc[i]);
  220508. return res;
  220509. }
  220510. OSStatus handleMouseEvent (EventHandlerCallRef callRef, EventRef theEvent)
  220511. {
  220512. MouseCheckTimer::getInstance()->moved (this);
  220513. ::Point where;
  220514. GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, 0, sizeof (::Point), 0, &where);
  220515. int x = where.h;
  220516. int y = where.v;
  220517. globalPositionToRelative (x, y);
  220518. int64 time = getEventTime (theEvent);
  220519. switch (GetEventKind (theEvent))
  220520. {
  220521. case kEventMouseMoved:
  220522. MouseCheckTimer::getInstance()->hasEverHadAMouseMove = true;
  220523. updateModifiers (theEvent);
  220524. handleMouseMove (x, y, time);
  220525. break;
  220526. case kEventMouseDragged:
  220527. updateModifiers (theEvent);
  220528. handleMouseDrag (x, y, time);
  220529. break;
  220530. case kEventMouseDown:
  220531. {
  220532. if (! Process::isForegroundProcess())
  220533. {
  220534. ProcessSerialNumber psn;
  220535. GetCurrentProcess (&psn);
  220536. SetFrontProcessWithOptions (&psn, kSetFrontProcessFrontWindowOnly);
  220537. toFront (true);
  220538. }
  220539. #if JUCE_QUICKTIME
  220540. {
  220541. long mods;
  220542. GetEventParameter (theEvent, kEventParamKeyModifiers, typeUInt32, 0, sizeof (mods), 0, &mods);
  220543. ::Point where;
  220544. GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, 0, sizeof (::Point), 0, &where);
  220545. OfferMouseClickToQuickTime (windowRef, where, EventTimeToTicks (GetEventTime (theEvent)), mods, component);
  220546. }
  220547. #endif
  220548. if (component->isBroughtToFrontOnMouseClick()
  220549. && ! component->isCurrentlyBlockedByAnotherModalComponent())
  220550. {
  220551. //ActivateWindow (windowRef, true);
  220552. SelectWindow (windowRef);
  220553. }
  220554. EventMouseButton button;
  220555. GetEventParameter (theEvent, kEventParamMouseButton, typeMouseButton, 0, sizeof (EventMouseButton), 0, &button);
  220556. // need to clear all these flags because sometimes the mac can swallow (right) mouse-up events and
  220557. // this makes a button get stuck down. Since there's no other way to tell what buttons are down,
  220558. // this is all I can think of doing about it..
  220559. currentModifiers &= ~(ModifierKeys::leftButtonModifier | ModifierKeys::rightButtonModifier | ModifierKeys::middleButtonModifier);
  220560. if (button == kEventMouseButtonPrimary)
  220561. currentModifiers |= ModifierKeys::leftButtonModifier;
  220562. else if (button == kEventMouseButtonSecondary)
  220563. currentModifiers |= ModifierKeys::rightButtonModifier;
  220564. else if (button == kEventMouseButtonTertiary)
  220565. currentModifiers |= ModifierKeys::middleButtonModifier;
  220566. updateModifiers (theEvent);
  220567. juce_currentMouseTrackingPeer = this; // puts the message dispatcher into mouse-tracking mode..
  220568. handleMouseDown (x, y, time);
  220569. break;
  220570. }
  220571. case kEventMouseUp:
  220572. {
  220573. const int oldModifiers = currentModifiers;
  220574. EventMouseButton button;
  220575. GetEventParameter (theEvent, kEventParamMouseButton, typeMouseButton, 0, sizeof (EventMouseButton), 0, &button);
  220576. if (button == kEventMouseButtonPrimary)
  220577. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  220578. else if (button == kEventMouseButtonSecondary)
  220579. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  220580. updateModifiers (theEvent);
  220581. juce_currentMouseTrackingPeer = 0;
  220582. handleMouseUp (oldModifiers, x, y, time);
  220583. break;
  220584. }
  220585. case kEventMouseWheelMoved:
  220586. {
  220587. EventMouseWheelAxis axis;
  220588. GetEventParameter (theEvent, kEventParamMouseWheelAxis, typeMouseWheelAxis, 0, sizeof (axis), 0, &axis);
  220589. SInt32 delta;
  220590. GetEventParameter (theEvent, kEventParamMouseWheelDelta,
  220591. typeLongInteger, 0, sizeof (delta), 0, &delta);
  220592. updateModifiers (theEvent);
  220593. handleMouseWheel (axis == kEventMouseWheelAxisX ? delta * 10 : 0,
  220594. axis == kEventMouseWheelAxisX ? 0 : delta * 10,
  220595. time);
  220596. break;
  220597. }
  220598. }
  220599. return noErr;
  220600. }
  220601. void doDragDropEnter (EventRef theEvent)
  220602. {
  220603. updateDragAndDropFileList (theEvent);
  220604. if (dragAndDropFiles.size() > 0)
  220605. {
  220606. int x, y;
  220607. component->getMouseXYRelative (x, y);
  220608. handleFileDragMove (dragAndDropFiles, x, y);
  220609. }
  220610. }
  220611. void doDragDropMove (EventRef theEvent)
  220612. {
  220613. if (dragAndDropFiles.size() > 0)
  220614. {
  220615. int x, y;
  220616. component->getMouseXYRelative (x, y);
  220617. handleFileDragMove (dragAndDropFiles, x, y);
  220618. }
  220619. }
  220620. void doDragDropExit (EventRef theEvent)
  220621. {
  220622. if (dragAndDropFiles.size() > 0)
  220623. handleFileDragExit (dragAndDropFiles);
  220624. }
  220625. void doDragDrop (EventRef theEvent)
  220626. {
  220627. updateDragAndDropFileList (theEvent);
  220628. if (dragAndDropFiles.size() > 0)
  220629. {
  220630. int x, y;
  220631. component->getMouseXYRelative (x, y);
  220632. handleFileDragDrop (dragAndDropFiles, x, y);
  220633. }
  220634. }
  220635. void updateDragAndDropFileList (EventRef theEvent)
  220636. {
  220637. dragAndDropFiles.clear();
  220638. DragRef dragRef;
  220639. if (GetEventParameter (theEvent, kEventParamDragRef, typeDragRef, 0, sizeof (dragRef), 0, &dragRef) == noErr)
  220640. {
  220641. UInt16 numItems = 0;
  220642. if (CountDragItems (dragRef, &numItems) == noErr)
  220643. {
  220644. for (int i = 0; i < (int) numItems; ++i)
  220645. {
  220646. DragItemRef ref;
  220647. if (GetDragItemReferenceNumber (dragRef, i + 1, &ref) == noErr)
  220648. {
  220649. const FlavorType flavorType = kDragFlavorTypeHFS;
  220650. Size size = 0;
  220651. if (GetFlavorDataSize (dragRef, ref, flavorType, &size) == noErr)
  220652. {
  220653. void* data = juce_calloc (size);
  220654. if (GetFlavorData (dragRef, ref, flavorType, data, &size, 0) == noErr)
  220655. {
  220656. HFSFlavor* f = (HFSFlavor*) data;
  220657. FSRef fsref;
  220658. if (FSpMakeFSRef (&f->fileSpec, &fsref) == noErr)
  220659. {
  220660. const String path (PlatformUtilities::makePathFromFSRef (&fsref));
  220661. if (path.isNotEmpty())
  220662. dragAndDropFiles.add (path);
  220663. }
  220664. }
  220665. juce_free (data);
  220666. }
  220667. }
  220668. }
  220669. dragAndDropFiles.trim();
  220670. dragAndDropFiles.removeEmptyStrings();
  220671. }
  220672. }
  220673. }
  220674. void resizeViewToFitWindow()
  220675. {
  220676. HIRect r;
  220677. if (isSharedWindow)
  220678. {
  220679. HIViewGetFrame (viewRef, &r);
  220680. r.size.width = (float) component->getWidth();
  220681. r.size.height = (float) component->getHeight();
  220682. }
  220683. else
  220684. {
  220685. r.origin.x = 0;
  220686. r.origin.y = 0;
  220687. Rect w;
  220688. GetWindowBounds (windowRef, windowRegionToUse, &w);
  220689. r.size.width = (float) (w.right - w.left);
  220690. r.size.height = (float) (w.bottom - w.top);
  220691. }
  220692. HIViewSetFrame (viewRef, &r);
  220693. #if MACOS_10_3_OR_EARLIER
  220694. component->repaint();
  220695. #endif
  220696. }
  220697. OSStatus hiViewDraw (EventRef theEvent)
  220698. {
  220699. CGContextRef context = 0;
  220700. GetEventParameter (theEvent, kEventParamCGContextRef, typeCGContextRef, 0, sizeof (CGContextRef), 0, &context);
  220701. CGrafPtr oldPort;
  220702. CGrafPtr port = 0;
  220703. if (context == 0)
  220704. {
  220705. GetEventParameter (theEvent, kEventParamGrafPort, typeGrafPtr, 0, sizeof (CGrafPtr), 0, &port);
  220706. GetPort (&oldPort);
  220707. SetPort (port);
  220708. if (port != 0)
  220709. QDBeginCGContext (port, &context);
  220710. if (! isCompositingWindow)
  220711. {
  220712. Rect bounds;
  220713. GetWindowBounds (windowRef, windowRegionToUse, &bounds);
  220714. CGContextTranslateCTM (context, 0, bounds.bottom - bounds.top);
  220715. CGContextScaleCTM (context, 1.0, -1.0);
  220716. }
  220717. if (isSharedWindow)
  220718. {
  220719. // NB - Had terrible problems trying to correctly get the position
  220720. // of this view relative to the window, and this seems wrong, but
  220721. // works better than any other method I've tried..
  220722. HIRect hiViewPos;
  220723. HIViewGetFrame (viewRef, &hiViewPos);
  220724. CGContextTranslateCTM (context, hiViewPos.origin.x, hiViewPos.origin.y);
  220725. }
  220726. }
  220727. #if MACOS_10_2_OR_EARLIER
  220728. RgnHandle rgn = 0;
  220729. GetEventParameter (theEvent, kEventParamRgnHandle, typeQDRgnHandle, 0, sizeof (RgnHandle), 0, &rgn);
  220730. CGRect clip;
  220731. // (avoid doing this in plugins because of some strange redraw bugs..)
  220732. if (rgn != 0 && JUCEApplication::getInstance() != 0)
  220733. {
  220734. Rect bounds;
  220735. GetRegionBounds (rgn, &bounds);
  220736. clip.origin.x = bounds.left;
  220737. clip.origin.y = bounds.top;
  220738. clip.size.width = bounds.right - bounds.left;
  220739. clip.size.height = bounds.bottom - bounds.top;
  220740. }
  220741. else
  220742. {
  220743. HIViewGetBounds (viewRef, &clip);
  220744. clip.origin.x = 0;
  220745. clip.origin.y = 0;
  220746. }
  220747. #else
  220748. CGRect clip (CGContextGetClipBoundingBox (context));
  220749. #endif
  220750. clip = CGRectIntegral (clip);
  220751. if (clip.origin.x < 0)
  220752. {
  220753. clip.size.width += clip.origin.x;
  220754. clip.origin.x = 0;
  220755. }
  220756. if (clip.origin.y < 0)
  220757. {
  220758. clip.size.height += clip.origin.y;
  220759. clip.origin.y = 0;
  220760. }
  220761. if (! component->isOpaque())
  220762. CGContextClearRect (context, clip);
  220763. repainter->paint (context,
  220764. (int) clip.origin.x, (int) clip.origin.y,
  220765. (int) clip.size.width, (int) clip.size.height);
  220766. if (port != 0)
  220767. {
  220768. CGContextFlush (context);
  220769. QDEndCGContext (port, &context);
  220770. SetPort (oldPort);
  220771. }
  220772. repainter->repaintAnyRemainingRegions();
  220773. return noErr;
  220774. }
  220775. OSStatus handleWindowClassEvent (EventRef theEvent)
  220776. {
  220777. switch (GetEventKind (theEvent))
  220778. {
  220779. case kEventWindowBoundsChanged:
  220780. resizeViewToFitWindow();
  220781. break; // allow other handlers in the event chain to also get a look at the events
  220782. case kEventWindowBoundsChanging:
  220783. if ((styleFlags & (windowIsResizable | windowHasTitleBar)) == (windowIsResizable | windowHasTitleBar))
  220784. {
  220785. UInt32 atts = 0;
  220786. GetEventParameter (theEvent, kEventParamAttributes, typeUInt32,
  220787. 0, sizeof (UInt32), 0, &atts);
  220788. if ((atts & (kWindowBoundsChangeUserDrag | kWindowBoundsChangeUserResize)) != 0)
  220789. {
  220790. if (component->isCurrentlyBlockedByAnotherModalComponent())
  220791. {
  220792. Component* const modal = Component::getCurrentlyModalComponent();
  220793. if (modal != 0)
  220794. {
  220795. static uint32 lastDragTime = 0;
  220796. const uint32 now = Time::currentTimeMillis();
  220797. if (now > lastDragTime + 1000)
  220798. {
  220799. lastDragTime = now;
  220800. modal->inputAttemptWhenModal();
  220801. }
  220802. const Rectangle currentRect (getComponent()->getBounds());
  220803. Rect current;
  220804. current.left = currentRect.getX();
  220805. current.top = currentRect.getY();
  220806. current.right = currentRect.getRight();
  220807. current.bottom = currentRect.getBottom();
  220808. // stop the window getting dragged..
  220809. SetEventParameter (theEvent, kEventParamCurrentBounds, typeQDRectangle,
  220810. sizeof (Rect), &current);
  220811. return noErr;
  220812. }
  220813. }
  220814. if ((atts & kWindowBoundsChangeUserResize) != 0
  220815. && constrainer != 0 && ! isSharedWindow)
  220816. {
  220817. Rect current;
  220818. GetEventParameter (theEvent, kEventParamCurrentBounds, typeQDRectangle,
  220819. 0, sizeof (Rect), 0, &current);
  220820. int x = current.left;
  220821. int y = current.top;
  220822. int w = current.right - current.left;
  220823. int h = current.bottom - current.top;
  220824. const Rectangle currentRect (getComponent()->getBounds());
  220825. constrainer->checkBounds (x, y, w, h, currentRect,
  220826. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  220827. y != currentRect.getY() && y + h == currentRect.getBottom(),
  220828. x != currentRect.getX() && x + w == currentRect.getRight(),
  220829. y == currentRect.getY() && y + h != currentRect.getBottom(),
  220830. x == currentRect.getX() && x + w != currentRect.getRight());
  220831. current.left = x;
  220832. current.top = y;
  220833. current.right = x + w;
  220834. current.bottom = y + h;
  220835. SetEventParameter (theEvent, kEventParamCurrentBounds, typeQDRectangle,
  220836. sizeof (Rect), &current);
  220837. return noErr;
  220838. }
  220839. }
  220840. }
  220841. break;
  220842. case kEventWindowFocusAcquired:
  220843. keysCurrentlyDown.clear();
  220844. if ((! isSharedWindow) || HIViewSubtreeContainsFocus (viewRef))
  220845. viewFocusGain();
  220846. break; // allow other handlers in the event chain to also get a look at the events
  220847. case kEventWindowFocusRelinquish:
  220848. keysCurrentlyDown.clear();
  220849. viewFocusLoss();
  220850. break; // allow other handlers in the event chain to also get a look at the events
  220851. case kEventWindowCollapsed:
  220852. minimisedWindows.addIfNotAlreadyThere (windowRef);
  220853. handleMovedOrResized();
  220854. break; // allow other handlers in the event chain to also get a look at the events
  220855. case kEventWindowExpanded:
  220856. minimisedWindows.removeValue (windowRef);
  220857. handleMovedOrResized();
  220858. break; // allow other handlers in the event chain to also get a look at the events
  220859. case kEventWindowShown:
  220860. break; // allow other handlers in the event chain to also get a look at the events
  220861. case kEventWindowClose:
  220862. if (isSharedWindow)
  220863. break; // break to let the OS delete the window
  220864. handleUserClosingWindow();
  220865. return noErr; // avoids letting the OS to delete the window, we'll do that ourselves.
  220866. default:
  220867. break;
  220868. }
  220869. return eventNotHandledErr;
  220870. }
  220871. OSStatus handleWindowEventForPeer (EventHandlerCallRef callRef, EventRef theEvent)
  220872. {
  220873. switch (GetEventClass (theEvent))
  220874. {
  220875. case kEventClassMouse:
  220876. {
  220877. static HIViewComponentPeer* lastMouseDownPeer = 0;
  220878. const UInt32 eventKind = GetEventKind (theEvent);
  220879. HIViewRef view = 0;
  220880. if (eventKind == kEventMouseDragged)
  220881. {
  220882. view = viewRef;
  220883. }
  220884. else
  220885. {
  220886. HIViewGetViewForMouseEvent (HIViewGetRoot (windowRef), theEvent, &view);
  220887. if (view != viewRef)
  220888. {
  220889. if ((eventKind == kEventMouseUp
  220890. || eventKind == kEventMouseExited)
  220891. && ComponentPeer::isValidPeer (lastMouseDownPeer))
  220892. {
  220893. return lastMouseDownPeer->handleMouseEvent (callRef, theEvent);
  220894. }
  220895. return eventNotHandledErr;
  220896. }
  220897. }
  220898. if (eventKind == kEventMouseDown
  220899. || eventKind == kEventMouseDragged
  220900. || eventKind == kEventMouseEntered)
  220901. {
  220902. lastMouseDownPeer = this;
  220903. }
  220904. return handleMouseEvent (callRef, theEvent);
  220905. }
  220906. break;
  220907. case kEventClassWindow:
  220908. return handleWindowClassEvent (theEvent);
  220909. case kEventClassKeyboard:
  220910. if (isFocused())
  220911. return handleKeyEvent (theEvent, 0);
  220912. break;
  220913. case kEventClassTextInput:
  220914. if (isFocused())
  220915. return handleTextInputEvent (theEvent);
  220916. break;
  220917. default:
  220918. break;
  220919. }
  220920. return eventNotHandledErr;
  220921. }
  220922. static pascal OSStatus handleWindowEvent (EventHandlerCallRef callRef, EventRef theEvent, void* userData)
  220923. {
  220924. MessageManager::delayWaitCursor();
  220925. HIViewComponentPeer* const peer = (HIViewComponentPeer*) userData;
  220926. const MessageManagerLock messLock;
  220927. if (ComponentPeer::isValidPeer (peer))
  220928. return peer->handleWindowEventForPeer (callRef, theEvent);
  220929. return eventNotHandledErr;
  220930. }
  220931. static pascal OSStatus hiViewEventHandler (EventHandlerCallRef myHandler, EventRef theEvent, void* userData)
  220932. {
  220933. MessageManager::delayWaitCursor();
  220934. const UInt32 eventKind = GetEventKind (theEvent);
  220935. const UInt32 eventClass = GetEventClass (theEvent);
  220936. if (eventClass == kEventClassHIObject)
  220937. {
  220938. switch (eventKind)
  220939. {
  220940. case kEventHIObjectConstruct:
  220941. {
  220942. void* data = juce_calloc (sizeof (void*));
  220943. SetEventParameter (theEvent, kEventParamHIObjectInstance,
  220944. typeVoidPtr, sizeof (void*), &data);
  220945. return noErr;
  220946. }
  220947. case kEventHIObjectInitialize:
  220948. GetEventParameter (theEvent, 'peer', typeVoidPtr, 0, sizeof (void*), 0, (void**) userData);
  220949. return noErr;
  220950. case kEventHIObjectDestruct:
  220951. juce_free (userData);
  220952. return noErr;
  220953. default:
  220954. break;
  220955. }
  220956. }
  220957. else if (eventClass == kEventClassControl)
  220958. {
  220959. HIViewComponentPeer* const peer = *(HIViewComponentPeer**) userData;
  220960. const MessageManagerLock messLock;
  220961. if (! ComponentPeer::isValidPeer (peer))
  220962. return eventNotHandledErr;
  220963. switch (eventKind)
  220964. {
  220965. case kEventControlDraw:
  220966. return peer->hiViewDraw (theEvent);
  220967. case kEventControlBoundsChanged:
  220968. {
  220969. HIRect bounds;
  220970. HIViewGetBounds (peer->viewRef, &bounds);
  220971. peer->repaint (0, 0, roundFloatToInt (bounds.size.width), roundFloatToInt (bounds.size.height));
  220972. peer->handleMovedOrResized();
  220973. return noErr;
  220974. }
  220975. case kEventControlHitTest:
  220976. {
  220977. HIPoint where;
  220978. GetEventParameter (theEvent, kEventParamMouseLocation, typeHIPoint, 0, sizeof (HIPoint), 0, &where);
  220979. HIRect bounds;
  220980. HIViewGetBounds (peer->viewRef, &bounds);
  220981. ControlPartCode part = kControlNoPart;
  220982. if (CGRectContainsPoint (bounds, where))
  220983. part = 1;
  220984. SetEventParameter (theEvent, kEventParamControlPart, typeControlPartCode, sizeof (ControlPartCode), &part);
  220985. return noErr;
  220986. }
  220987. break;
  220988. case kEventControlSetFocusPart:
  220989. {
  220990. ControlPartCode desiredFocus;
  220991. if (GetEventParameter (theEvent, kEventParamControlPart, typeControlPartCode, 0, sizeof (ControlPartCode), 0, &desiredFocus) != noErr)
  220992. break;
  220993. if (desiredFocus == kControlNoPart)
  220994. peer->viewFocusLoss();
  220995. else
  220996. peer->viewFocusGain();
  220997. return noErr;
  220998. }
  220999. break;
  221000. case kEventControlDragEnter:
  221001. {
  221002. #if MACOS_10_2_OR_EARLIER
  221003. enum { kEventParamControlWouldAcceptDrop = 'cldg' };
  221004. #endif
  221005. Boolean accept = true;
  221006. SetEventParameter (theEvent, kEventParamControlWouldAcceptDrop, typeBoolean, sizeof (accept), &accept);
  221007. peer->doDragDropEnter (theEvent);
  221008. return noErr;
  221009. }
  221010. case kEventControlDragWithin:
  221011. peer->doDragDropMove (theEvent);
  221012. return noErr;
  221013. case kEventControlDragLeave:
  221014. peer->doDragDropExit (theEvent);
  221015. return noErr;
  221016. case kEventControlDragReceive:
  221017. peer->doDragDrop (theEvent);
  221018. return noErr;
  221019. case kEventControlOwningWindowChanged:
  221020. return peer->ownerWindowChanged (theEvent);
  221021. #if ! MACOS_10_2_OR_EARLIER
  221022. case kEventControlGetFrameMetrics:
  221023. {
  221024. CallNextEventHandler (myHandler, theEvent);
  221025. HIViewFrameMetrics metrics;
  221026. GetEventParameter (theEvent, kEventParamControlFrameMetrics, typeControlFrameMetrics, 0, sizeof (metrics), 0, &metrics);
  221027. metrics.top = metrics.bottom = 0;
  221028. SetEventParameter (theEvent, kEventParamControlFrameMetrics, typeControlFrameMetrics, sizeof (metrics), &metrics);
  221029. return noErr;
  221030. }
  221031. #endif
  221032. case kEventControlInitialize:
  221033. {
  221034. UInt32 features = kControlSupportsDragAndDrop
  221035. | kControlSupportsFocus
  221036. | kControlHandlesTracking
  221037. | kControlSupportsEmbedding
  221038. | (1 << 8) /*kHIViewFeatureGetsFocusOnClick*/;
  221039. SetEventParameter (theEvent, kEventParamControlFeatures, typeUInt32, sizeof (UInt32), &features);
  221040. return noErr;
  221041. }
  221042. default:
  221043. break;
  221044. }
  221045. }
  221046. return eventNotHandledErr;
  221047. }
  221048. WindowRef createNewWindow (const int windowStyleFlags)
  221049. {
  221050. jassert (windowRef == 0);
  221051. static ToolboxObjectClassRef customWindowClass = 0;
  221052. if (customWindowClass == 0)
  221053. {
  221054. // Register our window class
  221055. const EventTypeSpec customTypes[] = { { kEventClassWindow, kEventWindowDrawFrame } };
  221056. UnsignedWide t;
  221057. Microseconds (&t);
  221058. const String randomString ((int) (t.lo & 0x7ffffff));
  221059. const String juceWindowClassName (T("JUCEWindowClass_") + randomString);
  221060. CFStringRef juceWindowClassNameCFString = PlatformUtilities::juceStringToCFString (juceWindowClassName);
  221061. RegisterToolboxObjectClass (juceWindowClassNameCFString,
  221062. 0, 1, customTypes,
  221063. NewEventHandlerUPP (handleFrameRepaintEvent),
  221064. 0, &customWindowClass);
  221065. CFRelease (juceWindowClassNameCFString);
  221066. }
  221067. Rect pos;
  221068. pos.left = getComponent()->getX();
  221069. pos.top = getComponent()->getY();
  221070. pos.right = getComponent()->getRight();
  221071. pos.bottom = getComponent()->getBottom();
  221072. int attributes = kWindowStandardHandlerAttribute | kWindowCompositingAttribute;
  221073. if ((windowStyleFlags & windowHasDropShadow) == 0)
  221074. attributes |= kWindowNoShadowAttribute;
  221075. if ((windowStyleFlags & windowIgnoresMouseClicks) != 0)
  221076. attributes |= kWindowIgnoreClicksAttribute;
  221077. #if ! MACOS_10_3_OR_EARLIER
  221078. if ((windowStyleFlags & windowIsTemporary) != 0)
  221079. attributes |= kWindowDoesNotCycleAttribute;
  221080. #endif
  221081. WindowRef newWindow = 0;
  221082. if ((windowStyleFlags & windowHasTitleBar) == 0)
  221083. {
  221084. attributes |= kWindowCollapseBoxAttribute;
  221085. WindowDefSpec customWindowSpec;
  221086. customWindowSpec.defType = kWindowDefObjectClass;
  221087. customWindowSpec.u.classRef = customWindowClass;
  221088. CreateCustomWindow (&customWindowSpec,
  221089. ((windowStyleFlags & windowIsTemporary) != 0) ? kUtilityWindowClass :
  221090. (getComponent()->isAlwaysOnTop() ? kUtilityWindowClass
  221091. : kDocumentWindowClass),
  221092. attributes,
  221093. &pos,
  221094. &newWindow);
  221095. }
  221096. else
  221097. {
  221098. if ((windowStyleFlags & windowHasCloseButton) != 0)
  221099. attributes |= kWindowCloseBoxAttribute;
  221100. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  221101. attributes |= kWindowCollapseBoxAttribute;
  221102. if ((windowStyleFlags & windowHasMaximiseButton) != 0)
  221103. attributes |= kWindowFullZoomAttribute;
  221104. if ((windowStyleFlags & windowIsResizable) != 0)
  221105. attributes |= kWindowResizableAttribute | kWindowLiveResizeAttribute;
  221106. CreateNewWindow (kDocumentWindowClass, attributes, &pos, &newWindow);
  221107. }
  221108. jassert (newWindow != 0);
  221109. if (newWindow != 0)
  221110. {
  221111. HideWindow (newWindow);
  221112. SetAutomaticControlDragTrackingEnabledForWindow (newWindow, true);
  221113. if (! getComponent()->isOpaque())
  221114. SetWindowAlpha (newWindow, 0.9999999f); // to fool it into giving the window an alpha-channel
  221115. }
  221116. return newWindow;
  221117. }
  221118. OSStatus ownerWindowChanged (EventRef theEvent)
  221119. {
  221120. WindowRef newWindow = 0;
  221121. GetEventParameter (theEvent, kEventParamControlCurrentOwningWindow, typeWindowRef, 0, sizeof (newWindow), 0, &newWindow);
  221122. if (windowRef != newWindow)
  221123. {
  221124. if (eventHandlerRef != 0)
  221125. {
  221126. RemoveEventHandler (eventHandlerRef);
  221127. eventHandlerRef = 0;
  221128. }
  221129. windowRef = newWindow;
  221130. if (windowRef != 0)
  221131. {
  221132. const EventTypeSpec eventTypes[] =
  221133. {
  221134. { kEventClassWindow, kEventWindowBoundsChanged },
  221135. { kEventClassWindow, kEventWindowBoundsChanging },
  221136. { kEventClassWindow, kEventWindowFocusAcquired },
  221137. { kEventClassWindow, kEventWindowFocusRelinquish },
  221138. { kEventClassWindow, kEventWindowCollapsed },
  221139. { kEventClassWindow, kEventWindowExpanded },
  221140. { kEventClassWindow, kEventWindowShown },
  221141. { kEventClassWindow, kEventWindowClose },
  221142. { kEventClassMouse, kEventMouseDown },
  221143. { kEventClassMouse, kEventMouseUp },
  221144. { kEventClassMouse, kEventMouseMoved },
  221145. { kEventClassMouse, kEventMouseDragged },
  221146. { kEventClassMouse, kEventMouseEntered },
  221147. { kEventClassMouse, kEventMouseExited },
  221148. { kEventClassMouse, kEventMouseWheelMoved },
  221149. { kEventClassKeyboard, kEventRawKeyUp },
  221150. { kEventClassKeyboard, kEventRawKeyRepeat },
  221151. { kEventClassKeyboard, kEventRawKeyModifiersChanged },
  221152. { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent }
  221153. };
  221154. static EventHandlerUPP handleWindowEventUPP = 0;
  221155. if (handleWindowEventUPP == 0)
  221156. handleWindowEventUPP = NewEventHandlerUPP (handleWindowEvent);
  221157. InstallWindowEventHandler (windowRef, handleWindowEventUPP,
  221158. GetEventTypeCount (eventTypes), eventTypes,
  221159. (void*) this, (EventHandlerRef*) &eventHandlerRef);
  221160. WindowAttributes attributes;
  221161. GetWindowAttributes (windowRef, &attributes);
  221162. #if MACOS_10_3_OR_EARLIER
  221163. isCompositingWindow = ((attributes & kWindowCompositingAttribute) != 0);
  221164. #else
  221165. isCompositingWindow = HIViewIsCompositingEnabled (viewRef);
  221166. #endif
  221167. SetAutomaticControlDragTrackingEnabledForWindow (newWindow, true);
  221168. MouseCheckTimer::getInstance()->resetMouseMoveChecker();
  221169. }
  221170. }
  221171. resizeViewToFitWindow();
  221172. return noErr;
  221173. }
  221174. void createNewHIView()
  221175. {
  221176. jassert (viewRef == 0);
  221177. if (viewClassRef == 0)
  221178. {
  221179. // Register our HIView class
  221180. EventTypeSpec viewEvents[] =
  221181. {
  221182. { kEventClassHIObject, kEventHIObjectConstruct },
  221183. { kEventClassHIObject, kEventHIObjectInitialize },
  221184. { kEventClassHIObject, kEventHIObjectDestruct },
  221185. { kEventClassControl, kEventControlInitialize },
  221186. { kEventClassControl, kEventControlDraw },
  221187. { kEventClassControl, kEventControlBoundsChanged },
  221188. { kEventClassControl, kEventControlSetFocusPart },
  221189. { kEventClassControl, kEventControlHitTest },
  221190. { kEventClassControl, kEventControlDragEnter },
  221191. { kEventClassControl, kEventControlDragLeave },
  221192. { kEventClassControl, kEventControlDragWithin },
  221193. { kEventClassControl, kEventControlDragReceive },
  221194. { kEventClassControl, kEventControlOwningWindowChanged }
  221195. };
  221196. UnsignedWide t;
  221197. Microseconds (&t);
  221198. const String randomString ((int) (t.lo & 0x7ffffff));
  221199. const String juceHiViewClassName (T("JUCEHIViewClass_") + randomString);
  221200. juceHiViewClassNameCFString = PlatformUtilities::juceStringToCFString (juceHiViewClassName);
  221201. HIObjectRegisterSubclass (juceHiViewClassNameCFString,
  221202. kHIViewClassID, 0,
  221203. NewEventHandlerUPP (hiViewEventHandler),
  221204. GetEventTypeCount (viewEvents),
  221205. viewEvents, 0,
  221206. &viewClassRef);
  221207. }
  221208. EventRef event;
  221209. CreateEvent (0, kEventClassHIObject, kEventHIObjectInitialize, GetCurrentEventTime(), kEventAttributeNone, &event);
  221210. void* thisPointer = this;
  221211. SetEventParameter (event, 'peer', typeVoidPtr, sizeof (void*), &thisPointer);
  221212. HIObjectCreate (juceHiViewClassNameCFString, event, (HIObjectRef*) &viewRef);
  221213. SetControlDragTrackingEnabled (viewRef, true);
  221214. if (isSharedWindow)
  221215. {
  221216. setBounds (component->getX(), component->getY(),
  221217. component->getWidth(), component->getHeight(), false);
  221218. }
  221219. }
  221220. };
  221221. bool juce_isHIViewCreatedByJuce (HIViewRef view)
  221222. {
  221223. return juceHiViewClassNameCFString != 0
  221224. && HIObjectIsOfClass ((HIObjectRef) view, juceHiViewClassNameCFString);
  221225. }
  221226. bool juce_isWindowCreatedByJuce (WindowRef window)
  221227. {
  221228. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221229. if (ComponentPeer::getPeer(i)->getNativeHandle() == window)
  221230. return true;
  221231. return false;
  221232. }
  221233. static void trackNextMouseEvent()
  221234. {
  221235. UInt32 mods;
  221236. MouseTrackingResult result;
  221237. ::Point where;
  221238. if (TrackMouseLocationWithOptions ((GrafPtr) -1, 0, 0.01, //kEventDurationForever,
  221239. &where, &mods, &result) != noErr
  221240. || ! ComponentPeer::isValidPeer (juce_currentMouseTrackingPeer))
  221241. {
  221242. juce_currentMouseTrackingPeer = 0;
  221243. return;
  221244. }
  221245. if (result == kMouseTrackingTimedOut)
  221246. return;
  221247. #if MACOS_10_3_OR_EARLIER
  221248. const int x = where.h - juce_currentMouseTrackingPeer->getScreenX();
  221249. const int y = where.v - juce_currentMouseTrackingPeer->getScreenY();
  221250. #else
  221251. HIPoint p;
  221252. p.x = where.h;
  221253. p.y = where.v;
  221254. HIPointConvert (&p, kHICoordSpaceScreenPixel, 0,
  221255. kHICoordSpaceView, ((HIViewComponentPeer*) juce_currentMouseTrackingPeer)->viewRef);
  221256. const int x = p.x;
  221257. const int y = p.y;
  221258. #endif
  221259. if (result == kMouseTrackingMouseDragged)
  221260. {
  221261. updateModifiers (0);
  221262. juce_currentMouseTrackingPeer->handleMouseDrag (x, y, getEventTime (0));
  221263. if (! ComponentPeer::isValidPeer (juce_currentMouseTrackingPeer))
  221264. {
  221265. juce_currentMouseTrackingPeer = 0;
  221266. return;
  221267. }
  221268. }
  221269. else if (result == kMouseTrackingMouseUp
  221270. || result == kMouseTrackingUserCancelled
  221271. || result == kMouseTrackingMouseMoved)
  221272. {
  221273. ComponentPeer* const oldPeer = juce_currentMouseTrackingPeer;
  221274. juce_currentMouseTrackingPeer = 0;
  221275. if (ComponentPeer::isValidPeer (oldPeer))
  221276. {
  221277. const int oldModifiers = currentModifiers;
  221278. currentModifiers &= ~(ModifierKeys::leftButtonModifier | ModifierKeys::rightButtonModifier | ModifierKeys::middleButtonModifier);
  221279. updateModifiers (0);
  221280. oldPeer->handleMouseUp (oldModifiers, x, y, getEventTime (0));
  221281. }
  221282. }
  221283. }
  221284. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  221285. {
  221286. if (juce_currentMouseTrackingPeer != 0)
  221287. trackNextMouseEvent();
  221288. /* [[NSRunLoop mainRunLoop] acceptInputForMode: NSDefaultRunLoopMode
  221289. beforeDate: returnIfNoPendingMessages
  221290. ? [[NSDate date] addTimeInterval: 0.01]
  221291. : [NSDate distantFuture]];
  221292. */
  221293. EventRef theEvent;
  221294. if (ReceiveNextEvent (0, 0, (returnIfNoPendingMessages) ? kEventDurationNoWait
  221295. : kEventDurationForever,
  221296. true, &theEvent) == noErr)
  221297. {
  221298. if (GetEventClass (theEvent) == kEventClassAppleEvent)
  221299. {
  221300. EventRecord eventRec;
  221301. if (ConvertEventRefToEventRecord (theEvent, &eventRec))
  221302. AEProcessAppleEvent (&eventRec);
  221303. }
  221304. else
  221305. {
  221306. EventTargetRef theTarget = GetEventDispatcherTarget();
  221307. SendEventToEventTarget (theEvent, theTarget);
  221308. }
  221309. ReleaseEvent (theEvent);
  221310. return true;
  221311. }
  221312. return false;
  221313. }
  221314. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  221315. {
  221316. return new HIViewComponentPeer (this, styleFlags, (HIViewRef) windowToAttachTo);
  221317. }
  221318. void MouseCheckTimer::timerCallback()
  221319. {
  221320. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  221321. return;
  221322. if (Process::isForegroundProcess())
  221323. {
  221324. bool stillOver = false;
  221325. int x = 0, y = 0, w = 0, h = 0;
  221326. int mx = 0, my = 0;
  221327. const bool validWindow = ComponentPeer::isValidPeer (lastPeerUnderMouse);
  221328. if (validWindow)
  221329. {
  221330. lastPeerUnderMouse->getBounds (x, y, w, h, true);
  221331. Desktop::getMousePosition (mx, my);
  221332. stillOver = (mx >= x && my >= y && mx < x + w && my < y + h);
  221333. if (stillOver)
  221334. {
  221335. // check if it's over an embedded HIView
  221336. int rx = mx, ry = my;
  221337. lastPeerUnderMouse->globalPositionToRelative (rx, ry);
  221338. HIPoint hipoint;
  221339. hipoint.x = rx;
  221340. hipoint.y = ry;
  221341. HIViewRef root;
  221342. GetRootControl ((WindowRef) lastPeerUnderMouse->getNativeHandle(), &root);
  221343. HIViewRef hitview;
  221344. if (HIViewGetSubviewHit (root, &hipoint, true, &hitview) == noErr && hitview != 0)
  221345. {
  221346. stillOver = HIObjectIsOfClass ((HIObjectRef) hitview, juceHiViewClassNameCFString);
  221347. }
  221348. }
  221349. }
  221350. if (! stillOver)
  221351. {
  221352. // mouse is outside our windows so set a normal cursor (only
  221353. // if we're running as an app, not a plugin)
  221354. if (JUCEApplication::getInstance() != 0)
  221355. SetThemeCursor (kThemeArrowCursor);
  221356. if (validWindow)
  221357. lastPeerUnderMouse->handleMouseExit (mx - x, my - y, Time::currentTimeMillis());
  221358. if (hasEverHadAMouseMove)
  221359. stopTimer();
  221360. }
  221361. if ((! hasEverHadAMouseMove) && validWindow
  221362. && (mx != lastX || my != lastY))
  221363. {
  221364. lastX = mx;
  221365. lastY = my;
  221366. if (stillOver)
  221367. lastPeerUnderMouse->handleMouseMove (mx - x, my - y, Time::currentTimeMillis());
  221368. }
  221369. }
  221370. }
  221371. // called from juce_Messaging.cpp
  221372. void juce_HandleProcessFocusChange()
  221373. {
  221374. keysCurrentlyDown.clear();
  221375. if (HIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  221376. {
  221377. if (Process::isForegroundProcess())
  221378. currentlyFocusedPeer->handleFocusGain();
  221379. else
  221380. currentlyFocusedPeer->handleFocusLoss();
  221381. }
  221382. }
  221383. static bool performDrag (DragRef drag)
  221384. {
  221385. EventRecord event;
  221386. event.what = mouseDown;
  221387. event.message = 0;
  221388. event.when = TickCount();
  221389. int x, y;
  221390. Desktop::getMousePosition (x, y);
  221391. event.where.h = x;
  221392. event.where.v = y;
  221393. event.modifiers = GetCurrentKeyModifiers();
  221394. RgnHandle rgn = NewRgn();
  221395. RgnHandle rgn2 = NewRgn();
  221396. SetRectRgn (rgn,
  221397. event.where.h - 8, event.where.v - 8,
  221398. event.where.h + 8, event.where.v + 8);
  221399. CopyRgn (rgn, rgn2);
  221400. InsetRgn (rgn2, 1, 1);
  221401. DiffRgn (rgn, rgn2, rgn);
  221402. DisposeRgn (rgn2);
  221403. bool result = TrackDrag (drag, &event, rgn) == noErr;
  221404. DisposeRgn (rgn);
  221405. return result;
  221406. }
  221407. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  221408. {
  221409. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221410. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  221411. DragRef drag;
  221412. bool result = false;
  221413. if (NewDrag (&drag) == noErr)
  221414. {
  221415. for (int i = 0; i < files.size(); ++i)
  221416. {
  221417. HFSFlavor hfsData;
  221418. if (PlatformUtilities::makeFSSpecFromPath (&hfsData.fileSpec, files[i]))
  221419. {
  221420. FInfo info;
  221421. if (FSpGetFInfo (&hfsData.fileSpec, &info) == noErr)
  221422. {
  221423. hfsData.fileType = info.fdType;
  221424. hfsData.fileCreator = info.fdCreator;
  221425. hfsData.fdFlags = info.fdFlags;
  221426. AddDragItemFlavor (drag, i + 1, kDragFlavorTypeHFS, &hfsData, sizeof (hfsData), 0);
  221427. result = true;
  221428. }
  221429. }
  221430. }
  221431. SetDragAllowableActions (drag, canMoveFiles ? kDragActionAll
  221432. : kDragActionCopy, false);
  221433. if (result)
  221434. result = performDrag (drag);
  221435. DisposeDrag (drag);
  221436. }
  221437. return result;
  221438. }
  221439. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  221440. {
  221441. jassertfalse // not implemented!
  221442. return false;
  221443. }
  221444. bool Process::isForegroundProcess() throw()
  221445. {
  221446. ProcessSerialNumber psn, front;
  221447. GetCurrentProcess (&psn);
  221448. GetFrontProcess (&front);
  221449. Boolean b;
  221450. return (SameProcess (&psn, &front, &b) == noErr) && b;
  221451. }
  221452. bool Desktop::canUseSemiTransparentWindows() throw()
  221453. {
  221454. return true;
  221455. }
  221456. void Desktop::getMousePosition (int& x, int& y) throw()
  221457. {
  221458. CGrafPtr currentPort;
  221459. GetPort (&currentPort);
  221460. if (! IsValidPort (currentPort))
  221461. {
  221462. WindowRef front = FrontWindow();
  221463. if (front != 0)
  221464. {
  221465. SetPortWindowPort (front);
  221466. }
  221467. else
  221468. {
  221469. x = y = 0;
  221470. return;
  221471. }
  221472. }
  221473. ::Point p;
  221474. GetMouse (&p);
  221475. LocalToGlobal (&p);
  221476. x = p.h;
  221477. y = p.v;
  221478. SetPort (currentPort);
  221479. }
  221480. void Desktop::setMousePosition (int x, int y) throw()
  221481. {
  221482. // this rubbish needs to be done around the warp call, to avoid causing a
  221483. // bizarre glitch..
  221484. CGAssociateMouseAndMouseCursorPosition (false);
  221485. CGSetLocalEventsSuppressionInterval (0);
  221486. CGPoint pos = { x, y };
  221487. CGWarpMouseCursorPosition (pos);
  221488. CGAssociateMouseAndMouseCursorPosition (true);
  221489. }
  221490. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  221491. {
  221492. return ModifierKeys (currentModifiers);
  221493. }
  221494. class ScreenSaverDefeater : public Timer,
  221495. public DeletedAtShutdown
  221496. {
  221497. public:
  221498. ScreenSaverDefeater() throw()
  221499. {
  221500. startTimer (10000);
  221501. timerCallback();
  221502. }
  221503. ~ScreenSaverDefeater()
  221504. {
  221505. }
  221506. void timerCallback()
  221507. {
  221508. if (Process::isForegroundProcess())
  221509. UpdateSystemActivity (UsrActivity);
  221510. }
  221511. };
  221512. static ScreenSaverDefeater* screenSaverDefeater = 0;
  221513. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  221514. {
  221515. if (screenSaverDefeater == 0)
  221516. screenSaverDefeater = new ScreenSaverDefeater();
  221517. }
  221518. bool Desktop::isScreenSaverEnabled() throw()
  221519. {
  221520. return screenSaverDefeater == 0;
  221521. }
  221522. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  221523. {
  221524. int mainMonitorIndex = 0;
  221525. CGDirectDisplayID mainDisplayID = CGMainDisplayID();
  221526. CGDisplayCount count = 0;
  221527. CGDirectDisplayID disps [8];
  221528. if (CGGetOnlineDisplayList (numElementsInArray (disps), disps, &count) == noErr)
  221529. {
  221530. for (int i = 0; i < count; ++i)
  221531. {
  221532. if (mainDisplayID == disps[i])
  221533. mainMonitorIndex = monitorCoords.size();
  221534. GDHandle hGDevice;
  221535. if (clipToWorkArea
  221536. && DMGetGDeviceByDisplayID ((DisplayIDType) disps[i], &hGDevice, false) == noErr)
  221537. {
  221538. Rect rect;
  221539. GetAvailableWindowPositioningBounds (hGDevice, &rect);
  221540. monitorCoords.add (Rectangle (rect.left,
  221541. rect.top,
  221542. rect.right - rect.left,
  221543. rect.bottom - rect.top));
  221544. }
  221545. else
  221546. {
  221547. const CGRect r (CGDisplayBounds (disps[i]));
  221548. monitorCoords.add (Rectangle ((int) r.origin.x,
  221549. (int) r.origin.y,
  221550. (int) r.size.width,
  221551. (int) r.size.height));
  221552. }
  221553. }
  221554. }
  221555. // make sure the first in the list is the main monitor
  221556. if (mainMonitorIndex > 0)
  221557. monitorCoords.swap (mainMonitorIndex, 0);
  221558. jassert (monitorCoords.size() > 0);
  221559. if (monitorCoords.size() == 0)
  221560. monitorCoords.add (Rectangle (0, 0, 1024, 768));
  221561. }
  221562. static NSImage* juceImageToNSImage (const Image& image)
  221563. {
  221564. int lineStride, pixelStride;
  221565. const uint8* pixels = image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(),
  221566. lineStride, pixelStride);
  221567. NSBitmapImageRep* rep = [[NSBitmapImageRep alloc]
  221568. initWithBitmapDataPlanes: NULL
  221569. pixelsWide: image.getWidth()
  221570. pixelsHigh: image.getHeight()
  221571. bitsPerSample: 8
  221572. samplesPerPixel: image.hasAlphaChannel() ? 4 : 3
  221573. hasAlpha: image.hasAlphaChannel()
  221574. isPlanar: NO
  221575. colorSpaceName: NSCalibratedRGBColorSpace
  221576. bitmapFormat: (NSBitmapFormat) 0
  221577. bytesPerRow: lineStride
  221578. bitsPerPixel: pixelStride * 8];
  221579. unsigned char* newData = [rep bitmapData];
  221580. memcpy (newData, pixels, lineStride * image.getHeight());
  221581. image.releasePixelDataReadOnly (pixels);
  221582. NSImage* im = [[NSImage alloc] init];
  221583. [im addRepresentation: rep];
  221584. [rep release];
  221585. return im;
  221586. }
  221587. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  221588. {
  221589. NSImage* im = juceImageToNSImage (image);
  221590. [im autorelease];
  221591. NSPoint hs;
  221592. hs.x = (int) hotspotX;
  221593. hs.y = (int) hotspotY;
  221594. NSCursor* c = [[NSCursor alloc] initWithImage: im hotSpot: hs];
  221595. return (void*) c;
  221596. }
  221597. static void* juce_cursorFromData (const unsigned char* data, const int size, float hx, float hy) throw()
  221598. {
  221599. Image* const im = ImageFileFormat::loadFrom ((const char*) data, size);
  221600. jassert (im != 0);
  221601. if (im == 0)
  221602. return 0;
  221603. void* const curs = juce_createMouseCursorFromImage (*im,
  221604. (int) (hx * im->getWidth()),
  221605. (int) (hy * im->getHeight()));
  221606. delete im;
  221607. return curs;
  221608. }
  221609. static void* juce_cursorFromWebKitFile (const char* filename, float hx, float hy)
  221610. {
  221611. File f ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources");
  221612. MemoryBlock mb;
  221613. if (f.getChildFile (filename).loadFileAsData (mb))
  221614. return juce_cursorFromData ((const unsigned char*) mb.getData(), mb.getSize(), hx, hy);
  221615. return 0;
  221616. }
  221617. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  221618. {
  221619. NSCursor* c = 0;
  221620. switch (type)
  221621. {
  221622. case MouseCursor::NormalCursor:
  221623. c = [NSCursor arrowCursor];
  221624. break;
  221625. case MouseCursor::NoCursor:
  221626. {
  221627. Image blank (Image::ARGB, 8, 8, true);
  221628. return juce_createMouseCursorFromImage (blank, 0, 0);
  221629. }
  221630. case MouseCursor::DraggingHandCursor:
  221631. c = [NSCursor openHandCursor];
  221632. break;
  221633. case MouseCursor::CopyingCursor:
  221634. return juce_cursorFromWebKitFile ("copyCursor.png", 0, 0);
  221635. case MouseCursor::WaitCursor:
  221636. c = [NSCursor arrowCursor]; // avoid this on the mac, let the OS provide the beachball
  221637. break;
  221638. //return juce_cursorFromWebKitFile ("waitCursor.png", 0.5f, 0.5f);
  221639. case MouseCursor::IBeamCursor:
  221640. c = [NSCursor IBeamCursor];
  221641. break;
  221642. case MouseCursor::PointingHandCursor:
  221643. c = [NSCursor pointingHandCursor];
  221644. break;
  221645. case MouseCursor::LeftRightResizeCursor:
  221646. c = [NSCursor resizeLeftRightCursor];
  221647. break;
  221648. case MouseCursor::LeftEdgeResizeCursor:
  221649. c = [NSCursor resizeLeftCursor];
  221650. break;
  221651. case MouseCursor::RightEdgeResizeCursor:
  221652. c = [NSCursor resizeRightCursor];
  221653. break;
  221654. case MouseCursor::UpDownResizeCursor:
  221655. case MouseCursor::TopEdgeResizeCursor:
  221656. case MouseCursor::BottomEdgeResizeCursor:
  221657. return juce_cursorFromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  221658. case MouseCursor::TopLeftCornerResizeCursor:
  221659. case MouseCursor::BottomRightCornerResizeCursor:
  221660. return juce_cursorFromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  221661. case MouseCursor::TopRightCornerResizeCursor:
  221662. case MouseCursor::BottomLeftCornerResizeCursor:
  221663. return juce_cursorFromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  221664. case MouseCursor::UpDownLeftRightResizeCursor:
  221665. return juce_cursorFromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  221666. case MouseCursor::CrosshairCursor:
  221667. c = [NSCursor crosshairCursor];
  221668. break;
  221669. }
  221670. [c retain];
  221671. return (void*) c;
  221672. }
  221673. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  221674. {
  221675. NSCursor* c = (NSCursor*) cursorHandle;
  221676. [c release];
  221677. }
  221678. void MouseCursor::showInAllWindows() const throw()
  221679. {
  221680. showInWindow (0);
  221681. }
  221682. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  221683. {
  221684. NSCursor* const c = (NSCursor*) getHandle();
  221685. if (c != 0)
  221686. [c set];
  221687. }
  221688. Image* juce_createIconForFile (const File& file)
  221689. {
  221690. return 0;
  221691. }
  221692. class MainMenuHandler;
  221693. static MainMenuHandler* mainMenu = 0;
  221694. class MainMenuHandler : private MenuBarModelListener,
  221695. private DeletedAtShutdown
  221696. {
  221697. public:
  221698. MainMenuHandler() throw()
  221699. : currentModel (0)
  221700. {
  221701. }
  221702. ~MainMenuHandler() throw()
  221703. {
  221704. setMenu (0);
  221705. jassert (mainMenu == this);
  221706. mainMenu = 0;
  221707. }
  221708. void setMenu (MenuBarModel* const newMenuBarModel) throw()
  221709. {
  221710. if (currentModel != newMenuBarModel)
  221711. {
  221712. if (currentModel != 0)
  221713. currentModel->removeListener (this);
  221714. currentModel = newMenuBarModel;
  221715. if (currentModel != 0)
  221716. currentModel->addListener (this);
  221717. menuBarItemsChanged (0);
  221718. }
  221719. }
  221720. void menuBarItemsChanged (MenuBarModel*)
  221721. {
  221722. ClearMenuBar();
  221723. if (currentModel != 0)
  221724. {
  221725. int menuId = 1000;
  221726. const StringArray menuNames (currentModel->getMenuBarNames());
  221727. for (int i = 0; i < menuNames.size(); ++i)
  221728. {
  221729. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  221730. MenuRef m = createMenu (menu, menuNames [i], menuId, i);
  221731. InsertMenu (m, 0);
  221732. CFRelease (m);
  221733. }
  221734. }
  221735. }
  221736. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  221737. {
  221738. MenuRef menu = 0;
  221739. MenuItemIndex index = 0;
  221740. GetIndMenuItemWithCommandID (0, info.commandID, 1, &menu, &index);
  221741. if (menu != 0)
  221742. {
  221743. FlashMenuBar (GetMenuID (menu));
  221744. FlashMenuBar (GetMenuID (menu));
  221745. }
  221746. }
  221747. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  221748. {
  221749. if (currentModel != 0)
  221750. {
  221751. if (commandManager != 0)
  221752. {
  221753. ApplicationCommandTarget::InvocationInfo info (commandId);
  221754. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  221755. commandManager->invoke (info, true);
  221756. }
  221757. currentModel->menuItemSelected (commandId, topLevelIndex);
  221758. }
  221759. }
  221760. MenuBarModel* currentModel;
  221761. private:
  221762. static MenuRef createMenu (const PopupMenu menu,
  221763. const String& menuName,
  221764. int& id,
  221765. const int topLevelIndex)
  221766. {
  221767. MenuRef m = 0;
  221768. if (CreateNewMenu (id++, kMenuAttrAutoDisable, &m) == noErr)
  221769. {
  221770. CFStringRef name = PlatformUtilities::juceStringToCFString (menuName);
  221771. SetMenuTitleWithCFString (m, name);
  221772. CFRelease (name);
  221773. PopupMenu::MenuItemIterator iter (menu);
  221774. while (iter.next())
  221775. {
  221776. MenuItemIndex index = 0;
  221777. int flags = kMenuAttrAutoDisable | kMenuItemAttrIgnoreMeta | kMenuItemAttrNotPreviousAlternate;
  221778. if (! iter.isEnabled)
  221779. flags |= kMenuItemAttrDisabled;
  221780. CFStringRef text = PlatformUtilities::juceStringToCFString (iter.itemName.upToFirstOccurrenceOf (T("<end>"), false, true));
  221781. if (iter.isSeparator)
  221782. {
  221783. AppendMenuItemTextWithCFString (m, text, kMenuItemAttrSeparator, 0, &index);
  221784. }
  221785. else if (iter.isSectionHeader)
  221786. {
  221787. AppendMenuItemTextWithCFString (m, text, kMenuItemAttrSectionHeader, 0, &index);
  221788. }
  221789. else if (iter.subMenu != 0)
  221790. {
  221791. AppendMenuItemTextWithCFString (m, text, flags, id++, &index);
  221792. MenuRef sub = createMenu (*iter.subMenu, iter.itemName, id, topLevelIndex);
  221793. SetMenuItemHierarchicalMenu (m, index, sub);
  221794. CFRelease (sub);
  221795. }
  221796. else
  221797. {
  221798. AppendMenuItemTextWithCFString (m, text, flags, iter.itemId, &index);
  221799. if (iter.isTicked)
  221800. CheckMenuItem (m, index, true);
  221801. SetMenuItemProperty (m, index, 'juce', 'apcm', sizeof (void*), &iter.commandManager);
  221802. SetMenuItemProperty (m, index, 'juce', 'topi', sizeof (int), &topLevelIndex);
  221803. if (iter.commandManager != 0)
  221804. {
  221805. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  221806. ->getKeyPressesAssignedToCommand (iter.itemId));
  221807. if (keyPresses.size() > 0)
  221808. {
  221809. const KeyPress& kp = keyPresses.getReference(0);
  221810. int mods = 0;
  221811. if (kp.getModifiers().isShiftDown())
  221812. mods |= kMenuShiftModifier;
  221813. if (kp.getModifiers().isCtrlDown())
  221814. mods |= kMenuControlModifier;
  221815. if (kp.getModifiers().isAltDown())
  221816. mods |= kMenuOptionModifier;
  221817. if (! kp.getModifiers().isCommandDown())
  221818. mods |= kMenuNoCommandModifier;
  221819. tchar keyCode = (tchar) kp.getKeyCode();
  221820. if (kp.getKeyCode() >= KeyPress::numberPad0
  221821. && kp.getKeyCode() <= KeyPress::numberPad9)
  221822. {
  221823. keyCode = (tchar) ((T('0') - KeyPress::numberPad0) + kp.getKeyCode());
  221824. }
  221825. SetMenuItemCommandKey (m, index, true, 255);
  221826. if (CharacterFunctions::isLetterOrDigit (keyCode)
  221827. || CharacterFunctions::indexOfChar (T(",.;/\\'[]=-+_<>?{}\":"), keyCode, false) >= 0)
  221828. {
  221829. SetMenuItemModifiers (m, index, mods);
  221830. SetMenuItemCommandKey (m, index, false, CharacterFunctions::toUpperCase (keyCode));
  221831. }
  221832. else
  221833. {
  221834. const SInt16 glyph = getGlyphForKeyCode (kp.getKeyCode());
  221835. if (glyph != 0)
  221836. {
  221837. SetMenuItemModifiers (m, index, mods);
  221838. SetMenuItemKeyGlyph (m, index, glyph);
  221839. }
  221840. }
  221841. // if we set the key glyph to be a text char, and enable virtual
  221842. // key triggering, it stops the menu automatically triggering the callback
  221843. ChangeMenuItemAttributes (m, index, kMenuItemAttrUseVirtualKey, 0);
  221844. }
  221845. }
  221846. }
  221847. CFRelease (text);
  221848. }
  221849. }
  221850. return m;
  221851. }
  221852. static SInt16 getGlyphForKeyCode (const int keyCode) throw()
  221853. {
  221854. if (keyCode == KeyPress::spaceKey)
  221855. return kMenuSpaceGlyph;
  221856. else if (keyCode == KeyPress::returnKey)
  221857. return kMenuReturnGlyph;
  221858. else if (keyCode == KeyPress::escapeKey)
  221859. return kMenuEscapeGlyph;
  221860. else if (keyCode == KeyPress::backspaceKey)
  221861. return kMenuDeleteLeftGlyph;
  221862. else if (keyCode == KeyPress::leftKey)
  221863. return kMenuLeftArrowGlyph;
  221864. else if (keyCode == KeyPress::rightKey)
  221865. return kMenuRightArrowGlyph;
  221866. else if (keyCode == KeyPress::upKey)
  221867. return kMenuUpArrowGlyph;
  221868. else if (keyCode == KeyPress::downKey)
  221869. return kMenuDownArrowGlyph;
  221870. else if (keyCode == KeyPress::pageUpKey)
  221871. return kMenuPageUpGlyph;
  221872. else if (keyCode == KeyPress::pageDownKey)
  221873. return kMenuPageDownGlyph;
  221874. else if (keyCode == KeyPress::endKey)
  221875. return kMenuSoutheastArrowGlyph;
  221876. else if (keyCode == KeyPress::homeKey)
  221877. return kMenuNorthwestArrowGlyph;
  221878. else if (keyCode == KeyPress::deleteKey)
  221879. return kMenuDeleteRightGlyph;
  221880. else if (keyCode == KeyPress::tabKey)
  221881. return kMenuTabRightGlyph;
  221882. else if (keyCode == KeyPress::F1Key)
  221883. return kMenuF1Glyph;
  221884. else if (keyCode == KeyPress::F2Key)
  221885. return kMenuF2Glyph;
  221886. else if (keyCode == KeyPress::F3Key)
  221887. return kMenuF3Glyph;
  221888. else if (keyCode == KeyPress::F4Key)
  221889. return kMenuF4Glyph;
  221890. else if (keyCode == KeyPress::F5Key)
  221891. return kMenuF5Glyph;
  221892. else if (keyCode == KeyPress::F6Key)
  221893. return kMenuF6Glyph;
  221894. else if (keyCode == KeyPress::F7Key)
  221895. return kMenuF7Glyph;
  221896. else if (keyCode == KeyPress::F8Key)
  221897. return kMenuF8Glyph;
  221898. else if (keyCode == KeyPress::F9Key)
  221899. return kMenuF9Glyph;
  221900. else if (keyCode == KeyPress::F10Key)
  221901. return kMenuF10Glyph;
  221902. else if (keyCode == KeyPress::F11Key)
  221903. return kMenuF11Glyph;
  221904. else if (keyCode == KeyPress::F12Key)
  221905. return kMenuF12Glyph;
  221906. else if (keyCode == KeyPress::F13Key)
  221907. return kMenuF13Glyph;
  221908. else if (keyCode == KeyPress::F14Key)
  221909. return kMenuF14Glyph;
  221910. else if (keyCode == KeyPress::F15Key)
  221911. return kMenuF15Glyph;
  221912. return 0;
  221913. }
  221914. };
  221915. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel) throw()
  221916. {
  221917. if (getMacMainMenu() != newMenuBarModel)
  221918. {
  221919. if (newMenuBarModel == 0)
  221920. {
  221921. delete mainMenu;
  221922. jassert (mainMenu == 0); // should be zeroed in the destructor
  221923. }
  221924. else
  221925. {
  221926. if (mainMenu == 0)
  221927. mainMenu = new MainMenuHandler();
  221928. mainMenu->setMenu (newMenuBarModel);
  221929. }
  221930. }
  221931. }
  221932. MenuBarModel* MenuBarModel::getMacMainMenu() throw()
  221933. {
  221934. return mainMenu != 0 ? mainMenu->currentModel : 0;
  221935. }
  221936. // these functions are called externally from the message handling code
  221937. void juce_MainMenuAboutToBeUsed()
  221938. {
  221939. // force an update of the items just before the menu appears..
  221940. if (mainMenu != 0)
  221941. mainMenu->menuBarItemsChanged (0);
  221942. }
  221943. void juce_InvokeMainMenuCommand (const HICommand& command)
  221944. {
  221945. if (mainMenu != 0)
  221946. {
  221947. ApplicationCommandManager* commandManager = 0;
  221948. int topLevelIndex = 0;
  221949. if (GetMenuItemProperty (command.menu.menuRef, command.menu.menuItemIndex,
  221950. 'juce', 'apcm', sizeof (commandManager), 0, &commandManager) == noErr
  221951. && GetMenuItemProperty (command.menu.menuRef, command.menu.menuItemIndex,
  221952. 'juce', 'topi', sizeof (topLevelIndex), 0, &topLevelIndex) == noErr)
  221953. {
  221954. mainMenu->invoke (command.commandID, commandManager, topLevelIndex);
  221955. }
  221956. }
  221957. }
  221958. void PlatformUtilities::beep()
  221959. {
  221960. SysBeep (30);
  221961. }
  221962. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  221963. {
  221964. ClearCurrentScrap();
  221965. ScrapRef ref;
  221966. GetCurrentScrap (&ref);
  221967. const int len = text.length();
  221968. const int numBytes = sizeof (UniChar) * len;
  221969. UniChar* const temp = (UniChar*) juce_calloc (numBytes);
  221970. for (int i = 0; i < len; ++i)
  221971. temp[i] = (UniChar) text[i];
  221972. PutScrapFlavor (ref,
  221973. kScrapFlavorTypeUnicode,
  221974. kScrapFlavorMaskNone,
  221975. numBytes,
  221976. temp);
  221977. juce_free (temp);
  221978. }
  221979. const String SystemClipboard::getTextFromClipboard() throw()
  221980. {
  221981. String result;
  221982. ScrapRef ref;
  221983. GetCurrentScrap (&ref);
  221984. Size size = 0;
  221985. if (GetScrapFlavorSize (ref, kScrapFlavorTypeUnicode, &size) == noErr
  221986. && size > 0)
  221987. {
  221988. void* const data = juce_calloc (size + 8);
  221989. if (GetScrapFlavorData (ref, kScrapFlavorTypeUnicode, &size, data) == noErr)
  221990. {
  221991. result = PlatformUtilities::convertUTF16ToString ((UniChar*) data);
  221992. }
  221993. juce_free (data);
  221994. }
  221995. return result;
  221996. }
  221997. bool AlertWindow::showNativeDialogBox (const String& title,
  221998. const String& bodyText,
  221999. bool isOkCancel)
  222000. {
  222001. Str255 tit, txt;
  222002. PlatformUtilities::copyToStr255 (tit, title);
  222003. PlatformUtilities::copyToStr255 (txt, bodyText);
  222004. AlertStdAlertParamRec ar;
  222005. ar.movable = true;
  222006. ar.helpButton = false;
  222007. ar.filterProc = 0;
  222008. ar.defaultText = (const unsigned char*)-1;
  222009. ar.cancelText = (const unsigned char*)((isOkCancel) ? -1 : 0);
  222010. ar.otherText = 0;
  222011. ar.defaultButton = kAlertStdAlertOKButton;
  222012. ar.cancelButton = 0;
  222013. ar.position = kWindowDefaultPosition;
  222014. SInt16 result;
  222015. StandardAlert (kAlertNoteAlert, tit, txt, &ar, &result);
  222016. return result == kAlertStdAlertOKButton;
  222017. }
  222018. const int KeyPress::spaceKey = ' ';
  222019. const int KeyPress::returnKey = kReturnCharCode;
  222020. const int KeyPress::escapeKey = kEscapeCharCode;
  222021. const int KeyPress::backspaceKey = kBackspaceCharCode;
  222022. const int KeyPress::leftKey = kLeftArrowCharCode;
  222023. const int KeyPress::rightKey = kRightArrowCharCode;
  222024. const int KeyPress::upKey = kUpArrowCharCode;
  222025. const int KeyPress::downKey = kDownArrowCharCode;
  222026. const int KeyPress::pageUpKey = kPageUpCharCode;
  222027. const int KeyPress::pageDownKey = kPageDownCharCode;
  222028. const int KeyPress::endKey = kEndCharCode;
  222029. const int KeyPress::homeKey = kHomeCharCode;
  222030. const int KeyPress::deleteKey = kDeleteCharCode;
  222031. const int KeyPress::insertKey = -1;
  222032. const int KeyPress::tabKey = kTabCharCode;
  222033. const int KeyPress::F1Key = 0x10110;
  222034. const int KeyPress::F2Key = 0x10111;
  222035. const int KeyPress::F3Key = 0x10112;
  222036. const int KeyPress::F4Key = 0x10113;
  222037. const int KeyPress::F5Key = 0x10114;
  222038. const int KeyPress::F6Key = 0x10115;
  222039. const int KeyPress::F7Key = 0x10116;
  222040. const int KeyPress::F8Key = 0x10117;
  222041. const int KeyPress::F9Key = 0x10118;
  222042. const int KeyPress::F10Key = 0x10119;
  222043. const int KeyPress::F11Key = 0x1011a;
  222044. const int KeyPress::F12Key = 0x1011b;
  222045. const int KeyPress::F13Key = 0x1011c;
  222046. const int KeyPress::F14Key = 0x1011d;
  222047. const int KeyPress::F15Key = 0x1011e;
  222048. const int KeyPress::F16Key = 0x1011f;
  222049. const int KeyPress::numberPad0 = 0x30020;
  222050. const int KeyPress::numberPad1 = 0x30021;
  222051. const int KeyPress::numberPad2 = 0x30022;
  222052. const int KeyPress::numberPad3 = 0x30023;
  222053. const int KeyPress::numberPad4 = 0x30024;
  222054. const int KeyPress::numberPad5 = 0x30025;
  222055. const int KeyPress::numberPad6 = 0x30026;
  222056. const int KeyPress::numberPad7 = 0x30027;
  222057. const int KeyPress::numberPad8 = 0x30028;
  222058. const int KeyPress::numberPad9 = 0x30029;
  222059. const int KeyPress::numberPadAdd = 0x3002a;
  222060. const int KeyPress::numberPadSubtract = 0x3002b;
  222061. const int KeyPress::numberPadMultiply = 0x3002c;
  222062. const int KeyPress::numberPadDivide = 0x3002d;
  222063. const int KeyPress::numberPadSeparator = 0x3002e;
  222064. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  222065. const int KeyPress::numberPadEquals = 0x30030;
  222066. const int KeyPress::numberPadDelete = 0x30031;
  222067. const int KeyPress::playKey = 0x30000;
  222068. const int KeyPress::stopKey = 0x30001;
  222069. const int KeyPress::fastForwardKey = 0x30002;
  222070. const int KeyPress::rewindKey = 0x30003;
  222071. AppleRemoteDevice::AppleRemoteDevice()
  222072. : device (0),
  222073. queue (0),
  222074. remoteId (0)
  222075. {
  222076. }
  222077. AppleRemoteDevice::~AppleRemoteDevice()
  222078. {
  222079. stop();
  222080. }
  222081. static io_object_t getAppleRemoteDevice() throw()
  222082. {
  222083. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  222084. io_iterator_t iter = 0;
  222085. io_object_t iod = 0;
  222086. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  222087. && iter != 0)
  222088. {
  222089. iod = IOIteratorNext (iter);
  222090. }
  222091. IOObjectRelease (iter);
  222092. return iod;
  222093. }
  222094. static bool createAppleRemoteInterface (io_object_t iod, void** device) throw()
  222095. {
  222096. jassert (*device == 0);
  222097. io_name_t classname;
  222098. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  222099. {
  222100. IOCFPlugInInterface** cfPlugInInterface = 0;
  222101. SInt32 score = 0;
  222102. if (IOCreatePlugInInterfaceForService (iod,
  222103. kIOHIDDeviceUserClientTypeID,
  222104. kIOCFPlugInInterfaceID,
  222105. &cfPlugInInterface,
  222106. &score) == kIOReturnSuccess)
  222107. {
  222108. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  222109. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  222110. device);
  222111. (void) hr;
  222112. (*cfPlugInInterface)->Release (cfPlugInInterface);
  222113. }
  222114. }
  222115. return *device != 0;
  222116. }
  222117. bool AppleRemoteDevice::start (const bool inExclusiveMode) throw()
  222118. {
  222119. if (queue != 0)
  222120. return true;
  222121. stop();
  222122. bool result = false;
  222123. io_object_t iod = getAppleRemoteDevice();
  222124. if (iod != 0)
  222125. {
  222126. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  222127. result = true;
  222128. else
  222129. stop();
  222130. IOObjectRelease (iod);
  222131. }
  222132. return result;
  222133. }
  222134. void AppleRemoteDevice::stop() throw()
  222135. {
  222136. if (queue != 0)
  222137. {
  222138. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  222139. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  222140. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  222141. queue = 0;
  222142. }
  222143. if (device != 0)
  222144. {
  222145. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  222146. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  222147. device = 0;
  222148. }
  222149. }
  222150. bool AppleRemoteDevice::isActive() const throw()
  222151. {
  222152. return queue != 0;
  222153. }
  222154. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  222155. {
  222156. if (result == kIOReturnSuccess)
  222157. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  222158. }
  222159. bool AppleRemoteDevice::open (const bool openInExclusiveMode) throw()
  222160. {
  222161. #if ! MACOS_10_2_OR_EARLIER
  222162. Array <int> cookies;
  222163. CFArrayRef elements;
  222164. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  222165. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  222166. return false;
  222167. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  222168. {
  222169. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  222170. // get the cookie
  222171. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  222172. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  222173. continue;
  222174. long number;
  222175. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  222176. continue;
  222177. cookies.add ((int) number);
  222178. }
  222179. CFRelease (elements);
  222180. if ((*(IOHIDDeviceInterface**) device)
  222181. ->open ((IOHIDDeviceInterface**) device,
  222182. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  222183. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  222184. {
  222185. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  222186. if (queue != 0)
  222187. {
  222188. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  222189. for (int i = 0; i < cookies.size(); ++i)
  222190. {
  222191. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  222192. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  222193. }
  222194. CFRunLoopSourceRef eventSource;
  222195. if ((*(IOHIDQueueInterface**) queue)
  222196. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  222197. {
  222198. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  222199. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  222200. {
  222201. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  222202. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  222203. return true;
  222204. }
  222205. }
  222206. }
  222207. }
  222208. #endif
  222209. return false;
  222210. }
  222211. void AppleRemoteDevice::handleCallbackInternal()
  222212. {
  222213. int totalValues = 0;
  222214. AbsoluteTime nullTime = { 0, 0 };
  222215. char cookies [12];
  222216. int numCookies = 0;
  222217. while (numCookies < numElementsInArray (cookies))
  222218. {
  222219. IOHIDEventStruct e;
  222220. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  222221. break;
  222222. if ((int) e.elementCookie == 19)
  222223. {
  222224. remoteId = e.value;
  222225. buttonPressed (switched, false);
  222226. }
  222227. else
  222228. {
  222229. totalValues += e.value;
  222230. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  222231. }
  222232. }
  222233. cookies [numCookies++] = 0;
  222234. static const char buttonPatterns[] =
  222235. {
  222236. 14, 7, 6, 5, 14, 7, 6, 5, 0,
  222237. 14, 8, 6, 5, 14, 8, 6, 5, 0,
  222238. 14, 12, 11, 6, 5, 0,
  222239. 14, 13, 11, 6, 5, 0,
  222240. 14, 9, 6, 5, 14, 9, 6, 5, 0,
  222241. 14, 10, 6, 5, 14, 10, 6, 5, 0,
  222242. 14, 6, 5, 4, 2, 0,
  222243. 14, 6, 5, 3, 2, 0,
  222244. 14, 6, 5, 14, 6, 5, 0,
  222245. 18, 14, 6, 5, 18, 14, 6, 5, 0,
  222246. 19, 0
  222247. };
  222248. int buttonNum = (int) menuButton;
  222249. int i = 0;
  222250. while (i < numElementsInArray (buttonPatterns))
  222251. {
  222252. if (strcmp (cookies, buttonPatterns + i) == 0)
  222253. {
  222254. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  222255. break;
  222256. }
  222257. i += strlen (buttonPatterns + i) + 1;
  222258. ++buttonNum;
  222259. }
  222260. }
  222261. #if JUCE_OPENGL
  222262. class WindowedGLContext : public OpenGLContext
  222263. {
  222264. public:
  222265. WindowedGLContext (Component* const component,
  222266. const OpenGLPixelFormat& pixelFormat_,
  222267. AGLContext sharedContext)
  222268. : renderContext (0),
  222269. pixelFormat (pixelFormat_)
  222270. {
  222271. jassert (component != 0);
  222272. HIViewComponentPeer* const peer = dynamic_cast <HIViewComponentPeer*> (component->getTopLevelComponent()->getPeer());
  222273. if (peer == 0)
  222274. return;
  222275. GLint attribs [64];
  222276. int n = 0;
  222277. attribs[n++] = AGL_RGBA;
  222278. attribs[n++] = AGL_DOUBLEBUFFER;
  222279. attribs[n++] = AGL_ACCELERATED;
  222280. attribs[n++] = AGL_RED_SIZE;
  222281. attribs[n++] = pixelFormat.redBits;
  222282. attribs[n++] = AGL_GREEN_SIZE;
  222283. attribs[n++] = pixelFormat.greenBits;
  222284. attribs[n++] = AGL_BLUE_SIZE;
  222285. attribs[n++] = pixelFormat.blueBits;
  222286. attribs[n++] = AGL_ALPHA_SIZE;
  222287. attribs[n++] = pixelFormat.alphaBits;
  222288. attribs[n++] = AGL_DEPTH_SIZE;
  222289. attribs[n++] = pixelFormat.depthBufferBits;
  222290. attribs[n++] = AGL_STENCIL_SIZE;
  222291. attribs[n++] = pixelFormat.stencilBufferBits;
  222292. attribs[n++] = AGL_ACCUM_RED_SIZE;
  222293. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  222294. attribs[n++] = AGL_ACCUM_GREEN_SIZE;
  222295. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  222296. attribs[n++] = AGL_ACCUM_BLUE_SIZE;
  222297. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  222298. attribs[n++] = AGL_ACCUM_ALPHA_SIZE;
  222299. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  222300. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  222301. attribs[n++] = AGL_SAMPLE_BUFFERS_ARB;
  222302. attribs[n++] = 1;
  222303. attribs[n++] = AGL_SAMPLES_ARB;
  222304. attribs[n++] = 4;
  222305. attribs[n++] = AGL_CLOSEST_POLICY;
  222306. attribs[n++] = AGL_NO_RECOVERY;
  222307. attribs[n++] = AGL_NONE;
  222308. renderContext = aglCreateContext (aglChoosePixelFormat (0, 0, attribs),
  222309. sharedContext);
  222310. aglSetDrawable (renderContext, GetWindowPort (peer->windowRef));
  222311. }
  222312. ~WindowedGLContext()
  222313. {
  222314. makeInactive();
  222315. aglSetDrawable (renderContext, 0);
  222316. aglDestroyContext (renderContext);
  222317. }
  222318. bool makeActive() const throw()
  222319. {
  222320. jassert (renderContext != 0);
  222321. return aglSetCurrentContext (renderContext);
  222322. }
  222323. bool makeInactive() const throw()
  222324. {
  222325. return (! isActive()) || aglSetCurrentContext (0);
  222326. }
  222327. bool isActive() const throw()
  222328. {
  222329. return aglGetCurrentContext() == renderContext;
  222330. }
  222331. const OpenGLPixelFormat getPixelFormat() const
  222332. {
  222333. return pixelFormat;
  222334. }
  222335. void* getRawContext() const throw()
  222336. {
  222337. return renderContext;
  222338. }
  222339. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  222340. {
  222341. GLint bufferRect[4];
  222342. bufferRect[0] = x;
  222343. bufferRect[1] = outerWindowHeight - (y + h);
  222344. bufferRect[2] = w;
  222345. bufferRect[3] = h;
  222346. aglSetInteger (renderContext, AGL_BUFFER_RECT, bufferRect);
  222347. aglEnable (renderContext, AGL_BUFFER_RECT);
  222348. }
  222349. void swapBuffers()
  222350. {
  222351. aglSwapBuffers (renderContext);
  222352. }
  222353. bool setSwapInterval (const int numFramesPerSwap)
  222354. {
  222355. return aglSetInteger (renderContext, AGL_SWAP_INTERVAL, (const GLint*) &numFramesPerSwap);
  222356. }
  222357. int getSwapInterval() const
  222358. {
  222359. GLint numFrames = 0;
  222360. aglGetInteger (renderContext, AGL_SWAP_INTERVAL, &numFrames);
  222361. return numFrames;
  222362. }
  222363. void repaint()
  222364. {
  222365. }
  222366. juce_UseDebuggingNewOperator
  222367. AGLContext renderContext;
  222368. private:
  222369. OpenGLPixelFormat pixelFormat;
  222370. WindowedGLContext (const WindowedGLContext&);
  222371. const WindowedGLContext& operator= (const WindowedGLContext&);
  222372. };
  222373. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  222374. const OpenGLPixelFormat& pixelFormat,
  222375. const OpenGLContext* const contextToShareWith)
  222376. {
  222377. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  222378. contextToShareWith != 0 ? (AGLContext) contextToShareWith->getRawContext() : 0);
  222379. if (c->renderContext == 0)
  222380. deleteAndZero (c);
  222381. return c;
  222382. }
  222383. void juce_glViewport (const int w, const int h)
  222384. {
  222385. glViewport (0, 0, w, h);
  222386. }
  222387. static int getAGLAttribute (AGLPixelFormat p, const GLint attrib)
  222388. {
  222389. GLint result = 0;
  222390. aglDescribePixelFormat (p, attrib, &result);
  222391. return result;
  222392. }
  222393. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  222394. OwnedArray <OpenGLPixelFormat>& results)
  222395. {
  222396. GLint attribs [64];
  222397. int n = 0;
  222398. attribs[n++] = AGL_RGBA;
  222399. attribs[n++] = AGL_DOUBLEBUFFER;
  222400. attribs[n++] = AGL_ACCELERATED;
  222401. attribs[n++] = AGL_NO_RECOVERY;
  222402. attribs[n++] = AGL_NONE;
  222403. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  222404. while (p != 0)
  222405. {
  222406. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  222407. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  222408. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  222409. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  222410. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  222411. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  222412. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  222413. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  222414. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  222415. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  222416. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  222417. results.add (pf);
  222418. p = aglNextPixelFormat (p);
  222419. }
  222420. }
  222421. #endif
  222422. END_JUCE_NAMESPACE
  222423. /********* End of inlined file: juce_mac_Windowing.mm *********/
  222424. #endif
  222425. #endif